echarts.js 3.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. (function (global, factory) {
  20. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  21. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  22. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.echarts = {}));
  23. }(this, (function (exports) { 'use strict';
  24. /*! *****************************************************************************
  25. Copyright (c) Microsoft Corporation.
  26. Permission to use, copy, modify, and/or distribute this software for any
  27. purpose with or without fee is hereby granted.
  28. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  29. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  30. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  31. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  32. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  33. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  34. PERFORMANCE OF THIS SOFTWARE.
  35. ***************************************************************************** */
  36. /* global Reflect, Promise */
  37. var extendStatics = function(d, b) {
  38. extendStatics = Object.setPrototypeOf ||
  39. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  40. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  41. return extendStatics(d, b);
  42. };
  43. function __extends(d, b) {
  44. if (typeof b !== "function" && b !== null)
  45. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  46. extendStatics(d, b);
  47. function __() { this.constructor = d; }
  48. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  49. }
  50. var Browser = (function () {
  51. function Browser() {
  52. this.firefox = false;
  53. this.ie = false;
  54. this.edge = false;
  55. this.newEdge = false;
  56. this.weChat = false;
  57. }
  58. return Browser;
  59. }());
  60. var Env = (function () {
  61. function Env() {
  62. this.browser = new Browser();
  63. this.node = false;
  64. this.wxa = false;
  65. this.worker = false;
  66. this.svgSupported = false;
  67. this.touchEventsSupported = false;
  68. this.pointerEventsSupported = false;
  69. this.domSupported = false;
  70. this.transformSupported = false;
  71. this.transform3dSupported = false;
  72. this.hasGlobalWindow = typeof window !== 'undefined';
  73. }
  74. return Env;
  75. }());
  76. var env = new Env();
  77. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  78. env.wxa = true;
  79. env.touchEventsSupported = true;
  80. }
  81. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  82. env.worker = true;
  83. }
  84. else if (typeof navigator === 'undefined') {
  85. env.node = true;
  86. env.svgSupported = true;
  87. }
  88. else {
  89. detect(navigator.userAgent, env);
  90. }
  91. function detect(ua, env) {
  92. var browser = env.browser;
  93. var firefox = ua.match(/Firefox\/([\d.]+)/);
  94. var ie = ua.match(/MSIE\s([\d.]+)/)
  95. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  96. var edge = ua.match(/Edge?\/([\d.]+)/);
  97. var weChat = (/micromessenger/i).test(ua);
  98. if (firefox) {
  99. browser.firefox = true;
  100. browser.version = firefox[1];
  101. }
  102. if (ie) {
  103. browser.ie = true;
  104. browser.version = ie[1];
  105. }
  106. if (edge) {
  107. browser.edge = true;
  108. browser.version = edge[1];
  109. browser.newEdge = +edge[1].split('.')[0] > 18;
  110. }
  111. if (weChat) {
  112. browser.weChat = true;
  113. }
  114. env.svgSupported = typeof SVGRect !== 'undefined';
  115. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  116. env.pointerEventsSupported = 'onpointerdown' in window
  117. && (browser.edge || (browser.ie && +browser.version >= 11));
  118. env.domSupported = typeof document !== 'undefined';
  119. var style = document.documentElement.style;
  120. env.transform3dSupported = ((browser.ie && 'transition' in style)
  121. || browser.edge
  122. || (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
  123. || 'MozPerspective' in style)
  124. && !('OTransition' in style);
  125. env.transformSupported = env.transform3dSupported
  126. || (browser.ie && +browser.version >= 9);
  127. }
  128. var DEFAULT_FONT_SIZE = 12;
  129. var DEFAULT_FONT_FAMILY = 'sans-serif';
  130. var DEFAULT_FONT = DEFAULT_FONT_SIZE + "px " + DEFAULT_FONT_FAMILY;
  131. var OFFSET = 20;
  132. var SCALE = 100;
  133. var defaultWidthMapStr = "007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";
  134. function getTextWidthMap(mapStr) {
  135. var map = {};
  136. if (typeof JSON === 'undefined') {
  137. return map;
  138. }
  139. for (var i = 0; i < mapStr.length; i++) {
  140. var char = String.fromCharCode(i + 32);
  141. var size = (mapStr.charCodeAt(i) - OFFSET) / SCALE;
  142. map[char] = size;
  143. }
  144. return map;
  145. }
  146. var DEFAULT_TEXT_WIDTH_MAP = getTextWidthMap(defaultWidthMapStr);
  147. var platformApi = {
  148. createCanvas: function () {
  149. return typeof document !== 'undefined'
  150. && document.createElement('canvas');
  151. },
  152. measureText: (function () {
  153. var _ctx;
  154. var _cachedFont;
  155. return function (text, font) {
  156. if (!_ctx) {
  157. var canvas = platformApi.createCanvas();
  158. _ctx = canvas && canvas.getContext('2d');
  159. }
  160. if (_ctx) {
  161. if (_cachedFont !== font) {
  162. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  163. }
  164. return _ctx.measureText(text);
  165. }
  166. else {
  167. text = text || '';
  168. font = font || DEFAULT_FONT;
  169. var res = /(\d+)px/.exec(font);
  170. var fontSize = res && +res[1] || DEFAULT_FONT_SIZE;
  171. var width = 0;
  172. if (font.indexOf('mono') >= 0) {
  173. width = fontSize * text.length;
  174. }
  175. else {
  176. for (var i = 0; i < text.length; i++) {
  177. var preCalcWidth = DEFAULT_TEXT_WIDTH_MAP[text[i]];
  178. width += preCalcWidth == null ? fontSize : (preCalcWidth * fontSize);
  179. }
  180. }
  181. return { width: width };
  182. }
  183. };
  184. })(),
  185. loadImage: function (src, onload, onerror) {
  186. var image = new Image();
  187. image.onload = onload;
  188. image.onerror = onerror;
  189. image.src = src;
  190. return image;
  191. }
  192. };
  193. function setPlatformAPI(newPlatformApis) {
  194. for (var key in platformApi) {
  195. if (newPlatformApis[key]) {
  196. platformApi[key] = newPlatformApis[key];
  197. }
  198. }
  199. }
  200. var BUILTIN_OBJECT = reduce([
  201. 'Function',
  202. 'RegExp',
  203. 'Date',
  204. 'Error',
  205. 'CanvasGradient',
  206. 'CanvasPattern',
  207. 'Image',
  208. 'Canvas'
  209. ], function (obj, val) {
  210. obj['[object ' + val + ']'] = true;
  211. return obj;
  212. }, {});
  213. var TYPED_ARRAY = reduce([
  214. 'Int8',
  215. 'Uint8',
  216. 'Uint8Clamped',
  217. 'Int16',
  218. 'Uint16',
  219. 'Int32',
  220. 'Uint32',
  221. 'Float32',
  222. 'Float64'
  223. ], function (obj, val) {
  224. obj['[object ' + val + 'Array]'] = true;
  225. return obj;
  226. }, {});
  227. var objToString = Object.prototype.toString;
  228. var arrayProto = Array.prototype;
  229. var nativeForEach = arrayProto.forEach;
  230. var nativeFilter = arrayProto.filter;
  231. var nativeSlice = arrayProto.slice;
  232. var nativeMap = arrayProto.map;
  233. var ctorFunction = function () { }.constructor;
  234. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  235. var protoKey = '__proto__';
  236. var idStart = 0x0907;
  237. function guid() {
  238. return idStart++;
  239. }
  240. function logError() {
  241. var args = [];
  242. for (var _i = 0; _i < arguments.length; _i++) {
  243. args[_i] = arguments[_i];
  244. }
  245. if (typeof console !== 'undefined') {
  246. console.error.apply(console, args);
  247. }
  248. }
  249. function clone(source) {
  250. if (source == null || typeof source !== 'object') {
  251. return source;
  252. }
  253. var result = source;
  254. var typeStr = objToString.call(source);
  255. if (typeStr === '[object Array]') {
  256. if (!isPrimitive(source)) {
  257. result = [];
  258. for (var i = 0, len = source.length; i < len; i++) {
  259. result[i] = clone(source[i]);
  260. }
  261. }
  262. }
  263. else if (TYPED_ARRAY[typeStr]) {
  264. if (!isPrimitive(source)) {
  265. var Ctor = source.constructor;
  266. if (Ctor.from) {
  267. result = Ctor.from(source);
  268. }
  269. else {
  270. result = new Ctor(source.length);
  271. for (var i = 0, len = source.length; i < len; i++) {
  272. result[i] = source[i];
  273. }
  274. }
  275. }
  276. }
  277. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  278. result = {};
  279. for (var key in source) {
  280. if (source.hasOwnProperty(key) && key !== protoKey) {
  281. result[key] = clone(source[key]);
  282. }
  283. }
  284. }
  285. return result;
  286. }
  287. function merge(target, source, overwrite) {
  288. if (!isObject(source) || !isObject(target)) {
  289. return overwrite ? clone(source) : target;
  290. }
  291. for (var key in source) {
  292. if (source.hasOwnProperty(key) && key !== protoKey) {
  293. var targetProp = target[key];
  294. var sourceProp = source[key];
  295. if (isObject(sourceProp)
  296. && isObject(targetProp)
  297. && !isArray(sourceProp)
  298. && !isArray(targetProp)
  299. && !isDom(sourceProp)
  300. && !isDom(targetProp)
  301. && !isBuiltInObject(sourceProp)
  302. && !isBuiltInObject(targetProp)
  303. && !isPrimitive(sourceProp)
  304. && !isPrimitive(targetProp)) {
  305. merge(targetProp, sourceProp, overwrite);
  306. }
  307. else if (overwrite || !(key in target)) {
  308. target[key] = clone(source[key]);
  309. }
  310. }
  311. }
  312. return target;
  313. }
  314. function mergeAll(targetAndSources, overwrite) {
  315. var result = targetAndSources[0];
  316. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  317. result = merge(result, targetAndSources[i], overwrite);
  318. }
  319. return result;
  320. }
  321. function extend(target, source) {
  322. if (Object.assign) {
  323. Object.assign(target, source);
  324. }
  325. else {
  326. for (var key in source) {
  327. if (source.hasOwnProperty(key) && key !== protoKey) {
  328. target[key] = source[key];
  329. }
  330. }
  331. }
  332. return target;
  333. }
  334. function defaults(target, source, overlay) {
  335. var keysArr = keys(source);
  336. for (var i = 0; i < keysArr.length; i++) {
  337. var key = keysArr[i];
  338. if ((overlay ? source[key] != null : target[key] == null)) {
  339. target[key] = source[key];
  340. }
  341. }
  342. return target;
  343. }
  344. var createCanvas = platformApi.createCanvas;
  345. function indexOf(array, value) {
  346. if (array) {
  347. if (array.indexOf) {
  348. return array.indexOf(value);
  349. }
  350. for (var i = 0, len = array.length; i < len; i++) {
  351. if (array[i] === value) {
  352. return i;
  353. }
  354. }
  355. }
  356. return -1;
  357. }
  358. function inherits(clazz, baseClazz) {
  359. var clazzPrototype = clazz.prototype;
  360. function F() { }
  361. F.prototype = baseClazz.prototype;
  362. clazz.prototype = new F();
  363. for (var prop in clazzPrototype) {
  364. if (clazzPrototype.hasOwnProperty(prop)) {
  365. clazz.prototype[prop] = clazzPrototype[prop];
  366. }
  367. }
  368. clazz.prototype.constructor = clazz;
  369. clazz.superClass = baseClazz;
  370. }
  371. function mixin(target, source, override) {
  372. target = 'prototype' in target ? target.prototype : target;
  373. source = 'prototype' in source ? source.prototype : source;
  374. if (Object.getOwnPropertyNames) {
  375. var keyList = Object.getOwnPropertyNames(source);
  376. for (var i = 0; i < keyList.length; i++) {
  377. var key = keyList[i];
  378. if (key !== 'constructor') {
  379. if ((override ? source[key] != null : target[key] == null)) {
  380. target[key] = source[key];
  381. }
  382. }
  383. }
  384. }
  385. else {
  386. defaults(target, source, override);
  387. }
  388. }
  389. function isArrayLike(data) {
  390. if (!data) {
  391. return false;
  392. }
  393. if (typeof data === 'string') {
  394. return false;
  395. }
  396. return typeof data.length === 'number';
  397. }
  398. function each(arr, cb, context) {
  399. if (!(arr && cb)) {
  400. return;
  401. }
  402. if (arr.forEach && arr.forEach === nativeForEach) {
  403. arr.forEach(cb, context);
  404. }
  405. else if (arr.length === +arr.length) {
  406. for (var i = 0, len = arr.length; i < len; i++) {
  407. cb.call(context, arr[i], i, arr);
  408. }
  409. }
  410. else {
  411. for (var key in arr) {
  412. if (arr.hasOwnProperty(key)) {
  413. cb.call(context, arr[key], key, arr);
  414. }
  415. }
  416. }
  417. }
  418. function map(arr, cb, context) {
  419. if (!arr) {
  420. return [];
  421. }
  422. if (!cb) {
  423. return slice(arr);
  424. }
  425. if (arr.map && arr.map === nativeMap) {
  426. return arr.map(cb, context);
  427. }
  428. else {
  429. var result = [];
  430. for (var i = 0, len = arr.length; i < len; i++) {
  431. result.push(cb.call(context, arr[i], i, arr));
  432. }
  433. return result;
  434. }
  435. }
  436. function reduce(arr, cb, memo, context) {
  437. if (!(arr && cb)) {
  438. return;
  439. }
  440. for (var i = 0, len = arr.length; i < len; i++) {
  441. memo = cb.call(context, memo, arr[i], i, arr);
  442. }
  443. return memo;
  444. }
  445. function filter(arr, cb, context) {
  446. if (!arr) {
  447. return [];
  448. }
  449. if (!cb) {
  450. return slice(arr);
  451. }
  452. if (arr.filter && arr.filter === nativeFilter) {
  453. return arr.filter(cb, context);
  454. }
  455. else {
  456. var result = [];
  457. for (var i = 0, len = arr.length; i < len; i++) {
  458. if (cb.call(context, arr[i], i, arr)) {
  459. result.push(arr[i]);
  460. }
  461. }
  462. return result;
  463. }
  464. }
  465. function find(arr, cb, context) {
  466. if (!(arr && cb)) {
  467. return;
  468. }
  469. for (var i = 0, len = arr.length; i < len; i++) {
  470. if (cb.call(context, arr[i], i, arr)) {
  471. return arr[i];
  472. }
  473. }
  474. }
  475. function keys(obj) {
  476. if (!obj) {
  477. return [];
  478. }
  479. if (Object.keys) {
  480. return Object.keys(obj);
  481. }
  482. var keyList = [];
  483. for (var key in obj) {
  484. if (obj.hasOwnProperty(key)) {
  485. keyList.push(key);
  486. }
  487. }
  488. return keyList;
  489. }
  490. function bindPolyfill(func, context) {
  491. var args = [];
  492. for (var _i = 2; _i < arguments.length; _i++) {
  493. args[_i - 2] = arguments[_i];
  494. }
  495. return function () {
  496. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  497. };
  498. }
  499. var bind = (protoFunction && isFunction(protoFunction.bind))
  500. ? protoFunction.call.bind(protoFunction.bind)
  501. : bindPolyfill;
  502. function curry(func) {
  503. var args = [];
  504. for (var _i = 1; _i < arguments.length; _i++) {
  505. args[_i - 1] = arguments[_i];
  506. }
  507. return function () {
  508. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  509. };
  510. }
  511. function isArray(value) {
  512. if (Array.isArray) {
  513. return Array.isArray(value);
  514. }
  515. return objToString.call(value) === '[object Array]';
  516. }
  517. function isFunction(value) {
  518. return typeof value === 'function';
  519. }
  520. function isString(value) {
  521. return typeof value === 'string';
  522. }
  523. function isStringSafe(value) {
  524. return objToString.call(value) === '[object String]';
  525. }
  526. function isNumber(value) {
  527. return typeof value === 'number';
  528. }
  529. function isObject(value) {
  530. var type = typeof value;
  531. return type === 'function' || (!!value && type === 'object');
  532. }
  533. function isBuiltInObject(value) {
  534. return !!BUILTIN_OBJECT[objToString.call(value)];
  535. }
  536. function isTypedArray(value) {
  537. return !!TYPED_ARRAY[objToString.call(value)];
  538. }
  539. function isDom(value) {
  540. return typeof value === 'object'
  541. && typeof value.nodeType === 'number'
  542. && typeof value.ownerDocument === 'object';
  543. }
  544. function isGradientObject(value) {
  545. return value.colorStops != null;
  546. }
  547. function isImagePatternObject(value) {
  548. return value.image != null;
  549. }
  550. function isRegExp(value) {
  551. return objToString.call(value) === '[object RegExp]';
  552. }
  553. function eqNaN(value) {
  554. return value !== value;
  555. }
  556. function retrieve() {
  557. var args = [];
  558. for (var _i = 0; _i < arguments.length; _i++) {
  559. args[_i] = arguments[_i];
  560. }
  561. for (var i = 0, len = args.length; i < len; i++) {
  562. if (args[i] != null) {
  563. return args[i];
  564. }
  565. }
  566. }
  567. function retrieve2(value0, value1) {
  568. return value0 != null
  569. ? value0
  570. : value1;
  571. }
  572. function retrieve3(value0, value1, value2) {
  573. return value0 != null
  574. ? value0
  575. : value1 != null
  576. ? value1
  577. : value2;
  578. }
  579. function slice(arr) {
  580. var args = [];
  581. for (var _i = 1; _i < arguments.length; _i++) {
  582. args[_i - 1] = arguments[_i];
  583. }
  584. return nativeSlice.apply(arr, args);
  585. }
  586. function normalizeCssArray(val) {
  587. if (typeof (val) === 'number') {
  588. return [val, val, val, val];
  589. }
  590. var len = val.length;
  591. if (len === 2) {
  592. return [val[0], val[1], val[0], val[1]];
  593. }
  594. else if (len === 3) {
  595. return [val[0], val[1], val[2], val[1]];
  596. }
  597. return val;
  598. }
  599. function assert(condition, message) {
  600. if (!condition) {
  601. throw new Error(message);
  602. }
  603. }
  604. function trim(str) {
  605. if (str == null) {
  606. return null;
  607. }
  608. else if (typeof str.trim === 'function') {
  609. return str.trim();
  610. }
  611. else {
  612. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  613. }
  614. }
  615. var primitiveKey = '__ec_primitive__';
  616. function setAsPrimitive(obj) {
  617. obj[primitiveKey] = true;
  618. }
  619. function isPrimitive(obj) {
  620. return obj[primitiveKey];
  621. }
  622. var MapPolyfill = (function () {
  623. function MapPolyfill() {
  624. this.data = {};
  625. }
  626. MapPolyfill.prototype["delete"] = function (key) {
  627. var existed = this.has(key);
  628. if (existed) {
  629. delete this.data[key];
  630. }
  631. return existed;
  632. };
  633. MapPolyfill.prototype.has = function (key) {
  634. return this.data.hasOwnProperty(key);
  635. };
  636. MapPolyfill.prototype.get = function (key) {
  637. return this.data[key];
  638. };
  639. MapPolyfill.prototype.set = function (key, value) {
  640. this.data[key] = value;
  641. return this;
  642. };
  643. MapPolyfill.prototype.keys = function () {
  644. return keys(this.data);
  645. };
  646. MapPolyfill.prototype.forEach = function (callback) {
  647. var data = this.data;
  648. for (var key in data) {
  649. if (data.hasOwnProperty(key)) {
  650. callback(data[key], key);
  651. }
  652. }
  653. };
  654. return MapPolyfill;
  655. }());
  656. var isNativeMapSupported = typeof Map === 'function';
  657. function maybeNativeMap() {
  658. return (isNativeMapSupported ? new Map() : new MapPolyfill());
  659. }
  660. var HashMap = (function () {
  661. function HashMap(obj) {
  662. var isArr = isArray(obj);
  663. this.data = maybeNativeMap();
  664. var thisMap = this;
  665. (obj instanceof HashMap)
  666. ? obj.each(visit)
  667. : (obj && each(obj, visit));
  668. function visit(value, key) {
  669. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  670. }
  671. }
  672. HashMap.prototype.hasKey = function (key) {
  673. return this.data.has(key);
  674. };
  675. HashMap.prototype.get = function (key) {
  676. return this.data.get(key);
  677. };
  678. HashMap.prototype.set = function (key, value) {
  679. this.data.set(key, value);
  680. return value;
  681. };
  682. HashMap.prototype.each = function (cb, context) {
  683. this.data.forEach(function (value, key) {
  684. cb.call(context, value, key);
  685. });
  686. };
  687. HashMap.prototype.keys = function () {
  688. var keys = this.data.keys();
  689. return isNativeMapSupported
  690. ? Array.from(keys)
  691. : keys;
  692. };
  693. HashMap.prototype.removeKey = function (key) {
  694. this.data["delete"](key);
  695. };
  696. return HashMap;
  697. }());
  698. function createHashMap(obj) {
  699. return new HashMap(obj);
  700. }
  701. function concatArray(a, b) {
  702. var newArray = new a.constructor(a.length + b.length);
  703. for (var i = 0; i < a.length; i++) {
  704. newArray[i] = a[i];
  705. }
  706. var offset = a.length;
  707. for (var i = 0; i < b.length; i++) {
  708. newArray[i + offset] = b[i];
  709. }
  710. return newArray;
  711. }
  712. function createObject(proto, properties) {
  713. var obj;
  714. if (Object.create) {
  715. obj = Object.create(proto);
  716. }
  717. else {
  718. var StyleCtor = function () { };
  719. StyleCtor.prototype = proto;
  720. obj = new StyleCtor();
  721. }
  722. if (properties) {
  723. extend(obj, properties);
  724. }
  725. return obj;
  726. }
  727. function disableUserSelect(dom) {
  728. var domStyle = dom.style;
  729. domStyle.webkitUserSelect = 'none';
  730. domStyle.userSelect = 'none';
  731. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  732. domStyle['-webkit-touch-callout'] = 'none';
  733. }
  734. function hasOwn(own, prop) {
  735. return own.hasOwnProperty(prop);
  736. }
  737. function noop() { }
  738. var RADIAN_TO_DEGREE = 180 / Math.PI;
  739. var util = /*#__PURE__*/Object.freeze({
  740. __proto__: null,
  741. guid: guid,
  742. logError: logError,
  743. clone: clone,
  744. merge: merge,
  745. mergeAll: mergeAll,
  746. extend: extend,
  747. defaults: defaults,
  748. createCanvas: createCanvas,
  749. indexOf: indexOf,
  750. inherits: inherits,
  751. mixin: mixin,
  752. isArrayLike: isArrayLike,
  753. each: each,
  754. map: map,
  755. reduce: reduce,
  756. filter: filter,
  757. find: find,
  758. keys: keys,
  759. bind: bind,
  760. curry: curry,
  761. isArray: isArray,
  762. isFunction: isFunction,
  763. isString: isString,
  764. isStringSafe: isStringSafe,
  765. isNumber: isNumber,
  766. isObject: isObject,
  767. isBuiltInObject: isBuiltInObject,
  768. isTypedArray: isTypedArray,
  769. isDom: isDom,
  770. isGradientObject: isGradientObject,
  771. isImagePatternObject: isImagePatternObject,
  772. isRegExp: isRegExp,
  773. eqNaN: eqNaN,
  774. retrieve: retrieve,
  775. retrieve2: retrieve2,
  776. retrieve3: retrieve3,
  777. slice: slice,
  778. normalizeCssArray: normalizeCssArray,
  779. assert: assert,
  780. trim: trim,
  781. setAsPrimitive: setAsPrimitive,
  782. isPrimitive: isPrimitive,
  783. HashMap: HashMap,
  784. createHashMap: createHashMap,
  785. concatArray: concatArray,
  786. createObject: createObject,
  787. disableUserSelect: disableUserSelect,
  788. hasOwn: hasOwn,
  789. noop: noop,
  790. RADIAN_TO_DEGREE: RADIAN_TO_DEGREE
  791. });
  792. function create(x, y) {
  793. if (x == null) {
  794. x = 0;
  795. }
  796. if (y == null) {
  797. y = 0;
  798. }
  799. return [x, y];
  800. }
  801. function copy(out, v) {
  802. out[0] = v[0];
  803. out[1] = v[1];
  804. return out;
  805. }
  806. function clone$1(v) {
  807. return [v[0], v[1]];
  808. }
  809. function set(out, a, b) {
  810. out[0] = a;
  811. out[1] = b;
  812. return out;
  813. }
  814. function add(out, v1, v2) {
  815. out[0] = v1[0] + v2[0];
  816. out[1] = v1[1] + v2[1];
  817. return out;
  818. }
  819. function scaleAndAdd(out, v1, v2, a) {
  820. out[0] = v1[0] + v2[0] * a;
  821. out[1] = v1[1] + v2[1] * a;
  822. return out;
  823. }
  824. function sub(out, v1, v2) {
  825. out[0] = v1[0] - v2[0];
  826. out[1] = v1[1] - v2[1];
  827. return out;
  828. }
  829. function len(v) {
  830. return Math.sqrt(lenSquare(v));
  831. }
  832. var length = len;
  833. function lenSquare(v) {
  834. return v[0] * v[0] + v[1] * v[1];
  835. }
  836. var lengthSquare = lenSquare;
  837. function mul(out, v1, v2) {
  838. out[0] = v1[0] * v2[0];
  839. out[1] = v1[1] * v2[1];
  840. return out;
  841. }
  842. function div(out, v1, v2) {
  843. out[0] = v1[0] / v2[0];
  844. out[1] = v1[1] / v2[1];
  845. return out;
  846. }
  847. function dot(v1, v2) {
  848. return v1[0] * v2[0] + v1[1] * v2[1];
  849. }
  850. function scale(out, v, s) {
  851. out[0] = v[0] * s;
  852. out[1] = v[1] * s;
  853. return out;
  854. }
  855. function normalize(out, v) {
  856. var d = len(v);
  857. if (d === 0) {
  858. out[0] = 0;
  859. out[1] = 0;
  860. }
  861. else {
  862. out[0] = v[0] / d;
  863. out[1] = v[1] / d;
  864. }
  865. return out;
  866. }
  867. function distance(v1, v2) {
  868. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  869. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  870. }
  871. var dist = distance;
  872. function distanceSquare(v1, v2) {
  873. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  874. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  875. }
  876. var distSquare = distanceSquare;
  877. function negate(out, v) {
  878. out[0] = -v[0];
  879. out[1] = -v[1];
  880. return out;
  881. }
  882. function lerp(out, v1, v2, t) {
  883. out[0] = v1[0] + t * (v2[0] - v1[0]);
  884. out[1] = v1[1] + t * (v2[1] - v1[1]);
  885. return out;
  886. }
  887. function applyTransform(out, v, m) {
  888. var x = v[0];
  889. var y = v[1];
  890. out[0] = m[0] * x + m[2] * y + m[4];
  891. out[1] = m[1] * x + m[3] * y + m[5];
  892. return out;
  893. }
  894. function min(out, v1, v2) {
  895. out[0] = Math.min(v1[0], v2[0]);
  896. out[1] = Math.min(v1[1], v2[1]);
  897. return out;
  898. }
  899. function max(out, v1, v2) {
  900. out[0] = Math.max(v1[0], v2[0]);
  901. out[1] = Math.max(v1[1], v2[1]);
  902. return out;
  903. }
  904. var vector = /*#__PURE__*/Object.freeze({
  905. __proto__: null,
  906. create: create,
  907. copy: copy,
  908. clone: clone$1,
  909. set: set,
  910. add: add,
  911. scaleAndAdd: scaleAndAdd,
  912. sub: sub,
  913. len: len,
  914. length: length,
  915. lenSquare: lenSquare,
  916. lengthSquare: lengthSquare,
  917. mul: mul,
  918. div: div,
  919. dot: dot,
  920. scale: scale,
  921. normalize: normalize,
  922. distance: distance,
  923. dist: dist,
  924. distanceSquare: distanceSquare,
  925. distSquare: distSquare,
  926. negate: negate,
  927. lerp: lerp,
  928. applyTransform: applyTransform,
  929. min: min,
  930. max: max
  931. });
  932. var Param = (function () {
  933. function Param(target, e) {
  934. this.target = target;
  935. this.topTarget = e && e.topTarget;
  936. }
  937. return Param;
  938. }());
  939. var Draggable = (function () {
  940. function Draggable(handler) {
  941. this.handler = handler;
  942. handler.on('mousedown', this._dragStart, this);
  943. handler.on('mousemove', this._drag, this);
  944. handler.on('mouseup', this._dragEnd, this);
  945. }
  946. Draggable.prototype._dragStart = function (e) {
  947. var draggingTarget = e.target;
  948. while (draggingTarget && !draggingTarget.draggable) {
  949. draggingTarget = draggingTarget.parent || draggingTarget.__hostTarget;
  950. }
  951. if (draggingTarget) {
  952. this._draggingTarget = draggingTarget;
  953. draggingTarget.dragging = true;
  954. this._x = e.offsetX;
  955. this._y = e.offsetY;
  956. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  957. }
  958. };
  959. Draggable.prototype._drag = function (e) {
  960. var draggingTarget = this._draggingTarget;
  961. if (draggingTarget) {
  962. var x = e.offsetX;
  963. var y = e.offsetY;
  964. var dx = x - this._x;
  965. var dy = y - this._y;
  966. this._x = x;
  967. this._y = y;
  968. draggingTarget.drift(dx, dy, e);
  969. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  970. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  971. var lastDropTarget = this._dropTarget;
  972. this._dropTarget = dropTarget;
  973. if (draggingTarget !== dropTarget) {
  974. if (lastDropTarget && dropTarget !== lastDropTarget) {
  975. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  976. }
  977. if (dropTarget && dropTarget !== lastDropTarget) {
  978. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  979. }
  980. }
  981. }
  982. };
  983. Draggable.prototype._dragEnd = function (e) {
  984. var draggingTarget = this._draggingTarget;
  985. if (draggingTarget) {
  986. draggingTarget.dragging = false;
  987. }
  988. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  989. if (this._dropTarget) {
  990. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  991. }
  992. this._draggingTarget = null;
  993. this._dropTarget = null;
  994. };
  995. return Draggable;
  996. }());
  997. var Eventful = (function () {
  998. function Eventful(eventProcessors) {
  999. if (eventProcessors) {
  1000. this._$eventProcessor = eventProcessors;
  1001. }
  1002. }
  1003. Eventful.prototype.on = function (event, query, handler, context) {
  1004. if (!this._$handlers) {
  1005. this._$handlers = {};
  1006. }
  1007. var _h = this._$handlers;
  1008. if (typeof query === 'function') {
  1009. context = handler;
  1010. handler = query;
  1011. query = null;
  1012. }
  1013. if (!handler || !event) {
  1014. return this;
  1015. }
  1016. var eventProcessor = this._$eventProcessor;
  1017. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1018. query = eventProcessor.normalizeQuery(query);
  1019. }
  1020. if (!_h[event]) {
  1021. _h[event] = [];
  1022. }
  1023. for (var i = 0; i < _h[event].length; i++) {
  1024. if (_h[event][i].h === handler) {
  1025. return this;
  1026. }
  1027. }
  1028. var wrap = {
  1029. h: handler,
  1030. query: query,
  1031. ctx: (context || this),
  1032. callAtLast: handler.zrEventfulCallAtLast
  1033. };
  1034. var lastIndex = _h[event].length - 1;
  1035. var lastWrap = _h[event][lastIndex];
  1036. (lastWrap && lastWrap.callAtLast)
  1037. ? _h[event].splice(lastIndex, 0, wrap)
  1038. : _h[event].push(wrap);
  1039. return this;
  1040. };
  1041. Eventful.prototype.isSilent = function (eventName) {
  1042. var _h = this._$handlers;
  1043. return !_h || !_h[eventName] || !_h[eventName].length;
  1044. };
  1045. Eventful.prototype.off = function (eventType, handler) {
  1046. var _h = this._$handlers;
  1047. if (!_h) {
  1048. return this;
  1049. }
  1050. if (!eventType) {
  1051. this._$handlers = {};
  1052. return this;
  1053. }
  1054. if (handler) {
  1055. if (_h[eventType]) {
  1056. var newList = [];
  1057. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  1058. if (_h[eventType][i].h !== handler) {
  1059. newList.push(_h[eventType][i]);
  1060. }
  1061. }
  1062. _h[eventType] = newList;
  1063. }
  1064. if (_h[eventType] && _h[eventType].length === 0) {
  1065. delete _h[eventType];
  1066. }
  1067. }
  1068. else {
  1069. delete _h[eventType];
  1070. }
  1071. return this;
  1072. };
  1073. Eventful.prototype.trigger = function (eventType) {
  1074. var args = [];
  1075. for (var _i = 1; _i < arguments.length; _i++) {
  1076. args[_i - 1] = arguments[_i];
  1077. }
  1078. if (!this._$handlers) {
  1079. return this;
  1080. }
  1081. var _h = this._$handlers[eventType];
  1082. var eventProcessor = this._$eventProcessor;
  1083. if (_h) {
  1084. var argLen = args.length;
  1085. var len = _h.length;
  1086. for (var i = 0; i < len; i++) {
  1087. var hItem = _h[i];
  1088. if (eventProcessor
  1089. && eventProcessor.filter
  1090. && hItem.query != null
  1091. && !eventProcessor.filter(eventType, hItem.query)) {
  1092. continue;
  1093. }
  1094. switch (argLen) {
  1095. case 0:
  1096. hItem.h.call(hItem.ctx);
  1097. break;
  1098. case 1:
  1099. hItem.h.call(hItem.ctx, args[0]);
  1100. break;
  1101. case 2:
  1102. hItem.h.call(hItem.ctx, args[0], args[1]);
  1103. break;
  1104. default:
  1105. hItem.h.apply(hItem.ctx, args);
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. eventProcessor && eventProcessor.afterTrigger
  1111. && eventProcessor.afterTrigger(eventType);
  1112. return this;
  1113. };
  1114. Eventful.prototype.triggerWithContext = function (type) {
  1115. var args = [];
  1116. for (var _i = 1; _i < arguments.length; _i++) {
  1117. args[_i - 1] = arguments[_i];
  1118. }
  1119. if (!this._$handlers) {
  1120. return this;
  1121. }
  1122. var _h = this._$handlers[type];
  1123. var eventProcessor = this._$eventProcessor;
  1124. if (_h) {
  1125. var argLen = args.length;
  1126. var ctx = args[argLen - 1];
  1127. var len = _h.length;
  1128. for (var i = 0; i < len; i++) {
  1129. var hItem = _h[i];
  1130. if (eventProcessor
  1131. && eventProcessor.filter
  1132. && hItem.query != null
  1133. && !eventProcessor.filter(type, hItem.query)) {
  1134. continue;
  1135. }
  1136. switch (argLen) {
  1137. case 0:
  1138. hItem.h.call(ctx);
  1139. break;
  1140. case 1:
  1141. hItem.h.call(ctx, args[0]);
  1142. break;
  1143. case 2:
  1144. hItem.h.call(ctx, args[0], args[1]);
  1145. break;
  1146. default:
  1147. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1148. break;
  1149. }
  1150. }
  1151. }
  1152. eventProcessor && eventProcessor.afterTrigger
  1153. && eventProcessor.afterTrigger(type);
  1154. return this;
  1155. };
  1156. return Eventful;
  1157. }());
  1158. var LN2 = Math.log(2);
  1159. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1160. var cacheKey = rowMask + '-' + colMask;
  1161. var fullRank = rows.length;
  1162. if (detCache.hasOwnProperty(cacheKey)) {
  1163. return detCache[cacheKey];
  1164. }
  1165. if (rank === 1) {
  1166. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1167. return rows[rowStart][colStart];
  1168. }
  1169. var subRowMask = rowMask | (1 << rowStart);
  1170. var subRowStart = rowStart + 1;
  1171. while (rowMask & (1 << subRowStart)) {
  1172. subRowStart++;
  1173. }
  1174. var sum = 0;
  1175. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1176. var colTag = 1 << j;
  1177. if (!(colTag & colMask)) {
  1178. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1179. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1180. colLocalIdx++;
  1181. }
  1182. }
  1183. detCache[cacheKey] = sum;
  1184. return sum;
  1185. }
  1186. function buildTransformer(src, dest) {
  1187. var mA = [
  1188. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1189. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1190. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1191. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1192. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1193. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1194. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1195. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1196. ];
  1197. var detCache = {};
  1198. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1199. if (det === 0) {
  1200. return;
  1201. }
  1202. var vh = [];
  1203. for (var i = 0; i < 8; i++) {
  1204. for (var j = 0; j < 8; j++) {
  1205. vh[j] == null && (vh[j] = 0);
  1206. vh[j] += ((i + j) % 2 ? -1 : 1)
  1207. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1208. / det * dest[i];
  1209. }
  1210. }
  1211. return function (out, srcPointX, srcPointY) {
  1212. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1213. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1214. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1215. };
  1216. }
  1217. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1218. var _calcOut = [];
  1219. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1220. return transformCoordWithViewport(_calcOut, elFrom, inX, inY, true)
  1221. && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1]);
  1222. }
  1223. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1224. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1225. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1226. var markers = prepareCoordMarkers(el, saved);
  1227. var transformer = preparePointerTransformer(markers, saved, inverse);
  1228. if (transformer) {
  1229. transformer(out, inX, inY);
  1230. return true;
  1231. }
  1232. }
  1233. return false;
  1234. }
  1235. function prepareCoordMarkers(el, saved) {
  1236. var markers = saved.markers;
  1237. if (markers) {
  1238. return markers;
  1239. }
  1240. markers = saved.markers = [];
  1241. var propLR = ['left', 'right'];
  1242. var propTB = ['top', 'bottom'];
  1243. for (var i = 0; i < 4; i++) {
  1244. var marker = document.createElement('div');
  1245. var stl = marker.style;
  1246. var idxLR = i % 2;
  1247. var idxTB = (i >> 1) % 2;
  1248. stl.cssText = [
  1249. 'position: absolute',
  1250. 'visibility: hidden',
  1251. 'padding: 0',
  1252. 'margin: 0',
  1253. 'border-width: 0',
  1254. 'user-select: none',
  1255. 'width:0',
  1256. 'height:0',
  1257. propLR[idxLR] + ':0',
  1258. propTB[idxTB] + ':0',
  1259. propLR[1 - idxLR] + ':auto',
  1260. propTB[1 - idxTB] + ':auto',
  1261. ''
  1262. ].join('!important;');
  1263. el.appendChild(marker);
  1264. markers.push(marker);
  1265. }
  1266. return markers;
  1267. }
  1268. function preparePointerTransformer(markers, saved, inverse) {
  1269. var transformerName = inverse ? 'invTrans' : 'trans';
  1270. var transformer = saved[transformerName];
  1271. var oldSrcCoords = saved.srcCoords;
  1272. var srcCoords = [];
  1273. var destCoords = [];
  1274. var oldCoordTheSame = true;
  1275. for (var i = 0; i < 4; i++) {
  1276. var rect = markers[i].getBoundingClientRect();
  1277. var ii = 2 * i;
  1278. var x = rect.left;
  1279. var y = rect.top;
  1280. srcCoords.push(x, y);
  1281. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1282. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1283. }
  1284. return (oldCoordTheSame && transformer)
  1285. ? transformer
  1286. : (saved.srcCoords = srcCoords,
  1287. saved[transformerName] = inverse
  1288. ? buildTransformer(destCoords, srcCoords)
  1289. : buildTransformer(srcCoords, destCoords));
  1290. }
  1291. function isCanvasEl(el) {
  1292. return el.nodeName.toUpperCase() === 'CANVAS';
  1293. }
  1294. var replaceReg = /([&<>"'])/g;
  1295. var replaceMap = {
  1296. '&': '&amp;',
  1297. '<': '&lt;',
  1298. '>': '&gt;',
  1299. '"': '&quot;',
  1300. '\'': '&#39;'
  1301. };
  1302. function encodeHTML(source) {
  1303. return source == null
  1304. ? ''
  1305. : (source + '').replace(replaceReg, function (str, c) {
  1306. return replaceMap[c];
  1307. });
  1308. }
  1309. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1310. var _calcOut$1 = [];
  1311. var firefoxNotSupportOffsetXY = env.browser.firefox
  1312. && +env.browser.version.split('.')[0] < 39;
  1313. function clientToLocal(el, e, out, calculate) {
  1314. out = out || {};
  1315. if (calculate) {
  1316. calculateZrXY(el, e, out);
  1317. }
  1318. else if (firefoxNotSupportOffsetXY
  1319. && e.layerX != null
  1320. && e.layerX !== e.offsetX) {
  1321. out.zrX = e.layerX;
  1322. out.zrY = e.layerY;
  1323. }
  1324. else if (e.offsetX != null) {
  1325. out.zrX = e.offsetX;
  1326. out.zrY = e.offsetY;
  1327. }
  1328. else {
  1329. calculateZrXY(el, e, out);
  1330. }
  1331. return out;
  1332. }
  1333. function calculateZrXY(el, e, out) {
  1334. if (env.domSupported && el.getBoundingClientRect) {
  1335. var ex = e.clientX;
  1336. var ey = e.clientY;
  1337. if (isCanvasEl(el)) {
  1338. var box = el.getBoundingClientRect();
  1339. out.zrX = ex - box.left;
  1340. out.zrY = ey - box.top;
  1341. return;
  1342. }
  1343. else {
  1344. if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) {
  1345. out.zrX = _calcOut$1[0];
  1346. out.zrY = _calcOut$1[1];
  1347. return;
  1348. }
  1349. }
  1350. }
  1351. out.zrX = out.zrY = 0;
  1352. }
  1353. function getNativeEvent(e) {
  1354. return e
  1355. || window.event;
  1356. }
  1357. function normalizeEvent(el, e, calculate) {
  1358. e = getNativeEvent(e);
  1359. if (e.zrX != null) {
  1360. return e;
  1361. }
  1362. var eventType = e.type;
  1363. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1364. if (!isTouch) {
  1365. clientToLocal(el, e, e, calculate);
  1366. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1367. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1368. }
  1369. else {
  1370. var touch = eventType !== 'touchend'
  1371. ? e.targetTouches[0]
  1372. : e.changedTouches[0];
  1373. touch && clientToLocal(el, touch, e, calculate);
  1374. }
  1375. var button = e.button;
  1376. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1377. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1378. }
  1379. return e;
  1380. }
  1381. function getWheelDeltaMayPolyfill(e) {
  1382. var rawWheelDelta = e.wheelDelta;
  1383. if (rawWheelDelta) {
  1384. return rawWheelDelta;
  1385. }
  1386. var deltaX = e.deltaX;
  1387. var deltaY = e.deltaY;
  1388. if (deltaX == null || deltaY == null) {
  1389. return rawWheelDelta;
  1390. }
  1391. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1392. var sign = deltaY > 0 ? -1
  1393. : deltaY < 0 ? 1
  1394. : deltaX > 0 ? -1
  1395. : 1;
  1396. return 3 * delta * sign;
  1397. }
  1398. function addEventListener(el, name, handler, opt) {
  1399. el.addEventListener(name, handler, opt);
  1400. }
  1401. function removeEventListener(el, name, handler, opt) {
  1402. el.removeEventListener(name, handler, opt);
  1403. }
  1404. var stop = function (e) {
  1405. e.preventDefault();
  1406. e.stopPropagation();
  1407. e.cancelBubble = true;
  1408. };
  1409. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1410. return e.which === 2 || e.which === 3;
  1411. }
  1412. var GestureMgr = (function () {
  1413. function GestureMgr() {
  1414. this._track = [];
  1415. }
  1416. GestureMgr.prototype.recognize = function (event, target, root) {
  1417. this._doTrack(event, target, root);
  1418. return this._recognize(event);
  1419. };
  1420. GestureMgr.prototype.clear = function () {
  1421. this._track.length = 0;
  1422. return this;
  1423. };
  1424. GestureMgr.prototype._doTrack = function (event, target, root) {
  1425. var touches = event.touches;
  1426. if (!touches) {
  1427. return;
  1428. }
  1429. var trackItem = {
  1430. points: [],
  1431. touches: [],
  1432. target: target,
  1433. event: event
  1434. };
  1435. for (var i = 0, len = touches.length; i < len; i++) {
  1436. var touch = touches[i];
  1437. var pos = clientToLocal(root, touch, {});
  1438. trackItem.points.push([pos.zrX, pos.zrY]);
  1439. trackItem.touches.push(touch);
  1440. }
  1441. this._track.push(trackItem);
  1442. };
  1443. GestureMgr.prototype._recognize = function (event) {
  1444. for (var eventName in recognizers) {
  1445. if (recognizers.hasOwnProperty(eventName)) {
  1446. var gestureInfo = recognizers[eventName](this._track, event);
  1447. if (gestureInfo) {
  1448. return gestureInfo;
  1449. }
  1450. }
  1451. }
  1452. };
  1453. return GestureMgr;
  1454. }());
  1455. function dist$1(pointPair) {
  1456. var dx = pointPair[1][0] - pointPair[0][0];
  1457. var dy = pointPair[1][1] - pointPair[0][1];
  1458. return Math.sqrt(dx * dx + dy * dy);
  1459. }
  1460. function center(pointPair) {
  1461. return [
  1462. (pointPair[0][0] + pointPair[1][0]) / 2,
  1463. (pointPair[0][1] + pointPair[1][1]) / 2
  1464. ];
  1465. }
  1466. var recognizers = {
  1467. pinch: function (tracks, event) {
  1468. var trackLen = tracks.length;
  1469. if (!trackLen) {
  1470. return;
  1471. }
  1472. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1473. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1474. if (pinchPre
  1475. && pinchPre.length > 1
  1476. && pinchEnd
  1477. && pinchEnd.length > 1) {
  1478. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1479. !isFinite(pinchScale) && (pinchScale = 1);
  1480. event.pinchScale = pinchScale;
  1481. var pinchCenter = center(pinchEnd);
  1482. event.pinchX = pinchCenter[0];
  1483. event.pinchY = pinchCenter[1];
  1484. return {
  1485. type: 'pinch',
  1486. target: tracks[0].target,
  1487. event: event
  1488. };
  1489. }
  1490. }
  1491. };
  1492. function create$1() {
  1493. return [1, 0, 0, 1, 0, 0];
  1494. }
  1495. function identity(out) {
  1496. out[0] = 1;
  1497. out[1] = 0;
  1498. out[2] = 0;
  1499. out[3] = 1;
  1500. out[4] = 0;
  1501. out[5] = 0;
  1502. return out;
  1503. }
  1504. function copy$1(out, m) {
  1505. out[0] = m[0];
  1506. out[1] = m[1];
  1507. out[2] = m[2];
  1508. out[3] = m[3];
  1509. out[4] = m[4];
  1510. out[5] = m[5];
  1511. return out;
  1512. }
  1513. function mul$1(out, m1, m2) {
  1514. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1515. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1516. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1517. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1518. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1519. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1520. out[0] = out0;
  1521. out[1] = out1;
  1522. out[2] = out2;
  1523. out[3] = out3;
  1524. out[4] = out4;
  1525. out[5] = out5;
  1526. return out;
  1527. }
  1528. function translate(out, a, v) {
  1529. out[0] = a[0];
  1530. out[1] = a[1];
  1531. out[2] = a[2];
  1532. out[3] = a[3];
  1533. out[4] = a[4] + v[0];
  1534. out[5] = a[5] + v[1];
  1535. return out;
  1536. }
  1537. function rotate(out, a, rad) {
  1538. var aa = a[0];
  1539. var ac = a[2];
  1540. var atx = a[4];
  1541. var ab = a[1];
  1542. var ad = a[3];
  1543. var aty = a[5];
  1544. var st = Math.sin(rad);
  1545. var ct = Math.cos(rad);
  1546. out[0] = aa * ct + ab * st;
  1547. out[1] = -aa * st + ab * ct;
  1548. out[2] = ac * ct + ad * st;
  1549. out[3] = -ac * st + ct * ad;
  1550. out[4] = ct * atx + st * aty;
  1551. out[5] = ct * aty - st * atx;
  1552. return out;
  1553. }
  1554. function scale$1(out, a, v) {
  1555. var vx = v[0];
  1556. var vy = v[1];
  1557. out[0] = a[0] * vx;
  1558. out[1] = a[1] * vy;
  1559. out[2] = a[2] * vx;
  1560. out[3] = a[3] * vy;
  1561. out[4] = a[4] * vx;
  1562. out[5] = a[5] * vy;
  1563. return out;
  1564. }
  1565. function invert(out, a) {
  1566. var aa = a[0];
  1567. var ac = a[2];
  1568. var atx = a[4];
  1569. var ab = a[1];
  1570. var ad = a[3];
  1571. var aty = a[5];
  1572. var det = aa * ad - ab * ac;
  1573. if (!det) {
  1574. return null;
  1575. }
  1576. det = 1.0 / det;
  1577. out[0] = ad * det;
  1578. out[1] = -ab * det;
  1579. out[2] = -ac * det;
  1580. out[3] = aa * det;
  1581. out[4] = (ac * aty - ad * atx) * det;
  1582. out[5] = (ab * atx - aa * aty) * det;
  1583. return out;
  1584. }
  1585. function clone$2(a) {
  1586. var b = create$1();
  1587. copy$1(b, a);
  1588. return b;
  1589. }
  1590. var matrix = /*#__PURE__*/Object.freeze({
  1591. __proto__: null,
  1592. create: create$1,
  1593. identity: identity,
  1594. copy: copy$1,
  1595. mul: mul$1,
  1596. translate: translate,
  1597. rotate: rotate,
  1598. scale: scale$1,
  1599. invert: invert,
  1600. clone: clone$2
  1601. });
  1602. var Point = (function () {
  1603. function Point(x, y) {
  1604. this.x = x || 0;
  1605. this.y = y || 0;
  1606. }
  1607. Point.prototype.copy = function (other) {
  1608. this.x = other.x;
  1609. this.y = other.y;
  1610. return this;
  1611. };
  1612. Point.prototype.clone = function () {
  1613. return new Point(this.x, this.y);
  1614. };
  1615. Point.prototype.set = function (x, y) {
  1616. this.x = x;
  1617. this.y = y;
  1618. return this;
  1619. };
  1620. Point.prototype.equal = function (other) {
  1621. return other.x === this.x && other.y === this.y;
  1622. };
  1623. Point.prototype.add = function (other) {
  1624. this.x += other.x;
  1625. this.y += other.y;
  1626. return this;
  1627. };
  1628. Point.prototype.scale = function (scalar) {
  1629. this.x *= scalar;
  1630. this.y *= scalar;
  1631. };
  1632. Point.prototype.scaleAndAdd = function (other, scalar) {
  1633. this.x += other.x * scalar;
  1634. this.y += other.y * scalar;
  1635. };
  1636. Point.prototype.sub = function (other) {
  1637. this.x -= other.x;
  1638. this.y -= other.y;
  1639. return this;
  1640. };
  1641. Point.prototype.dot = function (other) {
  1642. return this.x * other.x + this.y * other.y;
  1643. };
  1644. Point.prototype.len = function () {
  1645. return Math.sqrt(this.x * this.x + this.y * this.y);
  1646. };
  1647. Point.prototype.lenSquare = function () {
  1648. return this.x * this.x + this.y * this.y;
  1649. };
  1650. Point.prototype.normalize = function () {
  1651. var len = this.len();
  1652. this.x /= len;
  1653. this.y /= len;
  1654. return this;
  1655. };
  1656. Point.prototype.distance = function (other) {
  1657. var dx = this.x - other.x;
  1658. var dy = this.y - other.y;
  1659. return Math.sqrt(dx * dx + dy * dy);
  1660. };
  1661. Point.prototype.distanceSquare = function (other) {
  1662. var dx = this.x - other.x;
  1663. var dy = this.y - other.y;
  1664. return dx * dx + dy * dy;
  1665. };
  1666. Point.prototype.negate = function () {
  1667. this.x = -this.x;
  1668. this.y = -this.y;
  1669. return this;
  1670. };
  1671. Point.prototype.transform = function (m) {
  1672. if (!m) {
  1673. return;
  1674. }
  1675. var x = this.x;
  1676. var y = this.y;
  1677. this.x = m[0] * x + m[2] * y + m[4];
  1678. this.y = m[1] * x + m[3] * y + m[5];
  1679. return this;
  1680. };
  1681. Point.prototype.toArray = function (out) {
  1682. out[0] = this.x;
  1683. out[1] = this.y;
  1684. return out;
  1685. };
  1686. Point.prototype.fromArray = function (input) {
  1687. this.x = input[0];
  1688. this.y = input[1];
  1689. };
  1690. Point.set = function (p, x, y) {
  1691. p.x = x;
  1692. p.y = y;
  1693. };
  1694. Point.copy = function (p, p2) {
  1695. p.x = p2.x;
  1696. p.y = p2.y;
  1697. };
  1698. Point.len = function (p) {
  1699. return Math.sqrt(p.x * p.x + p.y * p.y);
  1700. };
  1701. Point.lenSquare = function (p) {
  1702. return p.x * p.x + p.y * p.y;
  1703. };
  1704. Point.dot = function (p0, p1) {
  1705. return p0.x * p1.x + p0.y * p1.y;
  1706. };
  1707. Point.add = function (out, p0, p1) {
  1708. out.x = p0.x + p1.x;
  1709. out.y = p0.y + p1.y;
  1710. };
  1711. Point.sub = function (out, p0, p1) {
  1712. out.x = p0.x - p1.x;
  1713. out.y = p0.y - p1.y;
  1714. };
  1715. Point.scale = function (out, p0, scalar) {
  1716. out.x = p0.x * scalar;
  1717. out.y = p0.y * scalar;
  1718. };
  1719. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  1720. out.x = p0.x + p1.x * scalar;
  1721. out.y = p0.y + p1.y * scalar;
  1722. };
  1723. Point.lerp = function (out, p0, p1, t) {
  1724. var onet = 1 - t;
  1725. out.x = onet * p0.x + t * p1.x;
  1726. out.y = onet * p0.y + t * p1.y;
  1727. };
  1728. return Point;
  1729. }());
  1730. var mathMin = Math.min;
  1731. var mathMax = Math.max;
  1732. var lt = new Point();
  1733. var rb = new Point();
  1734. var lb = new Point();
  1735. var rt = new Point();
  1736. var minTv = new Point();
  1737. var maxTv = new Point();
  1738. var BoundingRect = (function () {
  1739. function BoundingRect(x, y, width, height) {
  1740. if (width < 0) {
  1741. x = x + width;
  1742. width = -width;
  1743. }
  1744. if (height < 0) {
  1745. y = y + height;
  1746. height = -height;
  1747. }
  1748. this.x = x;
  1749. this.y = y;
  1750. this.width = width;
  1751. this.height = height;
  1752. }
  1753. BoundingRect.prototype.union = function (other) {
  1754. var x = mathMin(other.x, this.x);
  1755. var y = mathMin(other.y, this.y);
  1756. if (isFinite(this.x) && isFinite(this.width)) {
  1757. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  1758. }
  1759. else {
  1760. this.width = other.width;
  1761. }
  1762. if (isFinite(this.y) && isFinite(this.height)) {
  1763. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  1764. }
  1765. else {
  1766. this.height = other.height;
  1767. }
  1768. this.x = x;
  1769. this.y = y;
  1770. };
  1771. BoundingRect.prototype.applyTransform = function (m) {
  1772. BoundingRect.applyTransform(this, this, m);
  1773. };
  1774. BoundingRect.prototype.calculateTransform = function (b) {
  1775. var a = this;
  1776. var sx = b.width / a.width;
  1777. var sy = b.height / a.height;
  1778. var m = create$1();
  1779. translate(m, m, [-a.x, -a.y]);
  1780. scale$1(m, m, [sx, sy]);
  1781. translate(m, m, [b.x, b.y]);
  1782. return m;
  1783. };
  1784. BoundingRect.prototype.intersect = function (b, mtv) {
  1785. if (!b) {
  1786. return false;
  1787. }
  1788. if (!(b instanceof BoundingRect)) {
  1789. b = BoundingRect.create(b);
  1790. }
  1791. var a = this;
  1792. var ax0 = a.x;
  1793. var ax1 = a.x + a.width;
  1794. var ay0 = a.y;
  1795. var ay1 = a.y + a.height;
  1796. var bx0 = b.x;
  1797. var bx1 = b.x + b.width;
  1798. var by0 = b.y;
  1799. var by1 = b.y + b.height;
  1800. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  1801. if (mtv) {
  1802. var dMin = Infinity;
  1803. var dMax = 0;
  1804. var d0 = Math.abs(ax1 - bx0);
  1805. var d1 = Math.abs(bx1 - ax0);
  1806. var d2 = Math.abs(ay1 - by0);
  1807. var d3 = Math.abs(by1 - ay0);
  1808. var dx = Math.min(d0, d1);
  1809. var dy = Math.min(d2, d3);
  1810. if (ax1 < bx0 || bx1 < ax0) {
  1811. if (dx > dMax) {
  1812. dMax = dx;
  1813. if (d0 < d1) {
  1814. Point.set(maxTv, -d0, 0);
  1815. }
  1816. else {
  1817. Point.set(maxTv, d1, 0);
  1818. }
  1819. }
  1820. }
  1821. else {
  1822. if (dx < dMin) {
  1823. dMin = dx;
  1824. if (d0 < d1) {
  1825. Point.set(minTv, d0, 0);
  1826. }
  1827. else {
  1828. Point.set(minTv, -d1, 0);
  1829. }
  1830. }
  1831. }
  1832. if (ay1 < by0 || by1 < ay0) {
  1833. if (dy > dMax) {
  1834. dMax = dy;
  1835. if (d2 < d3) {
  1836. Point.set(maxTv, 0, -d2);
  1837. }
  1838. else {
  1839. Point.set(maxTv, 0, d3);
  1840. }
  1841. }
  1842. }
  1843. else {
  1844. if (dx < dMin) {
  1845. dMin = dx;
  1846. if (d2 < d3) {
  1847. Point.set(minTv, 0, d2);
  1848. }
  1849. else {
  1850. Point.set(minTv, 0, -d3);
  1851. }
  1852. }
  1853. }
  1854. }
  1855. if (mtv) {
  1856. Point.copy(mtv, overlap ? minTv : maxTv);
  1857. }
  1858. return overlap;
  1859. };
  1860. BoundingRect.prototype.contain = function (x, y) {
  1861. var rect = this;
  1862. return x >= rect.x
  1863. && x <= (rect.x + rect.width)
  1864. && y >= rect.y
  1865. && y <= (rect.y + rect.height);
  1866. };
  1867. BoundingRect.prototype.clone = function () {
  1868. return new BoundingRect(this.x, this.y, this.width, this.height);
  1869. };
  1870. BoundingRect.prototype.copy = function (other) {
  1871. BoundingRect.copy(this, other);
  1872. };
  1873. BoundingRect.prototype.plain = function () {
  1874. return {
  1875. x: this.x,
  1876. y: this.y,
  1877. width: this.width,
  1878. height: this.height
  1879. };
  1880. };
  1881. BoundingRect.prototype.isFinite = function () {
  1882. return isFinite(this.x)
  1883. && isFinite(this.y)
  1884. && isFinite(this.width)
  1885. && isFinite(this.height);
  1886. };
  1887. BoundingRect.prototype.isZero = function () {
  1888. return this.width === 0 || this.height === 0;
  1889. };
  1890. BoundingRect.create = function (rect) {
  1891. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  1892. };
  1893. BoundingRect.copy = function (target, source) {
  1894. target.x = source.x;
  1895. target.y = source.y;
  1896. target.width = source.width;
  1897. target.height = source.height;
  1898. };
  1899. BoundingRect.applyTransform = function (target, source, m) {
  1900. if (!m) {
  1901. if (target !== source) {
  1902. BoundingRect.copy(target, source);
  1903. }
  1904. return;
  1905. }
  1906. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  1907. var sx = m[0];
  1908. var sy = m[3];
  1909. var tx = m[4];
  1910. var ty = m[5];
  1911. target.x = source.x * sx + tx;
  1912. target.y = source.y * sy + ty;
  1913. target.width = source.width * sx;
  1914. target.height = source.height * sy;
  1915. if (target.width < 0) {
  1916. target.x += target.width;
  1917. target.width = -target.width;
  1918. }
  1919. if (target.height < 0) {
  1920. target.y += target.height;
  1921. target.height = -target.height;
  1922. }
  1923. return;
  1924. }
  1925. lt.x = lb.x = source.x;
  1926. lt.y = rt.y = source.y;
  1927. rb.x = rt.x = source.x + source.width;
  1928. rb.y = lb.y = source.y + source.height;
  1929. lt.transform(m);
  1930. rt.transform(m);
  1931. rb.transform(m);
  1932. lb.transform(m);
  1933. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  1934. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  1935. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  1936. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  1937. target.width = maxX - target.x;
  1938. target.height = maxY - target.y;
  1939. };
  1940. return BoundingRect;
  1941. }());
  1942. var SILENT = 'silent';
  1943. function makeEventPacket(eveType, targetInfo, event) {
  1944. return {
  1945. type: eveType,
  1946. event: event,
  1947. target: targetInfo.target,
  1948. topTarget: targetInfo.topTarget,
  1949. cancelBubble: false,
  1950. offsetX: event.zrX,
  1951. offsetY: event.zrY,
  1952. gestureEvent: event.gestureEvent,
  1953. pinchX: event.pinchX,
  1954. pinchY: event.pinchY,
  1955. pinchScale: event.pinchScale,
  1956. wheelDelta: event.zrDelta,
  1957. zrByTouch: event.zrByTouch,
  1958. which: event.which,
  1959. stop: stopEvent
  1960. };
  1961. }
  1962. function stopEvent() {
  1963. stop(this.event);
  1964. }
  1965. var EmptyProxy = (function (_super) {
  1966. __extends(EmptyProxy, _super);
  1967. function EmptyProxy() {
  1968. var _this = _super !== null && _super.apply(this, arguments) || this;
  1969. _this.handler = null;
  1970. return _this;
  1971. }
  1972. EmptyProxy.prototype.dispose = function () { };
  1973. EmptyProxy.prototype.setCursor = function () { };
  1974. return EmptyProxy;
  1975. }(Eventful));
  1976. var HoveredResult = (function () {
  1977. function HoveredResult(x, y) {
  1978. this.x = x;
  1979. this.y = y;
  1980. }
  1981. return HoveredResult;
  1982. }());
  1983. var handlerNames = [
  1984. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1985. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1986. ];
  1987. var tmpRect = new BoundingRect(0, 0, 0, 0);
  1988. var Handler = (function (_super) {
  1989. __extends(Handler, _super);
  1990. function Handler(storage, painter, proxy, painterRoot, pointerSize) {
  1991. var _this = _super.call(this) || this;
  1992. _this._hovered = new HoveredResult(0, 0);
  1993. _this.storage = storage;
  1994. _this.painter = painter;
  1995. _this.painterRoot = painterRoot;
  1996. _this._pointerSize = pointerSize;
  1997. proxy = proxy || new EmptyProxy();
  1998. _this.proxy = null;
  1999. _this.setHandlerProxy(proxy);
  2000. _this._draggingMgr = new Draggable(_this);
  2001. return _this;
  2002. }
  2003. Handler.prototype.setHandlerProxy = function (proxy) {
  2004. if (this.proxy) {
  2005. this.proxy.dispose();
  2006. }
  2007. if (proxy) {
  2008. each(handlerNames, function (name) {
  2009. proxy.on && proxy.on(name, this[name], this);
  2010. }, this);
  2011. proxy.handler = this;
  2012. }
  2013. this.proxy = proxy;
  2014. };
  2015. Handler.prototype.mousemove = function (event) {
  2016. var x = event.zrX;
  2017. var y = event.zrY;
  2018. var isOutside = isOutsideBoundary(this, x, y);
  2019. var lastHovered = this._hovered;
  2020. var lastHoveredTarget = lastHovered.target;
  2021. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2022. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2023. lastHoveredTarget = lastHovered.target;
  2024. }
  2025. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  2026. var hoveredTarget = hovered.target;
  2027. var proxy = this.proxy;
  2028. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2029. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2030. this.dispatchToElement(lastHovered, 'mouseout', event);
  2031. }
  2032. this.dispatchToElement(hovered, 'mousemove', event);
  2033. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2034. this.dispatchToElement(hovered, 'mouseover', event);
  2035. }
  2036. };
  2037. Handler.prototype.mouseout = function (event) {
  2038. var eventControl = event.zrEventControl;
  2039. if (eventControl !== 'only_globalout') {
  2040. this.dispatchToElement(this._hovered, 'mouseout', event);
  2041. }
  2042. if (eventControl !== 'no_globalout') {
  2043. this.trigger('globalout', { type: 'globalout', event: event });
  2044. }
  2045. };
  2046. Handler.prototype.resize = function () {
  2047. this._hovered = new HoveredResult(0, 0);
  2048. };
  2049. Handler.prototype.dispatch = function (eventName, eventArgs) {
  2050. var handler = this[eventName];
  2051. handler && handler.call(this, eventArgs);
  2052. };
  2053. Handler.prototype.dispose = function () {
  2054. this.proxy.dispose();
  2055. this.storage = null;
  2056. this.proxy = null;
  2057. this.painter = null;
  2058. };
  2059. Handler.prototype.setCursorStyle = function (cursorStyle) {
  2060. var proxy = this.proxy;
  2061. proxy.setCursor && proxy.setCursor(cursorStyle);
  2062. };
  2063. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  2064. targetInfo = targetInfo || {};
  2065. var el = targetInfo.target;
  2066. if (el && el.silent) {
  2067. return;
  2068. }
  2069. var eventKey = ('on' + eventName);
  2070. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2071. while (el) {
  2072. el[eventKey]
  2073. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  2074. el.trigger(eventName, eventPacket);
  2075. el = el.__hostTarget ? el.__hostTarget : el.parent;
  2076. if (eventPacket.cancelBubble) {
  2077. break;
  2078. }
  2079. }
  2080. if (!eventPacket.cancelBubble) {
  2081. this.trigger(eventName, eventPacket);
  2082. if (this.painter && this.painter.eachOtherLayer) {
  2083. this.painter.eachOtherLayer(function (layer) {
  2084. if (typeof (layer[eventKey]) === 'function') {
  2085. layer[eventKey].call(layer, eventPacket);
  2086. }
  2087. if (layer.trigger) {
  2088. layer.trigger(eventName, eventPacket);
  2089. }
  2090. });
  2091. }
  2092. }
  2093. };
  2094. Handler.prototype.findHover = function (x, y, exclude) {
  2095. var list = this.storage.getDisplayList();
  2096. var out = new HoveredResult(x, y);
  2097. setHoverTarget(list, out, x, y, exclude);
  2098. if (this._pointerSize && !out.target) {
  2099. var candidates = [];
  2100. var pointerSize = this._pointerSize;
  2101. var targetSizeHalf = pointerSize / 2;
  2102. var pointerRect = new BoundingRect(x - targetSizeHalf, y - targetSizeHalf, pointerSize, pointerSize);
  2103. for (var i = list.length - 1; i >= 0; i--) {
  2104. var el = list[i];
  2105. if (el !== exclude
  2106. && !el.ignore
  2107. && !el.ignoreCoarsePointer
  2108. && (!el.parent || !el.parent.ignoreCoarsePointer)) {
  2109. tmpRect.copy(el.getBoundingRect());
  2110. if (el.transform) {
  2111. tmpRect.applyTransform(el.transform);
  2112. }
  2113. if (tmpRect.intersect(pointerRect)) {
  2114. candidates.push(el);
  2115. }
  2116. }
  2117. }
  2118. if (candidates.length) {
  2119. var rStep = 4;
  2120. var thetaStep = Math.PI / 12;
  2121. var PI2 = Math.PI * 2;
  2122. for (var r = 0; r < targetSizeHalf; r += rStep) {
  2123. for (var theta = 0; theta < PI2; theta += thetaStep) {
  2124. var x1 = x + r * Math.cos(theta);
  2125. var y1 = y + r * Math.sin(theta);
  2126. setHoverTarget(candidates, out, x1, y1, exclude);
  2127. if (out.target) {
  2128. return out;
  2129. }
  2130. }
  2131. }
  2132. }
  2133. }
  2134. return out;
  2135. };
  2136. Handler.prototype.processGesture = function (event, stage) {
  2137. if (!this._gestureMgr) {
  2138. this._gestureMgr = new GestureMgr();
  2139. }
  2140. var gestureMgr = this._gestureMgr;
  2141. stage === 'start' && gestureMgr.clear();
  2142. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  2143. stage === 'end' && gestureMgr.clear();
  2144. if (gestureInfo) {
  2145. var type = gestureInfo.type;
  2146. event.gestureEvent = type;
  2147. var res = new HoveredResult();
  2148. res.target = gestureInfo.target;
  2149. this.dispatchToElement(res, type, gestureInfo.event);
  2150. }
  2151. };
  2152. return Handler;
  2153. }(Eventful));
  2154. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2155. Handler.prototype[name] = function (event) {
  2156. var x = event.zrX;
  2157. var y = event.zrY;
  2158. var isOutside = isOutsideBoundary(this, x, y);
  2159. var hovered;
  2160. var hoveredTarget;
  2161. if (name !== 'mouseup' || !isOutside) {
  2162. hovered = this.findHover(x, y);
  2163. hoveredTarget = hovered.target;
  2164. }
  2165. if (name === 'mousedown') {
  2166. this._downEl = hoveredTarget;
  2167. this._downPoint = [event.zrX, event.zrY];
  2168. this._upEl = hoveredTarget;
  2169. }
  2170. else if (name === 'mouseup') {
  2171. this._upEl = hoveredTarget;
  2172. }
  2173. else if (name === 'click') {
  2174. if (this._downEl !== this._upEl
  2175. || !this._downPoint
  2176. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  2177. return;
  2178. }
  2179. this._downPoint = null;
  2180. }
  2181. this.dispatchToElement(hovered, name, event);
  2182. };
  2183. });
  2184. function isHover(displayable, x, y) {
  2185. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2186. var el = displayable;
  2187. var isSilent = void 0;
  2188. var ignoreClip = false;
  2189. while (el) {
  2190. if (el.ignoreClip) {
  2191. ignoreClip = true;
  2192. }
  2193. if (!ignoreClip) {
  2194. var clipPath = el.getClipPath();
  2195. if (clipPath && !clipPath.contain(x, y)) {
  2196. return false;
  2197. }
  2198. if (el.silent) {
  2199. isSilent = true;
  2200. }
  2201. }
  2202. var hostEl = el.__hostTarget;
  2203. el = hostEl ? hostEl : el.parent;
  2204. }
  2205. return isSilent ? SILENT : true;
  2206. }
  2207. return false;
  2208. }
  2209. function setHoverTarget(list, out, x, y, exclude) {
  2210. for (var i = list.length - 1; i >= 0; i--) {
  2211. var el = list[i];
  2212. var hoverCheckResult = void 0;
  2213. if (el !== exclude
  2214. && !el.ignore
  2215. && (hoverCheckResult = isHover(el, x, y))) {
  2216. !out.topTarget && (out.topTarget = el);
  2217. if (hoverCheckResult !== SILENT) {
  2218. out.target = el;
  2219. break;
  2220. }
  2221. }
  2222. }
  2223. }
  2224. function isOutsideBoundary(handlerInstance, x, y) {
  2225. var painter = handlerInstance.painter;
  2226. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2227. }
  2228. var DEFAULT_MIN_MERGE = 32;
  2229. var DEFAULT_MIN_GALLOPING = 7;
  2230. function minRunLength(n) {
  2231. var r = 0;
  2232. while (n >= DEFAULT_MIN_MERGE) {
  2233. r |= n & 1;
  2234. n >>= 1;
  2235. }
  2236. return n + r;
  2237. }
  2238. function makeAscendingRun(array, lo, hi, compare) {
  2239. var runHi = lo + 1;
  2240. if (runHi === hi) {
  2241. return 1;
  2242. }
  2243. if (compare(array[runHi++], array[lo]) < 0) {
  2244. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  2245. runHi++;
  2246. }
  2247. reverseRun(array, lo, runHi);
  2248. }
  2249. else {
  2250. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  2251. runHi++;
  2252. }
  2253. }
  2254. return runHi - lo;
  2255. }
  2256. function reverseRun(array, lo, hi) {
  2257. hi--;
  2258. while (lo < hi) {
  2259. var t = array[lo];
  2260. array[lo++] = array[hi];
  2261. array[hi--] = t;
  2262. }
  2263. }
  2264. function binaryInsertionSort(array, lo, hi, start, compare) {
  2265. if (start === lo) {
  2266. start++;
  2267. }
  2268. for (; start < hi; start++) {
  2269. var pivot = array[start];
  2270. var left = lo;
  2271. var right = start;
  2272. var mid;
  2273. while (left < right) {
  2274. mid = left + right >>> 1;
  2275. if (compare(pivot, array[mid]) < 0) {
  2276. right = mid;
  2277. }
  2278. else {
  2279. left = mid + 1;
  2280. }
  2281. }
  2282. var n = start - left;
  2283. switch (n) {
  2284. case 3:
  2285. array[left + 3] = array[left + 2];
  2286. case 2:
  2287. array[left + 2] = array[left + 1];
  2288. case 1:
  2289. array[left + 1] = array[left];
  2290. break;
  2291. default:
  2292. while (n > 0) {
  2293. array[left + n] = array[left + n - 1];
  2294. n--;
  2295. }
  2296. }
  2297. array[left] = pivot;
  2298. }
  2299. }
  2300. function gallopLeft(value, array, start, length, hint, compare) {
  2301. var lastOffset = 0;
  2302. var maxOffset = 0;
  2303. var offset = 1;
  2304. if (compare(value, array[start + hint]) > 0) {
  2305. maxOffset = length - hint;
  2306. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  2307. lastOffset = offset;
  2308. offset = (offset << 1) + 1;
  2309. if (offset <= 0) {
  2310. offset = maxOffset;
  2311. }
  2312. }
  2313. if (offset > maxOffset) {
  2314. offset = maxOffset;
  2315. }
  2316. lastOffset += hint;
  2317. offset += hint;
  2318. }
  2319. else {
  2320. maxOffset = hint + 1;
  2321. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  2322. lastOffset = offset;
  2323. offset = (offset << 1) + 1;
  2324. if (offset <= 0) {
  2325. offset = maxOffset;
  2326. }
  2327. }
  2328. if (offset > maxOffset) {
  2329. offset = maxOffset;
  2330. }
  2331. var tmp = lastOffset;
  2332. lastOffset = hint - offset;
  2333. offset = hint - tmp;
  2334. }
  2335. lastOffset++;
  2336. while (lastOffset < offset) {
  2337. var m = lastOffset + (offset - lastOffset >>> 1);
  2338. if (compare(value, array[start + m]) > 0) {
  2339. lastOffset = m + 1;
  2340. }
  2341. else {
  2342. offset = m;
  2343. }
  2344. }
  2345. return offset;
  2346. }
  2347. function gallopRight(value, array, start, length, hint, compare) {
  2348. var lastOffset = 0;
  2349. var maxOffset = 0;
  2350. var offset = 1;
  2351. if (compare(value, array[start + hint]) < 0) {
  2352. maxOffset = hint + 1;
  2353. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  2354. lastOffset = offset;
  2355. offset = (offset << 1) + 1;
  2356. if (offset <= 0) {
  2357. offset = maxOffset;
  2358. }
  2359. }
  2360. if (offset > maxOffset) {
  2361. offset = maxOffset;
  2362. }
  2363. var tmp = lastOffset;
  2364. lastOffset = hint - offset;
  2365. offset = hint - tmp;
  2366. }
  2367. else {
  2368. maxOffset = length - hint;
  2369. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  2370. lastOffset = offset;
  2371. offset = (offset << 1) + 1;
  2372. if (offset <= 0) {
  2373. offset = maxOffset;
  2374. }
  2375. }
  2376. if (offset > maxOffset) {
  2377. offset = maxOffset;
  2378. }
  2379. lastOffset += hint;
  2380. offset += hint;
  2381. }
  2382. lastOffset++;
  2383. while (lastOffset < offset) {
  2384. var m = lastOffset + (offset - lastOffset >>> 1);
  2385. if (compare(value, array[start + m]) < 0) {
  2386. offset = m;
  2387. }
  2388. else {
  2389. lastOffset = m + 1;
  2390. }
  2391. }
  2392. return offset;
  2393. }
  2394. function TimSort(array, compare) {
  2395. var minGallop = DEFAULT_MIN_GALLOPING;
  2396. var length = 0;
  2397. var runStart;
  2398. var runLength;
  2399. var stackSize = 0;
  2400. length = array.length;
  2401. var tmp = [];
  2402. runStart = [];
  2403. runLength = [];
  2404. function pushRun(_runStart, _runLength) {
  2405. runStart[stackSize] = _runStart;
  2406. runLength[stackSize] = _runLength;
  2407. stackSize += 1;
  2408. }
  2409. function mergeRuns() {
  2410. while (stackSize > 1) {
  2411. var n = stackSize - 2;
  2412. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  2413. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  2414. if (runLength[n - 1] < runLength[n + 1]) {
  2415. n--;
  2416. }
  2417. }
  2418. else if (runLength[n] > runLength[n + 1]) {
  2419. break;
  2420. }
  2421. mergeAt(n);
  2422. }
  2423. }
  2424. function forceMergeRuns() {
  2425. while (stackSize > 1) {
  2426. var n = stackSize - 2;
  2427. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  2428. n--;
  2429. }
  2430. mergeAt(n);
  2431. }
  2432. }
  2433. function mergeAt(i) {
  2434. var start1 = runStart[i];
  2435. var length1 = runLength[i];
  2436. var start2 = runStart[i + 1];
  2437. var length2 = runLength[i + 1];
  2438. runLength[i] = length1 + length2;
  2439. if (i === stackSize - 3) {
  2440. runStart[i + 1] = runStart[i + 2];
  2441. runLength[i + 1] = runLength[i + 2];
  2442. }
  2443. stackSize--;
  2444. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  2445. start1 += k;
  2446. length1 -= k;
  2447. if (length1 === 0) {
  2448. return;
  2449. }
  2450. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  2451. if (length2 === 0) {
  2452. return;
  2453. }
  2454. if (length1 <= length2) {
  2455. mergeLow(start1, length1, start2, length2);
  2456. }
  2457. else {
  2458. mergeHigh(start1, length1, start2, length2);
  2459. }
  2460. }
  2461. function mergeLow(start1, length1, start2, length2) {
  2462. var i = 0;
  2463. for (i = 0; i < length1; i++) {
  2464. tmp[i] = array[start1 + i];
  2465. }
  2466. var cursor1 = 0;
  2467. var cursor2 = start2;
  2468. var dest = start1;
  2469. array[dest++] = array[cursor2++];
  2470. if (--length2 === 0) {
  2471. for (i = 0; i < length1; i++) {
  2472. array[dest + i] = tmp[cursor1 + i];
  2473. }
  2474. return;
  2475. }
  2476. if (length1 === 1) {
  2477. for (i = 0; i < length2; i++) {
  2478. array[dest + i] = array[cursor2 + i];
  2479. }
  2480. array[dest + length2] = tmp[cursor1];
  2481. return;
  2482. }
  2483. var _minGallop = minGallop;
  2484. var count1;
  2485. var count2;
  2486. var exit;
  2487. while (1) {
  2488. count1 = 0;
  2489. count2 = 0;
  2490. exit = false;
  2491. do {
  2492. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  2493. array[dest++] = array[cursor2++];
  2494. count2++;
  2495. count1 = 0;
  2496. if (--length2 === 0) {
  2497. exit = true;
  2498. break;
  2499. }
  2500. }
  2501. else {
  2502. array[dest++] = tmp[cursor1++];
  2503. count1++;
  2504. count2 = 0;
  2505. if (--length1 === 1) {
  2506. exit = true;
  2507. break;
  2508. }
  2509. }
  2510. } while ((count1 | count2) < _minGallop);
  2511. if (exit) {
  2512. break;
  2513. }
  2514. do {
  2515. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  2516. if (count1 !== 0) {
  2517. for (i = 0; i < count1; i++) {
  2518. array[dest + i] = tmp[cursor1 + i];
  2519. }
  2520. dest += count1;
  2521. cursor1 += count1;
  2522. length1 -= count1;
  2523. if (length1 <= 1) {
  2524. exit = true;
  2525. break;
  2526. }
  2527. }
  2528. array[dest++] = array[cursor2++];
  2529. if (--length2 === 0) {
  2530. exit = true;
  2531. break;
  2532. }
  2533. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  2534. if (count2 !== 0) {
  2535. for (i = 0; i < count2; i++) {
  2536. array[dest + i] = array[cursor2 + i];
  2537. }
  2538. dest += count2;
  2539. cursor2 += count2;
  2540. length2 -= count2;
  2541. if (length2 === 0) {
  2542. exit = true;
  2543. break;
  2544. }
  2545. }
  2546. array[dest++] = tmp[cursor1++];
  2547. if (--length1 === 1) {
  2548. exit = true;
  2549. break;
  2550. }
  2551. _minGallop--;
  2552. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2553. if (exit) {
  2554. break;
  2555. }
  2556. if (_minGallop < 0) {
  2557. _minGallop = 0;
  2558. }
  2559. _minGallop += 2;
  2560. }
  2561. minGallop = _minGallop;
  2562. minGallop < 1 && (minGallop = 1);
  2563. if (length1 === 1) {
  2564. for (i = 0; i < length2; i++) {
  2565. array[dest + i] = array[cursor2 + i];
  2566. }
  2567. array[dest + length2] = tmp[cursor1];
  2568. }
  2569. else if (length1 === 0) {
  2570. throw new Error();
  2571. }
  2572. else {
  2573. for (i = 0; i < length1; i++) {
  2574. array[dest + i] = tmp[cursor1 + i];
  2575. }
  2576. }
  2577. }
  2578. function mergeHigh(start1, length1, start2, length2) {
  2579. var i = 0;
  2580. for (i = 0; i < length2; i++) {
  2581. tmp[i] = array[start2 + i];
  2582. }
  2583. var cursor1 = start1 + length1 - 1;
  2584. var cursor2 = length2 - 1;
  2585. var dest = start2 + length2 - 1;
  2586. var customCursor = 0;
  2587. var customDest = 0;
  2588. array[dest--] = array[cursor1--];
  2589. if (--length1 === 0) {
  2590. customCursor = dest - (length2 - 1);
  2591. for (i = 0; i < length2; i++) {
  2592. array[customCursor + i] = tmp[i];
  2593. }
  2594. return;
  2595. }
  2596. if (length2 === 1) {
  2597. dest -= length1;
  2598. cursor1 -= length1;
  2599. customDest = dest + 1;
  2600. customCursor = cursor1 + 1;
  2601. for (i = length1 - 1; i >= 0; i--) {
  2602. array[customDest + i] = array[customCursor + i];
  2603. }
  2604. array[dest] = tmp[cursor2];
  2605. return;
  2606. }
  2607. var _minGallop = minGallop;
  2608. while (true) {
  2609. var count1 = 0;
  2610. var count2 = 0;
  2611. var exit = false;
  2612. do {
  2613. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2614. array[dest--] = array[cursor1--];
  2615. count1++;
  2616. count2 = 0;
  2617. if (--length1 === 0) {
  2618. exit = true;
  2619. break;
  2620. }
  2621. }
  2622. else {
  2623. array[dest--] = tmp[cursor2--];
  2624. count2++;
  2625. count1 = 0;
  2626. if (--length2 === 1) {
  2627. exit = true;
  2628. break;
  2629. }
  2630. }
  2631. } while ((count1 | count2) < _minGallop);
  2632. if (exit) {
  2633. break;
  2634. }
  2635. do {
  2636. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2637. if (count1 !== 0) {
  2638. dest -= count1;
  2639. cursor1 -= count1;
  2640. length1 -= count1;
  2641. customDest = dest + 1;
  2642. customCursor = cursor1 + 1;
  2643. for (i = count1 - 1; i >= 0; i--) {
  2644. array[customDest + i] = array[customCursor + i];
  2645. }
  2646. if (length1 === 0) {
  2647. exit = true;
  2648. break;
  2649. }
  2650. }
  2651. array[dest--] = tmp[cursor2--];
  2652. if (--length2 === 1) {
  2653. exit = true;
  2654. break;
  2655. }
  2656. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2657. if (count2 !== 0) {
  2658. dest -= count2;
  2659. cursor2 -= count2;
  2660. length2 -= count2;
  2661. customDest = dest + 1;
  2662. customCursor = cursor2 + 1;
  2663. for (i = 0; i < count2; i++) {
  2664. array[customDest + i] = tmp[customCursor + i];
  2665. }
  2666. if (length2 <= 1) {
  2667. exit = true;
  2668. break;
  2669. }
  2670. }
  2671. array[dest--] = array[cursor1--];
  2672. if (--length1 === 0) {
  2673. exit = true;
  2674. break;
  2675. }
  2676. _minGallop--;
  2677. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2678. if (exit) {
  2679. break;
  2680. }
  2681. if (_minGallop < 0) {
  2682. _minGallop = 0;
  2683. }
  2684. _minGallop += 2;
  2685. }
  2686. minGallop = _minGallop;
  2687. if (minGallop < 1) {
  2688. minGallop = 1;
  2689. }
  2690. if (length2 === 1) {
  2691. dest -= length1;
  2692. cursor1 -= length1;
  2693. customDest = dest + 1;
  2694. customCursor = cursor1 + 1;
  2695. for (i = length1 - 1; i >= 0; i--) {
  2696. array[customDest + i] = array[customCursor + i];
  2697. }
  2698. array[dest] = tmp[cursor2];
  2699. }
  2700. else if (length2 === 0) {
  2701. throw new Error();
  2702. }
  2703. else {
  2704. customCursor = dest - (length2 - 1);
  2705. for (i = 0; i < length2; i++) {
  2706. array[customCursor + i] = tmp[i];
  2707. }
  2708. }
  2709. }
  2710. return {
  2711. mergeRuns: mergeRuns,
  2712. forceMergeRuns: forceMergeRuns,
  2713. pushRun: pushRun
  2714. };
  2715. }
  2716. function sort(array, compare, lo, hi) {
  2717. if (!lo) {
  2718. lo = 0;
  2719. }
  2720. if (!hi) {
  2721. hi = array.length;
  2722. }
  2723. var remaining = hi - lo;
  2724. if (remaining < 2) {
  2725. return;
  2726. }
  2727. var runLength = 0;
  2728. if (remaining < DEFAULT_MIN_MERGE) {
  2729. runLength = makeAscendingRun(array, lo, hi, compare);
  2730. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2731. return;
  2732. }
  2733. var ts = TimSort(array, compare);
  2734. var minRun = minRunLength(remaining);
  2735. do {
  2736. runLength = makeAscendingRun(array, lo, hi, compare);
  2737. if (runLength < minRun) {
  2738. var force = remaining;
  2739. if (force > minRun) {
  2740. force = minRun;
  2741. }
  2742. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2743. runLength = force;
  2744. }
  2745. ts.pushRun(lo, runLength);
  2746. ts.mergeRuns();
  2747. remaining -= runLength;
  2748. lo += runLength;
  2749. } while (remaining !== 0);
  2750. ts.forceMergeRuns();
  2751. }
  2752. var REDRAW_BIT = 1;
  2753. var STYLE_CHANGED_BIT = 2;
  2754. var SHAPE_CHANGED_BIT = 4;
  2755. var invalidZErrorLogged = false;
  2756. function logInvalidZError() {
  2757. if (invalidZErrorLogged) {
  2758. return;
  2759. }
  2760. invalidZErrorLogged = true;
  2761. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2762. }
  2763. function shapeCompareFunc(a, b) {
  2764. if (a.zlevel === b.zlevel) {
  2765. if (a.z === b.z) {
  2766. return a.z2 - b.z2;
  2767. }
  2768. return a.z - b.z;
  2769. }
  2770. return a.zlevel - b.zlevel;
  2771. }
  2772. var Storage = (function () {
  2773. function Storage() {
  2774. this._roots = [];
  2775. this._displayList = [];
  2776. this._displayListLen = 0;
  2777. this.displayableSortFunc = shapeCompareFunc;
  2778. }
  2779. Storage.prototype.traverse = function (cb, context) {
  2780. for (var i = 0; i < this._roots.length; i++) {
  2781. this._roots[i].traverse(cb, context);
  2782. }
  2783. };
  2784. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2785. includeIgnore = includeIgnore || false;
  2786. var displayList = this._displayList;
  2787. if (update || !displayList.length) {
  2788. this.updateDisplayList(includeIgnore);
  2789. }
  2790. return displayList;
  2791. };
  2792. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2793. this._displayListLen = 0;
  2794. var roots = this._roots;
  2795. var displayList = this._displayList;
  2796. for (var i = 0, len = roots.length; i < len; i++) {
  2797. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2798. }
  2799. displayList.length = this._displayListLen;
  2800. sort(displayList, shapeCompareFunc);
  2801. };
  2802. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  2803. if (el.ignore && !includeIgnore) {
  2804. return;
  2805. }
  2806. el.beforeUpdate();
  2807. el.update();
  2808. el.afterUpdate();
  2809. var userSetClipPath = el.getClipPath();
  2810. if (el.ignoreClip) {
  2811. clipPaths = null;
  2812. }
  2813. else if (userSetClipPath) {
  2814. if (clipPaths) {
  2815. clipPaths = clipPaths.slice();
  2816. }
  2817. else {
  2818. clipPaths = [];
  2819. }
  2820. var currentClipPath = userSetClipPath;
  2821. var parentClipPath = el;
  2822. while (currentClipPath) {
  2823. currentClipPath.parent = parentClipPath;
  2824. currentClipPath.updateTransform();
  2825. clipPaths.push(currentClipPath);
  2826. parentClipPath = currentClipPath;
  2827. currentClipPath = currentClipPath.getClipPath();
  2828. }
  2829. }
  2830. if (el.childrenRef) {
  2831. var children = el.childrenRef();
  2832. for (var i = 0; i < children.length; i++) {
  2833. var child = children[i];
  2834. if (el.__dirty) {
  2835. child.__dirty |= REDRAW_BIT;
  2836. }
  2837. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  2838. }
  2839. el.__dirty = 0;
  2840. }
  2841. else {
  2842. var disp = el;
  2843. if (clipPaths && clipPaths.length) {
  2844. disp.__clipPaths = clipPaths;
  2845. }
  2846. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  2847. disp.__clipPaths = [];
  2848. }
  2849. if (isNaN(disp.z)) {
  2850. logInvalidZError();
  2851. disp.z = 0;
  2852. }
  2853. if (isNaN(disp.z2)) {
  2854. logInvalidZError();
  2855. disp.z2 = 0;
  2856. }
  2857. if (isNaN(disp.zlevel)) {
  2858. logInvalidZError();
  2859. disp.zlevel = 0;
  2860. }
  2861. this._displayList[this._displayListLen++] = disp;
  2862. }
  2863. var decalEl = el.getDecalElement && el.getDecalElement();
  2864. if (decalEl) {
  2865. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  2866. }
  2867. var textGuide = el.getTextGuideLine();
  2868. if (textGuide) {
  2869. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  2870. }
  2871. var textEl = el.getTextContent();
  2872. if (textEl) {
  2873. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  2874. }
  2875. };
  2876. Storage.prototype.addRoot = function (el) {
  2877. if (el.__zr && el.__zr.storage === this) {
  2878. return;
  2879. }
  2880. this._roots.push(el);
  2881. };
  2882. Storage.prototype.delRoot = function (el) {
  2883. if (el instanceof Array) {
  2884. for (var i = 0, l = el.length; i < l; i++) {
  2885. this.delRoot(el[i]);
  2886. }
  2887. return;
  2888. }
  2889. var idx = indexOf(this._roots, el);
  2890. if (idx >= 0) {
  2891. this._roots.splice(idx, 1);
  2892. }
  2893. };
  2894. Storage.prototype.delAllRoots = function () {
  2895. this._roots = [];
  2896. this._displayList = [];
  2897. this._displayListLen = 0;
  2898. return;
  2899. };
  2900. Storage.prototype.getRoots = function () {
  2901. return this._roots;
  2902. };
  2903. Storage.prototype.dispose = function () {
  2904. this._displayList = null;
  2905. this._roots = null;
  2906. };
  2907. return Storage;
  2908. }());
  2909. var requestAnimationFrame;
  2910. requestAnimationFrame = (env.hasGlobalWindow
  2911. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  2912. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  2913. || window.mozRequestAnimationFrame
  2914. || window.webkitRequestAnimationFrame)) || function (func) {
  2915. return setTimeout(func, 16);
  2916. };
  2917. var requestAnimationFrame$1 = requestAnimationFrame;
  2918. var easingFuncs = {
  2919. linear: function (k) {
  2920. return k;
  2921. },
  2922. quadraticIn: function (k) {
  2923. return k * k;
  2924. },
  2925. quadraticOut: function (k) {
  2926. return k * (2 - k);
  2927. },
  2928. quadraticInOut: function (k) {
  2929. if ((k *= 2) < 1) {
  2930. return 0.5 * k * k;
  2931. }
  2932. return -0.5 * (--k * (k - 2) - 1);
  2933. },
  2934. cubicIn: function (k) {
  2935. return k * k * k;
  2936. },
  2937. cubicOut: function (k) {
  2938. return --k * k * k + 1;
  2939. },
  2940. cubicInOut: function (k) {
  2941. if ((k *= 2) < 1) {
  2942. return 0.5 * k * k * k;
  2943. }
  2944. return 0.5 * ((k -= 2) * k * k + 2);
  2945. },
  2946. quarticIn: function (k) {
  2947. return k * k * k * k;
  2948. },
  2949. quarticOut: function (k) {
  2950. return 1 - (--k * k * k * k);
  2951. },
  2952. quarticInOut: function (k) {
  2953. if ((k *= 2) < 1) {
  2954. return 0.5 * k * k * k * k;
  2955. }
  2956. return -0.5 * ((k -= 2) * k * k * k - 2);
  2957. },
  2958. quinticIn: function (k) {
  2959. return k * k * k * k * k;
  2960. },
  2961. quinticOut: function (k) {
  2962. return --k * k * k * k * k + 1;
  2963. },
  2964. quinticInOut: function (k) {
  2965. if ((k *= 2) < 1) {
  2966. return 0.5 * k * k * k * k * k;
  2967. }
  2968. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2969. },
  2970. sinusoidalIn: function (k) {
  2971. return 1 - Math.cos(k * Math.PI / 2);
  2972. },
  2973. sinusoidalOut: function (k) {
  2974. return Math.sin(k * Math.PI / 2);
  2975. },
  2976. sinusoidalInOut: function (k) {
  2977. return 0.5 * (1 - Math.cos(Math.PI * k));
  2978. },
  2979. exponentialIn: function (k) {
  2980. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2981. },
  2982. exponentialOut: function (k) {
  2983. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2984. },
  2985. exponentialInOut: function (k) {
  2986. if (k === 0) {
  2987. return 0;
  2988. }
  2989. if (k === 1) {
  2990. return 1;
  2991. }
  2992. if ((k *= 2) < 1) {
  2993. return 0.5 * Math.pow(1024, k - 1);
  2994. }
  2995. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2996. },
  2997. circularIn: function (k) {
  2998. return 1 - Math.sqrt(1 - k * k);
  2999. },
  3000. circularOut: function (k) {
  3001. return Math.sqrt(1 - (--k * k));
  3002. },
  3003. circularInOut: function (k) {
  3004. if ((k *= 2) < 1) {
  3005. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  3006. }
  3007. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  3008. },
  3009. elasticIn: function (k) {
  3010. var s;
  3011. var a = 0.1;
  3012. var p = 0.4;
  3013. if (k === 0) {
  3014. return 0;
  3015. }
  3016. if (k === 1) {
  3017. return 1;
  3018. }
  3019. if (!a || a < 1) {
  3020. a = 1;
  3021. s = p / 4;
  3022. }
  3023. else {
  3024. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3025. }
  3026. return -(a * Math.pow(2, 10 * (k -= 1))
  3027. * Math.sin((k - s) * (2 * Math.PI) / p));
  3028. },
  3029. elasticOut: function (k) {
  3030. var s;
  3031. var a = 0.1;
  3032. var p = 0.4;
  3033. if (k === 0) {
  3034. return 0;
  3035. }
  3036. if (k === 1) {
  3037. return 1;
  3038. }
  3039. if (!a || a < 1) {
  3040. a = 1;
  3041. s = p / 4;
  3042. }
  3043. else {
  3044. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3045. }
  3046. return (a * Math.pow(2, -10 * k)
  3047. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  3048. },
  3049. elasticInOut: function (k) {
  3050. var s;
  3051. var a = 0.1;
  3052. var p = 0.4;
  3053. if (k === 0) {
  3054. return 0;
  3055. }
  3056. if (k === 1) {
  3057. return 1;
  3058. }
  3059. if (!a || a < 1) {
  3060. a = 1;
  3061. s = p / 4;
  3062. }
  3063. else {
  3064. s = p * Math.asin(1 / a) / (2 * Math.PI);
  3065. }
  3066. if ((k *= 2) < 1) {
  3067. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  3068. * Math.sin((k - s) * (2 * Math.PI) / p));
  3069. }
  3070. return a * Math.pow(2, -10 * (k -= 1))
  3071. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  3072. },
  3073. backIn: function (k) {
  3074. var s = 1.70158;
  3075. return k * k * ((s + 1) * k - s);
  3076. },
  3077. backOut: function (k) {
  3078. var s = 1.70158;
  3079. return --k * k * ((s + 1) * k + s) + 1;
  3080. },
  3081. backInOut: function (k) {
  3082. var s = 1.70158 * 1.525;
  3083. if ((k *= 2) < 1) {
  3084. return 0.5 * (k * k * ((s + 1) * k - s));
  3085. }
  3086. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  3087. },
  3088. bounceIn: function (k) {
  3089. return 1 - easingFuncs.bounceOut(1 - k);
  3090. },
  3091. bounceOut: function (k) {
  3092. if (k < (1 / 2.75)) {
  3093. return 7.5625 * k * k;
  3094. }
  3095. else if (k < (2 / 2.75)) {
  3096. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3097. }
  3098. else if (k < (2.5 / 2.75)) {
  3099. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3100. }
  3101. else {
  3102. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3103. }
  3104. },
  3105. bounceInOut: function (k) {
  3106. if (k < 0.5) {
  3107. return easingFuncs.bounceIn(k * 2) * 0.5;
  3108. }
  3109. return easingFuncs.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3110. }
  3111. };
  3112. var mathPow = Math.pow;
  3113. var mathSqrt = Math.sqrt;
  3114. var EPSILON = 1e-8;
  3115. var EPSILON_NUMERIC = 1e-4;
  3116. var THREE_SQRT = mathSqrt(3);
  3117. var ONE_THIRD = 1 / 3;
  3118. var _v0 = create();
  3119. var _v1 = create();
  3120. var _v2 = create();
  3121. function isAroundZero(val) {
  3122. return val > -EPSILON && val < EPSILON;
  3123. }
  3124. function isNotAroundZero(val) {
  3125. return val > EPSILON || val < -EPSILON;
  3126. }
  3127. function cubicAt(p0, p1, p2, p3, t) {
  3128. var onet = 1 - t;
  3129. return onet * onet * (onet * p0 + 3 * t * p1)
  3130. + t * t * (t * p3 + 3 * onet * p2);
  3131. }
  3132. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  3133. var onet = 1 - t;
  3134. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  3135. + (p3 - p2) * t * t);
  3136. }
  3137. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  3138. var a = p3 + 3 * (p1 - p2) - p0;
  3139. var b = 3 * (p2 - p1 * 2 + p0);
  3140. var c = 3 * (p1 - p0);
  3141. var d = p0 - val;
  3142. var A = b * b - 3 * a * c;
  3143. var B = b * c - 9 * a * d;
  3144. var C = c * c - 3 * b * d;
  3145. var n = 0;
  3146. if (isAroundZero(A) && isAroundZero(B)) {
  3147. if (isAroundZero(b)) {
  3148. roots[0] = 0;
  3149. }
  3150. else {
  3151. var t1 = -c / b;
  3152. if (t1 >= 0 && t1 <= 1) {
  3153. roots[n++] = t1;
  3154. }
  3155. }
  3156. }
  3157. else {
  3158. var disc = B * B - 4 * A * C;
  3159. if (isAroundZero(disc)) {
  3160. var K = B / A;
  3161. var t1 = -b / a + K;
  3162. var t2 = -K / 2;
  3163. if (t1 >= 0 && t1 <= 1) {
  3164. roots[n++] = t1;
  3165. }
  3166. if (t2 >= 0 && t2 <= 1) {
  3167. roots[n++] = t2;
  3168. }
  3169. }
  3170. else if (disc > 0) {
  3171. var discSqrt = mathSqrt(disc);
  3172. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  3173. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  3174. if (Y1 < 0) {
  3175. Y1 = -mathPow(-Y1, ONE_THIRD);
  3176. }
  3177. else {
  3178. Y1 = mathPow(Y1, ONE_THIRD);
  3179. }
  3180. if (Y2 < 0) {
  3181. Y2 = -mathPow(-Y2, ONE_THIRD);
  3182. }
  3183. else {
  3184. Y2 = mathPow(Y2, ONE_THIRD);
  3185. }
  3186. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  3187. if (t1 >= 0 && t1 <= 1) {
  3188. roots[n++] = t1;
  3189. }
  3190. }
  3191. else {
  3192. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  3193. var theta = Math.acos(T) / 3;
  3194. var ASqrt = mathSqrt(A);
  3195. var tmp = Math.cos(theta);
  3196. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  3197. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  3198. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  3199. if (t1 >= 0 && t1 <= 1) {
  3200. roots[n++] = t1;
  3201. }
  3202. if (t2 >= 0 && t2 <= 1) {
  3203. roots[n++] = t2;
  3204. }
  3205. if (t3 >= 0 && t3 <= 1) {
  3206. roots[n++] = t3;
  3207. }
  3208. }
  3209. }
  3210. return n;
  3211. }
  3212. function cubicExtrema(p0, p1, p2, p3, extrema) {
  3213. var b = 6 * p2 - 12 * p1 + 6 * p0;
  3214. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  3215. var c = 3 * p1 - 3 * p0;
  3216. var n = 0;
  3217. if (isAroundZero(a)) {
  3218. if (isNotAroundZero(b)) {
  3219. var t1 = -c / b;
  3220. if (t1 >= 0 && t1 <= 1) {
  3221. extrema[n++] = t1;
  3222. }
  3223. }
  3224. }
  3225. else {
  3226. var disc = b * b - 4 * a * c;
  3227. if (isAroundZero(disc)) {
  3228. extrema[0] = -b / (2 * a);
  3229. }
  3230. else if (disc > 0) {
  3231. var discSqrt = mathSqrt(disc);
  3232. var t1 = (-b + discSqrt) / (2 * a);
  3233. var t2 = (-b - discSqrt) / (2 * a);
  3234. if (t1 >= 0 && t1 <= 1) {
  3235. extrema[n++] = t1;
  3236. }
  3237. if (t2 >= 0 && t2 <= 1) {
  3238. extrema[n++] = t2;
  3239. }
  3240. }
  3241. }
  3242. return n;
  3243. }
  3244. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  3245. var p01 = (p1 - p0) * t + p0;
  3246. var p12 = (p2 - p1) * t + p1;
  3247. var p23 = (p3 - p2) * t + p2;
  3248. var p012 = (p12 - p01) * t + p01;
  3249. var p123 = (p23 - p12) * t + p12;
  3250. var p0123 = (p123 - p012) * t + p012;
  3251. out[0] = p0;
  3252. out[1] = p01;
  3253. out[2] = p012;
  3254. out[3] = p0123;
  3255. out[4] = p0123;
  3256. out[5] = p123;
  3257. out[6] = p23;
  3258. out[7] = p3;
  3259. }
  3260. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  3261. var t;
  3262. var interval = 0.005;
  3263. var d = Infinity;
  3264. var prev;
  3265. var next;
  3266. var d1;
  3267. var d2;
  3268. _v0[0] = x;
  3269. _v0[1] = y;
  3270. for (var _t = 0; _t < 1; _t += 0.05) {
  3271. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  3272. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  3273. d1 = distSquare(_v0, _v1);
  3274. if (d1 < d) {
  3275. t = _t;
  3276. d = d1;
  3277. }
  3278. }
  3279. d = Infinity;
  3280. for (var i = 0; i < 32; i++) {
  3281. if (interval < EPSILON_NUMERIC) {
  3282. break;
  3283. }
  3284. prev = t - interval;
  3285. next = t + interval;
  3286. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  3287. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  3288. d1 = distSquare(_v1, _v0);
  3289. if (prev >= 0 && d1 < d) {
  3290. t = prev;
  3291. d = d1;
  3292. }
  3293. else {
  3294. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  3295. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  3296. d2 = distSquare(_v2, _v0);
  3297. if (next <= 1 && d2 < d) {
  3298. t = next;
  3299. d = d2;
  3300. }
  3301. else {
  3302. interval *= 0.5;
  3303. }
  3304. }
  3305. }
  3306. if (out) {
  3307. out[0] = cubicAt(x0, x1, x2, x3, t);
  3308. out[1] = cubicAt(y0, y1, y2, y3, t);
  3309. }
  3310. return mathSqrt(d);
  3311. }
  3312. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  3313. var px = x0;
  3314. var py = y0;
  3315. var d = 0;
  3316. var step = 1 / iteration;
  3317. for (var i = 1; i <= iteration; i++) {
  3318. var t = i * step;
  3319. var x = cubicAt(x0, x1, x2, x3, t);
  3320. var y = cubicAt(y0, y1, y2, y3, t);
  3321. var dx = x - px;
  3322. var dy = y - py;
  3323. d += Math.sqrt(dx * dx + dy * dy);
  3324. px = x;
  3325. py = y;
  3326. }
  3327. return d;
  3328. }
  3329. function quadraticAt(p0, p1, p2, t) {
  3330. var onet = 1 - t;
  3331. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  3332. }
  3333. function quadraticDerivativeAt(p0, p1, p2, t) {
  3334. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  3335. }
  3336. function quadraticRootAt(p0, p1, p2, val, roots) {
  3337. var a = p0 - 2 * p1 + p2;
  3338. var b = 2 * (p1 - p0);
  3339. var c = p0 - val;
  3340. var n = 0;
  3341. if (isAroundZero(a)) {
  3342. if (isNotAroundZero(b)) {
  3343. var t1 = -c / b;
  3344. if (t1 >= 0 && t1 <= 1) {
  3345. roots[n++] = t1;
  3346. }
  3347. }
  3348. }
  3349. else {
  3350. var disc = b * b - 4 * a * c;
  3351. if (isAroundZero(disc)) {
  3352. var t1 = -b / (2 * a);
  3353. if (t1 >= 0 && t1 <= 1) {
  3354. roots[n++] = t1;
  3355. }
  3356. }
  3357. else if (disc > 0) {
  3358. var discSqrt = mathSqrt(disc);
  3359. var t1 = (-b + discSqrt) / (2 * a);
  3360. var t2 = (-b - discSqrt) / (2 * a);
  3361. if (t1 >= 0 && t1 <= 1) {
  3362. roots[n++] = t1;
  3363. }
  3364. if (t2 >= 0 && t2 <= 1) {
  3365. roots[n++] = t2;
  3366. }
  3367. }
  3368. }
  3369. return n;
  3370. }
  3371. function quadraticExtremum(p0, p1, p2) {
  3372. var divider = p0 + p2 - 2 * p1;
  3373. if (divider === 0) {
  3374. return 0.5;
  3375. }
  3376. else {
  3377. return (p0 - p1) / divider;
  3378. }
  3379. }
  3380. function quadraticSubdivide(p0, p1, p2, t, out) {
  3381. var p01 = (p1 - p0) * t + p0;
  3382. var p12 = (p2 - p1) * t + p1;
  3383. var p012 = (p12 - p01) * t + p01;
  3384. out[0] = p0;
  3385. out[1] = p01;
  3386. out[2] = p012;
  3387. out[3] = p012;
  3388. out[4] = p12;
  3389. out[5] = p2;
  3390. }
  3391. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  3392. var t;
  3393. var interval = 0.005;
  3394. var d = Infinity;
  3395. _v0[0] = x;
  3396. _v0[1] = y;
  3397. for (var _t = 0; _t < 1; _t += 0.05) {
  3398. _v1[0] = quadraticAt(x0, x1, x2, _t);
  3399. _v1[1] = quadraticAt(y0, y1, y2, _t);
  3400. var d1 = distSquare(_v0, _v1);
  3401. if (d1 < d) {
  3402. t = _t;
  3403. d = d1;
  3404. }
  3405. }
  3406. d = Infinity;
  3407. for (var i = 0; i < 32; i++) {
  3408. if (interval < EPSILON_NUMERIC) {
  3409. break;
  3410. }
  3411. var prev = t - interval;
  3412. var next = t + interval;
  3413. _v1[0] = quadraticAt(x0, x1, x2, prev);
  3414. _v1[1] = quadraticAt(y0, y1, y2, prev);
  3415. var d1 = distSquare(_v1, _v0);
  3416. if (prev >= 0 && d1 < d) {
  3417. t = prev;
  3418. d = d1;
  3419. }
  3420. else {
  3421. _v2[0] = quadraticAt(x0, x1, x2, next);
  3422. _v2[1] = quadraticAt(y0, y1, y2, next);
  3423. var d2 = distSquare(_v2, _v0);
  3424. if (next <= 1 && d2 < d) {
  3425. t = next;
  3426. d = d2;
  3427. }
  3428. else {
  3429. interval *= 0.5;
  3430. }
  3431. }
  3432. }
  3433. if (out) {
  3434. out[0] = quadraticAt(x0, x1, x2, t);
  3435. out[1] = quadraticAt(y0, y1, y2, t);
  3436. }
  3437. return mathSqrt(d);
  3438. }
  3439. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  3440. var px = x0;
  3441. var py = y0;
  3442. var d = 0;
  3443. var step = 1 / iteration;
  3444. for (var i = 1; i <= iteration; i++) {
  3445. var t = i * step;
  3446. var x = quadraticAt(x0, x1, x2, t);
  3447. var y = quadraticAt(y0, y1, y2, t);
  3448. var dx = x - px;
  3449. var dy = y - py;
  3450. d += Math.sqrt(dx * dx + dy * dy);
  3451. px = x;
  3452. py = y;
  3453. }
  3454. return d;
  3455. }
  3456. var regexp = /cubic-bezier\(([0-9,\.e ]+)\)/;
  3457. function createCubicEasingFunc(cubicEasingStr) {
  3458. var cubic = cubicEasingStr && regexp.exec(cubicEasingStr);
  3459. if (cubic) {
  3460. var points = cubic[1].split(',');
  3461. var a_1 = +trim(points[0]);
  3462. var b_1 = +trim(points[1]);
  3463. var c_1 = +trim(points[2]);
  3464. var d_1 = +trim(points[3]);
  3465. if (isNaN(a_1 + b_1 + c_1 + d_1)) {
  3466. return;
  3467. }
  3468. var roots_1 = [];
  3469. return function (p) {
  3470. return p <= 0
  3471. ? 0 : p >= 1
  3472. ? 1
  3473. : cubicRootAt(0, a_1, c_1, 1, p, roots_1) && cubicAt(0, b_1, d_1, 1, roots_1[0]);
  3474. };
  3475. }
  3476. }
  3477. var Clip = (function () {
  3478. function Clip(opts) {
  3479. this._inited = false;
  3480. this._startTime = 0;
  3481. this._pausedTime = 0;
  3482. this._paused = false;
  3483. this._life = opts.life || 1000;
  3484. this._delay = opts.delay || 0;
  3485. this.loop = opts.loop || false;
  3486. this.onframe = opts.onframe || noop;
  3487. this.ondestroy = opts.ondestroy || noop;
  3488. this.onrestart = opts.onrestart || noop;
  3489. opts.easing && this.setEasing(opts.easing);
  3490. }
  3491. Clip.prototype.step = function (globalTime, deltaTime) {
  3492. if (!this._inited) {
  3493. this._startTime = globalTime + this._delay;
  3494. this._inited = true;
  3495. }
  3496. if (this._paused) {
  3497. this._pausedTime += deltaTime;
  3498. return;
  3499. }
  3500. var life = this._life;
  3501. var elapsedTime = globalTime - this._startTime - this._pausedTime;
  3502. var percent = elapsedTime / life;
  3503. if (percent < 0) {
  3504. percent = 0;
  3505. }
  3506. percent = Math.min(percent, 1);
  3507. var easingFunc = this.easingFunc;
  3508. var schedule = easingFunc ? easingFunc(percent) : percent;
  3509. this.onframe(schedule);
  3510. if (percent === 1) {
  3511. if (this.loop) {
  3512. var remainder = elapsedTime % life;
  3513. this._startTime = globalTime - remainder;
  3514. this._pausedTime = 0;
  3515. this.onrestart();
  3516. }
  3517. else {
  3518. return true;
  3519. }
  3520. }
  3521. return false;
  3522. };
  3523. Clip.prototype.pause = function () {
  3524. this._paused = true;
  3525. };
  3526. Clip.prototype.resume = function () {
  3527. this._paused = false;
  3528. };
  3529. Clip.prototype.setEasing = function (easing) {
  3530. this.easing = easing;
  3531. this.easingFunc = isFunction(easing)
  3532. ? easing
  3533. : easingFuncs[easing] || createCubicEasingFunc(easing);
  3534. };
  3535. return Clip;
  3536. }());
  3537. var Entry = (function () {
  3538. function Entry(val) {
  3539. this.value = val;
  3540. }
  3541. return Entry;
  3542. }());
  3543. var LinkedList = (function () {
  3544. function LinkedList() {
  3545. this._len = 0;
  3546. }
  3547. LinkedList.prototype.insert = function (val) {
  3548. var entry = new Entry(val);
  3549. this.insertEntry(entry);
  3550. return entry;
  3551. };
  3552. LinkedList.prototype.insertEntry = function (entry) {
  3553. if (!this.head) {
  3554. this.head = this.tail = entry;
  3555. }
  3556. else {
  3557. this.tail.next = entry;
  3558. entry.prev = this.tail;
  3559. entry.next = null;
  3560. this.tail = entry;
  3561. }
  3562. this._len++;
  3563. };
  3564. LinkedList.prototype.remove = function (entry) {
  3565. var prev = entry.prev;
  3566. var next = entry.next;
  3567. if (prev) {
  3568. prev.next = next;
  3569. }
  3570. else {
  3571. this.head = next;
  3572. }
  3573. if (next) {
  3574. next.prev = prev;
  3575. }
  3576. else {
  3577. this.tail = prev;
  3578. }
  3579. entry.next = entry.prev = null;
  3580. this._len--;
  3581. };
  3582. LinkedList.prototype.len = function () {
  3583. return this._len;
  3584. };
  3585. LinkedList.prototype.clear = function () {
  3586. this.head = this.tail = null;
  3587. this._len = 0;
  3588. };
  3589. return LinkedList;
  3590. }());
  3591. var LRU = (function () {
  3592. function LRU(maxSize) {
  3593. this._list = new LinkedList();
  3594. this._maxSize = 10;
  3595. this._map = {};
  3596. this._maxSize = maxSize;
  3597. }
  3598. LRU.prototype.put = function (key, value) {
  3599. var list = this._list;
  3600. var map = this._map;
  3601. var removed = null;
  3602. if (map[key] == null) {
  3603. var len = list.len();
  3604. var entry = this._lastRemovedEntry;
  3605. if (len >= this._maxSize && len > 0) {
  3606. var leastUsedEntry = list.head;
  3607. list.remove(leastUsedEntry);
  3608. delete map[leastUsedEntry.key];
  3609. removed = leastUsedEntry.value;
  3610. this._lastRemovedEntry = leastUsedEntry;
  3611. }
  3612. if (entry) {
  3613. entry.value = value;
  3614. }
  3615. else {
  3616. entry = new Entry(value);
  3617. }
  3618. entry.key = key;
  3619. list.insertEntry(entry);
  3620. map[key] = entry;
  3621. }
  3622. return removed;
  3623. };
  3624. LRU.prototype.get = function (key) {
  3625. var entry = this._map[key];
  3626. var list = this._list;
  3627. if (entry != null) {
  3628. if (entry !== list.tail) {
  3629. list.remove(entry);
  3630. list.insertEntry(entry);
  3631. }
  3632. return entry.value;
  3633. }
  3634. };
  3635. LRU.prototype.clear = function () {
  3636. this._list.clear();
  3637. this._map = {};
  3638. };
  3639. LRU.prototype.len = function () {
  3640. return this._list.len();
  3641. };
  3642. return LRU;
  3643. }());
  3644. var kCSSColorTable = {
  3645. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3646. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3647. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3648. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3649. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3650. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3651. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3652. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3653. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3654. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3655. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3656. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3657. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3658. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3659. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3660. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3661. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3662. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3663. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3664. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3665. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3666. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3667. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3668. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3669. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3670. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3671. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3672. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3673. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3674. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3675. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3676. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3677. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3678. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3679. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3680. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3681. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3682. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3683. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3684. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3685. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3686. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3687. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3688. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3689. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3690. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3691. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3692. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3693. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3694. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3695. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3696. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3697. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3698. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3699. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3700. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3701. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3702. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3703. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3704. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3705. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3706. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3707. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3708. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3709. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3710. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3711. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3712. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3713. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3714. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3715. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3716. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3717. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3718. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3719. };
  3720. function clampCssByte(i) {
  3721. i = Math.round(i);
  3722. return i < 0 ? 0 : i > 255 ? 255 : i;
  3723. }
  3724. function clampCssAngle(i) {
  3725. i = Math.round(i);
  3726. return i < 0 ? 0 : i > 360 ? 360 : i;
  3727. }
  3728. function clampCssFloat(f) {
  3729. return f < 0 ? 0 : f > 1 ? 1 : f;
  3730. }
  3731. function parseCssInt(val) {
  3732. var str = val;
  3733. if (str.length && str.charAt(str.length - 1) === '%') {
  3734. return clampCssByte(parseFloat(str) / 100 * 255);
  3735. }
  3736. return clampCssByte(parseInt(str, 10));
  3737. }
  3738. function parseCssFloat(val) {
  3739. var str = val;
  3740. if (str.length && str.charAt(str.length - 1) === '%') {
  3741. return clampCssFloat(parseFloat(str) / 100);
  3742. }
  3743. return clampCssFloat(parseFloat(str));
  3744. }
  3745. function cssHueToRgb(m1, m2, h) {
  3746. if (h < 0) {
  3747. h += 1;
  3748. }
  3749. else if (h > 1) {
  3750. h -= 1;
  3751. }
  3752. if (h * 6 < 1) {
  3753. return m1 + (m2 - m1) * h * 6;
  3754. }
  3755. if (h * 2 < 1) {
  3756. return m2;
  3757. }
  3758. if (h * 3 < 2) {
  3759. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3760. }
  3761. return m1;
  3762. }
  3763. function lerpNumber(a, b, p) {
  3764. return a + (b - a) * p;
  3765. }
  3766. function setRgba(out, r, g, b, a) {
  3767. out[0] = r;
  3768. out[1] = g;
  3769. out[2] = b;
  3770. out[3] = a;
  3771. return out;
  3772. }
  3773. function copyRgba(out, a) {
  3774. out[0] = a[0];
  3775. out[1] = a[1];
  3776. out[2] = a[2];
  3777. out[3] = a[3];
  3778. return out;
  3779. }
  3780. var colorCache = new LRU(20);
  3781. var lastRemovedArr = null;
  3782. function putToCache(colorStr, rgbaArr) {
  3783. if (lastRemovedArr) {
  3784. copyRgba(lastRemovedArr, rgbaArr);
  3785. }
  3786. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3787. }
  3788. function parse(colorStr, rgbaArr) {
  3789. if (!colorStr) {
  3790. return;
  3791. }
  3792. rgbaArr = rgbaArr || [];
  3793. var cached = colorCache.get(colorStr);
  3794. if (cached) {
  3795. return copyRgba(rgbaArr, cached);
  3796. }
  3797. colorStr = colorStr + '';
  3798. var str = colorStr.replace(/ /g, '').toLowerCase();
  3799. if (str in kCSSColorTable) {
  3800. copyRgba(rgbaArr, kCSSColorTable[str]);
  3801. putToCache(colorStr, rgbaArr);
  3802. return rgbaArr;
  3803. }
  3804. var strLen = str.length;
  3805. if (str.charAt(0) === '#') {
  3806. if (strLen === 4 || strLen === 5) {
  3807. var iv = parseInt(str.slice(1, 4), 16);
  3808. if (!(iv >= 0 && iv <= 0xfff)) {
  3809. setRgba(rgbaArr, 0, 0, 0, 1);
  3810. return;
  3811. }
  3812. setRgba(rgbaArr, ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), (iv & 0xf0) | ((iv & 0xf0) >> 4), (iv & 0xf) | ((iv & 0xf) << 4), strLen === 5 ? parseInt(str.slice(4), 16) / 0xf : 1);
  3813. putToCache(colorStr, rgbaArr);
  3814. return rgbaArr;
  3815. }
  3816. else if (strLen === 7 || strLen === 9) {
  3817. var iv = parseInt(str.slice(1, 7), 16);
  3818. if (!(iv >= 0 && iv <= 0xffffff)) {
  3819. setRgba(rgbaArr, 0, 0, 0, 1);
  3820. return;
  3821. }
  3822. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  3823. putToCache(colorStr, rgbaArr);
  3824. return rgbaArr;
  3825. }
  3826. return;
  3827. }
  3828. var op = str.indexOf('(');
  3829. var ep = str.indexOf(')');
  3830. if (op !== -1 && ep + 1 === strLen) {
  3831. var fname = str.substr(0, op);
  3832. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3833. var alpha = 1;
  3834. switch (fname) {
  3835. case 'rgba':
  3836. if (params.length !== 4) {
  3837. return params.length === 3
  3838. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  3839. : setRgba(rgbaArr, 0, 0, 0, 1);
  3840. }
  3841. alpha = parseCssFloat(params.pop());
  3842. case 'rgb':
  3843. if (params.length >= 3) {
  3844. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), params.length === 3 ? alpha : parseCssFloat(params[3]));
  3845. putToCache(colorStr, rgbaArr);
  3846. return rgbaArr;
  3847. }
  3848. else {
  3849. setRgba(rgbaArr, 0, 0, 0, 1);
  3850. return;
  3851. }
  3852. case 'hsla':
  3853. if (params.length !== 4) {
  3854. setRgba(rgbaArr, 0, 0, 0, 1);
  3855. return;
  3856. }
  3857. params[3] = parseCssFloat(params[3]);
  3858. hsla2rgba(params, rgbaArr);
  3859. putToCache(colorStr, rgbaArr);
  3860. return rgbaArr;
  3861. case 'hsl':
  3862. if (params.length !== 3) {
  3863. setRgba(rgbaArr, 0, 0, 0, 1);
  3864. return;
  3865. }
  3866. hsla2rgba(params, rgbaArr);
  3867. putToCache(colorStr, rgbaArr);
  3868. return rgbaArr;
  3869. default:
  3870. return;
  3871. }
  3872. }
  3873. setRgba(rgbaArr, 0, 0, 0, 1);
  3874. return;
  3875. }
  3876. function hsla2rgba(hsla, rgba) {
  3877. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  3878. var s = parseCssFloat(hsla[1]);
  3879. var l = parseCssFloat(hsla[2]);
  3880. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3881. var m1 = l * 2 - m2;
  3882. rgba = rgba || [];
  3883. setRgba(rgba, clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255), clampCssByte(cssHueToRgb(m1, m2, h) * 255), clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255), 1);
  3884. if (hsla.length === 4) {
  3885. rgba[3] = hsla[3];
  3886. }
  3887. return rgba;
  3888. }
  3889. function rgba2hsla(rgba) {
  3890. if (!rgba) {
  3891. return;
  3892. }
  3893. var R = rgba[0] / 255;
  3894. var G = rgba[1] / 255;
  3895. var B = rgba[2] / 255;
  3896. var vMin = Math.min(R, G, B);
  3897. var vMax = Math.max(R, G, B);
  3898. var delta = vMax - vMin;
  3899. var L = (vMax + vMin) / 2;
  3900. var H;
  3901. var S;
  3902. if (delta === 0) {
  3903. H = 0;
  3904. S = 0;
  3905. }
  3906. else {
  3907. if (L < 0.5) {
  3908. S = delta / (vMax + vMin);
  3909. }
  3910. else {
  3911. S = delta / (2 - vMax - vMin);
  3912. }
  3913. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3914. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3915. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3916. if (R === vMax) {
  3917. H = deltaB - deltaG;
  3918. }
  3919. else if (G === vMax) {
  3920. H = (1 / 3) + deltaR - deltaB;
  3921. }
  3922. else if (B === vMax) {
  3923. H = (2 / 3) + deltaG - deltaR;
  3924. }
  3925. if (H < 0) {
  3926. H += 1;
  3927. }
  3928. if (H > 1) {
  3929. H -= 1;
  3930. }
  3931. }
  3932. var hsla = [H * 360, S, L];
  3933. if (rgba[3] != null) {
  3934. hsla.push(rgba[3]);
  3935. }
  3936. return hsla;
  3937. }
  3938. function lift(color, level) {
  3939. var colorArr = parse(color);
  3940. if (colorArr) {
  3941. for (var i = 0; i < 3; i++) {
  3942. if (level < 0) {
  3943. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3944. }
  3945. else {
  3946. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3947. }
  3948. if (colorArr[i] > 255) {
  3949. colorArr[i] = 255;
  3950. }
  3951. else if (colorArr[i] < 0) {
  3952. colorArr[i] = 0;
  3953. }
  3954. }
  3955. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3956. }
  3957. }
  3958. function toHex(color) {
  3959. var colorArr = parse(color);
  3960. if (colorArr) {
  3961. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3962. }
  3963. }
  3964. function fastLerp(normalizedValue, colors, out) {
  3965. if (!(colors && colors.length)
  3966. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3967. return;
  3968. }
  3969. out = out || [];
  3970. var value = normalizedValue * (colors.length - 1);
  3971. var leftIndex = Math.floor(value);
  3972. var rightIndex = Math.ceil(value);
  3973. var leftColor = colors[leftIndex];
  3974. var rightColor = colors[rightIndex];
  3975. var dv = value - leftIndex;
  3976. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3977. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3978. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3979. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3980. return out;
  3981. }
  3982. var fastMapToColor = fastLerp;
  3983. function lerp$1(normalizedValue, colors, fullOutput) {
  3984. if (!(colors && colors.length)
  3985. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3986. return;
  3987. }
  3988. var value = normalizedValue * (colors.length - 1);
  3989. var leftIndex = Math.floor(value);
  3990. var rightIndex = Math.ceil(value);
  3991. var leftColor = parse(colors[leftIndex]);
  3992. var rightColor = parse(colors[rightIndex]);
  3993. var dv = value - leftIndex;
  3994. var color = stringify([
  3995. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3996. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3997. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3998. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3999. ], 'rgba');
  4000. return fullOutput
  4001. ? {
  4002. color: color,
  4003. leftIndex: leftIndex,
  4004. rightIndex: rightIndex,
  4005. value: value
  4006. }
  4007. : color;
  4008. }
  4009. var mapToColor = lerp$1;
  4010. function modifyHSL(color, h, s, l) {
  4011. var colorArr = parse(color);
  4012. if (color) {
  4013. colorArr = rgba2hsla(colorArr);
  4014. h != null && (colorArr[0] = clampCssAngle(h));
  4015. s != null && (colorArr[1] = parseCssFloat(s));
  4016. l != null && (colorArr[2] = parseCssFloat(l));
  4017. return stringify(hsla2rgba(colorArr), 'rgba');
  4018. }
  4019. }
  4020. function modifyAlpha(color, alpha) {
  4021. var colorArr = parse(color);
  4022. if (colorArr && alpha != null) {
  4023. colorArr[3] = clampCssFloat(alpha);
  4024. return stringify(colorArr, 'rgba');
  4025. }
  4026. }
  4027. function stringify(arrColor, type) {
  4028. if (!arrColor || !arrColor.length) {
  4029. return;
  4030. }
  4031. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  4032. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  4033. colorStr += ',' + arrColor[3];
  4034. }
  4035. return type + '(' + colorStr + ')';
  4036. }
  4037. function lum(color, backgroundLum) {
  4038. var arr = parse(color);
  4039. return arr
  4040. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  4041. + (1 - arr[3]) * backgroundLum
  4042. : 0;
  4043. }
  4044. function random() {
  4045. return stringify([
  4046. Math.round(Math.random() * 255),
  4047. Math.round(Math.random() * 255),
  4048. Math.round(Math.random() * 255)
  4049. ], 'rgb');
  4050. }
  4051. var color = /*#__PURE__*/Object.freeze({
  4052. __proto__: null,
  4053. parse: parse,
  4054. lift: lift,
  4055. toHex: toHex,
  4056. fastLerp: fastLerp,
  4057. fastMapToColor: fastMapToColor,
  4058. lerp: lerp$1,
  4059. mapToColor: mapToColor,
  4060. modifyHSL: modifyHSL,
  4061. modifyAlpha: modifyAlpha,
  4062. stringify: stringify,
  4063. lum: lum,
  4064. random: random
  4065. });
  4066. var mathRound = Math.round;
  4067. function normalizeColor(color) {
  4068. var opacity;
  4069. if (!color || color === 'transparent') {
  4070. color = 'none';
  4071. }
  4072. else if (typeof color === 'string' && color.indexOf('rgba') > -1) {
  4073. var arr = parse(color);
  4074. if (arr) {
  4075. color = 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ')';
  4076. opacity = arr[3];
  4077. }
  4078. }
  4079. return {
  4080. color: color,
  4081. opacity: opacity == null ? 1 : opacity
  4082. };
  4083. }
  4084. var EPSILON$1 = 1e-4;
  4085. function isAroundZero$1(transform) {
  4086. return transform < EPSILON$1 && transform > -EPSILON$1;
  4087. }
  4088. function round3(transform) {
  4089. return mathRound(transform * 1e3) / 1e3;
  4090. }
  4091. function round4(transform) {
  4092. return mathRound(transform * 1e4) / 1e4;
  4093. }
  4094. function getMatrixStr(m) {
  4095. return 'matrix('
  4096. + round3(m[0]) + ','
  4097. + round3(m[1]) + ','
  4098. + round3(m[2]) + ','
  4099. + round3(m[3]) + ','
  4100. + round4(m[4]) + ','
  4101. + round4(m[5])
  4102. + ')';
  4103. }
  4104. var TEXT_ALIGN_TO_ANCHOR = {
  4105. left: 'start',
  4106. right: 'end',
  4107. center: 'middle',
  4108. middle: 'middle'
  4109. };
  4110. function adjustTextY(y, lineHeight, textBaseline) {
  4111. if (textBaseline === 'top') {
  4112. y += lineHeight / 2;
  4113. }
  4114. else if (textBaseline === 'bottom') {
  4115. y -= lineHeight / 2;
  4116. }
  4117. return y;
  4118. }
  4119. function hasShadow(style) {
  4120. return style
  4121. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  4122. }
  4123. function getShadowKey(displayable) {
  4124. var style = displayable.style;
  4125. var globalScale = displayable.getGlobalScale();
  4126. return [
  4127. style.shadowColor,
  4128. (style.shadowBlur || 0).toFixed(2),
  4129. (style.shadowOffsetX || 0).toFixed(2),
  4130. (style.shadowOffsetY || 0).toFixed(2),
  4131. globalScale[0],
  4132. globalScale[1]
  4133. ].join(',');
  4134. }
  4135. function isImagePattern(val) {
  4136. return val && (!!val.image);
  4137. }
  4138. function isSVGPattern(val) {
  4139. return val && (!!val.svgElement);
  4140. }
  4141. function isPattern(val) {
  4142. return isImagePattern(val) || isSVGPattern(val);
  4143. }
  4144. function isLinearGradient(val) {
  4145. return val.type === 'linear';
  4146. }
  4147. function isRadialGradient(val) {
  4148. return val.type === 'radial';
  4149. }
  4150. function isGradient(val) {
  4151. return val && (val.type === 'linear'
  4152. || val.type === 'radial');
  4153. }
  4154. function getIdURL(id) {
  4155. return "url(#" + id + ")";
  4156. }
  4157. function getPathPrecision(el) {
  4158. var scale = el.getGlobalScale();
  4159. var size = Math.max(scale[0], scale[1]);
  4160. return Math.max(Math.ceil(Math.log(size) / Math.log(10)), 1);
  4161. }
  4162. function getSRTTransformString(transform) {
  4163. var x = transform.x || 0;
  4164. var y = transform.y || 0;
  4165. var rotation = (transform.rotation || 0) * RADIAN_TO_DEGREE;
  4166. var scaleX = retrieve2(transform.scaleX, 1);
  4167. var scaleY = retrieve2(transform.scaleY, 1);
  4168. var skewX = transform.skewX || 0;
  4169. var skewY = transform.skewY || 0;
  4170. var res = [];
  4171. if (x || y) {
  4172. res.push("translate(" + x + "px," + y + "px)");
  4173. }
  4174. if (rotation) {
  4175. res.push("rotate(" + rotation + ")");
  4176. }
  4177. if (scaleX !== 1 || scaleY !== 1) {
  4178. res.push("scale(" + scaleX + "," + scaleY + ")");
  4179. }
  4180. if (skewX || skewY) {
  4181. res.push("skew(" + mathRound(skewX * RADIAN_TO_DEGREE) + "deg, " + mathRound(skewY * RADIAN_TO_DEGREE) + "deg)");
  4182. }
  4183. return res.join(' ');
  4184. }
  4185. var encodeBase64 = (function () {
  4186. if (env.hasGlobalWindow && isFunction(window.btoa)) {
  4187. return function (str) {
  4188. return window.btoa(unescape(encodeURIComponent(str)));
  4189. };
  4190. }
  4191. if (typeof Buffer !== 'undefined') {
  4192. return function (str) {
  4193. return Buffer.from(str).toString('base64');
  4194. };
  4195. }
  4196. return function (str) {
  4197. if ("development" !== 'production') {
  4198. logError('Base64 isn\'t natively supported in the current environment.');
  4199. }
  4200. return null;
  4201. };
  4202. })();
  4203. var arraySlice = Array.prototype.slice;
  4204. function interpolateNumber(p0, p1, percent) {
  4205. return (p1 - p0) * percent + p0;
  4206. }
  4207. function interpolate1DArray(out, p0, p1, percent) {
  4208. var len = p0.length;
  4209. for (var i = 0; i < len; i++) {
  4210. out[i] = interpolateNumber(p0[i], p1[i], percent);
  4211. }
  4212. return out;
  4213. }
  4214. function interpolate2DArray(out, p0, p1, percent) {
  4215. var len = p0.length;
  4216. var len2 = len && p0[0].length;
  4217. for (var i = 0; i < len; i++) {
  4218. if (!out[i]) {
  4219. out[i] = [];
  4220. }
  4221. for (var j = 0; j < len2; j++) {
  4222. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  4223. }
  4224. }
  4225. return out;
  4226. }
  4227. function add1DArray(out, p0, p1, sign) {
  4228. var len = p0.length;
  4229. for (var i = 0; i < len; i++) {
  4230. out[i] = p0[i] + p1[i] * sign;
  4231. }
  4232. return out;
  4233. }
  4234. function add2DArray(out, p0, p1, sign) {
  4235. var len = p0.length;
  4236. var len2 = len && p0[0].length;
  4237. for (var i = 0; i < len; i++) {
  4238. if (!out[i]) {
  4239. out[i] = [];
  4240. }
  4241. for (var j = 0; j < len2; j++) {
  4242. out[i][j] = p0[i][j] + p1[i][j] * sign;
  4243. }
  4244. }
  4245. return out;
  4246. }
  4247. function fillColorStops(val0, val1) {
  4248. var len0 = val0.length;
  4249. var len1 = val1.length;
  4250. var shorterArr = len0 > len1 ? val1 : val0;
  4251. var shorterLen = Math.min(len0, len1);
  4252. var last = shorterArr[shorterLen - 1] || { color: [0, 0, 0, 0], offset: 0 };
  4253. for (var i = shorterLen; i < Math.max(len0, len1); i++) {
  4254. shorterArr.push({
  4255. offset: last.offset,
  4256. color: last.color.slice()
  4257. });
  4258. }
  4259. }
  4260. function fillArray(val0, val1, arrDim) {
  4261. var arr0 = val0;
  4262. var arr1 = val1;
  4263. if (!arr0.push || !arr1.push) {
  4264. return;
  4265. }
  4266. var arr0Len = arr0.length;
  4267. var arr1Len = arr1.length;
  4268. if (arr0Len !== arr1Len) {
  4269. var isPreviousLarger = arr0Len > arr1Len;
  4270. if (isPreviousLarger) {
  4271. arr0.length = arr1Len;
  4272. }
  4273. else {
  4274. for (var i = arr0Len; i < arr1Len; i++) {
  4275. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  4276. }
  4277. }
  4278. }
  4279. var len2 = arr0[0] && arr0[0].length;
  4280. for (var i = 0; i < arr0.length; i++) {
  4281. if (arrDim === 1) {
  4282. if (isNaN(arr0[i])) {
  4283. arr0[i] = arr1[i];
  4284. }
  4285. }
  4286. else {
  4287. for (var j = 0; j < len2; j++) {
  4288. if (isNaN(arr0[i][j])) {
  4289. arr0[i][j] = arr1[i][j];
  4290. }
  4291. }
  4292. }
  4293. }
  4294. }
  4295. function cloneValue(value) {
  4296. if (isArrayLike(value)) {
  4297. var len = value.length;
  4298. if (isArrayLike(value[0])) {
  4299. var ret = [];
  4300. for (var i = 0; i < len; i++) {
  4301. ret.push(arraySlice.call(value[i]));
  4302. }
  4303. return ret;
  4304. }
  4305. return arraySlice.call(value);
  4306. }
  4307. return value;
  4308. }
  4309. function rgba2String(rgba) {
  4310. rgba[0] = Math.floor(rgba[0]) || 0;
  4311. rgba[1] = Math.floor(rgba[1]) || 0;
  4312. rgba[2] = Math.floor(rgba[2]) || 0;
  4313. rgba[3] = rgba[3] == null ? 1 : rgba[3];
  4314. return 'rgba(' + rgba.join(',') + ')';
  4315. }
  4316. function guessArrayDim(value) {
  4317. return isArrayLike(value && value[0]) ? 2 : 1;
  4318. }
  4319. var VALUE_TYPE_NUMBER = 0;
  4320. var VALUE_TYPE_1D_ARRAY = 1;
  4321. var VALUE_TYPE_2D_ARRAY = 2;
  4322. var VALUE_TYPE_COLOR = 3;
  4323. var VALUE_TYPE_LINEAR_GRADIENT = 4;
  4324. var VALUE_TYPE_RADIAL_GRADIENT = 5;
  4325. var VALUE_TYPE_UNKOWN = 6;
  4326. function isGradientValueType(valType) {
  4327. return valType === VALUE_TYPE_LINEAR_GRADIENT || valType === VALUE_TYPE_RADIAL_GRADIENT;
  4328. }
  4329. function isArrayValueType(valType) {
  4330. return valType === VALUE_TYPE_1D_ARRAY || valType === VALUE_TYPE_2D_ARRAY;
  4331. }
  4332. var tmpRgba = [0, 0, 0, 0];
  4333. var Track = (function () {
  4334. function Track(propName) {
  4335. this.keyframes = [];
  4336. this.discrete = false;
  4337. this._invalid = false;
  4338. this._needsSort = false;
  4339. this._lastFr = 0;
  4340. this._lastFrP = 0;
  4341. this.propName = propName;
  4342. }
  4343. Track.prototype.isFinished = function () {
  4344. return this._finished;
  4345. };
  4346. Track.prototype.setFinished = function () {
  4347. this._finished = true;
  4348. if (this._additiveTrack) {
  4349. this._additiveTrack.setFinished();
  4350. }
  4351. };
  4352. Track.prototype.needsAnimate = function () {
  4353. return this.keyframes.length >= 1;
  4354. };
  4355. Track.prototype.getAdditiveTrack = function () {
  4356. return this._additiveTrack;
  4357. };
  4358. Track.prototype.addKeyframe = function (time, rawValue, easing) {
  4359. this._needsSort = true;
  4360. var keyframes = this.keyframes;
  4361. var len = keyframes.length;
  4362. var discrete = false;
  4363. var valType = VALUE_TYPE_UNKOWN;
  4364. var value = rawValue;
  4365. if (isArrayLike(rawValue)) {
  4366. var arrayDim = guessArrayDim(rawValue);
  4367. valType = arrayDim;
  4368. if (arrayDim === 1 && !isNumber(rawValue[0])
  4369. || arrayDim === 2 && !isNumber(rawValue[0][0])) {
  4370. discrete = true;
  4371. }
  4372. }
  4373. else {
  4374. if (isNumber(rawValue) && !eqNaN(rawValue)) {
  4375. valType = VALUE_TYPE_NUMBER;
  4376. }
  4377. else if (isString(rawValue)) {
  4378. if (!isNaN(+rawValue)) {
  4379. valType = VALUE_TYPE_NUMBER;
  4380. }
  4381. else {
  4382. var colorArray = parse(rawValue);
  4383. if (colorArray) {
  4384. value = colorArray;
  4385. valType = VALUE_TYPE_COLOR;
  4386. }
  4387. }
  4388. }
  4389. else if (isGradientObject(rawValue)) {
  4390. var parsedGradient = extend({}, value);
  4391. parsedGradient.colorStops = map(rawValue.colorStops, function (colorStop) { return ({
  4392. offset: colorStop.offset,
  4393. color: parse(colorStop.color)
  4394. }); });
  4395. if (isLinearGradient(rawValue)) {
  4396. valType = VALUE_TYPE_LINEAR_GRADIENT;
  4397. }
  4398. else if (isRadialGradient(rawValue)) {
  4399. valType = VALUE_TYPE_RADIAL_GRADIENT;
  4400. }
  4401. value = parsedGradient;
  4402. }
  4403. }
  4404. if (len === 0) {
  4405. this.valType = valType;
  4406. }
  4407. else if (valType !== this.valType || valType === VALUE_TYPE_UNKOWN) {
  4408. discrete = true;
  4409. }
  4410. this.discrete = this.discrete || discrete;
  4411. var kf = {
  4412. time: time,
  4413. value: value,
  4414. rawValue: rawValue,
  4415. percent: 0
  4416. };
  4417. if (easing) {
  4418. kf.easing = easing;
  4419. kf.easingFunc = isFunction(easing)
  4420. ? easing
  4421. : easingFuncs[easing] || createCubicEasingFunc(easing);
  4422. }
  4423. keyframes.push(kf);
  4424. return kf;
  4425. };
  4426. Track.prototype.prepare = function (maxTime, additiveTrack) {
  4427. var kfs = this.keyframes;
  4428. if (this._needsSort) {
  4429. kfs.sort(function (a, b) {
  4430. return a.time - b.time;
  4431. });
  4432. }
  4433. var valType = this.valType;
  4434. var kfsLen = kfs.length;
  4435. var lastKf = kfs[kfsLen - 1];
  4436. var isDiscrete = this.discrete;
  4437. var isArr = isArrayValueType(valType);
  4438. var isGradient = isGradientValueType(valType);
  4439. for (var i = 0; i < kfsLen; i++) {
  4440. var kf = kfs[i];
  4441. var value = kf.value;
  4442. var lastValue = lastKf.value;
  4443. kf.percent = kf.time / maxTime;
  4444. if (!isDiscrete) {
  4445. if (isArr && i !== kfsLen - 1) {
  4446. fillArray(value, lastValue, valType);
  4447. }
  4448. else if (isGradient) {
  4449. fillColorStops(value.colorStops, lastValue.colorStops);
  4450. }
  4451. }
  4452. }
  4453. if (!isDiscrete
  4454. && valType !== VALUE_TYPE_RADIAL_GRADIENT
  4455. && additiveTrack
  4456. && this.needsAnimate()
  4457. && additiveTrack.needsAnimate()
  4458. && valType === additiveTrack.valType
  4459. && !additiveTrack._finished) {
  4460. this._additiveTrack = additiveTrack;
  4461. var startValue = kfs[0].value;
  4462. for (var i = 0; i < kfsLen; i++) {
  4463. if (valType === VALUE_TYPE_NUMBER) {
  4464. kfs[i].additiveValue = kfs[i].value - startValue;
  4465. }
  4466. else if (valType === VALUE_TYPE_COLOR) {
  4467. kfs[i].additiveValue =
  4468. add1DArray([], kfs[i].value, startValue, -1);
  4469. }
  4470. else if (isArrayValueType(valType)) {
  4471. kfs[i].additiveValue = valType === VALUE_TYPE_1D_ARRAY
  4472. ? add1DArray([], kfs[i].value, startValue, -1)
  4473. : add2DArray([], kfs[i].value, startValue, -1);
  4474. }
  4475. }
  4476. }
  4477. };
  4478. Track.prototype.step = function (target, percent) {
  4479. if (this._finished) {
  4480. return;
  4481. }
  4482. if (this._additiveTrack && this._additiveTrack._finished) {
  4483. this._additiveTrack = null;
  4484. }
  4485. var isAdditive = this._additiveTrack != null;
  4486. var valueKey = isAdditive ? 'additiveValue' : 'value';
  4487. var valType = this.valType;
  4488. var keyframes = this.keyframes;
  4489. var kfsNum = keyframes.length;
  4490. var propName = this.propName;
  4491. var isValueColor = valType === VALUE_TYPE_COLOR;
  4492. var frameIdx;
  4493. var lastFrame = this._lastFr;
  4494. var mathMin = Math.min;
  4495. var frame;
  4496. var nextFrame;
  4497. if (kfsNum === 1) {
  4498. frame = nextFrame = keyframes[0];
  4499. }
  4500. else {
  4501. if (percent < 0) {
  4502. frameIdx = 0;
  4503. }
  4504. else if (percent < this._lastFrP) {
  4505. var start = mathMin(lastFrame + 1, kfsNum - 1);
  4506. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  4507. if (keyframes[frameIdx].percent <= percent) {
  4508. break;
  4509. }
  4510. }
  4511. frameIdx = mathMin(frameIdx, kfsNum - 2);
  4512. }
  4513. else {
  4514. for (frameIdx = lastFrame; frameIdx < kfsNum; frameIdx++) {
  4515. if (keyframes[frameIdx].percent > percent) {
  4516. break;
  4517. }
  4518. }
  4519. frameIdx = mathMin(frameIdx - 1, kfsNum - 2);
  4520. }
  4521. nextFrame = keyframes[frameIdx + 1];
  4522. frame = keyframes[frameIdx];
  4523. }
  4524. if (!(frame && nextFrame)) {
  4525. return;
  4526. }
  4527. this._lastFr = frameIdx;
  4528. this._lastFrP = percent;
  4529. var interval = (nextFrame.percent - frame.percent);
  4530. var w = interval === 0 ? 1 : mathMin((percent - frame.percent) / interval, 1);
  4531. if (nextFrame.easingFunc) {
  4532. w = nextFrame.easingFunc(w);
  4533. }
  4534. var targetArr = isAdditive ? this._additiveValue
  4535. : (isValueColor ? tmpRgba : target[propName]);
  4536. if ((isArrayValueType(valType) || isValueColor) && !targetArr) {
  4537. targetArr = this._additiveValue = [];
  4538. }
  4539. if (this.discrete) {
  4540. target[propName] = w < 1 ? frame.rawValue : nextFrame.rawValue;
  4541. }
  4542. else if (isArrayValueType(valType)) {
  4543. valType === VALUE_TYPE_1D_ARRAY
  4544. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  4545. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4546. }
  4547. else if (isGradientValueType(valType)) {
  4548. var val = frame[valueKey];
  4549. var nextVal_1 = nextFrame[valueKey];
  4550. var isLinearGradient_1 = valType === VALUE_TYPE_LINEAR_GRADIENT;
  4551. target[propName] = {
  4552. type: isLinearGradient_1 ? 'linear' : 'radial',
  4553. x: interpolateNumber(val.x, nextVal_1.x, w),
  4554. y: interpolateNumber(val.y, nextVal_1.y, w),
  4555. colorStops: map(val.colorStops, function (colorStop, idx) {
  4556. var nextColorStop = nextVal_1.colorStops[idx];
  4557. return {
  4558. offset: interpolateNumber(colorStop.offset, nextColorStop.offset, w),
  4559. color: rgba2String(interpolate1DArray([], colorStop.color, nextColorStop.color, w))
  4560. };
  4561. }),
  4562. global: nextVal_1.global
  4563. };
  4564. if (isLinearGradient_1) {
  4565. target[propName].x2 = interpolateNumber(val.x2, nextVal_1.x2, w);
  4566. target[propName].y2 = interpolateNumber(val.y2, nextVal_1.y2, w);
  4567. }
  4568. else {
  4569. target[propName].r = interpolateNumber(val.r, nextVal_1.r, w);
  4570. }
  4571. }
  4572. else if (isValueColor) {
  4573. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  4574. if (!isAdditive) {
  4575. target[propName] = rgba2String(targetArr);
  4576. }
  4577. }
  4578. else {
  4579. var value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  4580. if (isAdditive) {
  4581. this._additiveValue = value;
  4582. }
  4583. else {
  4584. target[propName] = value;
  4585. }
  4586. }
  4587. if (isAdditive) {
  4588. this._addToTarget(target);
  4589. }
  4590. };
  4591. Track.prototype._addToTarget = function (target) {
  4592. var valType = this.valType;
  4593. var propName = this.propName;
  4594. var additiveValue = this._additiveValue;
  4595. if (valType === VALUE_TYPE_NUMBER) {
  4596. target[propName] = target[propName] + additiveValue;
  4597. }
  4598. else if (valType === VALUE_TYPE_COLOR) {
  4599. parse(target[propName], tmpRgba);
  4600. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  4601. target[propName] = rgba2String(tmpRgba);
  4602. }
  4603. else if (valType === VALUE_TYPE_1D_ARRAY) {
  4604. add1DArray(target[propName], target[propName], additiveValue, 1);
  4605. }
  4606. else if (valType === VALUE_TYPE_2D_ARRAY) {
  4607. add2DArray(target[propName], target[propName], additiveValue, 1);
  4608. }
  4609. };
  4610. return Track;
  4611. }());
  4612. var Animator = (function () {
  4613. function Animator(target, loop, allowDiscreteAnimation, additiveTo) {
  4614. this._tracks = {};
  4615. this._trackKeys = [];
  4616. this._maxTime = 0;
  4617. this._started = 0;
  4618. this._clip = null;
  4619. this._target = target;
  4620. this._loop = loop;
  4621. if (loop && additiveTo) {
  4622. logError('Can\' use additive animation on looped animation.');
  4623. return;
  4624. }
  4625. this._additiveAnimators = additiveTo;
  4626. this._allowDiscrete = allowDiscreteAnimation;
  4627. }
  4628. Animator.prototype.getMaxTime = function () {
  4629. return this._maxTime;
  4630. };
  4631. Animator.prototype.getDelay = function () {
  4632. return this._delay;
  4633. };
  4634. Animator.prototype.getLoop = function () {
  4635. return this._loop;
  4636. };
  4637. Animator.prototype.getTarget = function () {
  4638. return this._target;
  4639. };
  4640. Animator.prototype.changeTarget = function (target) {
  4641. this._target = target;
  4642. };
  4643. Animator.prototype.when = function (time, props, easing) {
  4644. return this.whenWithKeys(time, props, keys(props), easing);
  4645. };
  4646. Animator.prototype.whenWithKeys = function (time, props, propNames, easing) {
  4647. var tracks = this._tracks;
  4648. for (var i = 0; i < propNames.length; i++) {
  4649. var propName = propNames[i];
  4650. var track = tracks[propName];
  4651. if (!track) {
  4652. track = tracks[propName] = new Track(propName);
  4653. var initialValue = void 0;
  4654. var additiveTrack = this._getAdditiveTrack(propName);
  4655. if (additiveTrack) {
  4656. var addtiveTrackKfs = additiveTrack.keyframes;
  4657. var lastFinalKf = addtiveTrackKfs[addtiveTrackKfs.length - 1];
  4658. initialValue = lastFinalKf && lastFinalKf.value;
  4659. if (additiveTrack.valType === VALUE_TYPE_COLOR && initialValue) {
  4660. initialValue = rgba2String(initialValue);
  4661. }
  4662. }
  4663. else {
  4664. initialValue = this._target[propName];
  4665. }
  4666. if (initialValue == null) {
  4667. continue;
  4668. }
  4669. if (time > 0) {
  4670. track.addKeyframe(0, cloneValue(initialValue), easing);
  4671. }
  4672. this._trackKeys.push(propName);
  4673. }
  4674. track.addKeyframe(time, cloneValue(props[propName]), easing);
  4675. }
  4676. this._maxTime = Math.max(this._maxTime, time);
  4677. return this;
  4678. };
  4679. Animator.prototype.pause = function () {
  4680. this._clip.pause();
  4681. this._paused = true;
  4682. };
  4683. Animator.prototype.resume = function () {
  4684. this._clip.resume();
  4685. this._paused = false;
  4686. };
  4687. Animator.prototype.isPaused = function () {
  4688. return !!this._paused;
  4689. };
  4690. Animator.prototype.duration = function (duration) {
  4691. this._maxTime = duration;
  4692. this._force = true;
  4693. return this;
  4694. };
  4695. Animator.prototype._doneCallback = function () {
  4696. this._setTracksFinished();
  4697. this._clip = null;
  4698. var doneList = this._doneCbs;
  4699. if (doneList) {
  4700. var len = doneList.length;
  4701. for (var i = 0; i < len; i++) {
  4702. doneList[i].call(this);
  4703. }
  4704. }
  4705. };
  4706. Animator.prototype._abortedCallback = function () {
  4707. this._setTracksFinished();
  4708. var animation = this.animation;
  4709. var abortedList = this._abortedCbs;
  4710. if (animation) {
  4711. animation.removeClip(this._clip);
  4712. }
  4713. this._clip = null;
  4714. if (abortedList) {
  4715. for (var i = 0; i < abortedList.length; i++) {
  4716. abortedList[i].call(this);
  4717. }
  4718. }
  4719. };
  4720. Animator.prototype._setTracksFinished = function () {
  4721. var tracks = this._tracks;
  4722. var tracksKeys = this._trackKeys;
  4723. for (var i = 0; i < tracksKeys.length; i++) {
  4724. tracks[tracksKeys[i]].setFinished();
  4725. }
  4726. };
  4727. Animator.prototype._getAdditiveTrack = function (trackName) {
  4728. var additiveTrack;
  4729. var additiveAnimators = this._additiveAnimators;
  4730. if (additiveAnimators) {
  4731. for (var i = 0; i < additiveAnimators.length; i++) {
  4732. var track = additiveAnimators[i].getTrack(trackName);
  4733. if (track) {
  4734. additiveTrack = track;
  4735. }
  4736. }
  4737. }
  4738. return additiveTrack;
  4739. };
  4740. Animator.prototype.start = function (easing) {
  4741. if (this._started > 0) {
  4742. return;
  4743. }
  4744. this._started = 1;
  4745. var self = this;
  4746. var tracks = [];
  4747. var maxTime = this._maxTime || 0;
  4748. for (var i = 0; i < this._trackKeys.length; i++) {
  4749. var propName = this._trackKeys[i];
  4750. var track = this._tracks[propName];
  4751. var additiveTrack = this._getAdditiveTrack(propName);
  4752. var kfs = track.keyframes;
  4753. var kfsNum = kfs.length;
  4754. track.prepare(maxTime, additiveTrack);
  4755. if (track.needsAnimate()) {
  4756. if (!this._allowDiscrete && track.discrete) {
  4757. var lastKf = kfs[kfsNum - 1];
  4758. if (lastKf) {
  4759. self._target[track.propName] = lastKf.rawValue;
  4760. }
  4761. track.setFinished();
  4762. }
  4763. else {
  4764. tracks.push(track);
  4765. }
  4766. }
  4767. }
  4768. if (tracks.length || this._force) {
  4769. var clip = new Clip({
  4770. life: maxTime,
  4771. loop: this._loop,
  4772. delay: this._delay || 0,
  4773. onframe: function (percent) {
  4774. self._started = 2;
  4775. var additiveAnimators = self._additiveAnimators;
  4776. if (additiveAnimators) {
  4777. var stillHasAdditiveAnimator = false;
  4778. for (var i = 0; i < additiveAnimators.length; i++) {
  4779. if (additiveAnimators[i]._clip) {
  4780. stillHasAdditiveAnimator = true;
  4781. break;
  4782. }
  4783. }
  4784. if (!stillHasAdditiveAnimator) {
  4785. self._additiveAnimators = null;
  4786. }
  4787. }
  4788. for (var i = 0; i < tracks.length; i++) {
  4789. tracks[i].step(self._target, percent);
  4790. }
  4791. var onframeList = self._onframeCbs;
  4792. if (onframeList) {
  4793. for (var i = 0; i < onframeList.length; i++) {
  4794. onframeList[i](self._target, percent);
  4795. }
  4796. }
  4797. },
  4798. ondestroy: function () {
  4799. self._doneCallback();
  4800. }
  4801. });
  4802. this._clip = clip;
  4803. if (this.animation) {
  4804. this.animation.addClip(clip);
  4805. }
  4806. if (easing) {
  4807. clip.setEasing(easing);
  4808. }
  4809. }
  4810. else {
  4811. this._doneCallback();
  4812. }
  4813. return this;
  4814. };
  4815. Animator.prototype.stop = function (forwardToLast) {
  4816. if (!this._clip) {
  4817. return;
  4818. }
  4819. var clip = this._clip;
  4820. if (forwardToLast) {
  4821. clip.onframe(1);
  4822. }
  4823. this._abortedCallback();
  4824. };
  4825. Animator.prototype.delay = function (time) {
  4826. this._delay = time;
  4827. return this;
  4828. };
  4829. Animator.prototype.during = function (cb) {
  4830. if (cb) {
  4831. if (!this._onframeCbs) {
  4832. this._onframeCbs = [];
  4833. }
  4834. this._onframeCbs.push(cb);
  4835. }
  4836. return this;
  4837. };
  4838. Animator.prototype.done = function (cb) {
  4839. if (cb) {
  4840. if (!this._doneCbs) {
  4841. this._doneCbs = [];
  4842. }
  4843. this._doneCbs.push(cb);
  4844. }
  4845. return this;
  4846. };
  4847. Animator.prototype.aborted = function (cb) {
  4848. if (cb) {
  4849. if (!this._abortedCbs) {
  4850. this._abortedCbs = [];
  4851. }
  4852. this._abortedCbs.push(cb);
  4853. }
  4854. return this;
  4855. };
  4856. Animator.prototype.getClip = function () {
  4857. return this._clip;
  4858. };
  4859. Animator.prototype.getTrack = function (propName) {
  4860. return this._tracks[propName];
  4861. };
  4862. Animator.prototype.getTracks = function () {
  4863. var _this = this;
  4864. return map(this._trackKeys, function (key) { return _this._tracks[key]; });
  4865. };
  4866. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  4867. if (!propNames.length || !this._clip) {
  4868. return true;
  4869. }
  4870. var tracks = this._tracks;
  4871. var tracksKeys = this._trackKeys;
  4872. for (var i = 0; i < propNames.length; i++) {
  4873. var track = tracks[propNames[i]];
  4874. if (track && !track.isFinished()) {
  4875. if (forwardToLast) {
  4876. track.step(this._target, 1);
  4877. }
  4878. else if (this._started === 1) {
  4879. track.step(this._target, 0);
  4880. }
  4881. track.setFinished();
  4882. }
  4883. }
  4884. var allAborted = true;
  4885. for (var i = 0; i < tracksKeys.length; i++) {
  4886. if (!tracks[tracksKeys[i]].isFinished()) {
  4887. allAborted = false;
  4888. break;
  4889. }
  4890. }
  4891. if (allAborted) {
  4892. this._abortedCallback();
  4893. }
  4894. return allAborted;
  4895. };
  4896. Animator.prototype.saveTo = function (target, trackKeys, firstOrLast) {
  4897. if (!target) {
  4898. return;
  4899. }
  4900. trackKeys = trackKeys || this._trackKeys;
  4901. for (var i = 0; i < trackKeys.length; i++) {
  4902. var propName = trackKeys[i];
  4903. var track = this._tracks[propName];
  4904. if (!track || track.isFinished()) {
  4905. continue;
  4906. }
  4907. var kfs = track.keyframes;
  4908. var kf = kfs[firstOrLast ? 0 : kfs.length - 1];
  4909. if (kf) {
  4910. target[propName] = cloneValue(kf.rawValue);
  4911. }
  4912. }
  4913. };
  4914. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  4915. trackKeys = trackKeys || keys(finalProps);
  4916. for (var i = 0; i < trackKeys.length; i++) {
  4917. var propName = trackKeys[i];
  4918. var track = this._tracks[propName];
  4919. if (!track) {
  4920. continue;
  4921. }
  4922. var kfs = track.keyframes;
  4923. if (kfs.length > 1) {
  4924. var lastKf = kfs.pop();
  4925. track.addKeyframe(lastKf.time, finalProps[propName]);
  4926. track.prepare(this._maxTime, track.getAdditiveTrack());
  4927. }
  4928. }
  4929. };
  4930. return Animator;
  4931. }());
  4932. function getTime() {
  4933. return new Date().getTime();
  4934. }
  4935. var Animation = (function (_super) {
  4936. __extends(Animation, _super);
  4937. function Animation(opts) {
  4938. var _this = _super.call(this) || this;
  4939. _this._running = false;
  4940. _this._time = 0;
  4941. _this._pausedTime = 0;
  4942. _this._pauseStart = 0;
  4943. _this._paused = false;
  4944. opts = opts || {};
  4945. _this.stage = opts.stage || {};
  4946. return _this;
  4947. }
  4948. Animation.prototype.addClip = function (clip) {
  4949. if (clip.animation) {
  4950. this.removeClip(clip);
  4951. }
  4952. if (!this._head) {
  4953. this._head = this._tail = clip;
  4954. }
  4955. else {
  4956. this._tail.next = clip;
  4957. clip.prev = this._tail;
  4958. clip.next = null;
  4959. this._tail = clip;
  4960. }
  4961. clip.animation = this;
  4962. };
  4963. Animation.prototype.addAnimator = function (animator) {
  4964. animator.animation = this;
  4965. var clip = animator.getClip();
  4966. if (clip) {
  4967. this.addClip(clip);
  4968. }
  4969. };
  4970. Animation.prototype.removeClip = function (clip) {
  4971. if (!clip.animation) {
  4972. return;
  4973. }
  4974. var prev = clip.prev;
  4975. var next = clip.next;
  4976. if (prev) {
  4977. prev.next = next;
  4978. }
  4979. else {
  4980. this._head = next;
  4981. }
  4982. if (next) {
  4983. next.prev = prev;
  4984. }
  4985. else {
  4986. this._tail = prev;
  4987. }
  4988. clip.next = clip.prev = clip.animation = null;
  4989. };
  4990. Animation.prototype.removeAnimator = function (animator) {
  4991. var clip = animator.getClip();
  4992. if (clip) {
  4993. this.removeClip(clip);
  4994. }
  4995. animator.animation = null;
  4996. };
  4997. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  4998. var time = getTime() - this._pausedTime;
  4999. var delta = time - this._time;
  5000. var clip = this._head;
  5001. while (clip) {
  5002. var nextClip = clip.next;
  5003. var finished = clip.step(time, delta);
  5004. if (finished) {
  5005. clip.ondestroy();
  5006. this.removeClip(clip);
  5007. clip = nextClip;
  5008. }
  5009. else {
  5010. clip = nextClip;
  5011. }
  5012. }
  5013. this._time = time;
  5014. if (!notTriggerFrameAndStageUpdate) {
  5015. this.trigger('frame', delta);
  5016. this.stage.update && this.stage.update();
  5017. }
  5018. };
  5019. Animation.prototype._startLoop = function () {
  5020. var self = this;
  5021. this._running = true;
  5022. function step() {
  5023. if (self._running) {
  5024. requestAnimationFrame$1(step);
  5025. !self._paused && self.update();
  5026. }
  5027. }
  5028. requestAnimationFrame$1(step);
  5029. };
  5030. Animation.prototype.start = function () {
  5031. if (this._running) {
  5032. return;
  5033. }
  5034. this._time = getTime();
  5035. this._pausedTime = 0;
  5036. this._startLoop();
  5037. };
  5038. Animation.prototype.stop = function () {
  5039. this._running = false;
  5040. };
  5041. Animation.prototype.pause = function () {
  5042. if (!this._paused) {
  5043. this._pauseStart = getTime();
  5044. this._paused = true;
  5045. }
  5046. };
  5047. Animation.prototype.resume = function () {
  5048. if (this._paused) {
  5049. this._pausedTime += getTime() - this._pauseStart;
  5050. this._paused = false;
  5051. }
  5052. };
  5053. Animation.prototype.clear = function () {
  5054. var clip = this._head;
  5055. while (clip) {
  5056. var nextClip = clip.next;
  5057. clip.prev = clip.next = clip.animation = null;
  5058. clip = nextClip;
  5059. }
  5060. this._head = this._tail = null;
  5061. };
  5062. Animation.prototype.isFinished = function () {
  5063. return this._head == null;
  5064. };
  5065. Animation.prototype.animate = function (target, options) {
  5066. options = options || {};
  5067. this.start();
  5068. var animator = new Animator(target, options.loop);
  5069. this.addAnimator(animator);
  5070. return animator;
  5071. };
  5072. return Animation;
  5073. }(Eventful));
  5074. var TOUCH_CLICK_DELAY = 300;
  5075. var globalEventSupported = env.domSupported;
  5076. var localNativeListenerNames = (function () {
  5077. var mouseHandlerNames = [
  5078. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  5079. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  5080. ];
  5081. var touchHandlerNames = [
  5082. 'touchstart', 'touchend', 'touchmove'
  5083. ];
  5084. var pointerEventNameMap = {
  5085. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  5086. };
  5087. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  5088. var nm = name.replace('mouse', 'pointer');
  5089. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  5090. });
  5091. return {
  5092. mouse: mouseHandlerNames,
  5093. touch: touchHandlerNames,
  5094. pointer: pointerHandlerNames
  5095. };
  5096. })();
  5097. var globalNativeListenerNames = {
  5098. mouse: ['mousemove', 'mouseup'],
  5099. pointer: ['pointermove', 'pointerup']
  5100. };
  5101. var wheelEventSupported = false;
  5102. function isPointerFromTouch(event) {
  5103. var pointerType = event.pointerType;
  5104. return pointerType === 'pen' || pointerType === 'touch';
  5105. }
  5106. function setTouchTimer(scope) {
  5107. scope.touching = true;
  5108. if (scope.touchTimer != null) {
  5109. clearTimeout(scope.touchTimer);
  5110. scope.touchTimer = null;
  5111. }
  5112. scope.touchTimer = setTimeout(function () {
  5113. scope.touching = false;
  5114. scope.touchTimer = null;
  5115. }, 700);
  5116. }
  5117. function markTouch(event) {
  5118. event && (event.zrByTouch = true);
  5119. }
  5120. function normalizeGlobalEvent(instance, event) {
  5121. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5122. }
  5123. function isLocalEl(instance, el) {
  5124. var elTmp = el;
  5125. var isLocal = false;
  5126. while (elTmp && elTmp.nodeType !== 9
  5127. && !(isLocal = elTmp.domBelongToZr
  5128. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5129. elTmp = elTmp.parentNode;
  5130. }
  5131. return isLocal;
  5132. }
  5133. var FakeGlobalEvent = (function () {
  5134. function FakeGlobalEvent(instance, event) {
  5135. this.stopPropagation = noop;
  5136. this.stopImmediatePropagation = noop;
  5137. this.preventDefault = noop;
  5138. this.type = event.type;
  5139. this.target = this.currentTarget = instance.dom;
  5140. this.pointerType = event.pointerType;
  5141. this.clientX = event.clientX;
  5142. this.clientY = event.clientY;
  5143. }
  5144. return FakeGlobalEvent;
  5145. }());
  5146. var localDOMHandlers = {
  5147. mousedown: function (event) {
  5148. event = normalizeEvent(this.dom, event);
  5149. this.__mayPointerCapture = [event.zrX, event.zrY];
  5150. this.trigger('mousedown', event);
  5151. },
  5152. mousemove: function (event) {
  5153. event = normalizeEvent(this.dom, event);
  5154. var downPoint = this.__mayPointerCapture;
  5155. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5156. this.__togglePointerCapture(true);
  5157. }
  5158. this.trigger('mousemove', event);
  5159. },
  5160. mouseup: function (event) {
  5161. event = normalizeEvent(this.dom, event);
  5162. this.__togglePointerCapture(false);
  5163. this.trigger('mouseup', event);
  5164. },
  5165. mouseout: function (event) {
  5166. event = normalizeEvent(this.dom, event);
  5167. var element = event.toElement || event.relatedTarget;
  5168. if (!isLocalEl(this, element)) {
  5169. if (this.__pointerCapturing) {
  5170. event.zrEventControl = 'no_globalout';
  5171. }
  5172. this.trigger('mouseout', event);
  5173. }
  5174. },
  5175. wheel: function (event) {
  5176. wheelEventSupported = true;
  5177. event = normalizeEvent(this.dom, event);
  5178. this.trigger('mousewheel', event);
  5179. },
  5180. mousewheel: function (event) {
  5181. if (wheelEventSupported) {
  5182. return;
  5183. }
  5184. event = normalizeEvent(this.dom, event);
  5185. this.trigger('mousewheel', event);
  5186. },
  5187. touchstart: function (event) {
  5188. event = normalizeEvent(this.dom, event);
  5189. markTouch(event);
  5190. this.__lastTouchMoment = new Date();
  5191. this.handler.processGesture(event, 'start');
  5192. localDOMHandlers.mousemove.call(this, event);
  5193. localDOMHandlers.mousedown.call(this, event);
  5194. },
  5195. touchmove: function (event) {
  5196. event = normalizeEvent(this.dom, event);
  5197. markTouch(event);
  5198. this.handler.processGesture(event, 'change');
  5199. localDOMHandlers.mousemove.call(this, event);
  5200. },
  5201. touchend: function (event) {
  5202. event = normalizeEvent(this.dom, event);
  5203. markTouch(event);
  5204. this.handler.processGesture(event, 'end');
  5205. localDOMHandlers.mouseup.call(this, event);
  5206. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5207. localDOMHandlers.click.call(this, event);
  5208. }
  5209. },
  5210. pointerdown: function (event) {
  5211. localDOMHandlers.mousedown.call(this, event);
  5212. },
  5213. pointermove: function (event) {
  5214. if (!isPointerFromTouch(event)) {
  5215. localDOMHandlers.mousemove.call(this, event);
  5216. }
  5217. },
  5218. pointerup: function (event) {
  5219. localDOMHandlers.mouseup.call(this, event);
  5220. },
  5221. pointerout: function (event) {
  5222. if (!isPointerFromTouch(event)) {
  5223. localDOMHandlers.mouseout.call(this, event);
  5224. }
  5225. }
  5226. };
  5227. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5228. localDOMHandlers[name] = function (event) {
  5229. event = normalizeEvent(this.dom, event);
  5230. this.trigger(name, event);
  5231. };
  5232. });
  5233. var globalDOMHandlers = {
  5234. pointermove: function (event) {
  5235. if (!isPointerFromTouch(event)) {
  5236. globalDOMHandlers.mousemove.call(this, event);
  5237. }
  5238. },
  5239. pointerup: function (event) {
  5240. globalDOMHandlers.mouseup.call(this, event);
  5241. },
  5242. mousemove: function (event) {
  5243. this.trigger('mousemove', event);
  5244. },
  5245. mouseup: function (event) {
  5246. var pointerCaptureReleasing = this.__pointerCapturing;
  5247. this.__togglePointerCapture(false);
  5248. this.trigger('mouseup', event);
  5249. if (pointerCaptureReleasing) {
  5250. event.zrEventControl = 'only_globalout';
  5251. this.trigger('mouseout', event);
  5252. }
  5253. }
  5254. };
  5255. function mountLocalDOMEventListeners(instance, scope) {
  5256. var domHandlers = scope.domHandlers;
  5257. if (env.pointerEventsSupported) {
  5258. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5259. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5260. domHandlers[nativeEventName].call(instance, event);
  5261. });
  5262. });
  5263. }
  5264. else {
  5265. if (env.touchEventsSupported) {
  5266. each(localNativeListenerNames.touch, function (nativeEventName) {
  5267. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5268. domHandlers[nativeEventName].call(instance, event);
  5269. setTouchTimer(scope);
  5270. });
  5271. });
  5272. }
  5273. each(localNativeListenerNames.mouse, function (nativeEventName) {
  5274. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5275. event = getNativeEvent(event);
  5276. if (!scope.touching) {
  5277. domHandlers[nativeEventName].call(instance, event);
  5278. }
  5279. });
  5280. });
  5281. }
  5282. }
  5283. function mountGlobalDOMEventListeners(instance, scope) {
  5284. if (env.pointerEventsSupported) {
  5285. each(globalNativeListenerNames.pointer, mount);
  5286. }
  5287. else if (!env.touchEventsSupported) {
  5288. each(globalNativeListenerNames.mouse, mount);
  5289. }
  5290. function mount(nativeEventName) {
  5291. function nativeEventListener(event) {
  5292. event = getNativeEvent(event);
  5293. if (!isLocalEl(instance, event.target)) {
  5294. event = normalizeGlobalEvent(instance, event);
  5295. scope.domHandlers[nativeEventName].call(instance, event);
  5296. }
  5297. }
  5298. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  5299. }
  5300. }
  5301. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  5302. scope.mounted[nativeEventName] = listener;
  5303. scope.listenerOpts[nativeEventName] = opt;
  5304. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  5305. }
  5306. function unmountDOMEventListeners(scope) {
  5307. var mounted = scope.mounted;
  5308. for (var nativeEventName in mounted) {
  5309. if (mounted.hasOwnProperty(nativeEventName)) {
  5310. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  5311. }
  5312. }
  5313. scope.mounted = {};
  5314. }
  5315. var DOMHandlerScope = (function () {
  5316. function DOMHandlerScope(domTarget, domHandlers) {
  5317. this.mounted = {};
  5318. this.listenerOpts = {};
  5319. this.touching = false;
  5320. this.domTarget = domTarget;
  5321. this.domHandlers = domHandlers;
  5322. }
  5323. return DOMHandlerScope;
  5324. }());
  5325. var HandlerDomProxy = (function (_super) {
  5326. __extends(HandlerDomProxy, _super);
  5327. function HandlerDomProxy(dom, painterRoot) {
  5328. var _this = _super.call(this) || this;
  5329. _this.__pointerCapturing = false;
  5330. _this.dom = dom;
  5331. _this.painterRoot = painterRoot;
  5332. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  5333. if (globalEventSupported) {
  5334. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  5335. }
  5336. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  5337. return _this;
  5338. }
  5339. HandlerDomProxy.prototype.dispose = function () {
  5340. unmountDOMEventListeners(this._localHandlerScope);
  5341. if (globalEventSupported) {
  5342. unmountDOMEventListeners(this._globalHandlerScope);
  5343. }
  5344. };
  5345. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  5346. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  5347. };
  5348. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  5349. this.__mayPointerCapture = null;
  5350. if (globalEventSupported
  5351. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  5352. this.__pointerCapturing = isPointerCapturing;
  5353. var globalHandlerScope = this._globalHandlerScope;
  5354. isPointerCapturing
  5355. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  5356. : unmountDOMEventListeners(globalHandlerScope);
  5357. }
  5358. };
  5359. return HandlerDomProxy;
  5360. }(Eventful));
  5361. var dpr = 1;
  5362. if (env.hasGlobalWindow) {
  5363. dpr = Math.max(window.devicePixelRatio
  5364. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  5365. || 1, 1);
  5366. }
  5367. var devicePixelRatio = dpr;
  5368. var DARK_MODE_THRESHOLD = 0.4;
  5369. var DARK_LABEL_COLOR = '#333';
  5370. var LIGHT_LABEL_COLOR = '#ccc';
  5371. var LIGHTER_LABEL_COLOR = '#eee';
  5372. var mIdentity = identity;
  5373. var EPSILON$2 = 5e-5;
  5374. function isNotAroundZero$1(val) {
  5375. return val > EPSILON$2 || val < -EPSILON$2;
  5376. }
  5377. var scaleTmp = [];
  5378. var tmpTransform = [];
  5379. var originTransform = create$1();
  5380. var abs = Math.abs;
  5381. var Transformable = (function () {
  5382. function Transformable() {
  5383. }
  5384. Transformable.prototype.getLocalTransform = function (m) {
  5385. return Transformable.getLocalTransform(this, m);
  5386. };
  5387. Transformable.prototype.setPosition = function (arr) {
  5388. this.x = arr[0];
  5389. this.y = arr[1];
  5390. };
  5391. Transformable.prototype.setScale = function (arr) {
  5392. this.scaleX = arr[0];
  5393. this.scaleY = arr[1];
  5394. };
  5395. Transformable.prototype.setSkew = function (arr) {
  5396. this.skewX = arr[0];
  5397. this.skewY = arr[1];
  5398. };
  5399. Transformable.prototype.setOrigin = function (arr) {
  5400. this.originX = arr[0];
  5401. this.originY = arr[1];
  5402. };
  5403. Transformable.prototype.needLocalTransform = function () {
  5404. return isNotAroundZero$1(this.rotation)
  5405. || isNotAroundZero$1(this.x)
  5406. || isNotAroundZero$1(this.y)
  5407. || isNotAroundZero$1(this.scaleX - 1)
  5408. || isNotAroundZero$1(this.scaleY - 1)
  5409. || isNotAroundZero$1(this.skewX)
  5410. || isNotAroundZero$1(this.skewY);
  5411. };
  5412. Transformable.prototype.updateTransform = function () {
  5413. var parentTransform = this.parent && this.parent.transform;
  5414. var needLocalTransform = this.needLocalTransform();
  5415. var m = this.transform;
  5416. if (!(needLocalTransform || parentTransform)) {
  5417. m && mIdentity(m);
  5418. return;
  5419. }
  5420. m = m || create$1();
  5421. if (needLocalTransform) {
  5422. this.getLocalTransform(m);
  5423. }
  5424. else {
  5425. mIdentity(m);
  5426. }
  5427. if (parentTransform) {
  5428. if (needLocalTransform) {
  5429. mul$1(m, parentTransform, m);
  5430. }
  5431. else {
  5432. copy$1(m, parentTransform);
  5433. }
  5434. }
  5435. this.transform = m;
  5436. this._resolveGlobalScaleRatio(m);
  5437. };
  5438. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  5439. var globalScaleRatio = this.globalScaleRatio;
  5440. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  5441. this.getGlobalScale(scaleTmp);
  5442. var relX = scaleTmp[0] < 0 ? -1 : 1;
  5443. var relY = scaleTmp[1] < 0 ? -1 : 1;
  5444. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  5445. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  5446. m[0] *= sx;
  5447. m[1] *= sx;
  5448. m[2] *= sy;
  5449. m[3] *= sy;
  5450. }
  5451. this.invTransform = this.invTransform || create$1();
  5452. invert(this.invTransform, m);
  5453. };
  5454. Transformable.prototype.getComputedTransform = function () {
  5455. var transformNode = this;
  5456. var ancestors = [];
  5457. while (transformNode) {
  5458. ancestors.push(transformNode);
  5459. transformNode = transformNode.parent;
  5460. }
  5461. while (transformNode = ancestors.pop()) {
  5462. transformNode.updateTransform();
  5463. }
  5464. return this.transform;
  5465. };
  5466. Transformable.prototype.setLocalTransform = function (m) {
  5467. if (!m) {
  5468. return;
  5469. }
  5470. var sx = m[0] * m[0] + m[1] * m[1];
  5471. var sy = m[2] * m[2] + m[3] * m[3];
  5472. var rotation = Math.atan2(m[1], m[0]);
  5473. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  5474. sy = Math.sqrt(sy) * Math.cos(shearX);
  5475. sx = Math.sqrt(sx);
  5476. this.skewX = shearX;
  5477. this.skewY = 0;
  5478. this.rotation = -rotation;
  5479. this.x = +m[4];
  5480. this.y = +m[5];
  5481. this.scaleX = sx;
  5482. this.scaleY = sy;
  5483. this.originX = 0;
  5484. this.originY = 0;
  5485. };
  5486. Transformable.prototype.decomposeTransform = function () {
  5487. if (!this.transform) {
  5488. return;
  5489. }
  5490. var parent = this.parent;
  5491. var m = this.transform;
  5492. if (parent && parent.transform) {
  5493. mul$1(tmpTransform, parent.invTransform, m);
  5494. m = tmpTransform;
  5495. }
  5496. var ox = this.originX;
  5497. var oy = this.originY;
  5498. if (ox || oy) {
  5499. originTransform[4] = ox;
  5500. originTransform[5] = oy;
  5501. mul$1(tmpTransform, m, originTransform);
  5502. tmpTransform[4] -= ox;
  5503. tmpTransform[5] -= oy;
  5504. m = tmpTransform;
  5505. }
  5506. this.setLocalTransform(m);
  5507. };
  5508. Transformable.prototype.getGlobalScale = function (out) {
  5509. var m = this.transform;
  5510. out = out || [];
  5511. if (!m) {
  5512. out[0] = 1;
  5513. out[1] = 1;
  5514. return out;
  5515. }
  5516. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  5517. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  5518. if (m[0] < 0) {
  5519. out[0] = -out[0];
  5520. }
  5521. if (m[3] < 0) {
  5522. out[1] = -out[1];
  5523. }
  5524. return out;
  5525. };
  5526. Transformable.prototype.transformCoordToLocal = function (x, y) {
  5527. var v2 = [x, y];
  5528. var invTransform = this.invTransform;
  5529. if (invTransform) {
  5530. applyTransform(v2, v2, invTransform);
  5531. }
  5532. return v2;
  5533. };
  5534. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  5535. var v2 = [x, y];
  5536. var transform = this.transform;
  5537. if (transform) {
  5538. applyTransform(v2, v2, transform);
  5539. }
  5540. return v2;
  5541. };
  5542. Transformable.prototype.getLineScale = function () {
  5543. var m = this.transform;
  5544. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  5545. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  5546. : 1;
  5547. };
  5548. Transformable.prototype.copyTransform = function (source) {
  5549. copyTransform(this, source);
  5550. };
  5551. Transformable.getLocalTransform = function (target, m) {
  5552. m = m || [];
  5553. var ox = target.originX || 0;
  5554. var oy = target.originY || 0;
  5555. var sx = target.scaleX;
  5556. var sy = target.scaleY;
  5557. var ax = target.anchorX;
  5558. var ay = target.anchorY;
  5559. var rotation = target.rotation || 0;
  5560. var x = target.x;
  5561. var y = target.y;
  5562. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  5563. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  5564. if (ox || oy || ax || ay) {
  5565. var dx = ox + ax;
  5566. var dy = oy + ay;
  5567. m[4] = -dx * sx - skewX * dy * sy;
  5568. m[5] = -dy * sy - skewY * dx * sx;
  5569. }
  5570. else {
  5571. m[4] = m[5] = 0;
  5572. }
  5573. m[0] = sx;
  5574. m[3] = sy;
  5575. m[1] = skewY * sx;
  5576. m[2] = skewX * sy;
  5577. rotation && rotate(m, m, rotation);
  5578. m[4] += ox + x;
  5579. m[5] += oy + y;
  5580. return m;
  5581. };
  5582. Transformable.initDefaultProps = (function () {
  5583. var proto = Transformable.prototype;
  5584. proto.scaleX =
  5585. proto.scaleY =
  5586. proto.globalScaleRatio = 1;
  5587. proto.x =
  5588. proto.y =
  5589. proto.originX =
  5590. proto.originY =
  5591. proto.skewX =
  5592. proto.skewY =
  5593. proto.rotation =
  5594. proto.anchorX =
  5595. proto.anchorY = 0;
  5596. })();
  5597. return Transformable;
  5598. }());
  5599. var TRANSFORMABLE_PROPS = [
  5600. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5601. ];
  5602. function copyTransform(target, source) {
  5603. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5604. var propName = TRANSFORMABLE_PROPS[i];
  5605. target[propName] = source[propName];
  5606. }
  5607. }
  5608. var textWidthCache = {};
  5609. function getWidth(text, font) {
  5610. font = font || DEFAULT_FONT;
  5611. var cacheOfFont = textWidthCache[font];
  5612. if (!cacheOfFont) {
  5613. cacheOfFont = textWidthCache[font] = new LRU(500);
  5614. }
  5615. var width = cacheOfFont.get(text);
  5616. if (width == null) {
  5617. width = platformApi.measureText(text, font).width;
  5618. cacheOfFont.put(text, width);
  5619. }
  5620. return width;
  5621. }
  5622. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5623. var width = getWidth(text, font);
  5624. var height = getLineHeight(font);
  5625. var x = adjustTextX(0, width, textAlign);
  5626. var y = adjustTextY$1(0, height, textBaseline);
  5627. var rect = new BoundingRect(x, y, width, height);
  5628. return rect;
  5629. }
  5630. function getBoundingRect(text, font, textAlign, textBaseline) {
  5631. var textLines = ((text || '') + '').split('\n');
  5632. var len = textLines.length;
  5633. if (len === 1) {
  5634. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5635. }
  5636. else {
  5637. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5638. for (var i = 0; i < textLines.length; i++) {
  5639. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5640. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5641. }
  5642. return uniondRect;
  5643. }
  5644. }
  5645. function adjustTextX(x, width, textAlign) {
  5646. if (textAlign === 'right') {
  5647. x -= width;
  5648. }
  5649. else if (textAlign === 'center') {
  5650. x -= width / 2;
  5651. }
  5652. return x;
  5653. }
  5654. function adjustTextY$1(y, height, verticalAlign) {
  5655. if (verticalAlign === 'middle') {
  5656. y -= height / 2;
  5657. }
  5658. else if (verticalAlign === 'bottom') {
  5659. y -= height;
  5660. }
  5661. return y;
  5662. }
  5663. function getLineHeight(font) {
  5664. return getWidth('国', font);
  5665. }
  5666. function parsePercent(value, maxValue) {
  5667. if (typeof value === 'string') {
  5668. if (value.lastIndexOf('%') >= 0) {
  5669. return parseFloat(value) / 100 * maxValue;
  5670. }
  5671. return parseFloat(value);
  5672. }
  5673. return value;
  5674. }
  5675. function calculateTextPosition(out, opts, rect) {
  5676. var textPosition = opts.position || 'inside';
  5677. var distance = opts.distance != null ? opts.distance : 5;
  5678. var height = rect.height;
  5679. var width = rect.width;
  5680. var halfHeight = height / 2;
  5681. var x = rect.x;
  5682. var y = rect.y;
  5683. var textAlign = 'left';
  5684. var textVerticalAlign = 'top';
  5685. if (textPosition instanceof Array) {
  5686. x += parsePercent(textPosition[0], rect.width);
  5687. y += parsePercent(textPosition[1], rect.height);
  5688. textAlign = null;
  5689. textVerticalAlign = null;
  5690. }
  5691. else {
  5692. switch (textPosition) {
  5693. case 'left':
  5694. x -= distance;
  5695. y += halfHeight;
  5696. textAlign = 'right';
  5697. textVerticalAlign = 'middle';
  5698. break;
  5699. case 'right':
  5700. x += distance + width;
  5701. y += halfHeight;
  5702. textVerticalAlign = 'middle';
  5703. break;
  5704. case 'top':
  5705. x += width / 2;
  5706. y -= distance;
  5707. textAlign = 'center';
  5708. textVerticalAlign = 'bottom';
  5709. break;
  5710. case 'bottom':
  5711. x += width / 2;
  5712. y += height + distance;
  5713. textAlign = 'center';
  5714. break;
  5715. case 'inside':
  5716. x += width / 2;
  5717. y += halfHeight;
  5718. textAlign = 'center';
  5719. textVerticalAlign = 'middle';
  5720. break;
  5721. case 'insideLeft':
  5722. x += distance;
  5723. y += halfHeight;
  5724. textVerticalAlign = 'middle';
  5725. break;
  5726. case 'insideRight':
  5727. x += width - distance;
  5728. y += halfHeight;
  5729. textAlign = 'right';
  5730. textVerticalAlign = 'middle';
  5731. break;
  5732. case 'insideTop':
  5733. x += width / 2;
  5734. y += distance;
  5735. textAlign = 'center';
  5736. break;
  5737. case 'insideBottom':
  5738. x += width / 2;
  5739. y += height - distance;
  5740. textAlign = 'center';
  5741. textVerticalAlign = 'bottom';
  5742. break;
  5743. case 'insideTopLeft':
  5744. x += distance;
  5745. y += distance;
  5746. break;
  5747. case 'insideTopRight':
  5748. x += width - distance;
  5749. y += distance;
  5750. textAlign = 'right';
  5751. break;
  5752. case 'insideBottomLeft':
  5753. x += distance;
  5754. y += height - distance;
  5755. textVerticalAlign = 'bottom';
  5756. break;
  5757. case 'insideBottomRight':
  5758. x += width - distance;
  5759. y += height - distance;
  5760. textAlign = 'right';
  5761. textVerticalAlign = 'bottom';
  5762. break;
  5763. }
  5764. }
  5765. out = out || {};
  5766. out.x = x;
  5767. out.y = y;
  5768. out.align = textAlign;
  5769. out.verticalAlign = textVerticalAlign;
  5770. return out;
  5771. }
  5772. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5773. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5774. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5775. obj[key] = true;
  5776. return obj;
  5777. }, { ignore: false });
  5778. var tmpTextPosCalcRes = {};
  5779. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5780. var Element = (function () {
  5781. function Element(props) {
  5782. this.id = guid();
  5783. this.animators = [];
  5784. this.currentStates = [];
  5785. this.states = {};
  5786. this._init(props);
  5787. }
  5788. Element.prototype._init = function (props) {
  5789. this.attr(props);
  5790. };
  5791. Element.prototype.drift = function (dx, dy, e) {
  5792. switch (this.draggable) {
  5793. case 'horizontal':
  5794. dy = 0;
  5795. break;
  5796. case 'vertical':
  5797. dx = 0;
  5798. break;
  5799. }
  5800. var m = this.transform;
  5801. if (!m) {
  5802. m = this.transform = [1, 0, 0, 1, 0, 0];
  5803. }
  5804. m[4] += dx;
  5805. m[5] += dy;
  5806. this.decomposeTransform();
  5807. this.markRedraw();
  5808. };
  5809. Element.prototype.beforeUpdate = function () { };
  5810. Element.prototype.afterUpdate = function () { };
  5811. Element.prototype.update = function () {
  5812. this.updateTransform();
  5813. if (this.__dirty) {
  5814. this.updateInnerText();
  5815. }
  5816. };
  5817. Element.prototype.updateInnerText = function (forceUpdate) {
  5818. var textEl = this._textContent;
  5819. if (textEl && (!textEl.ignore || forceUpdate)) {
  5820. if (!this.textConfig) {
  5821. this.textConfig = {};
  5822. }
  5823. var textConfig = this.textConfig;
  5824. var isLocal = textConfig.local;
  5825. var innerTransformable = textEl.innerTransformable;
  5826. var textAlign = void 0;
  5827. var textVerticalAlign = void 0;
  5828. var textStyleChanged = false;
  5829. innerTransformable.parent = isLocal ? this : null;
  5830. var innerOrigin = false;
  5831. innerTransformable.copyTransform(textEl);
  5832. if (textConfig.position != null) {
  5833. var layoutRect = tmpBoundingRect;
  5834. if (textConfig.layoutRect) {
  5835. layoutRect.copy(textConfig.layoutRect);
  5836. }
  5837. else {
  5838. layoutRect.copy(this.getBoundingRect());
  5839. }
  5840. if (!isLocal) {
  5841. layoutRect.applyTransform(this.transform);
  5842. }
  5843. if (this.calculateTextPosition) {
  5844. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5845. }
  5846. else {
  5847. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5848. }
  5849. innerTransformable.x = tmpTextPosCalcRes.x;
  5850. innerTransformable.y = tmpTextPosCalcRes.y;
  5851. textAlign = tmpTextPosCalcRes.align;
  5852. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5853. var textOrigin = textConfig.origin;
  5854. if (textOrigin && textConfig.rotation != null) {
  5855. var relOriginX = void 0;
  5856. var relOriginY = void 0;
  5857. if (textOrigin === 'center') {
  5858. relOriginX = layoutRect.width * 0.5;
  5859. relOriginY = layoutRect.height * 0.5;
  5860. }
  5861. else {
  5862. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5863. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5864. }
  5865. innerOrigin = true;
  5866. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5867. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5868. }
  5869. }
  5870. if (textConfig.rotation != null) {
  5871. innerTransformable.rotation = textConfig.rotation;
  5872. }
  5873. var textOffset = textConfig.offset;
  5874. if (textOffset) {
  5875. innerTransformable.x += textOffset[0];
  5876. innerTransformable.y += textOffset[1];
  5877. if (!innerOrigin) {
  5878. innerTransformable.originX = -textOffset[0];
  5879. innerTransformable.originY = -textOffset[1];
  5880. }
  5881. }
  5882. var isInside = textConfig.inside == null
  5883. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5884. : textConfig.inside;
  5885. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5886. var textFill = void 0;
  5887. var textStroke = void 0;
  5888. var autoStroke = void 0;
  5889. if (isInside && this.canBeInsideText()) {
  5890. textFill = textConfig.insideFill;
  5891. textStroke = textConfig.insideStroke;
  5892. if (textFill == null || textFill === 'auto') {
  5893. textFill = this.getInsideTextFill();
  5894. }
  5895. if (textStroke == null || textStroke === 'auto') {
  5896. textStroke = this.getInsideTextStroke(textFill);
  5897. autoStroke = true;
  5898. }
  5899. }
  5900. else {
  5901. textFill = textConfig.outsideFill;
  5902. textStroke = textConfig.outsideStroke;
  5903. if (textFill == null || textFill === 'auto') {
  5904. textFill = this.getOutsideFill();
  5905. }
  5906. if (textStroke == null || textStroke === 'auto') {
  5907. textStroke = this.getOutsideStroke(textFill);
  5908. autoStroke = true;
  5909. }
  5910. }
  5911. textFill = textFill || '#000';
  5912. if (textFill !== innerTextDefaultStyle.fill
  5913. || textStroke !== innerTextDefaultStyle.stroke
  5914. || autoStroke !== innerTextDefaultStyle.autoStroke
  5915. || textAlign !== innerTextDefaultStyle.align
  5916. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5917. textStyleChanged = true;
  5918. innerTextDefaultStyle.fill = textFill;
  5919. innerTextDefaultStyle.stroke = textStroke;
  5920. innerTextDefaultStyle.autoStroke = autoStroke;
  5921. innerTextDefaultStyle.align = textAlign;
  5922. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5923. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5924. }
  5925. textEl.__dirty |= REDRAW_BIT;
  5926. if (textStyleChanged) {
  5927. textEl.dirtyStyle(true);
  5928. }
  5929. }
  5930. };
  5931. Element.prototype.canBeInsideText = function () {
  5932. return true;
  5933. };
  5934. Element.prototype.getInsideTextFill = function () {
  5935. return '#fff';
  5936. };
  5937. Element.prototype.getInsideTextStroke = function (textFill) {
  5938. return '#000';
  5939. };
  5940. Element.prototype.getOutsideFill = function () {
  5941. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5942. };
  5943. Element.prototype.getOutsideStroke = function (textFill) {
  5944. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5945. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5946. if (!colorArr) {
  5947. colorArr = [255, 255, 255, 1];
  5948. }
  5949. var alpha = colorArr[3];
  5950. var isDark = this.__zr.isDarkMode();
  5951. for (var i = 0; i < 3; i++) {
  5952. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5953. }
  5954. colorArr[3] = 1;
  5955. return stringify(colorArr, 'rgba');
  5956. };
  5957. Element.prototype.traverse = function (cb, context) { };
  5958. Element.prototype.attrKV = function (key, value) {
  5959. if (key === 'textConfig') {
  5960. this.setTextConfig(value);
  5961. }
  5962. else if (key === 'textContent') {
  5963. this.setTextContent(value);
  5964. }
  5965. else if (key === 'clipPath') {
  5966. this.setClipPath(value);
  5967. }
  5968. else if (key === 'extra') {
  5969. this.extra = this.extra || {};
  5970. extend(this.extra, value);
  5971. }
  5972. else {
  5973. this[key] = value;
  5974. }
  5975. };
  5976. Element.prototype.hide = function () {
  5977. this.ignore = true;
  5978. this.markRedraw();
  5979. };
  5980. Element.prototype.show = function () {
  5981. this.ignore = false;
  5982. this.markRedraw();
  5983. };
  5984. Element.prototype.attr = function (keyOrObj, value) {
  5985. if (typeof keyOrObj === 'string') {
  5986. this.attrKV(keyOrObj, value);
  5987. }
  5988. else if (isObject(keyOrObj)) {
  5989. var obj = keyOrObj;
  5990. var keysArr = keys(obj);
  5991. for (var i = 0; i < keysArr.length; i++) {
  5992. var key = keysArr[i];
  5993. this.attrKV(key, keyOrObj[key]);
  5994. }
  5995. }
  5996. this.markRedraw();
  5997. return this;
  5998. };
  5999. Element.prototype.saveCurrentToNormalState = function (toState) {
  6000. this._innerSaveToNormal(toState);
  6001. var normalState = this._normalState;
  6002. for (var i = 0; i < this.animators.length; i++) {
  6003. var animator = this.animators[i];
  6004. var fromStateTransition = animator.__fromStateTransition;
  6005. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  6006. continue;
  6007. }
  6008. var targetName = animator.targetName;
  6009. var target = targetName
  6010. ? normalState[targetName] : normalState;
  6011. animator.saveTo(target);
  6012. }
  6013. };
  6014. Element.prototype._innerSaveToNormal = function (toState) {
  6015. var normalState = this._normalState;
  6016. if (!normalState) {
  6017. normalState = this._normalState = {};
  6018. }
  6019. if (toState.textConfig && !normalState.textConfig) {
  6020. normalState.textConfig = this.textConfig;
  6021. }
  6022. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  6023. };
  6024. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  6025. for (var i = 0; i < primaryKeys.length; i++) {
  6026. var key = primaryKeys[i];
  6027. if (toState[key] != null && !(key in normalState)) {
  6028. normalState[key] = this[key];
  6029. }
  6030. }
  6031. };
  6032. Element.prototype.hasState = function () {
  6033. return this.currentStates.length > 0;
  6034. };
  6035. Element.prototype.getState = function (name) {
  6036. return this.states[name];
  6037. };
  6038. Element.prototype.ensureState = function (name) {
  6039. var states = this.states;
  6040. if (!states[name]) {
  6041. states[name] = {};
  6042. }
  6043. return states[name];
  6044. };
  6045. Element.prototype.clearStates = function (noAnimation) {
  6046. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  6047. };
  6048. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  6049. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  6050. var hasStates = this.hasState();
  6051. if (!hasStates && toNormalState) {
  6052. return;
  6053. }
  6054. var currentStates = this.currentStates;
  6055. var animationCfg = this.stateTransition;
  6056. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  6057. return;
  6058. }
  6059. var state;
  6060. if (this.stateProxy && !toNormalState) {
  6061. state = this.stateProxy(stateName);
  6062. }
  6063. if (!state) {
  6064. state = (this.states && this.states[stateName]);
  6065. }
  6066. if (!state && !toNormalState) {
  6067. logError("State " + stateName + " not exists.");
  6068. return;
  6069. }
  6070. if (!toNormalState) {
  6071. this.saveCurrentToNormalState(state);
  6072. }
  6073. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  6074. if (useHoverLayer) {
  6075. this._toggleHoverLayerFlag(true);
  6076. }
  6077. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6078. var textContent = this._textContent;
  6079. var textGuide = this._textGuide;
  6080. if (textContent) {
  6081. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6082. }
  6083. if (textGuide) {
  6084. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6085. }
  6086. if (toNormalState) {
  6087. this.currentStates = [];
  6088. this._normalState = {};
  6089. }
  6090. else {
  6091. if (!keepCurrentStates) {
  6092. this.currentStates = [stateName];
  6093. }
  6094. else {
  6095. this.currentStates.push(stateName);
  6096. }
  6097. }
  6098. this._updateAnimationTargets();
  6099. this.markRedraw();
  6100. if (!useHoverLayer && this.__inHover) {
  6101. this._toggleHoverLayerFlag(false);
  6102. this.__dirty &= ~REDRAW_BIT;
  6103. }
  6104. return state;
  6105. };
  6106. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  6107. if (!states.length) {
  6108. this.clearStates();
  6109. }
  6110. else {
  6111. var stateObjects = [];
  6112. var currentStates = this.currentStates;
  6113. var len = states.length;
  6114. var notChange = len === currentStates.length;
  6115. if (notChange) {
  6116. for (var i = 0; i < len; i++) {
  6117. if (states[i] !== currentStates[i]) {
  6118. notChange = false;
  6119. break;
  6120. }
  6121. }
  6122. }
  6123. if (notChange) {
  6124. return;
  6125. }
  6126. for (var i = 0; i < len; i++) {
  6127. var stateName = states[i];
  6128. var stateObj = void 0;
  6129. if (this.stateProxy) {
  6130. stateObj = this.stateProxy(stateName, states);
  6131. }
  6132. if (!stateObj) {
  6133. stateObj = this.states[stateName];
  6134. }
  6135. if (stateObj) {
  6136. stateObjects.push(stateObj);
  6137. }
  6138. }
  6139. var lastStateObj = stateObjects[len - 1];
  6140. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  6141. if (useHoverLayer) {
  6142. this._toggleHoverLayerFlag(true);
  6143. }
  6144. var mergedState = this._mergeStates(stateObjects);
  6145. var animationCfg = this.stateTransition;
  6146. this.saveCurrentToNormalState(mergedState);
  6147. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6148. var textContent = this._textContent;
  6149. var textGuide = this._textGuide;
  6150. if (textContent) {
  6151. textContent.useStates(states, noAnimation, useHoverLayer);
  6152. }
  6153. if (textGuide) {
  6154. textGuide.useStates(states, noAnimation, useHoverLayer);
  6155. }
  6156. this._updateAnimationTargets();
  6157. this.currentStates = states.slice();
  6158. this.markRedraw();
  6159. if (!useHoverLayer && this.__inHover) {
  6160. this._toggleHoverLayerFlag(false);
  6161. this.__dirty &= ~REDRAW_BIT;
  6162. }
  6163. }
  6164. };
  6165. Element.prototype._updateAnimationTargets = function () {
  6166. for (var i = 0; i < this.animators.length; i++) {
  6167. var animator = this.animators[i];
  6168. if (animator.targetName) {
  6169. animator.changeTarget(this[animator.targetName]);
  6170. }
  6171. }
  6172. };
  6173. Element.prototype.removeState = function (state) {
  6174. var idx = indexOf(this.currentStates, state);
  6175. if (idx >= 0) {
  6176. var currentStates = this.currentStates.slice();
  6177. currentStates.splice(idx, 1);
  6178. this.useStates(currentStates);
  6179. }
  6180. };
  6181. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  6182. var currentStates = this.currentStates.slice();
  6183. var idx = indexOf(currentStates, oldState);
  6184. var newStateExists = indexOf(currentStates, newState) >= 0;
  6185. if (idx >= 0) {
  6186. if (!newStateExists) {
  6187. currentStates[idx] = newState;
  6188. }
  6189. else {
  6190. currentStates.splice(idx, 1);
  6191. }
  6192. }
  6193. else if (forceAdd && !newStateExists) {
  6194. currentStates.push(newState);
  6195. }
  6196. this.useStates(currentStates);
  6197. };
  6198. Element.prototype.toggleState = function (state, enable) {
  6199. if (enable) {
  6200. this.useState(state, true);
  6201. }
  6202. else {
  6203. this.removeState(state);
  6204. }
  6205. };
  6206. Element.prototype._mergeStates = function (states) {
  6207. var mergedState = {};
  6208. var mergedTextConfig;
  6209. for (var i = 0; i < states.length; i++) {
  6210. var state = states[i];
  6211. extend(mergedState, state);
  6212. if (state.textConfig) {
  6213. mergedTextConfig = mergedTextConfig || {};
  6214. extend(mergedTextConfig, state.textConfig);
  6215. }
  6216. }
  6217. if (mergedTextConfig) {
  6218. mergedState.textConfig = mergedTextConfig;
  6219. }
  6220. return mergedState;
  6221. };
  6222. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  6223. var needsRestoreToNormal = !(state && keepCurrentStates);
  6224. if (state && state.textConfig) {
  6225. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  6226. extend(this.textConfig, state.textConfig);
  6227. }
  6228. else if (needsRestoreToNormal) {
  6229. if (normalState.textConfig) {
  6230. this.textConfig = normalState.textConfig;
  6231. }
  6232. }
  6233. var transitionTarget = {};
  6234. var hasTransition = false;
  6235. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  6236. var key = PRIMARY_STATES_KEYS[i];
  6237. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  6238. if (state && state[key] != null) {
  6239. if (propNeedsTransition) {
  6240. hasTransition = true;
  6241. transitionTarget[key] = state[key];
  6242. }
  6243. else {
  6244. this[key] = state[key];
  6245. }
  6246. }
  6247. else if (needsRestoreToNormal) {
  6248. if (normalState[key] != null) {
  6249. if (propNeedsTransition) {
  6250. hasTransition = true;
  6251. transitionTarget[key] = normalState[key];
  6252. }
  6253. else {
  6254. this[key] = normalState[key];
  6255. }
  6256. }
  6257. }
  6258. }
  6259. if (!transition) {
  6260. for (var i = 0; i < this.animators.length; i++) {
  6261. var animator = this.animators[i];
  6262. var targetName = animator.targetName;
  6263. if (!animator.getLoop()) {
  6264. animator.__changeFinalValue(targetName
  6265. ? (state || normalState)[targetName]
  6266. : (state || normalState));
  6267. }
  6268. }
  6269. }
  6270. if (hasTransition) {
  6271. this._transitionState(stateName, transitionTarget, animationCfg);
  6272. }
  6273. };
  6274. Element.prototype._attachComponent = function (componentEl) {
  6275. if (componentEl.__zr && !componentEl.__hostTarget) {
  6276. if ("development" !== 'production') {
  6277. throw new Error('Text element has been added to zrender.');
  6278. }
  6279. return;
  6280. }
  6281. if (componentEl === this) {
  6282. if ("development" !== 'production') {
  6283. throw new Error('Recursive component attachment.');
  6284. }
  6285. return;
  6286. }
  6287. var zr = this.__zr;
  6288. if (zr) {
  6289. componentEl.addSelfToZr(zr);
  6290. }
  6291. componentEl.__zr = zr;
  6292. componentEl.__hostTarget = this;
  6293. };
  6294. Element.prototype._detachComponent = function (componentEl) {
  6295. if (componentEl.__zr) {
  6296. componentEl.removeSelfFromZr(componentEl.__zr);
  6297. }
  6298. componentEl.__zr = null;
  6299. componentEl.__hostTarget = null;
  6300. };
  6301. Element.prototype.getClipPath = function () {
  6302. return this._clipPath;
  6303. };
  6304. Element.prototype.setClipPath = function (clipPath) {
  6305. if (this._clipPath && this._clipPath !== clipPath) {
  6306. this.removeClipPath();
  6307. }
  6308. this._attachComponent(clipPath);
  6309. this._clipPath = clipPath;
  6310. this.markRedraw();
  6311. };
  6312. Element.prototype.removeClipPath = function () {
  6313. var clipPath = this._clipPath;
  6314. if (clipPath) {
  6315. this._detachComponent(clipPath);
  6316. this._clipPath = null;
  6317. this.markRedraw();
  6318. }
  6319. };
  6320. Element.prototype.getTextContent = function () {
  6321. return this._textContent;
  6322. };
  6323. Element.prototype.setTextContent = function (textEl) {
  6324. var previousTextContent = this._textContent;
  6325. if (previousTextContent === textEl) {
  6326. return;
  6327. }
  6328. if (previousTextContent && previousTextContent !== textEl) {
  6329. this.removeTextContent();
  6330. }
  6331. if ("development" !== 'production') {
  6332. if (textEl.__zr && !textEl.__hostTarget) {
  6333. throw new Error('Text element has been added to zrender.');
  6334. }
  6335. }
  6336. textEl.innerTransformable = new Transformable();
  6337. this._attachComponent(textEl);
  6338. this._textContent = textEl;
  6339. this.markRedraw();
  6340. };
  6341. Element.prototype.setTextConfig = function (cfg) {
  6342. if (!this.textConfig) {
  6343. this.textConfig = {};
  6344. }
  6345. extend(this.textConfig, cfg);
  6346. this.markRedraw();
  6347. };
  6348. Element.prototype.removeTextConfig = function () {
  6349. this.textConfig = null;
  6350. this.markRedraw();
  6351. };
  6352. Element.prototype.removeTextContent = function () {
  6353. var textEl = this._textContent;
  6354. if (textEl) {
  6355. textEl.innerTransformable = null;
  6356. this._detachComponent(textEl);
  6357. this._textContent = null;
  6358. this._innerTextDefaultStyle = null;
  6359. this.markRedraw();
  6360. }
  6361. };
  6362. Element.prototype.getTextGuideLine = function () {
  6363. return this._textGuide;
  6364. };
  6365. Element.prototype.setTextGuideLine = function (guideLine) {
  6366. if (this._textGuide && this._textGuide !== guideLine) {
  6367. this.removeTextGuideLine();
  6368. }
  6369. this._attachComponent(guideLine);
  6370. this._textGuide = guideLine;
  6371. this.markRedraw();
  6372. };
  6373. Element.prototype.removeTextGuideLine = function () {
  6374. var textGuide = this._textGuide;
  6375. if (textGuide) {
  6376. this._detachComponent(textGuide);
  6377. this._textGuide = null;
  6378. this.markRedraw();
  6379. }
  6380. };
  6381. Element.prototype.markRedraw = function () {
  6382. this.__dirty |= REDRAW_BIT;
  6383. var zr = this.__zr;
  6384. if (zr) {
  6385. if (this.__inHover) {
  6386. zr.refreshHover();
  6387. }
  6388. else {
  6389. zr.refresh();
  6390. }
  6391. }
  6392. if (this.__hostTarget) {
  6393. this.__hostTarget.markRedraw();
  6394. }
  6395. };
  6396. Element.prototype.dirty = function () {
  6397. this.markRedraw();
  6398. };
  6399. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6400. this.__inHover = inHover;
  6401. var textContent = this._textContent;
  6402. var textGuide = this._textGuide;
  6403. if (textContent) {
  6404. textContent.__inHover = inHover;
  6405. }
  6406. if (textGuide) {
  6407. textGuide.__inHover = inHover;
  6408. }
  6409. };
  6410. Element.prototype.addSelfToZr = function (zr) {
  6411. if (this.__zr === zr) {
  6412. return;
  6413. }
  6414. this.__zr = zr;
  6415. var animators = this.animators;
  6416. if (animators) {
  6417. for (var i = 0; i < animators.length; i++) {
  6418. zr.animation.addAnimator(animators[i]);
  6419. }
  6420. }
  6421. if (this._clipPath) {
  6422. this._clipPath.addSelfToZr(zr);
  6423. }
  6424. if (this._textContent) {
  6425. this._textContent.addSelfToZr(zr);
  6426. }
  6427. if (this._textGuide) {
  6428. this._textGuide.addSelfToZr(zr);
  6429. }
  6430. };
  6431. Element.prototype.removeSelfFromZr = function (zr) {
  6432. if (!this.__zr) {
  6433. return;
  6434. }
  6435. this.__zr = null;
  6436. var animators = this.animators;
  6437. if (animators) {
  6438. for (var i = 0; i < animators.length; i++) {
  6439. zr.animation.removeAnimator(animators[i]);
  6440. }
  6441. }
  6442. if (this._clipPath) {
  6443. this._clipPath.removeSelfFromZr(zr);
  6444. }
  6445. if (this._textContent) {
  6446. this._textContent.removeSelfFromZr(zr);
  6447. }
  6448. if (this._textGuide) {
  6449. this._textGuide.removeSelfFromZr(zr);
  6450. }
  6451. };
  6452. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6453. var target = key ? this[key] : this;
  6454. if ("development" !== 'production') {
  6455. if (!target) {
  6456. logError('Property "'
  6457. + key
  6458. + '" is not existed in element '
  6459. + this.id);
  6460. return;
  6461. }
  6462. }
  6463. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6464. key && (animator.targetName = key);
  6465. this.addAnimator(animator, key);
  6466. return animator;
  6467. };
  6468. Element.prototype.addAnimator = function (animator, key) {
  6469. var zr = this.__zr;
  6470. var el = this;
  6471. animator.during(function () {
  6472. el.updateDuringAnimation(key);
  6473. }).done(function () {
  6474. var animators = el.animators;
  6475. var idx = indexOf(animators, animator);
  6476. if (idx >= 0) {
  6477. animators.splice(idx, 1);
  6478. }
  6479. });
  6480. this.animators.push(animator);
  6481. if (zr) {
  6482. zr.animation.addAnimator(animator);
  6483. }
  6484. zr && zr.wakeUp();
  6485. };
  6486. Element.prototype.updateDuringAnimation = function (key) {
  6487. this.markRedraw();
  6488. };
  6489. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6490. var animators = this.animators;
  6491. var len = animators.length;
  6492. var leftAnimators = [];
  6493. for (var i = 0; i < len; i++) {
  6494. var animator = animators[i];
  6495. if (!scope || scope === animator.scope) {
  6496. animator.stop(forwardToLast);
  6497. }
  6498. else {
  6499. leftAnimators.push(animator);
  6500. }
  6501. }
  6502. this.animators = leftAnimators;
  6503. return this;
  6504. };
  6505. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6506. animateTo(this, target, cfg, animationProps);
  6507. };
  6508. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6509. animateTo(this, target, cfg, animationProps, true);
  6510. };
  6511. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6512. var animators = animateTo(this, target, cfg, animationProps);
  6513. for (var i = 0; i < animators.length; i++) {
  6514. animators[i].__fromStateTransition = stateName;
  6515. }
  6516. };
  6517. Element.prototype.getBoundingRect = function () {
  6518. return null;
  6519. };
  6520. Element.prototype.getPaintRect = function () {
  6521. return null;
  6522. };
  6523. Element.initDefaultProps = (function () {
  6524. var elProto = Element.prototype;
  6525. elProto.type = 'element';
  6526. elProto.name = '';
  6527. elProto.ignore =
  6528. elProto.silent =
  6529. elProto.isGroup =
  6530. elProto.draggable =
  6531. elProto.dragging =
  6532. elProto.ignoreClip =
  6533. elProto.__inHover = false;
  6534. elProto.__dirty = REDRAW_BIT;
  6535. var logs = {};
  6536. function logDeprecatedError(key, xKey, yKey) {
  6537. if (!logs[key + xKey + yKey]) {
  6538. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6539. logs[key + xKey + yKey] = true;
  6540. }
  6541. }
  6542. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6543. Object.defineProperty(elProto, key, {
  6544. get: function () {
  6545. if ("development" !== 'production') {
  6546. logDeprecatedError(key, xKey, yKey);
  6547. }
  6548. if (!this[privateKey]) {
  6549. var pos = this[privateKey] = [];
  6550. enhanceArray(this, pos);
  6551. }
  6552. return this[privateKey];
  6553. },
  6554. set: function (pos) {
  6555. if ("development" !== 'production') {
  6556. logDeprecatedError(key, xKey, yKey);
  6557. }
  6558. this[xKey] = pos[0];
  6559. this[yKey] = pos[1];
  6560. this[privateKey] = pos;
  6561. enhanceArray(this, pos);
  6562. }
  6563. });
  6564. function enhanceArray(self, pos) {
  6565. Object.defineProperty(pos, 0, {
  6566. get: function () {
  6567. return self[xKey];
  6568. },
  6569. set: function (val) {
  6570. self[xKey] = val;
  6571. }
  6572. });
  6573. Object.defineProperty(pos, 1, {
  6574. get: function () {
  6575. return self[yKey];
  6576. },
  6577. set: function (val) {
  6578. self[yKey] = val;
  6579. }
  6580. });
  6581. }
  6582. }
  6583. if (Object.defineProperty) {
  6584. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6585. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6586. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6587. }
  6588. })();
  6589. return Element;
  6590. }());
  6591. mixin(Element, Eventful);
  6592. mixin(Element, Transformable);
  6593. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6594. cfg = cfg || {};
  6595. var animators = [];
  6596. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6597. var finishCount = animators.length;
  6598. var doneHappened = false;
  6599. var cfgDone = cfg.done;
  6600. var cfgAborted = cfg.aborted;
  6601. var doneCb = function () {
  6602. doneHappened = true;
  6603. finishCount--;
  6604. if (finishCount <= 0) {
  6605. doneHappened
  6606. ? (cfgDone && cfgDone())
  6607. : (cfgAborted && cfgAborted());
  6608. }
  6609. };
  6610. var abortedCb = function () {
  6611. finishCount--;
  6612. if (finishCount <= 0) {
  6613. doneHappened
  6614. ? (cfgDone && cfgDone())
  6615. : (cfgAborted && cfgAborted());
  6616. }
  6617. };
  6618. if (!finishCount) {
  6619. cfgDone && cfgDone();
  6620. }
  6621. if (animators.length > 0 && cfg.during) {
  6622. animators[0].during(function (target, percent) {
  6623. cfg.during(percent);
  6624. });
  6625. }
  6626. for (var i = 0; i < animators.length; i++) {
  6627. var animator = animators[i];
  6628. if (doneCb) {
  6629. animator.done(doneCb);
  6630. }
  6631. if (abortedCb) {
  6632. animator.aborted(abortedCb);
  6633. }
  6634. if (cfg.force) {
  6635. animator.duration(cfg.duration);
  6636. }
  6637. animator.start(cfg.easing);
  6638. }
  6639. return animators;
  6640. }
  6641. function copyArrShallow(source, target, len) {
  6642. for (var i = 0; i < len; i++) {
  6643. source[i] = target[i];
  6644. }
  6645. }
  6646. function is2DArray(value) {
  6647. return isArrayLike(value[0]);
  6648. }
  6649. function copyValue(target, source, key) {
  6650. if (isArrayLike(source[key])) {
  6651. if (!isArrayLike(target[key])) {
  6652. target[key] = [];
  6653. }
  6654. if (isTypedArray(source[key])) {
  6655. var len = source[key].length;
  6656. if (target[key].length !== len) {
  6657. target[key] = new (source[key].constructor)(len);
  6658. copyArrShallow(target[key], source[key], len);
  6659. }
  6660. }
  6661. else {
  6662. var sourceArr = source[key];
  6663. var targetArr = target[key];
  6664. var len0 = sourceArr.length;
  6665. if (is2DArray(sourceArr)) {
  6666. var len1 = sourceArr[0].length;
  6667. for (var i = 0; i < len0; i++) {
  6668. if (!targetArr[i]) {
  6669. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6670. }
  6671. else {
  6672. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6673. }
  6674. }
  6675. }
  6676. else {
  6677. copyArrShallow(targetArr, sourceArr, len0);
  6678. }
  6679. targetArr.length = sourceArr.length;
  6680. }
  6681. }
  6682. else {
  6683. target[key] = source[key];
  6684. }
  6685. }
  6686. function isValueSame(val1, val2) {
  6687. return val1 === val2
  6688. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6689. }
  6690. function is1DArraySame(arr0, arr1) {
  6691. var len = arr0.length;
  6692. if (len !== arr1.length) {
  6693. return false;
  6694. }
  6695. for (var i = 0; i < len; i++) {
  6696. if (arr0[i] !== arr1[i]) {
  6697. return false;
  6698. }
  6699. }
  6700. return true;
  6701. }
  6702. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6703. var targetKeys = keys(target);
  6704. var duration = cfg.duration;
  6705. var delay = cfg.delay;
  6706. var additive = cfg.additive;
  6707. var setToFinal = cfg.setToFinal;
  6708. var animateAll = !isObject(animationProps);
  6709. var existsAnimators = animatable.animators;
  6710. var animationKeys = [];
  6711. for (var k = 0; k < targetKeys.length; k++) {
  6712. var innerKey = targetKeys[k];
  6713. var targetVal = target[innerKey];
  6714. if (targetVal != null && animateObj[innerKey] != null
  6715. && (animateAll || animationProps[innerKey])) {
  6716. if (isObject(targetVal)
  6717. && !isArrayLike(targetVal)
  6718. && !isGradientObject(targetVal)) {
  6719. if (topKey) {
  6720. if (!reverse) {
  6721. animateObj[innerKey] = targetVal;
  6722. animatable.updateDuringAnimation(topKey);
  6723. }
  6724. continue;
  6725. }
  6726. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6727. }
  6728. else {
  6729. animationKeys.push(innerKey);
  6730. }
  6731. }
  6732. else if (!reverse) {
  6733. animateObj[innerKey] = targetVal;
  6734. animatable.updateDuringAnimation(topKey);
  6735. animationKeys.push(innerKey);
  6736. }
  6737. }
  6738. var keyLen = animationKeys.length;
  6739. if (!additive && keyLen) {
  6740. for (var i = 0; i < existsAnimators.length; i++) {
  6741. var animator = existsAnimators[i];
  6742. if (animator.targetName === topKey) {
  6743. var allAborted = animator.stopTracks(animationKeys);
  6744. if (allAborted) {
  6745. var idx = indexOf(existsAnimators, animator);
  6746. existsAnimators.splice(idx, 1);
  6747. }
  6748. }
  6749. }
  6750. }
  6751. if (!cfg.force) {
  6752. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6753. keyLen = animationKeys.length;
  6754. }
  6755. if (keyLen > 0
  6756. || (cfg.force && !animators.length)) {
  6757. var revertedSource = void 0;
  6758. var reversedTarget = void 0;
  6759. var sourceClone = void 0;
  6760. if (reverse) {
  6761. reversedTarget = {};
  6762. if (setToFinal) {
  6763. revertedSource = {};
  6764. }
  6765. for (var i = 0; i < keyLen; i++) {
  6766. var innerKey = animationKeys[i];
  6767. reversedTarget[innerKey] = animateObj[innerKey];
  6768. if (setToFinal) {
  6769. revertedSource[innerKey] = target[innerKey];
  6770. }
  6771. else {
  6772. animateObj[innerKey] = target[innerKey];
  6773. }
  6774. }
  6775. }
  6776. else if (setToFinal) {
  6777. sourceClone = {};
  6778. for (var i = 0; i < keyLen; i++) {
  6779. var innerKey = animationKeys[i];
  6780. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  6781. copyValue(animateObj, target, innerKey);
  6782. }
  6783. }
  6784. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  6785. animator.targetName = topKey;
  6786. if (cfg.scope) {
  6787. animator.scope = cfg.scope;
  6788. }
  6789. if (setToFinal && revertedSource) {
  6790. animator.whenWithKeys(0, revertedSource, animationKeys);
  6791. }
  6792. if (sourceClone) {
  6793. animator.whenWithKeys(0, sourceClone, animationKeys);
  6794. }
  6795. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  6796. animatable.addAnimator(animator, topKey);
  6797. animators.push(animator);
  6798. }
  6799. }
  6800. var Group = (function (_super) {
  6801. __extends(Group, _super);
  6802. function Group(opts) {
  6803. var _this = _super.call(this) || this;
  6804. _this.isGroup = true;
  6805. _this._children = [];
  6806. _this.attr(opts);
  6807. return _this;
  6808. }
  6809. Group.prototype.childrenRef = function () {
  6810. return this._children;
  6811. };
  6812. Group.prototype.children = function () {
  6813. return this._children.slice();
  6814. };
  6815. Group.prototype.childAt = function (idx) {
  6816. return this._children[idx];
  6817. };
  6818. Group.prototype.childOfName = function (name) {
  6819. var children = this._children;
  6820. for (var i = 0; i < children.length; i++) {
  6821. if (children[i].name === name) {
  6822. return children[i];
  6823. }
  6824. }
  6825. };
  6826. Group.prototype.childCount = function () {
  6827. return this._children.length;
  6828. };
  6829. Group.prototype.add = function (child) {
  6830. if (child) {
  6831. if (child !== this && child.parent !== this) {
  6832. this._children.push(child);
  6833. this._doAdd(child);
  6834. }
  6835. if ("development" !== 'production') {
  6836. if (child.__hostTarget) {
  6837. throw 'This elemenet has been used as an attachment';
  6838. }
  6839. }
  6840. }
  6841. return this;
  6842. };
  6843. Group.prototype.addBefore = function (child, nextSibling) {
  6844. if (child && child !== this && child.parent !== this
  6845. && nextSibling && nextSibling.parent === this) {
  6846. var children = this._children;
  6847. var idx = children.indexOf(nextSibling);
  6848. if (idx >= 0) {
  6849. children.splice(idx, 0, child);
  6850. this._doAdd(child);
  6851. }
  6852. }
  6853. return this;
  6854. };
  6855. Group.prototype.replace = function (oldChild, newChild) {
  6856. var idx = indexOf(this._children, oldChild);
  6857. if (idx >= 0) {
  6858. this.replaceAt(newChild, idx);
  6859. }
  6860. return this;
  6861. };
  6862. Group.prototype.replaceAt = function (child, index) {
  6863. var children = this._children;
  6864. var old = children[index];
  6865. if (child && child !== this && child.parent !== this && child !== old) {
  6866. children[index] = child;
  6867. old.parent = null;
  6868. var zr = this.__zr;
  6869. if (zr) {
  6870. old.removeSelfFromZr(zr);
  6871. }
  6872. this._doAdd(child);
  6873. }
  6874. return this;
  6875. };
  6876. Group.prototype._doAdd = function (child) {
  6877. if (child.parent) {
  6878. child.parent.remove(child);
  6879. }
  6880. child.parent = this;
  6881. var zr = this.__zr;
  6882. if (zr && zr !== child.__zr) {
  6883. child.addSelfToZr(zr);
  6884. }
  6885. zr && zr.refresh();
  6886. };
  6887. Group.prototype.remove = function (child) {
  6888. var zr = this.__zr;
  6889. var children = this._children;
  6890. var idx = indexOf(children, child);
  6891. if (idx < 0) {
  6892. return this;
  6893. }
  6894. children.splice(idx, 1);
  6895. child.parent = null;
  6896. if (zr) {
  6897. child.removeSelfFromZr(zr);
  6898. }
  6899. zr && zr.refresh();
  6900. return this;
  6901. };
  6902. Group.prototype.removeAll = function () {
  6903. var children = this._children;
  6904. var zr = this.__zr;
  6905. for (var i = 0; i < children.length; i++) {
  6906. var child = children[i];
  6907. if (zr) {
  6908. child.removeSelfFromZr(zr);
  6909. }
  6910. child.parent = null;
  6911. }
  6912. children.length = 0;
  6913. return this;
  6914. };
  6915. Group.prototype.eachChild = function (cb, context) {
  6916. var children = this._children;
  6917. for (var i = 0; i < children.length; i++) {
  6918. var child = children[i];
  6919. cb.call(context, child, i);
  6920. }
  6921. return this;
  6922. };
  6923. Group.prototype.traverse = function (cb, context) {
  6924. for (var i = 0; i < this._children.length; i++) {
  6925. var child = this._children[i];
  6926. var stopped = cb.call(context, child);
  6927. if (child.isGroup && !stopped) {
  6928. child.traverse(cb, context);
  6929. }
  6930. }
  6931. return this;
  6932. };
  6933. Group.prototype.addSelfToZr = function (zr) {
  6934. _super.prototype.addSelfToZr.call(this, zr);
  6935. for (var i = 0; i < this._children.length; i++) {
  6936. var child = this._children[i];
  6937. child.addSelfToZr(zr);
  6938. }
  6939. };
  6940. Group.prototype.removeSelfFromZr = function (zr) {
  6941. _super.prototype.removeSelfFromZr.call(this, zr);
  6942. for (var i = 0; i < this._children.length; i++) {
  6943. var child = this._children[i];
  6944. child.removeSelfFromZr(zr);
  6945. }
  6946. };
  6947. Group.prototype.getBoundingRect = function (includeChildren) {
  6948. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6949. var children = includeChildren || this._children;
  6950. var tmpMat = [];
  6951. var rect = null;
  6952. for (var i = 0; i < children.length; i++) {
  6953. var child = children[i];
  6954. if (child.ignore || child.invisible) {
  6955. continue;
  6956. }
  6957. var childRect = child.getBoundingRect();
  6958. var transform = child.getLocalTransform(tmpMat);
  6959. if (transform) {
  6960. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6961. rect = rect || tmpRect.clone();
  6962. rect.union(tmpRect);
  6963. }
  6964. else {
  6965. rect = rect || childRect.clone();
  6966. rect.union(childRect);
  6967. }
  6968. }
  6969. return rect || tmpRect;
  6970. };
  6971. return Group;
  6972. }(Element));
  6973. Group.prototype.type = 'group';
  6974. /*!
  6975. * ZRender, a high performance 2d drawing library.
  6976. *
  6977. * Copyright (c) 2013, Baidu Inc.
  6978. * All rights reserved.
  6979. *
  6980. * LICENSE
  6981. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6982. */
  6983. var painterCtors = {};
  6984. var instances = {};
  6985. function delInstance(id) {
  6986. delete instances[id];
  6987. }
  6988. function isDarkMode(backgroundColor) {
  6989. if (!backgroundColor) {
  6990. return false;
  6991. }
  6992. if (typeof backgroundColor === 'string') {
  6993. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6994. }
  6995. else if (backgroundColor.colorStops) {
  6996. var colorStops = backgroundColor.colorStops;
  6997. var totalLum = 0;
  6998. var len = colorStops.length;
  6999. for (var i = 0; i < len; i++) {
  7000. totalLum += lum(colorStops[i].color, 1);
  7001. }
  7002. totalLum /= len;
  7003. return totalLum < DARK_MODE_THRESHOLD;
  7004. }
  7005. return false;
  7006. }
  7007. var ZRender = (function () {
  7008. function ZRender(id, dom, opts) {
  7009. var _this = this;
  7010. this._sleepAfterStill = 10;
  7011. this._stillFrameAccum = 0;
  7012. this._needsRefresh = true;
  7013. this._needsRefreshHover = true;
  7014. this._darkMode = false;
  7015. opts = opts || {};
  7016. this.dom = dom;
  7017. this.id = id;
  7018. var storage = new Storage();
  7019. var rendererType = opts.renderer || 'canvas';
  7020. if (!painterCtors[rendererType]) {
  7021. rendererType = keys(painterCtors)[0];
  7022. }
  7023. if ("development" !== 'production') {
  7024. if (!painterCtors[rendererType]) {
  7025. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  7026. }
  7027. }
  7028. opts.useDirtyRect = opts.useDirtyRect == null
  7029. ? false
  7030. : opts.useDirtyRect;
  7031. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  7032. var ssrMode = opts.ssr || painter.ssrOnly;
  7033. this.storage = storage;
  7034. this.painter = painter;
  7035. var handerProxy = (!env.node && !env.worker && !ssrMode)
  7036. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  7037. : null;
  7038. var useCoarsePointer = opts.useCoarsePointer;
  7039. var usePointerSize = (useCoarsePointer == null || useCoarsePointer === 'auto')
  7040. ? env.touchEventsSupported
  7041. : !!useCoarsePointer;
  7042. var defaultPointerSize = 44;
  7043. var pointerSize;
  7044. if (usePointerSize) {
  7045. pointerSize = retrieve2(opts.pointerSize, defaultPointerSize);
  7046. }
  7047. this.handler = new Handler(storage, painter, handerProxy, painter.root, pointerSize);
  7048. this.animation = new Animation({
  7049. stage: {
  7050. update: ssrMode ? null : function () { return _this._flush(true); }
  7051. }
  7052. });
  7053. if (!ssrMode) {
  7054. this.animation.start();
  7055. }
  7056. }
  7057. ZRender.prototype.add = function (el) {
  7058. if (!el) {
  7059. return;
  7060. }
  7061. this.storage.addRoot(el);
  7062. el.addSelfToZr(this);
  7063. this.refresh();
  7064. };
  7065. ZRender.prototype.remove = function (el) {
  7066. if (!el) {
  7067. return;
  7068. }
  7069. this.storage.delRoot(el);
  7070. el.removeSelfFromZr(this);
  7071. this.refresh();
  7072. };
  7073. ZRender.prototype.configLayer = function (zLevel, config) {
  7074. if (this.painter.configLayer) {
  7075. this.painter.configLayer(zLevel, config);
  7076. }
  7077. this.refresh();
  7078. };
  7079. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  7080. if (this.painter.setBackgroundColor) {
  7081. this.painter.setBackgroundColor(backgroundColor);
  7082. }
  7083. this.refresh();
  7084. this._backgroundColor = backgroundColor;
  7085. this._darkMode = isDarkMode(backgroundColor);
  7086. };
  7087. ZRender.prototype.getBackgroundColor = function () {
  7088. return this._backgroundColor;
  7089. };
  7090. ZRender.prototype.setDarkMode = function (darkMode) {
  7091. this._darkMode = darkMode;
  7092. };
  7093. ZRender.prototype.isDarkMode = function () {
  7094. return this._darkMode;
  7095. };
  7096. ZRender.prototype.refreshImmediately = function (fromInside) {
  7097. if (!fromInside) {
  7098. this.animation.update(true);
  7099. }
  7100. this._needsRefresh = false;
  7101. this.painter.refresh();
  7102. this._needsRefresh = false;
  7103. };
  7104. ZRender.prototype.refresh = function () {
  7105. this._needsRefresh = true;
  7106. this.animation.start();
  7107. };
  7108. ZRender.prototype.flush = function () {
  7109. this._flush(false);
  7110. };
  7111. ZRender.prototype._flush = function (fromInside) {
  7112. var triggerRendered;
  7113. var start = getTime();
  7114. if (this._needsRefresh) {
  7115. triggerRendered = true;
  7116. this.refreshImmediately(fromInside);
  7117. }
  7118. if (this._needsRefreshHover) {
  7119. triggerRendered = true;
  7120. this.refreshHoverImmediately();
  7121. }
  7122. var end = getTime();
  7123. if (triggerRendered) {
  7124. this._stillFrameAccum = 0;
  7125. this.trigger('rendered', {
  7126. elapsedTime: end - start
  7127. });
  7128. }
  7129. else if (this._sleepAfterStill > 0) {
  7130. this._stillFrameAccum++;
  7131. if (this._stillFrameAccum > this._sleepAfterStill) {
  7132. this.animation.stop();
  7133. }
  7134. }
  7135. };
  7136. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  7137. this._sleepAfterStill = stillFramesCount;
  7138. };
  7139. ZRender.prototype.wakeUp = function () {
  7140. this.animation.start();
  7141. this._stillFrameAccum = 0;
  7142. };
  7143. ZRender.prototype.refreshHover = function () {
  7144. this._needsRefreshHover = true;
  7145. };
  7146. ZRender.prototype.refreshHoverImmediately = function () {
  7147. this._needsRefreshHover = false;
  7148. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  7149. this.painter.refreshHover();
  7150. }
  7151. };
  7152. ZRender.prototype.resize = function (opts) {
  7153. opts = opts || {};
  7154. this.painter.resize(opts.width, opts.height);
  7155. this.handler.resize();
  7156. };
  7157. ZRender.prototype.clearAnimation = function () {
  7158. this.animation.clear();
  7159. };
  7160. ZRender.prototype.getWidth = function () {
  7161. return this.painter.getWidth();
  7162. };
  7163. ZRender.prototype.getHeight = function () {
  7164. return this.painter.getHeight();
  7165. };
  7166. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  7167. this.handler.setCursorStyle(cursorStyle);
  7168. };
  7169. ZRender.prototype.findHover = function (x, y) {
  7170. return this.handler.findHover(x, y);
  7171. };
  7172. ZRender.prototype.on = function (eventName, eventHandler, context) {
  7173. this.handler.on(eventName, eventHandler, context);
  7174. return this;
  7175. };
  7176. ZRender.prototype.off = function (eventName, eventHandler) {
  7177. this.handler.off(eventName, eventHandler);
  7178. };
  7179. ZRender.prototype.trigger = function (eventName, event) {
  7180. this.handler.trigger(eventName, event);
  7181. };
  7182. ZRender.prototype.clear = function () {
  7183. var roots = this.storage.getRoots();
  7184. for (var i = 0; i < roots.length; i++) {
  7185. if (roots[i] instanceof Group) {
  7186. roots[i].removeSelfFromZr(this);
  7187. }
  7188. }
  7189. this.storage.delAllRoots();
  7190. this.painter.clear();
  7191. };
  7192. ZRender.prototype.dispose = function () {
  7193. this.animation.stop();
  7194. this.clear();
  7195. this.storage.dispose();
  7196. this.painter.dispose();
  7197. this.handler.dispose();
  7198. this.animation =
  7199. this.storage =
  7200. this.painter =
  7201. this.handler = null;
  7202. delInstance(this.id);
  7203. };
  7204. return ZRender;
  7205. }());
  7206. function init(dom, opts) {
  7207. var zr = new ZRender(guid(), dom, opts);
  7208. instances[zr.id] = zr;
  7209. return zr;
  7210. }
  7211. function dispose(zr) {
  7212. zr.dispose();
  7213. }
  7214. function disposeAll() {
  7215. for (var key in instances) {
  7216. if (instances.hasOwnProperty(key)) {
  7217. instances[key].dispose();
  7218. }
  7219. }
  7220. instances = {};
  7221. }
  7222. function getInstance(id) {
  7223. return instances[id];
  7224. }
  7225. function registerPainter(name, Ctor) {
  7226. painterCtors[name] = Ctor;
  7227. }
  7228. var version = '5.4.3';
  7229. var zrender = /*#__PURE__*/Object.freeze({
  7230. __proto__: null,
  7231. init: init,
  7232. dispose: dispose,
  7233. disposeAll: disposeAll,
  7234. getInstance: getInstance,
  7235. registerPainter: registerPainter,
  7236. version: version
  7237. });
  7238. var RADIAN_EPSILON = 1e-4; // Although chrome already enlarge this number to 100 for `toFixed`, but
  7239. // we sill follow the spec for compatibility.
  7240. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  7241. function _trim(str) {
  7242. return str.replace(/^\s+|\s+$/g, '');
  7243. }
  7244. /**
  7245. * Linear mapping a value from domain to range
  7246. * @param val
  7247. * @param domain Domain extent domain[0] can be bigger than domain[1]
  7248. * @param range Range extent range[0] can be bigger than range[1]
  7249. * @param clamp Default to be false
  7250. */
  7251. function linearMap(val, domain, range, clamp) {
  7252. var d0 = domain[0];
  7253. var d1 = domain[1];
  7254. var r0 = range[0];
  7255. var r1 = range[1];
  7256. var subDomain = d1 - d0;
  7257. var subRange = r1 - r0;
  7258. if (subDomain === 0) {
  7259. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7260. } // Avoid accuracy problem in edge, such as
  7261. // 146.39 - 62.83 === 83.55999999999999.
  7262. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7263. // It is a little verbose for efficiency considering this method
  7264. // is a hotspot.
  7265. if (clamp) {
  7266. if (subDomain > 0) {
  7267. if (val <= d0) {
  7268. return r0;
  7269. } else if (val >= d1) {
  7270. return r1;
  7271. }
  7272. } else {
  7273. if (val >= d0) {
  7274. return r0;
  7275. } else if (val <= d1) {
  7276. return r1;
  7277. }
  7278. }
  7279. } else {
  7280. if (val === d0) {
  7281. return r0;
  7282. }
  7283. if (val === d1) {
  7284. return r1;
  7285. }
  7286. }
  7287. return (val - d0) / subDomain * subRange + r0;
  7288. }
  7289. /**
  7290. * Convert a percent string to absolute number.
  7291. * Returns NaN if percent is not a valid string or number
  7292. */
  7293. function parsePercent$1(percent, all) {
  7294. switch (percent) {
  7295. case 'center':
  7296. case 'middle':
  7297. percent = '50%';
  7298. break;
  7299. case 'left':
  7300. case 'top':
  7301. percent = '0%';
  7302. break;
  7303. case 'right':
  7304. case 'bottom':
  7305. percent = '100%';
  7306. break;
  7307. }
  7308. if (isString(percent)) {
  7309. if (_trim(percent).match(/%$/)) {
  7310. return parseFloat(percent) / 100 * all;
  7311. }
  7312. return parseFloat(percent);
  7313. }
  7314. return percent == null ? NaN : +percent;
  7315. }
  7316. function round(x, precision, returnStr) {
  7317. if (precision == null) {
  7318. precision = 10;
  7319. } // Avoid range error
  7320. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX); // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7321. x = (+x).toFixed(precision);
  7322. return returnStr ? x : +x;
  7323. }
  7324. /**
  7325. * Inplacd asc sort arr.
  7326. * The input arr will be modified.
  7327. */
  7328. function asc(arr) {
  7329. arr.sort(function (a, b) {
  7330. return a - b;
  7331. });
  7332. return arr;
  7333. }
  7334. /**
  7335. * Get precision.
  7336. */
  7337. function getPrecision(val) {
  7338. val = +val;
  7339. if (isNaN(val)) {
  7340. return 0;
  7341. } // It is much faster than methods converting number to string as follows
  7342. // let tmp = val.toString();
  7343. // return tmp.length - 1 - tmp.indexOf('.');
  7344. // especially when precision is low
  7345. // Notice:
  7346. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7347. // (see https://jsbench.me/2vkpcekkvw/1)
  7348. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7349. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7350. if (val > 1e-14) {
  7351. var e = 1;
  7352. for (var i = 0; i < 15; i++, e *= 10) {
  7353. if (Math.round(val * e) / e === val) {
  7354. return i;
  7355. }
  7356. }
  7357. }
  7358. return getPrecisionSafe(val);
  7359. }
  7360. /**
  7361. * Get precision with slow but safe method
  7362. */
  7363. function getPrecisionSafe(val) {
  7364. // toLowerCase for: '3.4E-12'
  7365. var str = val.toString().toLowerCase(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  7366. var eIndex = str.indexOf('e');
  7367. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7368. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7369. var dotIndex = str.indexOf('.');
  7370. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7371. return Math.max(0, decimalPartLen - exp);
  7372. }
  7373. /**
  7374. * Minimal dicernible data precisioin according to a single pixel.
  7375. */
  7376. function getPixelPrecision(dataExtent, pixelExtent) {
  7377. var log = Math.log;
  7378. var LN10 = Math.LN10;
  7379. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7380. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  7381. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7382. return !isFinite(precision) ? 20 : precision;
  7383. }
  7384. /**
  7385. * Get a data of given precision, assuring the sum of percentages
  7386. * in valueList is 1.
  7387. * The largest remainder method is used.
  7388. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7389. *
  7390. * @param valueList a list of all data
  7391. * @param idx index of the data to be processed in valueList
  7392. * @param precision integer number showing digits of precision
  7393. * @return percent ranging from 0 to 100
  7394. */
  7395. function getPercentWithPrecision(valueList, idx, precision) {
  7396. if (!valueList[idx]) {
  7397. return 0;
  7398. }
  7399. var seats = getPercentSeats(valueList, precision);
  7400. return seats[idx] || 0;
  7401. }
  7402. /**
  7403. * Get a data of given precision, assuring the sum of percentages
  7404. * in valueList is 1.
  7405. * The largest remainder method is used.
  7406. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7407. *
  7408. * @param valueList a list of all data
  7409. * @param precision integer number showing digits of precision
  7410. * @return {Array<number>}
  7411. */
  7412. function getPercentSeats(valueList, precision) {
  7413. var sum = reduce(valueList, function (acc, val) {
  7414. return acc + (isNaN(val) ? 0 : val);
  7415. }, 0);
  7416. if (sum === 0) {
  7417. return [];
  7418. }
  7419. var digits = Math.pow(10, precision);
  7420. var votesPerQuota = map(valueList, function (val) {
  7421. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7422. });
  7423. var targetSeats = digits * 100;
  7424. var seats = map(votesPerQuota, function (votes) {
  7425. // Assign automatic seats.
  7426. return Math.floor(votes);
  7427. });
  7428. var currentSum = reduce(seats, function (acc, val) {
  7429. return acc + val;
  7430. }, 0);
  7431. var remainder = map(votesPerQuota, function (votes, idx) {
  7432. return votes - seats[idx];
  7433. }); // Has remainding votes.
  7434. while (currentSum < targetSeats) {
  7435. // Find next largest remainder.
  7436. var max = Number.NEGATIVE_INFINITY;
  7437. var maxId = null;
  7438. for (var i = 0, len = remainder.length; i < len; ++i) {
  7439. if (remainder[i] > max) {
  7440. max = remainder[i];
  7441. maxId = i;
  7442. }
  7443. } // Add a vote to max remainder.
  7444. ++seats[maxId];
  7445. remainder[maxId] = 0;
  7446. ++currentSum;
  7447. }
  7448. return map(seats, function (seat) {
  7449. return seat / digits;
  7450. });
  7451. }
  7452. /**
  7453. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7454. * See <http://0.30000000000000004.com/>
  7455. */
  7456. function addSafe(val0, val1) {
  7457. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1)); // const multiplier = Math.pow(10, maxPrecision);
  7458. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7459. var sum = val0 + val1; // // PENDING: support more?
  7460. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7461. } // Number.MAX_SAFE_INTEGER, ie do not support.
  7462. var MAX_SAFE_INTEGER = 9007199254740991;
  7463. /**
  7464. * To 0 - 2 * PI, considering negative radian.
  7465. */
  7466. function remRadian(radian) {
  7467. var pi2 = Math.PI * 2;
  7468. return (radian % pi2 + pi2) % pi2;
  7469. }
  7470. /**
  7471. * @param {type} radian
  7472. * @return {boolean}
  7473. */
  7474. function isRadianAroundZero(val) {
  7475. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7476. } // eslint-disable-next-line
  7477. var TIME_REG = /^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d{1,2})(?::(\d{1,2})(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/; // jshint ignore:line
  7478. /**
  7479. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7480. * These values can be accepted:
  7481. * + An instance of Date, represent a time in its own time zone.
  7482. * + Or string in a subset of ISO 8601, only including:
  7483. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7484. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7485. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7486. * all of which will be treated as local time if time zone is not specified
  7487. * (see <https://momentjs.com/>).
  7488. * + Or other string format, including (all of which will be treated as local time):
  7489. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7490. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7491. * + a timestamp, which represent a time in UTC.
  7492. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7493. */
  7494. function parseDate(value) {
  7495. if (value instanceof Date) {
  7496. return value;
  7497. } else if (isString(value)) {
  7498. // Different browsers parse date in different way, so we parse it manually.
  7499. // Some other issues:
  7500. // new Date('1970-01-01') is UTC,
  7501. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7502. // See issue #3623
  7503. var match = TIME_REG.exec(value);
  7504. if (!match) {
  7505. // return Invalid Date.
  7506. return new Date(NaN);
  7507. } // Use local time when no timezone offset is specified.
  7508. if (!match[8]) {
  7509. // match[n] can only be string or undefined.
  7510. // But take care of '12' + 1 => '121'.
  7511. return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, match[7] ? +match[7].substring(0, 3) : 0);
  7512. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7513. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7514. // For example, system timezone is set as "Time Zone: America/Toronto",
  7515. // then these code will get different result:
  7516. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7517. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7518. // So we should not use `new Date`, but use `Date.UTC`.
  7519. else {
  7520. var hour = +match[4] || 0;
  7521. if (match[8].toUpperCase() !== 'Z') {
  7522. hour -= +match[8].slice(0, 3);
  7523. }
  7524. return new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, match[7] ? +match[7].substring(0, 3) : 0));
  7525. }
  7526. } else if (value == null) {
  7527. return new Date(NaN);
  7528. }
  7529. return new Date(Math.round(value));
  7530. }
  7531. /**
  7532. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7533. *
  7534. * @param val
  7535. * @return
  7536. */
  7537. function quantity(val) {
  7538. return Math.pow(10, quantityExponent(val));
  7539. }
  7540. /**
  7541. * Exponent of the quantity of a number
  7542. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7543. *
  7544. * @param val non-negative value
  7545. * @return
  7546. */
  7547. function quantityExponent(val) {
  7548. if (val === 0) {
  7549. return 0;
  7550. }
  7551. var exp = Math.floor(Math.log(val) / Math.LN10);
  7552. /**
  7553. * exp is expected to be the rounded-down result of the base-10 log of val.
  7554. * But due to the precision loss with Math.log(val), we need to restore it
  7555. * using 10^exp to make sure we can get val back from exp. #11249
  7556. */
  7557. if (val / Math.pow(10, exp) >= 10) {
  7558. exp++;
  7559. }
  7560. return exp;
  7561. }
  7562. /**
  7563. * find a “nice” number approximately equal to x. Round the number if round = true,
  7564. * take ceiling if round = false. The primary observation is that the “nicest”
  7565. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7566. *
  7567. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7568. *
  7569. * @param val Non-negative value.
  7570. * @param round
  7571. * @return Niced number
  7572. */
  7573. function nice(val, round) {
  7574. var exponent = quantityExponent(val);
  7575. var exp10 = Math.pow(10, exponent);
  7576. var f = val / exp10; // 1 <= f < 10
  7577. var nf;
  7578. if (round) {
  7579. if (f < 1.5) {
  7580. nf = 1;
  7581. } else if (f < 2.5) {
  7582. nf = 2;
  7583. } else if (f < 4) {
  7584. nf = 3;
  7585. } else if (f < 7) {
  7586. nf = 5;
  7587. } else {
  7588. nf = 10;
  7589. }
  7590. } else {
  7591. if (f < 1) {
  7592. nf = 1;
  7593. } else if (f < 2) {
  7594. nf = 2;
  7595. } else if (f < 3) {
  7596. nf = 3;
  7597. } else if (f < 5) {
  7598. nf = 5;
  7599. } else {
  7600. nf = 10;
  7601. }
  7602. }
  7603. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7604. // 20 is the uppper bound of toFixed.
  7605. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7606. }
  7607. /**
  7608. * This code was copied from "d3.js"
  7609. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7610. * See the license statement at the head of this file.
  7611. * @param ascArr
  7612. */
  7613. function quantile(ascArr, p) {
  7614. var H = (ascArr.length - 1) * p + 1;
  7615. var h = Math.floor(H);
  7616. var v = +ascArr[h - 1];
  7617. var e = H - h;
  7618. return e ? v + e * (ascArr[h] - v) : v;
  7619. }
  7620. /**
  7621. * Order intervals asc, and split them when overlap.
  7622. * expect(numberUtil.reformIntervals([
  7623. * {interval: [18, 62], close: [1, 1]},
  7624. * {interval: [-Infinity, -70], close: [0, 0]},
  7625. * {interval: [-70, -26], close: [1, 1]},
  7626. * {interval: [-26, 18], close: [1, 1]},
  7627. * {interval: [62, 150], close: [1, 1]},
  7628. * {interval: [106, 150], close: [1, 1]},
  7629. * {interval: [150, Infinity], close: [0, 0]}
  7630. * ])).toEqual([
  7631. * {interval: [-Infinity, -70], close: [0, 0]},
  7632. * {interval: [-70, -26], close: [1, 1]},
  7633. * {interval: [-26, 18], close: [0, 1]},
  7634. * {interval: [18, 62], close: [0, 1]},
  7635. * {interval: [62, 150], close: [0, 1]},
  7636. * {interval: [150, Infinity], close: [0, 0]}
  7637. * ]);
  7638. * @param list, where `close` mean open or close
  7639. * of the interval, and Infinity can be used.
  7640. * @return The origin list, which has been reformed.
  7641. */
  7642. function reformIntervals(list) {
  7643. list.sort(function (a, b) {
  7644. return littleThan(a, b, 0) ? -1 : 1;
  7645. });
  7646. var curr = -Infinity;
  7647. var currClose = 1;
  7648. for (var i = 0; i < list.length;) {
  7649. var interval = list[i].interval;
  7650. var close_1 = list[i].close;
  7651. for (var lg = 0; lg < 2; lg++) {
  7652. if (interval[lg] <= curr) {
  7653. interval[lg] = curr;
  7654. close_1[lg] = !lg ? 1 - currClose : 1;
  7655. }
  7656. curr = interval[lg];
  7657. currClose = close_1[lg];
  7658. }
  7659. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7660. list.splice(i, 1);
  7661. } else {
  7662. i++;
  7663. }
  7664. }
  7665. return list;
  7666. function littleThan(a, b, lg) {
  7667. return a.interval[lg] < b.interval[lg] || a.interval[lg] === b.interval[lg] && (a.close[lg] - b.close[lg] === (!lg ? 1 : -1) || !lg && littleThan(a, b, 1));
  7668. }
  7669. }
  7670. /**
  7671. * [Numeric is defined as]:
  7672. * `parseFloat(val) == val`
  7673. * For example:
  7674. * numeric:
  7675. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  7676. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  7677. * not-numeric:
  7678. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  7679. * empty string, string with only white-spaces or line-terminal (see es spec),
  7680. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  7681. * non-string, ...
  7682. *
  7683. * @test See full test cases in `test/ut/spec/util/number.js`.
  7684. * @return Must be a typeof number. If not numeric, return NaN.
  7685. */
  7686. function numericToNumber(val) {
  7687. var valFloat = parseFloat(val);
  7688. return valFloat == val // eslint-disable-line eqeqeq
  7689. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7690. ? valFloat : NaN;
  7691. }
  7692. /**
  7693. * Definition of "numeric": see `numericToNumber`.
  7694. */
  7695. function isNumeric(val) {
  7696. return !isNaN(numericToNumber(val));
  7697. }
  7698. /**
  7699. * Use random base to prevent users hard code depending on
  7700. * this auto generated marker id.
  7701. * @return An positive integer.
  7702. */
  7703. function getRandomIdBase() {
  7704. return Math.round(Math.random() * 9);
  7705. }
  7706. /**
  7707. * Get the greatest common divisor.
  7708. *
  7709. * @param {number} a one number
  7710. * @param {number} b the other number
  7711. */
  7712. function getGreatestCommonDividor(a, b) {
  7713. if (b === 0) {
  7714. return a;
  7715. }
  7716. return getGreatestCommonDividor(b, a % b);
  7717. }
  7718. /**
  7719. * Get the least common multiple.
  7720. *
  7721. * @param {number} a one number
  7722. * @param {number} b the other number
  7723. */
  7724. function getLeastCommonMultiple(a, b) {
  7725. if (a == null) {
  7726. return b;
  7727. }
  7728. if (b == null) {
  7729. return a;
  7730. }
  7731. return a * b / getGreatestCommonDividor(a, b);
  7732. }
  7733. var ECHARTS_PREFIX = '[ECharts] ';
  7734. var storedLogs = {};
  7735. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  7736. && console.warn && console.log;
  7737. function outputLog(type, str, onlyOnce) {
  7738. if (hasConsole) {
  7739. if (onlyOnce) {
  7740. if (storedLogs[str]) {
  7741. return;
  7742. }
  7743. storedLogs[str] = true;
  7744. } // eslint-disable-next-line
  7745. console[type](ECHARTS_PREFIX + str);
  7746. }
  7747. }
  7748. function log(str, onlyOnce) {
  7749. outputLog('log', str, onlyOnce);
  7750. }
  7751. function warn(str, onlyOnce) {
  7752. outputLog('warn', str, onlyOnce);
  7753. }
  7754. function error(str, onlyOnce) {
  7755. outputLog('error', str, onlyOnce);
  7756. }
  7757. function deprecateLog(str) {
  7758. if ("development" !== 'production') {
  7759. // Not display duplicate message.
  7760. outputLog('warn', 'DEPRECATED: ' + str, true);
  7761. }
  7762. }
  7763. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7764. if ("development" !== 'production') {
  7765. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7766. }
  7767. }
  7768. /**
  7769. * If in __DEV__ environment, get console printable message for users hint.
  7770. * Parameters are separated by ' '.
  7771. * @usage
  7772. * makePrintable('This is an error on', someVar, someObj);
  7773. *
  7774. * @param hintInfo anything about the current execution context to hint users.
  7775. * @throws Error
  7776. */
  7777. function makePrintable() {
  7778. var hintInfo = [];
  7779. for (var _i = 0; _i < arguments.length; _i++) {
  7780. hintInfo[_i] = arguments[_i];
  7781. }
  7782. var msg = '';
  7783. if ("development" !== 'production') {
  7784. // Fuzzy stringify for print.
  7785. // This code only exist in dev environment.
  7786. var makePrintableStringIfPossible_1 = function (val) {
  7787. return val === void 0 ? 'undefined' : val === Infinity ? 'Infinity' : val === -Infinity ? '-Infinity' : eqNaN(val) ? 'NaN' : val instanceof Date ? 'Date(' + val.toISOString() + ')' : isFunction(val) ? 'function () { ... }' : isRegExp(val) ? val + '' : null;
  7788. };
  7789. msg = map(hintInfo, function (arg) {
  7790. if (isString(arg)) {
  7791. // Print without quotation mark for some statement.
  7792. return arg;
  7793. } else {
  7794. var printableStr = makePrintableStringIfPossible_1(arg);
  7795. if (printableStr != null) {
  7796. return printableStr;
  7797. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7798. try {
  7799. return JSON.stringify(arg, function (n, val) {
  7800. var printableStr = makePrintableStringIfPossible_1(val);
  7801. return printableStr == null ? val : printableStr;
  7802. }); // In most cases the info object is small, so do not line break.
  7803. } catch (err) {
  7804. return '?';
  7805. }
  7806. } else {
  7807. return '?';
  7808. }
  7809. }
  7810. }).join(' ');
  7811. }
  7812. return msg;
  7813. }
  7814. /**
  7815. * @throws Error
  7816. */
  7817. function throwError(msg) {
  7818. throw new Error(msg);
  7819. }
  7820. function interpolateNumber$1(p0, p1, percent) {
  7821. return (p1 - p0) * percent + p0;
  7822. }
  7823. /**
  7824. * Make the name displayable. But we should
  7825. * make sure it is not duplicated with user
  7826. * specified name, so use '\0';
  7827. */
  7828. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7829. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7830. /**
  7831. * If value is not array, then translate it to array.
  7832. * @param {*} value
  7833. * @return {Array} [value] or value
  7834. */
  7835. function normalizeToArray(value) {
  7836. return value instanceof Array ? value : value == null ? [] : [value];
  7837. }
  7838. /**
  7839. * Sync default option between normal and emphasis like `position` and `show`
  7840. * In case some one will write code like
  7841. * label: {
  7842. * show: false,
  7843. * position: 'outside',
  7844. * fontSize: 18
  7845. * },
  7846. * emphasis: {
  7847. * label: { show: true }
  7848. * }
  7849. */
  7850. function defaultEmphasis(opt, key, subOpts) {
  7851. // Caution: performance sensitive.
  7852. if (opt) {
  7853. opt[key] = opt[key] || {};
  7854. opt.emphasis = opt.emphasis || {};
  7855. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7856. for (var i = 0, len = subOpts.length; i < len; i++) {
  7857. var subOptName = subOpts[i];
  7858. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7859. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7860. }
  7861. }
  7862. }
  7863. }
  7864. var TEXT_STYLE_OPTIONS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth', 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY', 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding']; // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  7865. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7866. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7867. // // FIXME: deprecated, check and remove it.
  7868. // 'textStyle'
  7869. // ]);
  7870. /**
  7871. * The method does not ensure performance.
  7872. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7873. * This helper method retrieves value from data.
  7874. */
  7875. function getDataItemValue(dataItem) {
  7876. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7877. }
  7878. /**
  7879. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7880. * This helper method determine if dataItem has extra option besides value
  7881. */
  7882. function isDataItemOption(dataItem) {
  7883. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7884. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7885. }
  7886. /**
  7887. * Mapping to existings for merge.
  7888. *
  7889. * Mode "normalMege":
  7890. * The mapping result (merge result) will keep the order of the existing
  7891. * component, rather than the order of new option. Because we should ensure
  7892. * some specified index reference (like xAxisIndex) keep work.
  7893. * And in most cases, "merge option" is used to update partial option but not
  7894. * be expected to change the order.
  7895. *
  7896. * Mode "replaceMege":
  7897. * (1) Only the id mapped components will be merged.
  7898. * (2) Other existing components (except internal components) will be removed.
  7899. * (3) Other new options will be used to create new component.
  7900. * (4) The index of the existing components will not be modified.
  7901. * That means their might be "hole" after the removal.
  7902. * The new components are created first at those available index.
  7903. *
  7904. * Mode "replaceAll":
  7905. * This mode try to support that reproduce an echarts instance from another
  7906. * echarts instance (via `getOption`) in some simple cases.
  7907. * In this scenario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7908. * which ensures the component index referring (like `xAxisIndex: ?`) corrent. That is,
  7909. * the "hole" in `newCmptOptions` will also be kept.
  7910. * On the contrary, other modes try best to eliminate holes.
  7911. * PENDING: This is an experimental mode yet.
  7912. *
  7913. * @return See the comment of <MappingResult>.
  7914. */
  7915. function mappingToExists(existings, newCmptOptions, mode) {
  7916. var isNormalMergeMode = mode === 'normalMerge';
  7917. var isReplaceMergeMode = mode === 'replaceMerge';
  7918. var isReplaceAllMode = mode === 'replaceAll';
  7919. existings = existings || [];
  7920. newCmptOptions = (newCmptOptions || []).slice();
  7921. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7922. each(newCmptOptions, function (cmptOption, index) {
  7923. if (!isObject(cmptOption)) {
  7924. newCmptOptions[index] = null;
  7925. return;
  7926. }
  7927. if ("development" !== 'production') {
  7928. // There is some legacy case that name is set as `false`.
  7929. // But should work normally rather than throw error.
  7930. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7931. warnInvalidateIdOrName(cmptOption.id);
  7932. }
  7933. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7934. warnInvalidateIdOrName(cmptOption.name);
  7935. }
  7936. }
  7937. });
  7938. var result = prepareResult(existings, existingIdIdxMap, mode);
  7939. if (isNormalMergeMode || isReplaceMergeMode) {
  7940. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7941. }
  7942. if (isNormalMergeMode) {
  7943. mappingByName(result, newCmptOptions);
  7944. }
  7945. if (isNormalMergeMode || isReplaceMergeMode) {
  7946. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7947. } else if (isReplaceAllMode) {
  7948. mappingInReplaceAllMode(result, newCmptOptions);
  7949. }
  7950. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7951. // forEach will omit those items and result in incorrect result.
  7952. return result;
  7953. }
  7954. function prepareResult(existings, existingIdIdxMap, mode) {
  7955. var result = [];
  7956. if (mode === 'replaceAll') {
  7957. return result;
  7958. } // Do not use native `map` to in case that the array `existings`
  7959. // contains elided items, which will be omitted.
  7960. for (var index = 0; index < existings.length; index++) {
  7961. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7962. if (existing && existing.id != null) {
  7963. existingIdIdxMap.set(existing.id, index);
  7964. } // For non-internal-componnets:
  7965. // Mode "normalMerge": all existings kept.
  7966. // Mode "replaceMerge": all existing removed unless mapped by id.
  7967. // For internal-components:
  7968. // go with "replaceMerge" approach in both mode.
  7969. result.push({
  7970. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7971. newOption: null,
  7972. keyInfo: null,
  7973. brandNew: null
  7974. });
  7975. }
  7976. return result;
  7977. }
  7978. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7979. // Mapping by id if specified.
  7980. each(newCmptOptions, function (cmptOption, index) {
  7981. if (!cmptOption || cmptOption.id == null) {
  7982. return;
  7983. }
  7984. var optionId = makeComparableKey(cmptOption.id);
  7985. var existingIdx = existingIdIdxMap.get(optionId);
  7986. if (existingIdx != null) {
  7987. var resultItem = result[existingIdx];
  7988. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7989. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7990. // the existings rather than creating new component model.
  7991. resultItem.existing = existings[existingIdx];
  7992. newCmptOptions[index] = null;
  7993. }
  7994. });
  7995. }
  7996. function mappingByName(result, newCmptOptions) {
  7997. // Mapping by name if specified.
  7998. each(newCmptOptions, function (cmptOption, index) {
  7999. if (!cmptOption || cmptOption.name == null) {
  8000. return;
  8001. }
  8002. for (var i = 0; i < result.length; i++) {
  8003. var existing = result[i].existing;
  8004. if (!result[i].newOption // Consider name: two map to one.
  8005. // Can not match when both ids existing but different.
  8006. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  8007. result[i].newOption = cmptOption;
  8008. newCmptOptions[index] = null;
  8009. return;
  8010. }
  8011. }
  8012. });
  8013. }
  8014. function mappingByIndex(result, newCmptOptions, brandNew) {
  8015. each(newCmptOptions, function (cmptOption) {
  8016. if (!cmptOption) {
  8017. return;
  8018. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  8019. var resultItem;
  8020. var nextIdx = 0;
  8021. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  8022. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  8023. // after mapping performed, model will always be assigned with an id if user not given.
  8024. // After that all models have id.
  8025. // (2) If new option has id, it can only set to a hole or append to the last. It should
  8026. // not be merged to the existings with different id. Because id should not be overwritten.
  8027. // (3) Name can be overwritten, because axis use name as 'show label text'.
  8028. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  8029. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  8030. nextIdx++;
  8031. }
  8032. if (resultItem) {
  8033. resultItem.newOption = cmptOption;
  8034. resultItem.brandNew = brandNew;
  8035. } else {
  8036. result.push({
  8037. newOption: cmptOption,
  8038. brandNew: brandNew,
  8039. existing: null,
  8040. keyInfo: null
  8041. });
  8042. }
  8043. nextIdx++;
  8044. });
  8045. }
  8046. function mappingInReplaceAllMode(result, newCmptOptions) {
  8047. each(newCmptOptions, function (cmptOption) {
  8048. // The feature "reproduce" requires "hole" will also reproduced
  8049. // in case that component index referring are broken.
  8050. result.push({
  8051. newOption: cmptOption,
  8052. brandNew: true,
  8053. existing: null,
  8054. keyInfo: null
  8055. });
  8056. });
  8057. }
  8058. /**
  8059. * Make id and name for mapping result (result of mappingToExists)
  8060. * into `keyInfo` field.
  8061. */
  8062. function makeIdAndName(mapResult) {
  8063. // We use this id to hash component models and view instances
  8064. // in echarts. id can be specified by user, or auto generated.
  8065. // The id generation rule ensures new view instance are able
  8066. // to mapped to old instance when setOption are called in
  8067. // no-merge mode. So we generate model id by name and plus
  8068. // type in view id.
  8069. // name can be duplicated among components, which is convenient
  8070. // to specify multi components (like series) by one name.
  8071. // Ensure that each id is distinct.
  8072. var idMap = createHashMap();
  8073. each(mapResult, function (item) {
  8074. var existing = item.existing;
  8075. existing && idMap.set(existing.id, item);
  8076. });
  8077. each(mapResult, function (item) {
  8078. var opt = item.newOption; // Force ensure id not duplicated.
  8079. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  8080. opt && opt.id != null && idMap.set(opt.id, item);
  8081. !item.keyInfo && (item.keyInfo = {});
  8082. }); // Make name and id.
  8083. each(mapResult, function (item, index) {
  8084. var existing = item.existing;
  8085. var opt = item.newOption;
  8086. var keyInfo = item.keyInfo;
  8087. if (!isObject(opt)) {
  8088. return;
  8089. } // Name can be overwritten. Consider case: axis.name = '20km'.
  8090. // But id generated by name will not be changed, which affect
  8091. // only in that case: setOption with 'not merge mode' and view
  8092. // instance will be recreated, which can be accepted.
  8093. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid that different series has the same name,
  8094. // because name may be used like in color pallet.
  8095. : DUMMY_COMPONENT_NAME_PREFIX + index;
  8096. if (existing) {
  8097. keyInfo.id = makeComparableKey(existing.id);
  8098. } else if (opt.id != null) {
  8099. keyInfo.id = makeComparableKey(opt.id);
  8100. } else {
  8101. // Consider this situatoin:
  8102. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  8103. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  8104. // Series with the same name between optionA and optionB
  8105. // should be mapped.
  8106. var idNum = 0;
  8107. do {
  8108. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  8109. } while (idMap.get(keyInfo.id));
  8110. }
  8111. idMap.set(keyInfo.id, item);
  8112. });
  8113. }
  8114. function keyExistAndEqual(attr, obj1, obj2) {
  8115. var key1 = convertOptionIdName(obj1[attr], null);
  8116. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  8117. return key1 != null && key2 != null && key1 === key2;
  8118. }
  8119. /**
  8120. * @return return null if not exist.
  8121. */
  8122. function makeComparableKey(val) {
  8123. if ("development" !== 'production') {
  8124. if (val == null) {
  8125. throw new Error();
  8126. }
  8127. }
  8128. return convertOptionIdName(val, '');
  8129. }
  8130. function convertOptionIdName(idOrName, defaultValue) {
  8131. if (idOrName == null) {
  8132. return defaultValue;
  8133. }
  8134. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  8135. }
  8136. function warnInvalidateIdOrName(idOrName) {
  8137. if ("development" !== 'production') {
  8138. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  8139. }
  8140. }
  8141. function isValidIdOrName(idOrName) {
  8142. return isStringSafe(idOrName) || isNumeric(idOrName);
  8143. }
  8144. function isNameSpecified(componentModel) {
  8145. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  8146. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  8147. }
  8148. /**
  8149. * @public
  8150. * @param {Object} cmptOption
  8151. * @return {boolean}
  8152. */
  8153. function isComponentIdInternal(cmptOption) {
  8154. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  8155. }
  8156. function makeInternalComponentId(idSuffix) {
  8157. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  8158. }
  8159. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  8160. // Set mainType and complete subType.
  8161. each(mappingResult, function (item) {
  8162. var newOption = item.newOption;
  8163. if (isObject(newOption)) {
  8164. item.keyInfo.mainType = mainType;
  8165. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  8166. }
  8167. });
  8168. }
  8169. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  8170. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  8171. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  8172. return subType;
  8173. }
  8174. /**
  8175. * A helper for removing duplicate items between batchA and batchB,
  8176. * and in themselves, and categorize by series.
  8177. *
  8178. * @param batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  8179. * @param batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  8180. * @return result: [resultBatchA, resultBatchB]
  8181. */
  8182. function compressBatches(batchA, batchB) {
  8183. var mapA = {};
  8184. var mapB = {};
  8185. makeMap(batchA || [], mapA);
  8186. makeMap(batchB || [], mapB, mapA);
  8187. return [mapToArray(mapA), mapToArray(mapB)];
  8188. function makeMap(sourceBatch, map, otherMap) {
  8189. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  8190. var seriesId = convertOptionIdName(sourceBatch[i].seriesId, null);
  8191. if (seriesId == null) {
  8192. return;
  8193. }
  8194. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  8195. var otherDataIndices = otherMap && otherMap[seriesId];
  8196. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  8197. var dataIndex = dataIndices[j];
  8198. if (otherDataIndices && otherDataIndices[dataIndex]) {
  8199. otherDataIndices[dataIndex] = null;
  8200. } else {
  8201. (map[seriesId] || (map[seriesId] = {}))[dataIndex] = 1;
  8202. }
  8203. }
  8204. }
  8205. }
  8206. function mapToArray(map, isData) {
  8207. var result = [];
  8208. for (var i in map) {
  8209. if (map.hasOwnProperty(i) && map[i] != null) {
  8210. if (isData) {
  8211. result.push(+i);
  8212. } else {
  8213. var dataIndices = mapToArray(map[i], true);
  8214. dataIndices.length && result.push({
  8215. seriesId: i,
  8216. dataIndex: dataIndices
  8217. });
  8218. }
  8219. }
  8220. }
  8221. return result;
  8222. }
  8223. }
  8224. /**
  8225. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  8226. * each of which can be Array or primary type.
  8227. * @return dataIndex If not found, return undefined/null.
  8228. */
  8229. function queryDataIndex(data, payload) {
  8230. if (payload.dataIndexInside != null) {
  8231. return payload.dataIndexInside;
  8232. } else if (payload.dataIndex != null) {
  8233. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  8234. return data.indexOfRawIndex(value);
  8235. }) : data.indexOfRawIndex(payload.dataIndex);
  8236. } else if (payload.name != null) {
  8237. return isArray(payload.name) ? map(payload.name, function (value) {
  8238. return data.indexOfName(value);
  8239. }) : data.indexOfName(payload.name);
  8240. }
  8241. }
  8242. /**
  8243. * Enable property storage to any host object.
  8244. * Notice: Serialization is not supported.
  8245. *
  8246. * For example:
  8247. * let inner = zrUitl.makeInner();
  8248. *
  8249. * function some1(hostObj) {
  8250. * inner(hostObj).someProperty = 1212;
  8251. * ...
  8252. * }
  8253. * function some2() {
  8254. * let fields = inner(this);
  8255. * fields.someProperty1 = 1212;
  8256. * fields.someProperty2 = 'xx';
  8257. * ...
  8258. * }
  8259. *
  8260. * @return {Function}
  8261. */
  8262. function makeInner() {
  8263. var key = '__ec_inner_' + innerUniqueIndex++;
  8264. return function (hostObj) {
  8265. return hostObj[key] || (hostObj[key] = {});
  8266. };
  8267. }
  8268. var innerUniqueIndex = getRandomIdBase();
  8269. /**
  8270. * The same behavior as `component.getReferringComponents`.
  8271. */
  8272. function parseFinder(ecModel, finderInput, opt) {
  8273. var _a = preParseFinder(finderInput, opt),
  8274. mainTypeSpecified = _a.mainTypeSpecified,
  8275. queryOptionMap = _a.queryOptionMap,
  8276. others = _a.others;
  8277. var result = others;
  8278. var defaultMainType = opt ? opt.defaultMainType : null;
  8279. if (!mainTypeSpecified && defaultMainType) {
  8280. queryOptionMap.set(defaultMainType, {});
  8281. }
  8282. queryOptionMap.each(function (queryOption, mainType) {
  8283. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  8284. useDefault: defaultMainType === mainType,
  8285. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  8286. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  8287. });
  8288. result[mainType + 'Models'] = queryResult.models;
  8289. result[mainType + 'Model'] = queryResult.models[0];
  8290. });
  8291. return result;
  8292. }
  8293. function preParseFinder(finderInput, opt) {
  8294. var finder;
  8295. if (isString(finderInput)) {
  8296. var obj = {};
  8297. obj[finderInput + 'Index'] = 0;
  8298. finder = obj;
  8299. } else {
  8300. finder = finderInput;
  8301. }
  8302. var queryOptionMap = createHashMap();
  8303. var others = {};
  8304. var mainTypeSpecified = false;
  8305. each(finder, function (value, key) {
  8306. // Exclude 'dataIndex' and other illgal keys.
  8307. if (key === 'dataIndex' || key === 'dataIndexInside') {
  8308. others[key] = value;
  8309. return;
  8310. }
  8311. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  8312. var mainType = parsedKey[1];
  8313. var queryType = (parsedKey[2] || '').toLowerCase();
  8314. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  8315. return;
  8316. }
  8317. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8318. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8319. queryOption[queryType] = value;
  8320. });
  8321. return {
  8322. mainTypeSpecified: mainTypeSpecified,
  8323. queryOptionMap: queryOptionMap,
  8324. others: others
  8325. };
  8326. }
  8327. var SINGLE_REFERRING = {
  8328. useDefault: true,
  8329. enableAll: false,
  8330. enableNone: false
  8331. };
  8332. var MULTIPLE_REFERRING = {
  8333. useDefault: false,
  8334. enableAll: true,
  8335. enableNone: true
  8336. };
  8337. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8338. opt = opt || SINGLE_REFERRING;
  8339. var indexOption = userOption.index;
  8340. var idOption = userOption.id;
  8341. var nameOption = userOption.name;
  8342. var result = {
  8343. models: null,
  8344. specified: indexOption != null || idOption != null || nameOption != null
  8345. };
  8346. if (!result.specified) {
  8347. // Use the first as default if `useDefault`.
  8348. var firstCmpt = void 0;
  8349. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8350. return result;
  8351. }
  8352. if (indexOption === 'none' || indexOption === false) {
  8353. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  8354. result.models = [];
  8355. return result;
  8356. } // `queryComponents` will return all components if
  8357. // both all of index/id/name are null/undefined.
  8358. if (indexOption === 'all') {
  8359. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  8360. indexOption = idOption = nameOption = null;
  8361. }
  8362. result.models = ecModel.queryComponents({
  8363. mainType: mainType,
  8364. index: indexOption,
  8365. id: idOption,
  8366. name: nameOption
  8367. });
  8368. return result;
  8369. }
  8370. function setAttribute(dom, key, value) {
  8371. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8372. }
  8373. function getAttribute(dom, key) {
  8374. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8375. }
  8376. function getTooltipRenderMode(renderModeOption) {
  8377. if (renderModeOption === 'auto') {
  8378. // Using html when `document` exists, use richText otherwise
  8379. return env.domSupported ? 'html' : 'richText';
  8380. } else {
  8381. return renderModeOption || 'html';
  8382. }
  8383. }
  8384. /**
  8385. * Group a list by key.
  8386. */
  8387. function groupData(array, getKey // return key
  8388. ) {
  8389. var buckets = createHashMap();
  8390. var keys = [];
  8391. each(array, function (item) {
  8392. var key = getKey(item);
  8393. (buckets.get(key) || (keys.push(key), buckets.set(key, []))).push(item);
  8394. });
  8395. return {
  8396. keys: keys,
  8397. buckets: buckets
  8398. };
  8399. }
  8400. /**
  8401. * Interpolate raw values of a series with percent
  8402. *
  8403. * @param data data
  8404. * @param labelModel label model of the text element
  8405. * @param sourceValue start value. May be null/undefined when init.
  8406. * @param targetValue end value
  8407. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8408. * @return interpolated values
  8409. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8410. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8411. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8412. * Other cases do not supported.
  8413. */
  8414. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8415. var isAutoPrecision = precision == null || precision === 'auto';
  8416. if (targetValue == null) {
  8417. return targetValue;
  8418. }
  8419. if (isNumber(targetValue)) {
  8420. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8421. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8422. } else if (isString(targetValue)) {
  8423. return percent < 1 ? sourceValue : targetValue;
  8424. } else {
  8425. var interpolated = [];
  8426. var leftArr = sourceValue;
  8427. var rightArr = targetValue;
  8428. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8429. for (var i = 0; i < length_1; ++i) {
  8430. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  8431. if (info && info.type === 'ordinal') {
  8432. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8433. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8434. } else {
  8435. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8436. var rightVal = rightArr[i];
  8437. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8438. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8439. }
  8440. }
  8441. return interpolated;
  8442. }
  8443. }
  8444. var TYPE_DELIMITER = '.';
  8445. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8446. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8447. /**
  8448. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8449. * @public
  8450. */
  8451. function parseClassType(componentType) {
  8452. var ret = {
  8453. main: '',
  8454. sub: ''
  8455. };
  8456. if (componentType) {
  8457. var typeArr = componentType.split(TYPE_DELIMITER);
  8458. ret.main = typeArr[0] || '';
  8459. ret.sub = typeArr[1] || '';
  8460. }
  8461. return ret;
  8462. }
  8463. /**
  8464. * @public
  8465. */
  8466. function checkClassType(componentType) {
  8467. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8468. }
  8469. function isExtendedClass(clz) {
  8470. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8471. }
  8472. /**
  8473. * Implements `ExtendableConstructor` for `rootClz`.
  8474. *
  8475. * @usage
  8476. * ```ts
  8477. * class Xxx {}
  8478. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8479. * enableClassExtend(Xxx as XxxConstructor);
  8480. * ```
  8481. */
  8482. function enableClassExtend(rootClz, mandatoryMethods) {
  8483. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8484. rootClz.extend = function (proto) {
  8485. if ("development" !== 'production') {
  8486. each(mandatoryMethods, function (method) {
  8487. if (!proto[method]) {
  8488. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8489. }
  8490. });
  8491. }
  8492. var superClass = this;
  8493. var ExtendedClass;
  8494. if (isESClass(superClass)) {
  8495. ExtendedClass =
  8496. /** @class */
  8497. function (_super) {
  8498. __extends(class_1, _super);
  8499. function class_1() {
  8500. return _super.apply(this, arguments) || this;
  8501. }
  8502. return class_1;
  8503. }(superClass);
  8504. } else {
  8505. // For backward compat, we both support ts class inheritance and this
  8506. // "extend" approach.
  8507. // The constructor should keep the same behavior as ts class inheritance:
  8508. // If this constructor/$constructor is not declared, auto invoke the super
  8509. // constructor.
  8510. // If this constructor/$constructor is declared, it is responsible for
  8511. // calling the super constructor.
  8512. ExtendedClass = function () {
  8513. (proto.$constructor || superClass).apply(this, arguments);
  8514. };
  8515. inherits(ExtendedClass, this);
  8516. }
  8517. extend(ExtendedClass.prototype, proto);
  8518. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8519. ExtendedClass.extend = this.extend;
  8520. ExtendedClass.superCall = superCall;
  8521. ExtendedClass.superApply = superApply;
  8522. ExtendedClass.superClass = superClass;
  8523. return ExtendedClass;
  8524. };
  8525. }
  8526. function isESClass(fn) {
  8527. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8528. }
  8529. /**
  8530. * A work around to both support ts extend and this extend mechanism.
  8531. * on sub-class.
  8532. * @usage
  8533. * ```ts
  8534. * class Component { ... }
  8535. * classUtil.enableClassExtend(Component);
  8536. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8537. *
  8538. * class Series extends Component { ... }
  8539. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8540. * Component.markExtend(Series);
  8541. * ```
  8542. */
  8543. function mountExtend(SubClz, SupperClz) {
  8544. SubClz.extend = SupperClz.extend;
  8545. } // A random offset.
  8546. var classBase = Math.round(Math.random() * 10);
  8547. /**
  8548. * Implements `CheckableConstructor` for `target`.
  8549. * Can not use instanceof, consider different scope by
  8550. * cross domain or es module import in ec extensions.
  8551. * Mount a method "isInstance()" to Clz.
  8552. *
  8553. * @usage
  8554. * ```ts
  8555. * class Xxx {}
  8556. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8557. * enableClassCheck(Xxx as XxxConstructor)
  8558. * ```
  8559. */
  8560. function enableClassCheck(target) {
  8561. var classAttr = ['__\0is_clz', classBase++].join('_');
  8562. target.prototype[classAttr] = true;
  8563. if ("development" !== 'production') {
  8564. assert(!target.isInstance, 'The method "is" can not be defined.');
  8565. }
  8566. target.isInstance = function (obj) {
  8567. return !!(obj && obj[classAttr]);
  8568. };
  8569. } // superCall should have class info, which can not be fetched from 'this'.
  8570. // Consider this case:
  8571. // class A has method f,
  8572. // class B inherits class A, overrides method f, f call superApply('f'),
  8573. // class C inherits class B, does not override method f,
  8574. // then when method of class C is called, dead loop occurred.
  8575. function superCall(context, methodName) {
  8576. var args = [];
  8577. for (var _i = 2; _i < arguments.length; _i++) {
  8578. args[_i - 2] = arguments[_i];
  8579. }
  8580. return this.superClass.prototype[methodName].apply(context, args);
  8581. }
  8582. function superApply(context, methodName, args) {
  8583. return this.superClass.prototype[methodName].apply(context, args);
  8584. }
  8585. /**
  8586. * Implements `ClassManager` for `target`
  8587. *
  8588. * @usage
  8589. * ```ts
  8590. * class Xxx {}
  8591. * type XxxConstructor = typeof Xxx & ClassManager
  8592. * enableClassManagement(Xxx as XxxConstructor);
  8593. * ```
  8594. */
  8595. function enableClassManagement(target) {
  8596. /**
  8597. * Component model classes
  8598. * key: componentType,
  8599. * value:
  8600. * componentClass, when componentType is 'a'
  8601. * or Object.<subKey, componentClass>, when componentType is 'a.b'
  8602. */
  8603. var storage = {};
  8604. target.registerClass = function (clz) {
  8605. // `type` should not be a "instance member".
  8606. // If using TS class, should better declared as `static type = 'series.pie'`.
  8607. // otherwise users have to mount `type` on prototype manually.
  8608. // For backward compat and enable instance visit type via `this.type`,
  8609. // we still support fetch `type` from prototype.
  8610. var componentFullType = clz.type || clz.prototype.type;
  8611. if (componentFullType) {
  8612. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  8613. clz.prototype.type = componentFullType;
  8614. var componentTypeInfo = parseClassType(componentFullType);
  8615. if (!componentTypeInfo.sub) {
  8616. if ("development" !== 'production') {
  8617. if (storage[componentTypeInfo.main]) {
  8618. console.warn(componentTypeInfo.main + ' exists.');
  8619. }
  8620. }
  8621. storage[componentTypeInfo.main] = clz;
  8622. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8623. var container = makeContainer(componentTypeInfo);
  8624. container[componentTypeInfo.sub] = clz;
  8625. }
  8626. }
  8627. return clz;
  8628. };
  8629. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8630. var clz = storage[mainType];
  8631. if (clz && clz[IS_CONTAINER]) {
  8632. clz = subType ? clz[subType] : null;
  8633. }
  8634. if (throwWhenNotFound && !clz) {
  8635. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8636. }
  8637. return clz;
  8638. };
  8639. target.getClassesByMainType = function (componentType) {
  8640. var componentTypeInfo = parseClassType(componentType);
  8641. var result = [];
  8642. var obj = storage[componentTypeInfo.main];
  8643. if (obj && obj[IS_CONTAINER]) {
  8644. each(obj, function (o, type) {
  8645. type !== IS_CONTAINER && result.push(o);
  8646. });
  8647. } else {
  8648. result.push(obj);
  8649. }
  8650. return result;
  8651. };
  8652. target.hasClass = function (componentType) {
  8653. // Just consider componentType.main.
  8654. var componentTypeInfo = parseClassType(componentType);
  8655. return !!storage[componentTypeInfo.main];
  8656. };
  8657. /**
  8658. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8659. */
  8660. target.getAllClassMainTypes = function () {
  8661. var types = [];
  8662. each(storage, function (obj, type) {
  8663. types.push(type);
  8664. });
  8665. return types;
  8666. };
  8667. /**
  8668. * If a main type is container and has sub types
  8669. */
  8670. target.hasSubTypes = function (componentType) {
  8671. var componentTypeInfo = parseClassType(componentType);
  8672. var obj = storage[componentTypeInfo.main];
  8673. return obj && obj[IS_CONTAINER];
  8674. };
  8675. function makeContainer(componentTypeInfo) {
  8676. var container = storage[componentTypeInfo.main];
  8677. if (!container || !container[IS_CONTAINER]) {
  8678. container = storage[componentTypeInfo.main] = {};
  8679. container[IS_CONTAINER] = true;
  8680. }
  8681. return container;
  8682. }
  8683. } // /**
  8684. // * @param {string|Array.<string>} properties
  8685. // */
  8686. // export function setReadOnly(obj, properties) {
  8687. // FIXME It seems broken in IE8 simulation of IE11
  8688. // if (!zrUtil.isArray(properties)) {
  8689. // properties = properties != null ? [properties] : [];
  8690. // }
  8691. // zrUtil.each(properties, function (prop) {
  8692. // let value = obj[prop];
  8693. // Object.defineProperty
  8694. // && Object.defineProperty(obj, prop, {
  8695. // value: value, writable: false
  8696. // });
  8697. // zrUtil.isArray(obj[prop])
  8698. // && Object.freeze
  8699. // && Object.freeze(obj[prop]);
  8700. // });
  8701. // }
  8702. function makeStyleMapper(properties, ignoreParent) {
  8703. // Normalize
  8704. for (var i = 0; i < properties.length; i++) {
  8705. if (!properties[i][1]) {
  8706. properties[i][1] = properties[i][0];
  8707. }
  8708. }
  8709. ignoreParent = ignoreParent || false;
  8710. return function (model, excludes, includes) {
  8711. var style = {};
  8712. for (var i = 0; i < properties.length; i++) {
  8713. var propName = properties[i][1];
  8714. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8715. continue;
  8716. }
  8717. var val = model.getShallow(propName, ignoreParent);
  8718. if (val != null) {
  8719. style[properties[i][0]] = val;
  8720. }
  8721. } // TODO Text or image?
  8722. return style;
  8723. };
  8724. }
  8725. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8726. // So do not transfer decal directly.
  8727. ];
  8728. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8729. var AreaStyleMixin =
  8730. /** @class */
  8731. function () {
  8732. function AreaStyleMixin() {}
  8733. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8734. return getAreaStyle(this, excludes, includes);
  8735. };
  8736. return AreaStyleMixin;
  8737. }();
  8738. var globalImageCache = new LRU(50);
  8739. function findExistImage(newImageOrSrc) {
  8740. if (typeof newImageOrSrc === 'string') {
  8741. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8742. return cachedImgObj && cachedImgObj.image;
  8743. }
  8744. else {
  8745. return newImageOrSrc;
  8746. }
  8747. }
  8748. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8749. if (!newImageOrSrc) {
  8750. return image;
  8751. }
  8752. else if (typeof newImageOrSrc === 'string') {
  8753. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8754. return image;
  8755. }
  8756. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8757. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8758. if (cachedImgObj) {
  8759. image = cachedImgObj.image;
  8760. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8761. }
  8762. else {
  8763. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  8764. image.__zrImageSrc = newImageOrSrc;
  8765. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8766. image: image,
  8767. pending: [pendingWrap]
  8768. });
  8769. }
  8770. return image;
  8771. }
  8772. else {
  8773. return newImageOrSrc;
  8774. }
  8775. }
  8776. function imageOnLoad() {
  8777. var cachedImgObj = this.__cachedImgObj;
  8778. this.onload = this.onerror = this.__cachedImgObj = null;
  8779. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8780. var pendingWrap = cachedImgObj.pending[i];
  8781. var cb = pendingWrap.cb;
  8782. cb && cb(this, pendingWrap.cbPayload);
  8783. pendingWrap.hostEl.dirty();
  8784. }
  8785. cachedImgObj.pending.length = 0;
  8786. }
  8787. function isImageReady(image) {
  8788. return image && image.width && image.height;
  8789. }
  8790. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8791. function truncateText(text, containerWidth, font, ellipsis, options) {
  8792. if (!containerWidth) {
  8793. return '';
  8794. }
  8795. var textLines = (text + '').split('\n');
  8796. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8797. for (var i = 0, len = textLines.length; i < len; i++) {
  8798. textLines[i] = truncateSingleLine(textLines[i], options);
  8799. }
  8800. return textLines.join('\n');
  8801. }
  8802. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8803. options = options || {};
  8804. var preparedOpts = extend({}, options);
  8805. preparedOpts.font = font;
  8806. ellipsis = retrieve2(ellipsis, '...');
  8807. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8808. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8809. preparedOpts.cnCharWidth = getWidth('国', font);
  8810. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8811. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8812. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8813. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8814. contentWidth -= ascCharWidth;
  8815. }
  8816. var ellipsisWidth = getWidth(ellipsis, font);
  8817. if (ellipsisWidth > contentWidth) {
  8818. ellipsis = '';
  8819. ellipsisWidth = 0;
  8820. }
  8821. contentWidth = containerWidth - ellipsisWidth;
  8822. preparedOpts.ellipsis = ellipsis;
  8823. preparedOpts.ellipsisWidth = ellipsisWidth;
  8824. preparedOpts.contentWidth = contentWidth;
  8825. preparedOpts.containerWidth = containerWidth;
  8826. return preparedOpts;
  8827. }
  8828. function truncateSingleLine(textLine, options) {
  8829. var containerWidth = options.containerWidth;
  8830. var font = options.font;
  8831. var contentWidth = options.contentWidth;
  8832. if (!containerWidth) {
  8833. return '';
  8834. }
  8835. var lineWidth = getWidth(textLine, font);
  8836. if (lineWidth <= containerWidth) {
  8837. return textLine;
  8838. }
  8839. for (var j = 0;; j++) {
  8840. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8841. textLine += options.ellipsis;
  8842. break;
  8843. }
  8844. var subLength = j === 0
  8845. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8846. : lineWidth > 0
  8847. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8848. : 0;
  8849. textLine = textLine.substr(0, subLength);
  8850. lineWidth = getWidth(textLine, font);
  8851. }
  8852. if (textLine === '') {
  8853. textLine = options.placeholder;
  8854. }
  8855. return textLine;
  8856. }
  8857. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8858. var width = 0;
  8859. var i = 0;
  8860. for (var len = text.length; i < len && width < contentWidth; i++) {
  8861. var charCode = text.charCodeAt(i);
  8862. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8863. }
  8864. return i;
  8865. }
  8866. function parsePlainText(text, style) {
  8867. text != null && (text += '');
  8868. var overflow = style.overflow;
  8869. var padding = style.padding;
  8870. var font = style.font;
  8871. var truncate = overflow === 'truncate';
  8872. var calculatedLineHeight = getLineHeight(font);
  8873. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8874. var bgColorDrawn = !!(style.backgroundColor);
  8875. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8876. var width = style.width;
  8877. var lines;
  8878. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  8879. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8880. }
  8881. else {
  8882. lines = text ? text.split('\n') : [];
  8883. }
  8884. var contentHeight = lines.length * lineHeight;
  8885. var height = retrieve2(style.height, contentHeight);
  8886. if (contentHeight > height && truncateLineOverflow) {
  8887. var lineCount = Math.floor(height / lineHeight);
  8888. lines = lines.slice(0, lineCount);
  8889. }
  8890. if (text && truncate && width != null) {
  8891. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8892. minChar: style.truncateMinChar,
  8893. placeholder: style.placeholder
  8894. });
  8895. for (var i = 0; i < lines.length; i++) {
  8896. lines[i] = truncateSingleLine(lines[i], options);
  8897. }
  8898. }
  8899. var outerHeight = height;
  8900. var contentWidth = 0;
  8901. for (var i = 0; i < lines.length; i++) {
  8902. contentWidth = Math.max(getWidth(lines[i], font), contentWidth);
  8903. }
  8904. if (width == null) {
  8905. width = contentWidth;
  8906. }
  8907. var outerWidth = contentWidth;
  8908. if (padding) {
  8909. outerHeight += padding[0] + padding[2];
  8910. outerWidth += padding[1] + padding[3];
  8911. width += padding[1] + padding[3];
  8912. }
  8913. if (bgColorDrawn) {
  8914. outerWidth = width;
  8915. }
  8916. return {
  8917. lines: lines,
  8918. height: height,
  8919. outerWidth: outerWidth,
  8920. outerHeight: outerHeight,
  8921. lineHeight: lineHeight,
  8922. calculatedLineHeight: calculatedLineHeight,
  8923. contentWidth: contentWidth,
  8924. contentHeight: contentHeight,
  8925. width: width
  8926. };
  8927. }
  8928. var RichTextToken = (function () {
  8929. function RichTextToken() {
  8930. }
  8931. return RichTextToken;
  8932. }());
  8933. var RichTextLine = (function () {
  8934. function RichTextLine(tokens) {
  8935. this.tokens = [];
  8936. if (tokens) {
  8937. this.tokens = tokens;
  8938. }
  8939. }
  8940. return RichTextLine;
  8941. }());
  8942. var RichTextContentBlock = (function () {
  8943. function RichTextContentBlock() {
  8944. this.width = 0;
  8945. this.height = 0;
  8946. this.contentWidth = 0;
  8947. this.contentHeight = 0;
  8948. this.outerWidth = 0;
  8949. this.outerHeight = 0;
  8950. this.lines = [];
  8951. }
  8952. return RichTextContentBlock;
  8953. }());
  8954. function parseRichText(text, style) {
  8955. var contentBlock = new RichTextContentBlock();
  8956. text != null && (text += '');
  8957. if (!text) {
  8958. return contentBlock;
  8959. }
  8960. var topWidth = style.width;
  8961. var topHeight = style.height;
  8962. var overflow = style.overflow;
  8963. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8964. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8965. : null;
  8966. var lastIndex = STYLE_REG.lastIndex = 0;
  8967. var result;
  8968. while ((result = STYLE_REG.exec(text)) != null) {
  8969. var matchedIndex = result.index;
  8970. if (matchedIndex > lastIndex) {
  8971. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8972. }
  8973. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8974. lastIndex = STYLE_REG.lastIndex;
  8975. }
  8976. if (lastIndex < text.length) {
  8977. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8978. }
  8979. var pendingList = [];
  8980. var calculatedHeight = 0;
  8981. var calculatedWidth = 0;
  8982. var stlPadding = style.padding;
  8983. var truncate = overflow === 'truncate';
  8984. var truncateLine = style.lineOverflow === 'truncate';
  8985. function finishLine(line, lineWidth, lineHeight) {
  8986. line.width = lineWidth;
  8987. line.lineHeight = lineHeight;
  8988. calculatedHeight += lineHeight;
  8989. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8990. }
  8991. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8992. var line = contentBlock.lines[i];
  8993. var lineHeight = 0;
  8994. var lineWidth = 0;
  8995. for (var j = 0; j < line.tokens.length; j++) {
  8996. var token = line.tokens[j];
  8997. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8998. var textPadding = token.textPadding = tokenStyle.padding;
  8999. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  9000. var font = token.font = tokenStyle.font || style.font;
  9001. token.contentHeight = getLineHeight(font);
  9002. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  9003. token.innerHeight = tokenHeight;
  9004. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  9005. token.height = tokenHeight;
  9006. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  9007. token.align = tokenStyle && tokenStyle.align || style.align;
  9008. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  9009. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  9010. if (j > 0) {
  9011. line.tokens = line.tokens.slice(0, j);
  9012. finishLine(line, lineWidth, lineHeight);
  9013. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  9014. }
  9015. else {
  9016. contentBlock.lines = contentBlock.lines.slice(0, i);
  9017. }
  9018. break outer;
  9019. }
  9020. var styleTokenWidth = tokenStyle.width;
  9021. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  9022. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  9023. token.percentWidth = styleTokenWidth;
  9024. pendingList.push(token);
  9025. token.contentWidth = getWidth(token.text, font);
  9026. }
  9027. else {
  9028. if (tokenWidthNotSpecified) {
  9029. var textBackgroundColor = tokenStyle.backgroundColor;
  9030. var bgImg = textBackgroundColor && textBackgroundColor.image;
  9031. if (bgImg) {
  9032. bgImg = findExistImage(bgImg);
  9033. if (isImageReady(bgImg)) {
  9034. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  9035. }
  9036. }
  9037. }
  9038. var remainTruncWidth = truncate && topWidth != null
  9039. ? topWidth - lineWidth : null;
  9040. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  9041. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  9042. token.text = '';
  9043. token.width = token.contentWidth = 0;
  9044. }
  9045. else {
  9046. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  9047. token.width = token.contentWidth = getWidth(token.text, font);
  9048. }
  9049. }
  9050. else {
  9051. token.contentWidth = getWidth(token.text, font);
  9052. }
  9053. }
  9054. token.width += paddingH;
  9055. lineWidth += token.width;
  9056. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  9057. }
  9058. finishLine(line, lineWidth, lineHeight);
  9059. }
  9060. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  9061. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  9062. contentBlock.contentHeight = calculatedHeight;
  9063. contentBlock.contentWidth = calculatedWidth;
  9064. if (stlPadding) {
  9065. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  9066. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  9067. }
  9068. for (var i = 0; i < pendingList.length; i++) {
  9069. var token = pendingList[i];
  9070. var percentWidth = token.percentWidth;
  9071. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  9072. }
  9073. return contentBlock;
  9074. }
  9075. function pushTokens(block, str, style, wrapInfo, styleName) {
  9076. var isEmptyStr = str === '';
  9077. var tokenStyle = styleName && style.rich[styleName] || {};
  9078. var lines = block.lines;
  9079. var font = tokenStyle.font || style.font;
  9080. var newLine = false;
  9081. var strLines;
  9082. var linesWidths;
  9083. if (wrapInfo) {
  9084. var tokenPadding = tokenStyle.padding;
  9085. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  9086. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  9087. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  9088. if (lines.length > 0) {
  9089. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  9090. strLines = str.split('\n');
  9091. newLine = true;
  9092. }
  9093. }
  9094. wrapInfo.accumWidth = outerWidth_1;
  9095. }
  9096. else {
  9097. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  9098. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  9099. linesWidths = res.linesWidths;
  9100. strLines = res.lines;
  9101. }
  9102. }
  9103. else {
  9104. strLines = str.split('\n');
  9105. }
  9106. for (var i = 0; i < strLines.length; i++) {
  9107. var text = strLines[i];
  9108. var token = new RichTextToken();
  9109. token.styleName = styleName;
  9110. token.text = text;
  9111. token.isLineHolder = !text && !isEmptyStr;
  9112. if (typeof tokenStyle.width === 'number') {
  9113. token.width = tokenStyle.width;
  9114. }
  9115. else {
  9116. token.width = linesWidths
  9117. ? linesWidths[i]
  9118. : getWidth(text, font);
  9119. }
  9120. if (!i && !newLine) {
  9121. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  9122. var tokensLen = tokens.length;
  9123. (tokensLen === 1 && tokens[0].isLineHolder)
  9124. ? (tokens[0] = token)
  9125. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  9126. }
  9127. else {
  9128. lines.push(new RichTextLine([token]));
  9129. }
  9130. }
  9131. }
  9132. function isAlphabeticLetter(ch) {
  9133. var code = ch.charCodeAt(0);
  9134. return code >= 0x20 && code <= 0x24F
  9135. || code >= 0x370 && code <= 0x10FF
  9136. || code >= 0x1200 && code <= 0x13FF
  9137. || code >= 0x1E00 && code <= 0x206F;
  9138. }
  9139. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  9140. obj[ch] = true;
  9141. return obj;
  9142. }, {});
  9143. function isWordBreakChar(ch) {
  9144. if (isAlphabeticLetter(ch)) {
  9145. if (breakCharMap[ch]) {
  9146. return true;
  9147. }
  9148. return false;
  9149. }
  9150. return true;
  9151. }
  9152. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  9153. var lines = [];
  9154. var linesWidths = [];
  9155. var line = '';
  9156. var currentWord = '';
  9157. var currentWordWidth = 0;
  9158. var accumWidth = 0;
  9159. for (var i = 0; i < text.length; i++) {
  9160. var ch = text.charAt(i);
  9161. if (ch === '\n') {
  9162. if (currentWord) {
  9163. line += currentWord;
  9164. accumWidth += currentWordWidth;
  9165. }
  9166. lines.push(line);
  9167. linesWidths.push(accumWidth);
  9168. line = '';
  9169. currentWord = '';
  9170. currentWordWidth = 0;
  9171. accumWidth = 0;
  9172. continue;
  9173. }
  9174. var chWidth = getWidth(ch, font);
  9175. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  9176. if (!lines.length
  9177. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  9178. : accumWidth + chWidth > lineWidth) {
  9179. if (!accumWidth) {
  9180. if (inWord) {
  9181. lines.push(currentWord);
  9182. linesWidths.push(currentWordWidth);
  9183. currentWord = ch;
  9184. currentWordWidth = chWidth;
  9185. }
  9186. else {
  9187. lines.push(ch);
  9188. linesWidths.push(chWidth);
  9189. }
  9190. }
  9191. else if (line || currentWord) {
  9192. if (inWord) {
  9193. if (!line) {
  9194. line = currentWord;
  9195. currentWord = '';
  9196. currentWordWidth = 0;
  9197. accumWidth = currentWordWidth;
  9198. }
  9199. lines.push(line);
  9200. linesWidths.push(accumWidth - currentWordWidth);
  9201. currentWord += ch;
  9202. currentWordWidth += chWidth;
  9203. line = '';
  9204. accumWidth = currentWordWidth;
  9205. }
  9206. else {
  9207. if (currentWord) {
  9208. line += currentWord;
  9209. currentWord = '';
  9210. currentWordWidth = 0;
  9211. }
  9212. lines.push(line);
  9213. linesWidths.push(accumWidth);
  9214. line = ch;
  9215. accumWidth = chWidth;
  9216. }
  9217. }
  9218. continue;
  9219. }
  9220. accumWidth += chWidth;
  9221. if (inWord) {
  9222. currentWord += ch;
  9223. currentWordWidth += chWidth;
  9224. }
  9225. else {
  9226. if (currentWord) {
  9227. line += currentWord;
  9228. currentWord = '';
  9229. currentWordWidth = 0;
  9230. }
  9231. line += ch;
  9232. }
  9233. }
  9234. if (!lines.length && !line) {
  9235. line = text;
  9236. currentWord = '';
  9237. currentWordWidth = 0;
  9238. }
  9239. if (currentWord) {
  9240. line += currentWord;
  9241. }
  9242. if (line) {
  9243. lines.push(line);
  9244. linesWidths.push(accumWidth);
  9245. }
  9246. if (lines.length === 1) {
  9247. accumWidth += lastAccumWidth;
  9248. }
  9249. return {
  9250. accumWidth: accumWidth,
  9251. lines: lines,
  9252. linesWidths: linesWidths
  9253. };
  9254. }
  9255. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  9256. var DEFAULT_COMMON_STYLE = {
  9257. shadowBlur: 0,
  9258. shadowOffsetX: 0,
  9259. shadowOffsetY: 0,
  9260. shadowColor: '#000',
  9261. opacity: 1,
  9262. blend: 'source-over'
  9263. };
  9264. var DEFAULT_COMMON_ANIMATION_PROPS = {
  9265. style: {
  9266. shadowBlur: true,
  9267. shadowOffsetX: true,
  9268. shadowOffsetY: true,
  9269. shadowColor: true,
  9270. opacity: true
  9271. }
  9272. };
  9273. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  9274. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  9275. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  9276. var Displayable = (function (_super) {
  9277. __extends(Displayable, _super);
  9278. function Displayable(props) {
  9279. return _super.call(this, props) || this;
  9280. }
  9281. Displayable.prototype._init = function (props) {
  9282. var keysArr = keys(props);
  9283. for (var i = 0; i < keysArr.length; i++) {
  9284. var key = keysArr[i];
  9285. if (key === 'style') {
  9286. this.useStyle(props[key]);
  9287. }
  9288. else {
  9289. _super.prototype.attrKV.call(this, key, props[key]);
  9290. }
  9291. }
  9292. if (!this.style) {
  9293. this.useStyle({});
  9294. }
  9295. };
  9296. Displayable.prototype.beforeBrush = function () { };
  9297. Displayable.prototype.afterBrush = function () { };
  9298. Displayable.prototype.innerBeforeBrush = function () { };
  9299. Displayable.prototype.innerAfterBrush = function () { };
  9300. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  9301. var m = this.transform;
  9302. if (this.ignore
  9303. || this.invisible
  9304. || this.style.opacity === 0
  9305. || (this.culling
  9306. && isDisplayableCulled(this, viewWidth, viewHeight))
  9307. || (m && !m[0] && !m[3])) {
  9308. return false;
  9309. }
  9310. if (considerClipPath && this.__clipPaths) {
  9311. for (var i = 0; i < this.__clipPaths.length; ++i) {
  9312. if (this.__clipPaths[i].isZeroArea()) {
  9313. return false;
  9314. }
  9315. }
  9316. }
  9317. if (considerAncestors && this.parent) {
  9318. var parent_1 = this.parent;
  9319. while (parent_1) {
  9320. if (parent_1.ignore) {
  9321. return false;
  9322. }
  9323. parent_1 = parent_1.parent;
  9324. }
  9325. }
  9326. return true;
  9327. };
  9328. Displayable.prototype.contain = function (x, y) {
  9329. return this.rectContain(x, y);
  9330. };
  9331. Displayable.prototype.traverse = function (cb, context) {
  9332. cb.call(context, this);
  9333. };
  9334. Displayable.prototype.rectContain = function (x, y) {
  9335. var coord = this.transformCoordToLocal(x, y);
  9336. var rect = this.getBoundingRect();
  9337. return rect.contain(coord[0], coord[1]);
  9338. };
  9339. Displayable.prototype.getPaintRect = function () {
  9340. var rect = this._paintRect;
  9341. if (!this._paintRect || this.__dirty) {
  9342. var transform = this.transform;
  9343. var elRect = this.getBoundingRect();
  9344. var style = this.style;
  9345. var shadowSize = style.shadowBlur || 0;
  9346. var shadowOffsetX = style.shadowOffsetX || 0;
  9347. var shadowOffsetY = style.shadowOffsetY || 0;
  9348. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  9349. if (transform) {
  9350. BoundingRect.applyTransform(rect, elRect, transform);
  9351. }
  9352. else {
  9353. rect.copy(elRect);
  9354. }
  9355. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9356. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9357. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9358. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9359. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9360. }
  9361. var tolerance = this.dirtyRectTolerance;
  9362. if (!rect.isZero()) {
  9363. rect.x = Math.floor(rect.x - tolerance);
  9364. rect.y = Math.floor(rect.y - tolerance);
  9365. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9366. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9367. }
  9368. }
  9369. return rect;
  9370. };
  9371. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9372. if (paintRect) {
  9373. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9374. this._prevPaintRect.copy(paintRect);
  9375. }
  9376. else {
  9377. this._prevPaintRect = null;
  9378. }
  9379. };
  9380. Displayable.prototype.getPrevPaintRect = function () {
  9381. return this._prevPaintRect;
  9382. };
  9383. Displayable.prototype.animateStyle = function (loop) {
  9384. return this.animate('style', loop);
  9385. };
  9386. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9387. if (targetKey === 'style') {
  9388. this.dirtyStyle();
  9389. }
  9390. else {
  9391. this.markRedraw();
  9392. }
  9393. };
  9394. Displayable.prototype.attrKV = function (key, value) {
  9395. if (key !== 'style') {
  9396. _super.prototype.attrKV.call(this, key, value);
  9397. }
  9398. else {
  9399. if (!this.style) {
  9400. this.useStyle(value);
  9401. }
  9402. else {
  9403. this.setStyle(value);
  9404. }
  9405. }
  9406. };
  9407. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9408. if (typeof keyOrObj === 'string') {
  9409. this.style[keyOrObj] = value;
  9410. }
  9411. else {
  9412. extend(this.style, keyOrObj);
  9413. }
  9414. this.dirtyStyle();
  9415. return this;
  9416. };
  9417. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9418. if (!notRedraw) {
  9419. this.markRedraw();
  9420. }
  9421. this.__dirty |= STYLE_CHANGED_BIT;
  9422. if (this._rect) {
  9423. this._rect = null;
  9424. }
  9425. };
  9426. Displayable.prototype.dirty = function () {
  9427. this.dirtyStyle();
  9428. };
  9429. Displayable.prototype.styleChanged = function () {
  9430. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9431. };
  9432. Displayable.prototype.styleUpdated = function () {
  9433. this.__dirty &= ~STYLE_CHANGED_BIT;
  9434. };
  9435. Displayable.prototype.createStyle = function (obj) {
  9436. return createObject(DEFAULT_COMMON_STYLE, obj);
  9437. };
  9438. Displayable.prototype.useStyle = function (obj) {
  9439. if (!obj[STYLE_MAGIC_KEY]) {
  9440. obj = this.createStyle(obj);
  9441. }
  9442. if (this.__inHover) {
  9443. this.__hoverStyle = obj;
  9444. }
  9445. else {
  9446. this.style = obj;
  9447. }
  9448. this.dirtyStyle();
  9449. };
  9450. Displayable.prototype.isStyleObject = function (obj) {
  9451. return obj[STYLE_MAGIC_KEY];
  9452. };
  9453. Displayable.prototype._innerSaveToNormal = function (toState) {
  9454. _super.prototype._innerSaveToNormal.call(this, toState);
  9455. var normalState = this._normalState;
  9456. if (toState.style && !normalState.style) {
  9457. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9458. }
  9459. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9460. };
  9461. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9462. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9463. var needsRestoreToNormal = !(state && keepCurrentStates);
  9464. var targetStyle;
  9465. if (state && state.style) {
  9466. if (transition) {
  9467. if (keepCurrentStates) {
  9468. targetStyle = state.style;
  9469. }
  9470. else {
  9471. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9472. this._mergeStyle(targetStyle, state.style);
  9473. }
  9474. }
  9475. else {
  9476. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9477. this._mergeStyle(targetStyle, state.style);
  9478. }
  9479. }
  9480. else if (needsRestoreToNormal) {
  9481. targetStyle = normalState.style;
  9482. }
  9483. if (targetStyle) {
  9484. if (transition) {
  9485. var sourceStyle = this.style;
  9486. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9487. if (needsRestoreToNormal) {
  9488. var changedKeys = keys(sourceStyle);
  9489. for (var i = 0; i < changedKeys.length; i++) {
  9490. var key = changedKeys[i];
  9491. if (key in targetStyle) {
  9492. targetStyle[key] = targetStyle[key];
  9493. this.style[key] = sourceStyle[key];
  9494. }
  9495. }
  9496. }
  9497. var targetKeys = keys(targetStyle);
  9498. for (var i = 0; i < targetKeys.length; i++) {
  9499. var key = targetKeys[i];
  9500. this.style[key] = this.style[key];
  9501. }
  9502. this._transitionState(stateName, {
  9503. style: targetStyle
  9504. }, animationCfg, this.getAnimationStyleProps());
  9505. }
  9506. else {
  9507. this.useStyle(targetStyle);
  9508. }
  9509. }
  9510. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9511. for (var i = 0; i < statesKeys.length; i++) {
  9512. var key = statesKeys[i];
  9513. if (state && state[key] != null) {
  9514. this[key] = state[key];
  9515. }
  9516. else if (needsRestoreToNormal) {
  9517. if (normalState[key] != null) {
  9518. this[key] = normalState[key];
  9519. }
  9520. }
  9521. }
  9522. };
  9523. Displayable.prototype._mergeStates = function (states) {
  9524. var mergedState = _super.prototype._mergeStates.call(this, states);
  9525. var mergedStyle;
  9526. for (var i = 0; i < states.length; i++) {
  9527. var state = states[i];
  9528. if (state.style) {
  9529. mergedStyle = mergedStyle || {};
  9530. this._mergeStyle(mergedStyle, state.style);
  9531. }
  9532. }
  9533. if (mergedStyle) {
  9534. mergedState.style = mergedStyle;
  9535. }
  9536. return mergedState;
  9537. };
  9538. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9539. extend(targetStyle, sourceStyle);
  9540. return targetStyle;
  9541. };
  9542. Displayable.prototype.getAnimationStyleProps = function () {
  9543. return DEFAULT_COMMON_ANIMATION_PROPS;
  9544. };
  9545. Displayable.initDefaultProps = (function () {
  9546. var dispProto = Displayable.prototype;
  9547. dispProto.type = 'displayable';
  9548. dispProto.invisible = false;
  9549. dispProto.z = 0;
  9550. dispProto.z2 = 0;
  9551. dispProto.zlevel = 0;
  9552. dispProto.culling = false;
  9553. dispProto.cursor = 'pointer';
  9554. dispProto.rectHover = false;
  9555. dispProto.incremental = false;
  9556. dispProto._rect = null;
  9557. dispProto.dirtyRectTolerance = 0;
  9558. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9559. })();
  9560. return Displayable;
  9561. }(Element));
  9562. var tmpRect$1 = new BoundingRect(0, 0, 0, 0);
  9563. var viewRect = new BoundingRect(0, 0, 0, 0);
  9564. function isDisplayableCulled(el, width, height) {
  9565. tmpRect$1.copy(el.getBoundingRect());
  9566. if (el.transform) {
  9567. tmpRect$1.applyTransform(el.transform);
  9568. }
  9569. viewRect.width = width;
  9570. viewRect.height = height;
  9571. return !tmpRect$1.intersect(viewRect);
  9572. }
  9573. var mathMin$1 = Math.min;
  9574. var mathMax$1 = Math.max;
  9575. var mathSin = Math.sin;
  9576. var mathCos = Math.cos;
  9577. var PI2 = Math.PI * 2;
  9578. var start = create();
  9579. var end = create();
  9580. var extremity = create();
  9581. function fromPoints(points, min, max) {
  9582. if (points.length === 0) {
  9583. return;
  9584. }
  9585. var p = points[0];
  9586. var left = p[0];
  9587. var right = p[0];
  9588. var top = p[1];
  9589. var bottom = p[1];
  9590. for (var i = 1; i < points.length; i++) {
  9591. p = points[i];
  9592. left = mathMin$1(left, p[0]);
  9593. right = mathMax$1(right, p[0]);
  9594. top = mathMin$1(top, p[1]);
  9595. bottom = mathMax$1(bottom, p[1]);
  9596. }
  9597. min[0] = left;
  9598. min[1] = top;
  9599. max[0] = right;
  9600. max[1] = bottom;
  9601. }
  9602. function fromLine(x0, y0, x1, y1, min, max) {
  9603. min[0] = mathMin$1(x0, x1);
  9604. min[1] = mathMin$1(y0, y1);
  9605. max[0] = mathMax$1(x0, x1);
  9606. max[1] = mathMax$1(y0, y1);
  9607. }
  9608. var xDim = [];
  9609. var yDim = [];
  9610. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9611. var cubicExtrema$1 = cubicExtrema;
  9612. var cubicAt$1 = cubicAt;
  9613. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9614. min[0] = Infinity;
  9615. min[1] = Infinity;
  9616. max[0] = -Infinity;
  9617. max[1] = -Infinity;
  9618. for (var i = 0; i < n; i++) {
  9619. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9620. min[0] = mathMin$1(x, min[0]);
  9621. max[0] = mathMax$1(x, max[0]);
  9622. }
  9623. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9624. for (var i = 0; i < n; i++) {
  9625. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9626. min[1] = mathMin$1(y, min[1]);
  9627. max[1] = mathMax$1(y, max[1]);
  9628. }
  9629. min[0] = mathMin$1(x0, min[0]);
  9630. max[0] = mathMax$1(x0, max[0]);
  9631. min[0] = mathMin$1(x3, min[0]);
  9632. max[0] = mathMax$1(x3, max[0]);
  9633. min[1] = mathMin$1(y0, min[1]);
  9634. max[1] = mathMax$1(y0, max[1]);
  9635. min[1] = mathMin$1(y3, min[1]);
  9636. max[1] = mathMax$1(y3, max[1]);
  9637. }
  9638. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9639. var quadraticExtremum$1 = quadraticExtremum;
  9640. var quadraticAt$1 = quadraticAt;
  9641. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9642. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9643. var x = quadraticAt$1(x0, x1, x2, tx);
  9644. var y = quadraticAt$1(y0, y1, y2, ty);
  9645. min[0] = mathMin$1(x0, x2, x);
  9646. min[1] = mathMin$1(y0, y2, y);
  9647. max[0] = mathMax$1(x0, x2, x);
  9648. max[1] = mathMax$1(y0, y2, y);
  9649. }
  9650. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9651. var vec2Min = min;
  9652. var vec2Max = max;
  9653. var diff = Math.abs(startAngle - endAngle);
  9654. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9655. min$1[0] = x - rx;
  9656. min$1[1] = y - ry;
  9657. max$1[0] = x + rx;
  9658. max$1[1] = y + ry;
  9659. return;
  9660. }
  9661. start[0] = mathCos(startAngle) * rx + x;
  9662. start[1] = mathSin(startAngle) * ry + y;
  9663. end[0] = mathCos(endAngle) * rx + x;
  9664. end[1] = mathSin(endAngle) * ry + y;
  9665. vec2Min(min$1, start, end);
  9666. vec2Max(max$1, start, end);
  9667. startAngle = startAngle % (PI2);
  9668. if (startAngle < 0) {
  9669. startAngle = startAngle + PI2;
  9670. }
  9671. endAngle = endAngle % (PI2);
  9672. if (endAngle < 0) {
  9673. endAngle = endAngle + PI2;
  9674. }
  9675. if (startAngle > endAngle && !anticlockwise) {
  9676. endAngle += PI2;
  9677. }
  9678. else if (startAngle < endAngle && anticlockwise) {
  9679. startAngle += PI2;
  9680. }
  9681. if (anticlockwise) {
  9682. var tmp = endAngle;
  9683. endAngle = startAngle;
  9684. startAngle = tmp;
  9685. }
  9686. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9687. if (angle > startAngle) {
  9688. extremity[0] = mathCos(angle) * rx + x;
  9689. extremity[1] = mathSin(angle) * ry + y;
  9690. vec2Min(min$1, extremity, min$1);
  9691. vec2Max(max$1, extremity, max$1);
  9692. }
  9693. }
  9694. }
  9695. var CMD = {
  9696. M: 1,
  9697. L: 2,
  9698. C: 3,
  9699. Q: 4,
  9700. A: 5,
  9701. Z: 6,
  9702. R: 7
  9703. };
  9704. var tmpOutX = [];
  9705. var tmpOutY = [];
  9706. var min$1 = [];
  9707. var max$1 = [];
  9708. var min2 = [];
  9709. var max2 = [];
  9710. var mathMin$2 = Math.min;
  9711. var mathMax$2 = Math.max;
  9712. var mathCos$1 = Math.cos;
  9713. var mathSin$1 = Math.sin;
  9714. var mathAbs = Math.abs;
  9715. var PI = Math.PI;
  9716. var PI2$1 = PI * 2;
  9717. var hasTypedArray = typeof Float32Array !== 'undefined';
  9718. var tmpAngles = [];
  9719. function modPI2(radian) {
  9720. var n = Math.round(radian / PI * 1e8) / 1e8;
  9721. return (n % 2) * PI;
  9722. }
  9723. function normalizeArcAngles(angles, anticlockwise) {
  9724. var newStartAngle = modPI2(angles[0]);
  9725. if (newStartAngle < 0) {
  9726. newStartAngle += PI2$1;
  9727. }
  9728. var delta = newStartAngle - angles[0];
  9729. var newEndAngle = angles[1];
  9730. newEndAngle += delta;
  9731. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9732. newEndAngle = newStartAngle + PI2$1;
  9733. }
  9734. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9735. newEndAngle = newStartAngle - PI2$1;
  9736. }
  9737. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9738. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9739. }
  9740. else if (anticlockwise && newStartAngle < newEndAngle) {
  9741. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9742. }
  9743. angles[0] = newStartAngle;
  9744. angles[1] = newEndAngle;
  9745. }
  9746. var PathProxy = (function () {
  9747. function PathProxy(notSaveData) {
  9748. this.dpr = 1;
  9749. this._xi = 0;
  9750. this._yi = 0;
  9751. this._x0 = 0;
  9752. this._y0 = 0;
  9753. this._len = 0;
  9754. if (notSaveData) {
  9755. this._saveData = false;
  9756. }
  9757. if (this._saveData) {
  9758. this.data = [];
  9759. }
  9760. }
  9761. PathProxy.prototype.increaseVersion = function () {
  9762. this._version++;
  9763. };
  9764. PathProxy.prototype.getVersion = function () {
  9765. return this._version;
  9766. };
  9767. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9768. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9769. if (segmentIgnoreThreshold > 0) {
  9770. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9771. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9772. }
  9773. };
  9774. PathProxy.prototype.setDPR = function (dpr) {
  9775. this.dpr = dpr;
  9776. };
  9777. PathProxy.prototype.setContext = function (ctx) {
  9778. this._ctx = ctx;
  9779. };
  9780. PathProxy.prototype.getContext = function () {
  9781. return this._ctx;
  9782. };
  9783. PathProxy.prototype.beginPath = function () {
  9784. this._ctx && this._ctx.beginPath();
  9785. this.reset();
  9786. return this;
  9787. };
  9788. PathProxy.prototype.reset = function () {
  9789. if (this._saveData) {
  9790. this._len = 0;
  9791. }
  9792. if (this._pathSegLen) {
  9793. this._pathSegLen = null;
  9794. this._pathLen = 0;
  9795. }
  9796. this._version++;
  9797. };
  9798. PathProxy.prototype.moveTo = function (x, y) {
  9799. this._drawPendingPt();
  9800. this.addData(CMD.M, x, y);
  9801. this._ctx && this._ctx.moveTo(x, y);
  9802. this._x0 = x;
  9803. this._y0 = y;
  9804. this._xi = x;
  9805. this._yi = y;
  9806. return this;
  9807. };
  9808. PathProxy.prototype.lineTo = function (x, y) {
  9809. var dx = mathAbs(x - this._xi);
  9810. var dy = mathAbs(y - this._yi);
  9811. var exceedUnit = dx > this._ux || dy > this._uy;
  9812. this.addData(CMD.L, x, y);
  9813. if (this._ctx && exceedUnit) {
  9814. this._ctx.lineTo(x, y);
  9815. }
  9816. if (exceedUnit) {
  9817. this._xi = x;
  9818. this._yi = y;
  9819. this._pendingPtDist = 0;
  9820. }
  9821. else {
  9822. var d2 = dx * dx + dy * dy;
  9823. if (d2 > this._pendingPtDist) {
  9824. this._pendingPtX = x;
  9825. this._pendingPtY = y;
  9826. this._pendingPtDist = d2;
  9827. }
  9828. }
  9829. return this;
  9830. };
  9831. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9832. this._drawPendingPt();
  9833. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9834. if (this._ctx) {
  9835. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9836. }
  9837. this._xi = x3;
  9838. this._yi = y3;
  9839. return this;
  9840. };
  9841. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9842. this._drawPendingPt();
  9843. this.addData(CMD.Q, x1, y1, x2, y2);
  9844. if (this._ctx) {
  9845. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9846. }
  9847. this._xi = x2;
  9848. this._yi = y2;
  9849. return this;
  9850. };
  9851. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9852. this._drawPendingPt();
  9853. tmpAngles[0] = startAngle;
  9854. tmpAngles[1] = endAngle;
  9855. normalizeArcAngles(tmpAngles, anticlockwise);
  9856. startAngle = tmpAngles[0];
  9857. endAngle = tmpAngles[1];
  9858. var delta = endAngle - startAngle;
  9859. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9860. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9861. this._xi = mathCos$1(endAngle) * r + cx;
  9862. this._yi = mathSin$1(endAngle) * r + cy;
  9863. return this;
  9864. };
  9865. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9866. this._drawPendingPt();
  9867. if (this._ctx) {
  9868. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9869. }
  9870. return this;
  9871. };
  9872. PathProxy.prototype.rect = function (x, y, w, h) {
  9873. this._drawPendingPt();
  9874. this._ctx && this._ctx.rect(x, y, w, h);
  9875. this.addData(CMD.R, x, y, w, h);
  9876. return this;
  9877. };
  9878. PathProxy.prototype.closePath = function () {
  9879. this._drawPendingPt();
  9880. this.addData(CMD.Z);
  9881. var ctx = this._ctx;
  9882. var x0 = this._x0;
  9883. var y0 = this._y0;
  9884. if (ctx) {
  9885. ctx.closePath();
  9886. }
  9887. this._xi = x0;
  9888. this._yi = y0;
  9889. return this;
  9890. };
  9891. PathProxy.prototype.fill = function (ctx) {
  9892. ctx && ctx.fill();
  9893. this.toStatic();
  9894. };
  9895. PathProxy.prototype.stroke = function (ctx) {
  9896. ctx && ctx.stroke();
  9897. this.toStatic();
  9898. };
  9899. PathProxy.prototype.len = function () {
  9900. return this._len;
  9901. };
  9902. PathProxy.prototype.setData = function (data) {
  9903. var len = data.length;
  9904. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9905. this.data = new Float32Array(len);
  9906. }
  9907. for (var i = 0; i < len; i++) {
  9908. this.data[i] = data[i];
  9909. }
  9910. this._len = len;
  9911. };
  9912. PathProxy.prototype.appendPath = function (path) {
  9913. if (!(path instanceof Array)) {
  9914. path = [path];
  9915. }
  9916. var len = path.length;
  9917. var appendSize = 0;
  9918. var offset = this._len;
  9919. for (var i = 0; i < len; i++) {
  9920. appendSize += path[i].len();
  9921. }
  9922. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9923. this.data = new Float32Array(offset + appendSize);
  9924. }
  9925. for (var i = 0; i < len; i++) {
  9926. var appendPathData = path[i].data;
  9927. for (var k = 0; k < appendPathData.length; k++) {
  9928. this.data[offset++] = appendPathData[k];
  9929. }
  9930. }
  9931. this._len = offset;
  9932. };
  9933. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9934. if (!this._saveData) {
  9935. return;
  9936. }
  9937. var data = this.data;
  9938. if (this._len + arguments.length > data.length) {
  9939. this._expandData();
  9940. data = this.data;
  9941. }
  9942. for (var i = 0; i < arguments.length; i++) {
  9943. data[this._len++] = arguments[i];
  9944. }
  9945. };
  9946. PathProxy.prototype._drawPendingPt = function () {
  9947. if (this._pendingPtDist > 0) {
  9948. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  9949. this._pendingPtDist = 0;
  9950. }
  9951. };
  9952. PathProxy.prototype._expandData = function () {
  9953. if (!(this.data instanceof Array)) {
  9954. var newData = [];
  9955. for (var i = 0; i < this._len; i++) {
  9956. newData[i] = this.data[i];
  9957. }
  9958. this.data = newData;
  9959. }
  9960. };
  9961. PathProxy.prototype.toStatic = function () {
  9962. if (!this._saveData) {
  9963. return;
  9964. }
  9965. this._drawPendingPt();
  9966. var data = this.data;
  9967. if (data instanceof Array) {
  9968. data.length = this._len;
  9969. if (hasTypedArray && this._len > 11) {
  9970. this.data = new Float32Array(data);
  9971. }
  9972. }
  9973. };
  9974. PathProxy.prototype.getBoundingRect = function () {
  9975. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9976. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9977. var data = this.data;
  9978. var xi = 0;
  9979. var yi = 0;
  9980. var x0 = 0;
  9981. var y0 = 0;
  9982. var i;
  9983. for (i = 0; i < this._len;) {
  9984. var cmd = data[i++];
  9985. var isFirst = i === 1;
  9986. if (isFirst) {
  9987. xi = data[i];
  9988. yi = data[i + 1];
  9989. x0 = xi;
  9990. y0 = yi;
  9991. }
  9992. switch (cmd) {
  9993. case CMD.M:
  9994. xi = x0 = data[i++];
  9995. yi = y0 = data[i++];
  9996. min2[0] = x0;
  9997. min2[1] = y0;
  9998. max2[0] = x0;
  9999. max2[1] = y0;
  10000. break;
  10001. case CMD.L:
  10002. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  10003. xi = data[i++];
  10004. yi = data[i++];
  10005. break;
  10006. case CMD.C:
  10007. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10008. xi = data[i++];
  10009. yi = data[i++];
  10010. break;
  10011. case CMD.Q:
  10012. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10013. xi = data[i++];
  10014. yi = data[i++];
  10015. break;
  10016. case CMD.A:
  10017. var cx = data[i++];
  10018. var cy = data[i++];
  10019. var rx = data[i++];
  10020. var ry = data[i++];
  10021. var startAngle = data[i++];
  10022. var endAngle = data[i++] + startAngle;
  10023. i += 1;
  10024. var anticlockwise = !data[i++];
  10025. if (isFirst) {
  10026. x0 = mathCos$1(startAngle) * rx + cx;
  10027. y0 = mathSin$1(startAngle) * ry + cy;
  10028. }
  10029. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  10030. xi = mathCos$1(endAngle) * rx + cx;
  10031. yi = mathSin$1(endAngle) * ry + cy;
  10032. break;
  10033. case CMD.R:
  10034. x0 = xi = data[i++];
  10035. y0 = yi = data[i++];
  10036. var width = data[i++];
  10037. var height = data[i++];
  10038. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  10039. break;
  10040. case CMD.Z:
  10041. xi = x0;
  10042. yi = y0;
  10043. break;
  10044. }
  10045. min(min$1, min$1, min2);
  10046. max(max$1, max$1, max2);
  10047. }
  10048. if (i === 0) {
  10049. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  10050. }
  10051. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  10052. };
  10053. PathProxy.prototype._calculateLength = function () {
  10054. var data = this.data;
  10055. var len = this._len;
  10056. var ux = this._ux;
  10057. var uy = this._uy;
  10058. var xi = 0;
  10059. var yi = 0;
  10060. var x0 = 0;
  10061. var y0 = 0;
  10062. if (!this._pathSegLen) {
  10063. this._pathSegLen = [];
  10064. }
  10065. var pathSegLen = this._pathSegLen;
  10066. var pathTotalLen = 0;
  10067. var segCount = 0;
  10068. for (var i = 0; i < len;) {
  10069. var cmd = data[i++];
  10070. var isFirst = i === 1;
  10071. if (isFirst) {
  10072. xi = data[i];
  10073. yi = data[i + 1];
  10074. x0 = xi;
  10075. y0 = yi;
  10076. }
  10077. var l = -1;
  10078. switch (cmd) {
  10079. case CMD.M:
  10080. xi = x0 = data[i++];
  10081. yi = y0 = data[i++];
  10082. break;
  10083. case CMD.L: {
  10084. var x2 = data[i++];
  10085. var y2 = data[i++];
  10086. var dx = x2 - xi;
  10087. var dy = y2 - yi;
  10088. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  10089. l = Math.sqrt(dx * dx + dy * dy);
  10090. xi = x2;
  10091. yi = y2;
  10092. }
  10093. break;
  10094. }
  10095. case CMD.C: {
  10096. var x1 = data[i++];
  10097. var y1 = data[i++];
  10098. var x2 = data[i++];
  10099. var y2 = data[i++];
  10100. var x3 = data[i++];
  10101. var y3 = data[i++];
  10102. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  10103. xi = x3;
  10104. yi = y3;
  10105. break;
  10106. }
  10107. case CMD.Q: {
  10108. var x1 = data[i++];
  10109. var y1 = data[i++];
  10110. var x2 = data[i++];
  10111. var y2 = data[i++];
  10112. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  10113. xi = x2;
  10114. yi = y2;
  10115. break;
  10116. }
  10117. case CMD.A:
  10118. var cx = data[i++];
  10119. var cy = data[i++];
  10120. var rx = data[i++];
  10121. var ry = data[i++];
  10122. var startAngle = data[i++];
  10123. var delta = data[i++];
  10124. var endAngle = delta + startAngle;
  10125. i += 1;
  10126. var anticlockwise = !data[i++];
  10127. if (isFirst) {
  10128. x0 = mathCos$1(startAngle) * rx + cx;
  10129. y0 = mathSin$1(startAngle) * ry + cy;
  10130. }
  10131. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  10132. xi = mathCos$1(endAngle) * rx + cx;
  10133. yi = mathSin$1(endAngle) * ry + cy;
  10134. break;
  10135. case CMD.R: {
  10136. x0 = xi = data[i++];
  10137. y0 = yi = data[i++];
  10138. var width = data[i++];
  10139. var height = data[i++];
  10140. l = width * 2 + height * 2;
  10141. break;
  10142. }
  10143. case CMD.Z: {
  10144. var dx = x0 - xi;
  10145. var dy = y0 - yi;
  10146. l = Math.sqrt(dx * dx + dy * dy);
  10147. xi = x0;
  10148. yi = y0;
  10149. break;
  10150. }
  10151. }
  10152. if (l >= 0) {
  10153. pathSegLen[segCount++] = l;
  10154. pathTotalLen += l;
  10155. }
  10156. }
  10157. this._pathLen = pathTotalLen;
  10158. return pathTotalLen;
  10159. };
  10160. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  10161. var d = this.data;
  10162. var ux = this._ux;
  10163. var uy = this._uy;
  10164. var len = this._len;
  10165. var x0;
  10166. var y0;
  10167. var xi;
  10168. var yi;
  10169. var x;
  10170. var y;
  10171. var drawPart = percent < 1;
  10172. var pathSegLen;
  10173. var pathTotalLen;
  10174. var accumLength = 0;
  10175. var segCount = 0;
  10176. var displayedLength;
  10177. var pendingPtDist = 0;
  10178. var pendingPtX;
  10179. var pendingPtY;
  10180. if (drawPart) {
  10181. if (!this._pathSegLen) {
  10182. this._calculateLength();
  10183. }
  10184. pathSegLen = this._pathSegLen;
  10185. pathTotalLen = this._pathLen;
  10186. displayedLength = percent * pathTotalLen;
  10187. if (!displayedLength) {
  10188. return;
  10189. }
  10190. }
  10191. lo: for (var i = 0; i < len;) {
  10192. var cmd = d[i++];
  10193. var isFirst = i === 1;
  10194. if (isFirst) {
  10195. xi = d[i];
  10196. yi = d[i + 1];
  10197. x0 = xi;
  10198. y0 = yi;
  10199. }
  10200. if (cmd !== CMD.L && pendingPtDist > 0) {
  10201. ctx.lineTo(pendingPtX, pendingPtY);
  10202. pendingPtDist = 0;
  10203. }
  10204. switch (cmd) {
  10205. case CMD.M:
  10206. x0 = xi = d[i++];
  10207. y0 = yi = d[i++];
  10208. ctx.moveTo(xi, yi);
  10209. break;
  10210. case CMD.L: {
  10211. x = d[i++];
  10212. y = d[i++];
  10213. var dx = mathAbs(x - xi);
  10214. var dy = mathAbs(y - yi);
  10215. if (dx > ux || dy > uy) {
  10216. if (drawPart) {
  10217. var l = pathSegLen[segCount++];
  10218. if (accumLength + l > displayedLength) {
  10219. var t = (displayedLength - accumLength) / l;
  10220. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10221. break lo;
  10222. }
  10223. accumLength += l;
  10224. }
  10225. ctx.lineTo(x, y);
  10226. xi = x;
  10227. yi = y;
  10228. pendingPtDist = 0;
  10229. }
  10230. else {
  10231. var d2 = dx * dx + dy * dy;
  10232. if (d2 > pendingPtDist) {
  10233. pendingPtX = x;
  10234. pendingPtY = y;
  10235. pendingPtDist = d2;
  10236. }
  10237. }
  10238. break;
  10239. }
  10240. case CMD.C: {
  10241. var x1 = d[i++];
  10242. var y1 = d[i++];
  10243. var x2 = d[i++];
  10244. var y2 = d[i++];
  10245. var x3 = d[i++];
  10246. var y3 = d[i++];
  10247. if (drawPart) {
  10248. var l = pathSegLen[segCount++];
  10249. if (accumLength + l > displayedLength) {
  10250. var t = (displayedLength - accumLength) / l;
  10251. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10252. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10253. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10254. break lo;
  10255. }
  10256. accumLength += l;
  10257. }
  10258. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10259. xi = x3;
  10260. yi = y3;
  10261. break;
  10262. }
  10263. case CMD.Q: {
  10264. var x1 = d[i++];
  10265. var y1 = d[i++];
  10266. var x2 = d[i++];
  10267. var y2 = d[i++];
  10268. if (drawPart) {
  10269. var l = pathSegLen[segCount++];
  10270. if (accumLength + l > displayedLength) {
  10271. var t = (displayedLength - accumLength) / l;
  10272. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10273. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10274. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10275. break lo;
  10276. }
  10277. accumLength += l;
  10278. }
  10279. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10280. xi = x2;
  10281. yi = y2;
  10282. break;
  10283. }
  10284. case CMD.A:
  10285. var cx = d[i++];
  10286. var cy = d[i++];
  10287. var rx = d[i++];
  10288. var ry = d[i++];
  10289. var startAngle = d[i++];
  10290. var delta = d[i++];
  10291. var psi = d[i++];
  10292. var anticlockwise = !d[i++];
  10293. var r = (rx > ry) ? rx : ry;
  10294. var isEllipse = mathAbs(rx - ry) > 1e-3;
  10295. var endAngle = startAngle + delta;
  10296. var breakBuild = false;
  10297. if (drawPart) {
  10298. var l = pathSegLen[segCount++];
  10299. if (accumLength + l > displayedLength) {
  10300. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10301. breakBuild = true;
  10302. }
  10303. accumLength += l;
  10304. }
  10305. if (isEllipse && ctx.ellipse) {
  10306. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10307. }
  10308. else {
  10309. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10310. }
  10311. if (breakBuild) {
  10312. break lo;
  10313. }
  10314. if (isFirst) {
  10315. x0 = mathCos$1(startAngle) * rx + cx;
  10316. y0 = mathSin$1(startAngle) * ry + cy;
  10317. }
  10318. xi = mathCos$1(endAngle) * rx + cx;
  10319. yi = mathSin$1(endAngle) * ry + cy;
  10320. break;
  10321. case CMD.R:
  10322. x0 = xi = d[i];
  10323. y0 = yi = d[i + 1];
  10324. x = d[i++];
  10325. y = d[i++];
  10326. var width = d[i++];
  10327. var height = d[i++];
  10328. if (drawPart) {
  10329. var l = pathSegLen[segCount++];
  10330. if (accumLength + l > displayedLength) {
  10331. var d_1 = displayedLength - accumLength;
  10332. ctx.moveTo(x, y);
  10333. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10334. d_1 -= width;
  10335. if (d_1 > 0) {
  10336. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10337. }
  10338. d_1 -= height;
  10339. if (d_1 > 0) {
  10340. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10341. }
  10342. d_1 -= width;
  10343. if (d_1 > 0) {
  10344. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10345. }
  10346. break lo;
  10347. }
  10348. accumLength += l;
  10349. }
  10350. ctx.rect(x, y, width, height);
  10351. break;
  10352. case CMD.Z:
  10353. if (drawPart) {
  10354. var l = pathSegLen[segCount++];
  10355. if (accumLength + l > displayedLength) {
  10356. var t = (displayedLength - accumLength) / l;
  10357. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10358. break lo;
  10359. }
  10360. accumLength += l;
  10361. }
  10362. ctx.closePath();
  10363. xi = x0;
  10364. yi = y0;
  10365. }
  10366. }
  10367. };
  10368. PathProxy.prototype.clone = function () {
  10369. var newProxy = new PathProxy();
  10370. var data = this.data;
  10371. newProxy.data = data.slice ? data.slice()
  10372. : Array.prototype.slice.call(data);
  10373. newProxy._len = this._len;
  10374. return newProxy;
  10375. };
  10376. PathProxy.CMD = CMD;
  10377. PathProxy.initDefaultProps = (function () {
  10378. var proto = PathProxy.prototype;
  10379. proto._saveData = true;
  10380. proto._ux = 0;
  10381. proto._uy = 0;
  10382. proto._pendingPtDist = 0;
  10383. proto._version = 0;
  10384. })();
  10385. return PathProxy;
  10386. }());
  10387. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10388. if (lineWidth === 0) {
  10389. return false;
  10390. }
  10391. var _l = lineWidth;
  10392. var _a = 0;
  10393. var _b = x0;
  10394. if ((y > y0 + _l && y > y1 + _l)
  10395. || (y < y0 - _l && y < y1 - _l)
  10396. || (x > x0 + _l && x > x1 + _l)
  10397. || (x < x0 - _l && x < x1 - _l)) {
  10398. return false;
  10399. }
  10400. if (x0 !== x1) {
  10401. _a = (y0 - y1) / (x0 - x1);
  10402. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10403. }
  10404. else {
  10405. return Math.abs(x - x0) <= _l / 2;
  10406. }
  10407. var tmp = _a * x - y + _b;
  10408. var _s = tmp * tmp / (_a * _a + 1);
  10409. return _s <= _l / 2 * _l / 2;
  10410. }
  10411. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10412. if (lineWidth === 0) {
  10413. return false;
  10414. }
  10415. var _l = lineWidth;
  10416. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10417. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10418. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10419. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10420. return false;
  10421. }
  10422. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10423. return d <= _l / 2;
  10424. }
  10425. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10426. if (lineWidth === 0) {
  10427. return false;
  10428. }
  10429. var _l = lineWidth;
  10430. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10431. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10432. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10433. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10434. return false;
  10435. }
  10436. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10437. return d <= _l / 2;
  10438. }
  10439. var PI2$2 = Math.PI * 2;
  10440. function normalizeRadian(angle) {
  10441. angle %= PI2$2;
  10442. if (angle < 0) {
  10443. angle += PI2$2;
  10444. }
  10445. return angle;
  10446. }
  10447. var PI2$3 = Math.PI * 2;
  10448. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10449. if (lineWidth === 0) {
  10450. return false;
  10451. }
  10452. var _l = lineWidth;
  10453. x -= cx;
  10454. y -= cy;
  10455. var d = Math.sqrt(x * x + y * y);
  10456. if ((d - _l > r) || (d + _l < r)) {
  10457. return false;
  10458. }
  10459. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10460. return true;
  10461. }
  10462. if (anticlockwise) {
  10463. var tmp = startAngle;
  10464. startAngle = normalizeRadian(endAngle);
  10465. endAngle = normalizeRadian(tmp);
  10466. }
  10467. else {
  10468. startAngle = normalizeRadian(startAngle);
  10469. endAngle = normalizeRadian(endAngle);
  10470. }
  10471. if (startAngle > endAngle) {
  10472. endAngle += PI2$3;
  10473. }
  10474. var angle = Math.atan2(y, x);
  10475. if (angle < 0) {
  10476. angle += PI2$3;
  10477. }
  10478. return (angle >= startAngle && angle <= endAngle)
  10479. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10480. }
  10481. function windingLine(x0, y0, x1, y1, x, y) {
  10482. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10483. return 0;
  10484. }
  10485. if (y1 === y0) {
  10486. return 0;
  10487. }
  10488. var t = (y - y0) / (y1 - y0);
  10489. var dir = y1 < y0 ? 1 : -1;
  10490. if (t === 1 || t === 0) {
  10491. dir = y1 < y0 ? 0.5 : -0.5;
  10492. }
  10493. var x_ = t * (x1 - x0) + x0;
  10494. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10495. }
  10496. var CMD$1 = PathProxy.CMD;
  10497. var PI2$4 = Math.PI * 2;
  10498. var EPSILON$3 = 1e-4;
  10499. function isAroundEqual(a, b) {
  10500. return Math.abs(a - b) < EPSILON$3;
  10501. }
  10502. var roots = [-1, -1, -1];
  10503. var extrema = [-1, -1];
  10504. function swapExtrema() {
  10505. var tmp = extrema[0];
  10506. extrema[0] = extrema[1];
  10507. extrema[1] = tmp;
  10508. }
  10509. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10510. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10511. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10512. return 0;
  10513. }
  10514. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10515. if (nRoots === 0) {
  10516. return 0;
  10517. }
  10518. else {
  10519. var w = 0;
  10520. var nExtrema = -1;
  10521. var y0_ = void 0;
  10522. var y1_ = void 0;
  10523. for (var i = 0; i < nRoots; i++) {
  10524. var t = roots[i];
  10525. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10526. var x_ = cubicAt(x0, x1, x2, x3, t);
  10527. if (x_ < x) {
  10528. continue;
  10529. }
  10530. if (nExtrema < 0) {
  10531. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10532. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10533. swapExtrema();
  10534. }
  10535. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10536. if (nExtrema > 1) {
  10537. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10538. }
  10539. }
  10540. if (nExtrema === 2) {
  10541. if (t < extrema[0]) {
  10542. w += y0_ < y0 ? unit : -unit;
  10543. }
  10544. else if (t < extrema[1]) {
  10545. w += y1_ < y0_ ? unit : -unit;
  10546. }
  10547. else {
  10548. w += y3 < y1_ ? unit : -unit;
  10549. }
  10550. }
  10551. else {
  10552. if (t < extrema[0]) {
  10553. w += y0_ < y0 ? unit : -unit;
  10554. }
  10555. else {
  10556. w += y3 < y0_ ? unit : -unit;
  10557. }
  10558. }
  10559. }
  10560. return w;
  10561. }
  10562. }
  10563. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10564. if ((y > y0 && y > y1 && y > y2)
  10565. || (y < y0 && y < y1 && y < y2)) {
  10566. return 0;
  10567. }
  10568. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10569. if (nRoots === 0) {
  10570. return 0;
  10571. }
  10572. else {
  10573. var t = quadraticExtremum(y0, y1, y2);
  10574. if (t >= 0 && t <= 1) {
  10575. var w = 0;
  10576. var y_ = quadraticAt(y0, y1, y2, t);
  10577. for (var i = 0; i < nRoots; i++) {
  10578. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10579. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10580. if (x_ < x) {
  10581. continue;
  10582. }
  10583. if (roots[i] < t) {
  10584. w += y_ < y0 ? unit : -unit;
  10585. }
  10586. else {
  10587. w += y2 < y_ ? unit : -unit;
  10588. }
  10589. }
  10590. return w;
  10591. }
  10592. else {
  10593. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10594. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10595. if (x_ < x) {
  10596. return 0;
  10597. }
  10598. return y2 < y0 ? unit : -unit;
  10599. }
  10600. }
  10601. }
  10602. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10603. y -= cy;
  10604. if (y > r || y < -r) {
  10605. return 0;
  10606. }
  10607. var tmp = Math.sqrt(r * r - y * y);
  10608. roots[0] = -tmp;
  10609. roots[1] = tmp;
  10610. var dTheta = Math.abs(startAngle - endAngle);
  10611. if (dTheta < 1e-4) {
  10612. return 0;
  10613. }
  10614. if (dTheta >= PI2$4 - 1e-4) {
  10615. startAngle = 0;
  10616. endAngle = PI2$4;
  10617. var dir = anticlockwise ? 1 : -1;
  10618. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10619. return dir;
  10620. }
  10621. else {
  10622. return 0;
  10623. }
  10624. }
  10625. if (startAngle > endAngle) {
  10626. var tmp_1 = startAngle;
  10627. startAngle = endAngle;
  10628. endAngle = tmp_1;
  10629. }
  10630. if (startAngle < 0) {
  10631. startAngle += PI2$4;
  10632. endAngle += PI2$4;
  10633. }
  10634. var w = 0;
  10635. for (var i = 0; i < 2; i++) {
  10636. var x_ = roots[i];
  10637. if (x_ + cx > x) {
  10638. var angle = Math.atan2(y, x_);
  10639. var dir = anticlockwise ? 1 : -1;
  10640. if (angle < 0) {
  10641. angle = PI2$4 + angle;
  10642. }
  10643. if ((angle >= startAngle && angle <= endAngle)
  10644. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10645. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10646. dir = -dir;
  10647. }
  10648. w += dir;
  10649. }
  10650. }
  10651. }
  10652. return w;
  10653. }
  10654. function containPath(path, lineWidth, isStroke, x, y) {
  10655. var data = path.data;
  10656. var len = path.len();
  10657. var w = 0;
  10658. var xi = 0;
  10659. var yi = 0;
  10660. var x0 = 0;
  10661. var y0 = 0;
  10662. var x1;
  10663. var y1;
  10664. for (var i = 0; i < len;) {
  10665. var cmd = data[i++];
  10666. var isFirst = i === 1;
  10667. if (cmd === CMD$1.M && i > 1) {
  10668. if (!isStroke) {
  10669. w += windingLine(xi, yi, x0, y0, x, y);
  10670. }
  10671. }
  10672. if (isFirst) {
  10673. xi = data[i];
  10674. yi = data[i + 1];
  10675. x0 = xi;
  10676. y0 = yi;
  10677. }
  10678. switch (cmd) {
  10679. case CMD$1.M:
  10680. x0 = data[i++];
  10681. y0 = data[i++];
  10682. xi = x0;
  10683. yi = y0;
  10684. break;
  10685. case CMD$1.L:
  10686. if (isStroke) {
  10687. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10688. return true;
  10689. }
  10690. }
  10691. else {
  10692. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10693. }
  10694. xi = data[i++];
  10695. yi = data[i++];
  10696. break;
  10697. case CMD$1.C:
  10698. if (isStroke) {
  10699. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10700. return true;
  10701. }
  10702. }
  10703. else {
  10704. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10705. }
  10706. xi = data[i++];
  10707. yi = data[i++];
  10708. break;
  10709. case CMD$1.Q:
  10710. if (isStroke) {
  10711. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10712. return true;
  10713. }
  10714. }
  10715. else {
  10716. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10717. }
  10718. xi = data[i++];
  10719. yi = data[i++];
  10720. break;
  10721. case CMD$1.A:
  10722. var cx = data[i++];
  10723. var cy = data[i++];
  10724. var rx = data[i++];
  10725. var ry = data[i++];
  10726. var theta = data[i++];
  10727. var dTheta = data[i++];
  10728. i += 1;
  10729. var anticlockwise = !!(1 - data[i++]);
  10730. x1 = Math.cos(theta) * rx + cx;
  10731. y1 = Math.sin(theta) * ry + cy;
  10732. if (!isFirst) {
  10733. w += windingLine(xi, yi, x1, y1, x, y);
  10734. }
  10735. else {
  10736. x0 = x1;
  10737. y0 = y1;
  10738. }
  10739. var _x = (x - cx) * ry / rx + cx;
  10740. if (isStroke) {
  10741. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10742. return true;
  10743. }
  10744. }
  10745. else {
  10746. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10747. }
  10748. xi = Math.cos(theta + dTheta) * rx + cx;
  10749. yi = Math.sin(theta + dTheta) * ry + cy;
  10750. break;
  10751. case CMD$1.R:
  10752. x0 = xi = data[i++];
  10753. y0 = yi = data[i++];
  10754. var width = data[i++];
  10755. var height = data[i++];
  10756. x1 = x0 + width;
  10757. y1 = y0 + height;
  10758. if (isStroke) {
  10759. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10760. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10761. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10762. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10763. return true;
  10764. }
  10765. }
  10766. else {
  10767. w += windingLine(x1, y0, x1, y1, x, y);
  10768. w += windingLine(x0, y1, x0, y0, x, y);
  10769. }
  10770. break;
  10771. case CMD$1.Z:
  10772. if (isStroke) {
  10773. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10774. return true;
  10775. }
  10776. }
  10777. else {
  10778. w += windingLine(xi, yi, x0, y0, x, y);
  10779. }
  10780. xi = x0;
  10781. yi = y0;
  10782. break;
  10783. }
  10784. }
  10785. if (!isStroke && !isAroundEqual(yi, y0)) {
  10786. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10787. }
  10788. return w !== 0;
  10789. }
  10790. function contain(pathProxy, x, y) {
  10791. return containPath(pathProxy, 0, false, x, y);
  10792. }
  10793. function containStroke$4(pathProxy, lineWidth, x, y) {
  10794. return containPath(pathProxy, lineWidth, true, x, y);
  10795. }
  10796. var DEFAULT_PATH_STYLE = defaults({
  10797. fill: '#000',
  10798. stroke: null,
  10799. strokePercent: 1,
  10800. fillOpacity: 1,
  10801. strokeOpacity: 1,
  10802. lineDashOffset: 0,
  10803. lineWidth: 1,
  10804. lineCap: 'butt',
  10805. miterLimit: 10,
  10806. strokeNoScale: false,
  10807. strokeFirst: false
  10808. }, DEFAULT_COMMON_STYLE);
  10809. var DEFAULT_PATH_ANIMATION_PROPS = {
  10810. style: defaults({
  10811. fill: true,
  10812. stroke: true,
  10813. strokePercent: true,
  10814. fillOpacity: true,
  10815. strokeOpacity: true,
  10816. lineDashOffset: true,
  10817. lineWidth: true,
  10818. miterLimit: true
  10819. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10820. };
  10821. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  10822. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10823. ]);
  10824. var Path = (function (_super) {
  10825. __extends(Path, _super);
  10826. function Path(opts) {
  10827. return _super.call(this, opts) || this;
  10828. }
  10829. Path.prototype.update = function () {
  10830. var _this = this;
  10831. _super.prototype.update.call(this);
  10832. var style = this.style;
  10833. if (style.decal) {
  10834. var decalEl = this._decalEl = this._decalEl || new Path();
  10835. if (decalEl.buildPath === Path.prototype.buildPath) {
  10836. decalEl.buildPath = function (ctx) {
  10837. _this.buildPath(ctx, _this.shape);
  10838. };
  10839. }
  10840. decalEl.silent = true;
  10841. var decalElStyle = decalEl.style;
  10842. for (var key in style) {
  10843. if (decalElStyle[key] !== style[key]) {
  10844. decalElStyle[key] = style[key];
  10845. }
  10846. }
  10847. decalElStyle.fill = style.fill ? style.decal : null;
  10848. decalElStyle.decal = null;
  10849. decalElStyle.shadowColor = null;
  10850. style.strokeFirst && (decalElStyle.stroke = null);
  10851. for (var i = 0; i < pathCopyParams.length; ++i) {
  10852. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10853. }
  10854. decalEl.__dirty |= REDRAW_BIT;
  10855. }
  10856. else if (this._decalEl) {
  10857. this._decalEl = null;
  10858. }
  10859. };
  10860. Path.prototype.getDecalElement = function () {
  10861. return this._decalEl;
  10862. };
  10863. Path.prototype._init = function (props) {
  10864. var keysArr = keys(props);
  10865. this.shape = this.getDefaultShape();
  10866. var defaultStyle = this.getDefaultStyle();
  10867. if (defaultStyle) {
  10868. this.useStyle(defaultStyle);
  10869. }
  10870. for (var i = 0; i < keysArr.length; i++) {
  10871. var key = keysArr[i];
  10872. var value = props[key];
  10873. if (key === 'style') {
  10874. if (!this.style) {
  10875. this.useStyle(value);
  10876. }
  10877. else {
  10878. extend(this.style, value);
  10879. }
  10880. }
  10881. else if (key === 'shape') {
  10882. extend(this.shape, value);
  10883. }
  10884. else {
  10885. _super.prototype.attrKV.call(this, key, value);
  10886. }
  10887. }
  10888. if (!this.style) {
  10889. this.useStyle({});
  10890. }
  10891. };
  10892. Path.prototype.getDefaultStyle = function () {
  10893. return null;
  10894. };
  10895. Path.prototype.getDefaultShape = function () {
  10896. return {};
  10897. };
  10898. Path.prototype.canBeInsideText = function () {
  10899. return this.hasFill();
  10900. };
  10901. Path.prototype.getInsideTextFill = function () {
  10902. var pathFill = this.style.fill;
  10903. if (pathFill !== 'none') {
  10904. if (isString(pathFill)) {
  10905. var fillLum = lum(pathFill, 0);
  10906. if (fillLum > 0.5) {
  10907. return DARK_LABEL_COLOR;
  10908. }
  10909. else if (fillLum > 0.2) {
  10910. return LIGHTER_LABEL_COLOR;
  10911. }
  10912. return LIGHT_LABEL_COLOR;
  10913. }
  10914. else if (pathFill) {
  10915. return LIGHT_LABEL_COLOR;
  10916. }
  10917. }
  10918. return DARK_LABEL_COLOR;
  10919. };
  10920. Path.prototype.getInsideTextStroke = function (textFill) {
  10921. var pathFill = this.style.fill;
  10922. if (isString(pathFill)) {
  10923. var zr = this.__zr;
  10924. var isDarkMode = !!(zr && zr.isDarkMode());
  10925. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10926. if (isDarkMode === isDarkLabel) {
  10927. return pathFill;
  10928. }
  10929. }
  10930. };
  10931. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  10932. Path.prototype.pathUpdated = function () {
  10933. this.__dirty &= ~SHAPE_CHANGED_BIT;
  10934. };
  10935. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  10936. !this.path && this.createPathProxy();
  10937. this.path.beginPath();
  10938. this.buildPath(this.path, this.shape, inBatch);
  10939. return this.path;
  10940. };
  10941. Path.prototype.createPathProxy = function () {
  10942. this.path = new PathProxy(false);
  10943. };
  10944. Path.prototype.hasStroke = function () {
  10945. var style = this.style;
  10946. var stroke = style.stroke;
  10947. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10948. };
  10949. Path.prototype.hasFill = function () {
  10950. var style = this.style;
  10951. var fill = style.fill;
  10952. return fill != null && fill !== 'none';
  10953. };
  10954. Path.prototype.getBoundingRect = function () {
  10955. var rect = this._rect;
  10956. var style = this.style;
  10957. var needsUpdateRect = !rect;
  10958. if (needsUpdateRect) {
  10959. var firstInvoke = false;
  10960. if (!this.path) {
  10961. firstInvoke = true;
  10962. this.createPathProxy();
  10963. }
  10964. var path = this.path;
  10965. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  10966. path.beginPath();
  10967. this.buildPath(path, this.shape, false);
  10968. this.pathUpdated();
  10969. }
  10970. rect = path.getBoundingRect();
  10971. }
  10972. this._rect = rect;
  10973. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10974. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  10975. if (this.__dirty || needsUpdateRect) {
  10976. rectStroke.copy(rect);
  10977. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10978. var w = style.lineWidth;
  10979. if (!this.hasFill()) {
  10980. var strokeContainThreshold = this.strokeContainThreshold;
  10981. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10982. }
  10983. if (lineScale > 1e-10) {
  10984. rectStroke.width += w / lineScale;
  10985. rectStroke.height += w / lineScale;
  10986. rectStroke.x -= w / lineScale / 2;
  10987. rectStroke.y -= w / lineScale / 2;
  10988. }
  10989. }
  10990. return rectStroke;
  10991. }
  10992. return rect;
  10993. };
  10994. Path.prototype.contain = function (x, y) {
  10995. var localPos = this.transformCoordToLocal(x, y);
  10996. var rect = this.getBoundingRect();
  10997. var style = this.style;
  10998. x = localPos[0];
  10999. y = localPos[1];
  11000. if (rect.contain(x, y)) {
  11001. var pathProxy = this.path;
  11002. if (this.hasStroke()) {
  11003. var lineWidth = style.lineWidth;
  11004. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11005. if (lineScale > 1e-10) {
  11006. if (!this.hasFill()) {
  11007. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  11008. }
  11009. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  11010. return true;
  11011. }
  11012. }
  11013. }
  11014. if (this.hasFill()) {
  11015. return contain(pathProxy, x, y);
  11016. }
  11017. }
  11018. return false;
  11019. };
  11020. Path.prototype.dirtyShape = function () {
  11021. this.__dirty |= SHAPE_CHANGED_BIT;
  11022. if (this._rect) {
  11023. this._rect = null;
  11024. }
  11025. if (this._decalEl) {
  11026. this._decalEl.dirtyShape();
  11027. }
  11028. this.markRedraw();
  11029. };
  11030. Path.prototype.dirty = function () {
  11031. this.dirtyStyle();
  11032. this.dirtyShape();
  11033. };
  11034. Path.prototype.animateShape = function (loop) {
  11035. return this.animate('shape', loop);
  11036. };
  11037. Path.prototype.updateDuringAnimation = function (targetKey) {
  11038. if (targetKey === 'style') {
  11039. this.dirtyStyle();
  11040. }
  11041. else if (targetKey === 'shape') {
  11042. this.dirtyShape();
  11043. }
  11044. else {
  11045. this.markRedraw();
  11046. }
  11047. };
  11048. Path.prototype.attrKV = function (key, value) {
  11049. if (key === 'shape') {
  11050. this.setShape(value);
  11051. }
  11052. else {
  11053. _super.prototype.attrKV.call(this, key, value);
  11054. }
  11055. };
  11056. Path.prototype.setShape = function (keyOrObj, value) {
  11057. var shape = this.shape;
  11058. if (!shape) {
  11059. shape = this.shape = {};
  11060. }
  11061. if (typeof keyOrObj === 'string') {
  11062. shape[keyOrObj] = value;
  11063. }
  11064. else {
  11065. extend(shape, keyOrObj);
  11066. }
  11067. this.dirtyShape();
  11068. return this;
  11069. };
  11070. Path.prototype.shapeChanged = function () {
  11071. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  11072. };
  11073. Path.prototype.createStyle = function (obj) {
  11074. return createObject(DEFAULT_PATH_STYLE, obj);
  11075. };
  11076. Path.prototype._innerSaveToNormal = function (toState) {
  11077. _super.prototype._innerSaveToNormal.call(this, toState);
  11078. var normalState = this._normalState;
  11079. if (toState.shape && !normalState.shape) {
  11080. normalState.shape = extend({}, this.shape);
  11081. }
  11082. };
  11083. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  11084. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  11085. var needsRestoreToNormal = !(state && keepCurrentStates);
  11086. var targetShape;
  11087. if (state && state.shape) {
  11088. if (transition) {
  11089. if (keepCurrentStates) {
  11090. targetShape = state.shape;
  11091. }
  11092. else {
  11093. targetShape = extend({}, normalState.shape);
  11094. extend(targetShape, state.shape);
  11095. }
  11096. }
  11097. else {
  11098. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  11099. extend(targetShape, state.shape);
  11100. }
  11101. }
  11102. else if (needsRestoreToNormal) {
  11103. targetShape = normalState.shape;
  11104. }
  11105. if (targetShape) {
  11106. if (transition) {
  11107. this.shape = extend({}, this.shape);
  11108. var targetShapePrimaryProps = {};
  11109. var shapeKeys = keys(targetShape);
  11110. for (var i = 0; i < shapeKeys.length; i++) {
  11111. var key = shapeKeys[i];
  11112. if (typeof targetShape[key] === 'object') {
  11113. this.shape[key] = targetShape[key];
  11114. }
  11115. else {
  11116. targetShapePrimaryProps[key] = targetShape[key];
  11117. }
  11118. }
  11119. this._transitionState(stateName, {
  11120. shape: targetShapePrimaryProps
  11121. }, animationCfg);
  11122. }
  11123. else {
  11124. this.shape = targetShape;
  11125. this.dirtyShape();
  11126. }
  11127. }
  11128. };
  11129. Path.prototype._mergeStates = function (states) {
  11130. var mergedState = _super.prototype._mergeStates.call(this, states);
  11131. var mergedShape;
  11132. for (var i = 0; i < states.length; i++) {
  11133. var state = states[i];
  11134. if (state.shape) {
  11135. mergedShape = mergedShape || {};
  11136. this._mergeStyle(mergedShape, state.shape);
  11137. }
  11138. }
  11139. if (mergedShape) {
  11140. mergedState.shape = mergedShape;
  11141. }
  11142. return mergedState;
  11143. };
  11144. Path.prototype.getAnimationStyleProps = function () {
  11145. return DEFAULT_PATH_ANIMATION_PROPS;
  11146. };
  11147. Path.prototype.isZeroArea = function () {
  11148. return false;
  11149. };
  11150. Path.extend = function (defaultProps) {
  11151. var Sub = (function (_super) {
  11152. __extends(Sub, _super);
  11153. function Sub(opts) {
  11154. var _this = _super.call(this, opts) || this;
  11155. defaultProps.init && defaultProps.init.call(_this, opts);
  11156. return _this;
  11157. }
  11158. Sub.prototype.getDefaultStyle = function () {
  11159. return clone(defaultProps.style);
  11160. };
  11161. Sub.prototype.getDefaultShape = function () {
  11162. return clone(defaultProps.shape);
  11163. };
  11164. return Sub;
  11165. }(Path));
  11166. for (var key in defaultProps) {
  11167. if (typeof defaultProps[key] === 'function') {
  11168. Sub.prototype[key] = defaultProps[key];
  11169. }
  11170. }
  11171. return Sub;
  11172. };
  11173. Path.initDefaultProps = (function () {
  11174. var pathProto = Path.prototype;
  11175. pathProto.type = 'path';
  11176. pathProto.strokeContainThreshold = 5;
  11177. pathProto.segmentIgnoreThreshold = 0;
  11178. pathProto.subPixelOptimize = false;
  11179. pathProto.autoBatch = false;
  11180. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  11181. })();
  11182. return Path;
  11183. }(Displayable));
  11184. var DEFAULT_TSPAN_STYLE = defaults({
  11185. strokeFirst: true,
  11186. font: DEFAULT_FONT,
  11187. x: 0,
  11188. y: 0,
  11189. textAlign: 'left',
  11190. textBaseline: 'top',
  11191. miterLimit: 2
  11192. }, DEFAULT_PATH_STYLE);
  11193. var TSpan = (function (_super) {
  11194. __extends(TSpan, _super);
  11195. function TSpan() {
  11196. return _super !== null && _super.apply(this, arguments) || this;
  11197. }
  11198. TSpan.prototype.hasStroke = function () {
  11199. var style = this.style;
  11200. var stroke = style.stroke;
  11201. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  11202. };
  11203. TSpan.prototype.hasFill = function () {
  11204. var style = this.style;
  11205. var fill = style.fill;
  11206. return fill != null && fill !== 'none';
  11207. };
  11208. TSpan.prototype.createStyle = function (obj) {
  11209. return createObject(DEFAULT_TSPAN_STYLE, obj);
  11210. };
  11211. TSpan.prototype.setBoundingRect = function (rect) {
  11212. this._rect = rect;
  11213. };
  11214. TSpan.prototype.getBoundingRect = function () {
  11215. var style = this.style;
  11216. if (!this._rect) {
  11217. var text = style.text;
  11218. text != null ? (text += '') : (text = '');
  11219. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  11220. rect.x += style.x || 0;
  11221. rect.y += style.y || 0;
  11222. if (this.hasStroke()) {
  11223. var w = style.lineWidth;
  11224. rect.x -= w / 2;
  11225. rect.y -= w / 2;
  11226. rect.width += w;
  11227. rect.height += w;
  11228. }
  11229. this._rect = rect;
  11230. }
  11231. return this._rect;
  11232. };
  11233. TSpan.initDefaultProps = (function () {
  11234. var tspanProto = TSpan.prototype;
  11235. tspanProto.dirtyRectTolerance = 10;
  11236. })();
  11237. return TSpan;
  11238. }(Displayable));
  11239. TSpan.prototype.type = 'tspan';
  11240. var DEFAULT_IMAGE_STYLE = defaults({
  11241. x: 0,
  11242. y: 0
  11243. }, DEFAULT_COMMON_STYLE);
  11244. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11245. style: defaults({
  11246. x: true,
  11247. y: true,
  11248. width: true,
  11249. height: true,
  11250. sx: true,
  11251. sy: true,
  11252. sWidth: true,
  11253. sHeight: true
  11254. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11255. };
  11256. function isImageLike(source) {
  11257. return !!(source
  11258. && typeof source !== 'string'
  11259. && source.width && source.height);
  11260. }
  11261. var ZRImage = (function (_super) {
  11262. __extends(ZRImage, _super);
  11263. function ZRImage() {
  11264. return _super !== null && _super.apply(this, arguments) || this;
  11265. }
  11266. ZRImage.prototype.createStyle = function (obj) {
  11267. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11268. };
  11269. ZRImage.prototype._getSize = function (dim) {
  11270. var style = this.style;
  11271. var size = style[dim];
  11272. if (size != null) {
  11273. return size;
  11274. }
  11275. var imageSource = isImageLike(style.image)
  11276. ? style.image : this.__image;
  11277. if (!imageSource) {
  11278. return 0;
  11279. }
  11280. var otherDim = dim === 'width' ? 'height' : 'width';
  11281. var otherDimSize = style[otherDim];
  11282. if (otherDimSize == null) {
  11283. return imageSource[dim];
  11284. }
  11285. else {
  11286. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11287. }
  11288. };
  11289. ZRImage.prototype.getWidth = function () {
  11290. return this._getSize('width');
  11291. };
  11292. ZRImage.prototype.getHeight = function () {
  11293. return this._getSize('height');
  11294. };
  11295. ZRImage.prototype.getAnimationStyleProps = function () {
  11296. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11297. };
  11298. ZRImage.prototype.getBoundingRect = function () {
  11299. var style = this.style;
  11300. if (!this._rect) {
  11301. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11302. }
  11303. return this._rect;
  11304. };
  11305. return ZRImage;
  11306. }(Displayable));
  11307. ZRImage.prototype.type = 'image';
  11308. function buildPath(ctx, shape) {
  11309. var x = shape.x;
  11310. var y = shape.y;
  11311. var width = shape.width;
  11312. var height = shape.height;
  11313. var r = shape.r;
  11314. var r1;
  11315. var r2;
  11316. var r3;
  11317. var r4;
  11318. if (width < 0) {
  11319. x = x + width;
  11320. width = -width;
  11321. }
  11322. if (height < 0) {
  11323. y = y + height;
  11324. height = -height;
  11325. }
  11326. if (typeof r === 'number') {
  11327. r1 = r2 = r3 = r4 = r;
  11328. }
  11329. else if (r instanceof Array) {
  11330. if (r.length === 1) {
  11331. r1 = r2 = r3 = r4 = r[0];
  11332. }
  11333. else if (r.length === 2) {
  11334. r1 = r3 = r[0];
  11335. r2 = r4 = r[1];
  11336. }
  11337. else if (r.length === 3) {
  11338. r1 = r[0];
  11339. r2 = r4 = r[1];
  11340. r3 = r[2];
  11341. }
  11342. else {
  11343. r1 = r[0];
  11344. r2 = r[1];
  11345. r3 = r[2];
  11346. r4 = r[3];
  11347. }
  11348. }
  11349. else {
  11350. r1 = r2 = r3 = r4 = 0;
  11351. }
  11352. var total;
  11353. if (r1 + r2 > width) {
  11354. total = r1 + r2;
  11355. r1 *= width / total;
  11356. r2 *= width / total;
  11357. }
  11358. if (r3 + r4 > width) {
  11359. total = r3 + r4;
  11360. r3 *= width / total;
  11361. r4 *= width / total;
  11362. }
  11363. if (r2 + r3 > height) {
  11364. total = r2 + r3;
  11365. r2 *= height / total;
  11366. r3 *= height / total;
  11367. }
  11368. if (r1 + r4 > height) {
  11369. total = r1 + r4;
  11370. r1 *= height / total;
  11371. r4 *= height / total;
  11372. }
  11373. ctx.moveTo(x + r1, y);
  11374. ctx.lineTo(x + width - r2, y);
  11375. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11376. ctx.lineTo(x + width, y + height - r3);
  11377. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11378. ctx.lineTo(x + r4, y + height);
  11379. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11380. ctx.lineTo(x, y + r1);
  11381. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11382. }
  11383. var round$1 = Math.round;
  11384. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11385. if (!inputShape) {
  11386. return;
  11387. }
  11388. var x1 = inputShape.x1;
  11389. var x2 = inputShape.x2;
  11390. var y1 = inputShape.y1;
  11391. var y2 = inputShape.y2;
  11392. outputShape.x1 = x1;
  11393. outputShape.x2 = x2;
  11394. outputShape.y1 = y1;
  11395. outputShape.y2 = y2;
  11396. var lineWidth = style && style.lineWidth;
  11397. if (!lineWidth) {
  11398. return outputShape;
  11399. }
  11400. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11401. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11402. }
  11403. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11404. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11405. }
  11406. return outputShape;
  11407. }
  11408. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11409. if (!inputShape) {
  11410. return;
  11411. }
  11412. var originX = inputShape.x;
  11413. var originY = inputShape.y;
  11414. var originWidth = inputShape.width;
  11415. var originHeight = inputShape.height;
  11416. outputShape.x = originX;
  11417. outputShape.y = originY;
  11418. outputShape.width = originWidth;
  11419. outputShape.height = originHeight;
  11420. var lineWidth = style && style.lineWidth;
  11421. if (!lineWidth) {
  11422. return outputShape;
  11423. }
  11424. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11425. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11426. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11427. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11428. return outputShape;
  11429. }
  11430. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11431. if (!lineWidth) {
  11432. return position;
  11433. }
  11434. var doubledPosition = round$1(position * 2);
  11435. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11436. ? doubledPosition / 2
  11437. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11438. }
  11439. var RectShape = (function () {
  11440. function RectShape() {
  11441. this.x = 0;
  11442. this.y = 0;
  11443. this.width = 0;
  11444. this.height = 0;
  11445. }
  11446. return RectShape;
  11447. }());
  11448. var subPixelOptimizeOutputShape = {};
  11449. var Rect = (function (_super) {
  11450. __extends(Rect, _super);
  11451. function Rect(opts) {
  11452. return _super.call(this, opts) || this;
  11453. }
  11454. Rect.prototype.getDefaultShape = function () {
  11455. return new RectShape();
  11456. };
  11457. Rect.prototype.buildPath = function (ctx, shape) {
  11458. var x;
  11459. var y;
  11460. var width;
  11461. var height;
  11462. if (this.subPixelOptimize) {
  11463. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11464. x = optimizedShape.x;
  11465. y = optimizedShape.y;
  11466. width = optimizedShape.width;
  11467. height = optimizedShape.height;
  11468. optimizedShape.r = shape.r;
  11469. shape = optimizedShape;
  11470. }
  11471. else {
  11472. x = shape.x;
  11473. y = shape.y;
  11474. width = shape.width;
  11475. height = shape.height;
  11476. }
  11477. if (!shape.r) {
  11478. ctx.rect(x, y, width, height);
  11479. }
  11480. else {
  11481. buildPath(ctx, shape);
  11482. }
  11483. };
  11484. Rect.prototype.isZeroArea = function () {
  11485. return !this.shape.width || !this.shape.height;
  11486. };
  11487. return Rect;
  11488. }(Path));
  11489. Rect.prototype.type = 'rect';
  11490. var DEFAULT_RICH_TEXT_COLOR = {
  11491. fill: '#000'
  11492. };
  11493. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11494. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11495. style: defaults({
  11496. fill: true,
  11497. stroke: true,
  11498. fillOpacity: true,
  11499. strokeOpacity: true,
  11500. lineWidth: true,
  11501. fontSize: true,
  11502. lineHeight: true,
  11503. width: true,
  11504. height: true,
  11505. textShadowColor: true,
  11506. textShadowBlur: true,
  11507. textShadowOffsetX: true,
  11508. textShadowOffsetY: true,
  11509. backgroundColor: true,
  11510. padding: true,
  11511. borderColor: true,
  11512. borderWidth: true,
  11513. borderRadius: true
  11514. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11515. };
  11516. var ZRText = (function (_super) {
  11517. __extends(ZRText, _super);
  11518. function ZRText(opts) {
  11519. var _this = _super.call(this) || this;
  11520. _this.type = 'text';
  11521. _this._children = [];
  11522. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11523. _this.attr(opts);
  11524. return _this;
  11525. }
  11526. ZRText.prototype.childrenRef = function () {
  11527. return this._children;
  11528. };
  11529. ZRText.prototype.update = function () {
  11530. _super.prototype.update.call(this);
  11531. if (this.styleChanged()) {
  11532. this._updateSubTexts();
  11533. }
  11534. for (var i = 0; i < this._children.length; i++) {
  11535. var child = this._children[i];
  11536. child.zlevel = this.zlevel;
  11537. child.z = this.z;
  11538. child.z2 = this.z2;
  11539. child.culling = this.culling;
  11540. child.cursor = this.cursor;
  11541. child.invisible = this.invisible;
  11542. }
  11543. };
  11544. ZRText.prototype.updateTransform = function () {
  11545. var innerTransformable = this.innerTransformable;
  11546. if (innerTransformable) {
  11547. innerTransformable.updateTransform();
  11548. if (innerTransformable.transform) {
  11549. this.transform = innerTransformable.transform;
  11550. }
  11551. }
  11552. else {
  11553. _super.prototype.updateTransform.call(this);
  11554. }
  11555. };
  11556. ZRText.prototype.getLocalTransform = function (m) {
  11557. var innerTransformable = this.innerTransformable;
  11558. return innerTransformable
  11559. ? innerTransformable.getLocalTransform(m)
  11560. : _super.prototype.getLocalTransform.call(this, m);
  11561. };
  11562. ZRText.prototype.getComputedTransform = function () {
  11563. if (this.__hostTarget) {
  11564. this.__hostTarget.getComputedTransform();
  11565. this.__hostTarget.updateInnerText(true);
  11566. }
  11567. return _super.prototype.getComputedTransform.call(this);
  11568. };
  11569. ZRText.prototype._updateSubTexts = function () {
  11570. this._childCursor = 0;
  11571. normalizeTextStyle(this.style);
  11572. this.style.rich
  11573. ? this._updateRichTexts()
  11574. : this._updatePlainTexts();
  11575. this._children.length = this._childCursor;
  11576. this.styleUpdated();
  11577. };
  11578. ZRText.prototype.addSelfToZr = function (zr) {
  11579. _super.prototype.addSelfToZr.call(this, zr);
  11580. for (var i = 0; i < this._children.length; i++) {
  11581. this._children[i].__zr = zr;
  11582. }
  11583. };
  11584. ZRText.prototype.removeSelfFromZr = function (zr) {
  11585. _super.prototype.removeSelfFromZr.call(this, zr);
  11586. for (var i = 0; i < this._children.length; i++) {
  11587. this._children[i].__zr = null;
  11588. }
  11589. };
  11590. ZRText.prototype.getBoundingRect = function () {
  11591. if (this.styleChanged()) {
  11592. this._updateSubTexts();
  11593. }
  11594. if (!this._rect) {
  11595. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11596. var children = this._children;
  11597. var tmpMat = [];
  11598. var rect = null;
  11599. for (var i = 0; i < children.length; i++) {
  11600. var child = children[i];
  11601. var childRect = child.getBoundingRect();
  11602. var transform = child.getLocalTransform(tmpMat);
  11603. if (transform) {
  11604. tmpRect.copy(childRect);
  11605. tmpRect.applyTransform(transform);
  11606. rect = rect || tmpRect.clone();
  11607. rect.union(tmpRect);
  11608. }
  11609. else {
  11610. rect = rect || childRect.clone();
  11611. rect.union(childRect);
  11612. }
  11613. }
  11614. this._rect = rect || tmpRect;
  11615. }
  11616. return this._rect;
  11617. };
  11618. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11619. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11620. };
  11621. ZRText.prototype.setTextContent = function (textContent) {
  11622. if ("development" !== 'production') {
  11623. throw new Error('Can\'t attach text on another text');
  11624. }
  11625. };
  11626. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11627. if (!sourceStyle) {
  11628. return targetStyle;
  11629. }
  11630. var sourceRich = sourceStyle.rich;
  11631. var targetRich = targetStyle.rich || (sourceRich && {});
  11632. extend(targetStyle, sourceStyle);
  11633. if (sourceRich && targetRich) {
  11634. this._mergeRich(targetRich, sourceRich);
  11635. targetStyle.rich = targetRich;
  11636. }
  11637. else if (targetRich) {
  11638. targetStyle.rich = targetRich;
  11639. }
  11640. return targetStyle;
  11641. };
  11642. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11643. var richNames = keys(sourceRich);
  11644. for (var i = 0; i < richNames.length; i++) {
  11645. var richName = richNames[i];
  11646. targetRich[richName] = targetRich[richName] || {};
  11647. extend(targetRich[richName], sourceRich[richName]);
  11648. }
  11649. };
  11650. ZRText.prototype.getAnimationStyleProps = function () {
  11651. return DEFAULT_TEXT_ANIMATION_PROPS;
  11652. };
  11653. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11654. var child = this._children[this._childCursor];
  11655. if (!child || !(child instanceof Ctor)) {
  11656. child = new Ctor();
  11657. }
  11658. this._children[this._childCursor++] = child;
  11659. child.__zr = this.__zr;
  11660. child.parent = this;
  11661. return child;
  11662. };
  11663. ZRText.prototype._updatePlainTexts = function () {
  11664. var style = this.style;
  11665. var textFont = style.font || DEFAULT_FONT;
  11666. var textPadding = style.padding;
  11667. var text = getStyleText(style);
  11668. var contentBlock = parsePlainText(text, style);
  11669. var needDrawBg = needDrawBackground(style);
  11670. var bgColorDrawn = !!(style.backgroundColor);
  11671. var outerHeight = contentBlock.outerHeight;
  11672. var outerWidth = contentBlock.outerWidth;
  11673. var contentWidth = contentBlock.contentWidth;
  11674. var textLines = contentBlock.lines;
  11675. var lineHeight = contentBlock.lineHeight;
  11676. var defaultStyle = this._defaultStyle;
  11677. var baseX = style.x || 0;
  11678. var baseY = style.y || 0;
  11679. var textAlign = style.align || defaultStyle.align || 'left';
  11680. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11681. var textX = baseX;
  11682. var textY = adjustTextY$1(baseY, contentBlock.contentHeight, verticalAlign);
  11683. if (needDrawBg || textPadding) {
  11684. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11685. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11686. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11687. }
  11688. textY += lineHeight / 2;
  11689. if (textPadding) {
  11690. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11691. if (verticalAlign === 'top') {
  11692. textY += textPadding[0];
  11693. }
  11694. else if (verticalAlign === 'bottom') {
  11695. textY -= textPadding[2];
  11696. }
  11697. }
  11698. var defaultLineWidth = 0;
  11699. var useDefaultFill = false;
  11700. var textFill = getFill('fill' in style
  11701. ? style.fill
  11702. : (useDefaultFill = true, defaultStyle.fill));
  11703. var textStroke = getStroke('stroke' in style
  11704. ? style.stroke
  11705. : (!bgColorDrawn
  11706. && (!defaultStyle.autoStroke || useDefaultFill))
  11707. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11708. : null);
  11709. var hasShadow = style.textShadowBlur > 0;
  11710. var fixedBoundingRect = style.width != null
  11711. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11712. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11713. for (var i = 0; i < textLines.length; i++) {
  11714. var el = this._getOrCreateChild(TSpan);
  11715. var subElStyle = el.createStyle();
  11716. el.useStyle(subElStyle);
  11717. subElStyle.text = textLines[i];
  11718. subElStyle.x = textX;
  11719. subElStyle.y = textY;
  11720. if (textAlign) {
  11721. subElStyle.textAlign = textAlign;
  11722. }
  11723. subElStyle.textBaseline = 'middle';
  11724. subElStyle.opacity = style.opacity;
  11725. subElStyle.strokeFirst = true;
  11726. if (hasShadow) {
  11727. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11728. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11729. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11730. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11731. }
  11732. subElStyle.stroke = textStroke;
  11733. subElStyle.fill = textFill;
  11734. if (textStroke) {
  11735. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11736. subElStyle.lineDash = style.lineDash;
  11737. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11738. }
  11739. subElStyle.font = textFont;
  11740. setSeparateFont(subElStyle, style);
  11741. textY += lineHeight;
  11742. if (fixedBoundingRect) {
  11743. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY$1(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), contentWidth, calculatedLineHeight));
  11744. }
  11745. }
  11746. };
  11747. ZRText.prototype._updateRichTexts = function () {
  11748. var style = this.style;
  11749. var text = getStyleText(style);
  11750. var contentBlock = parseRichText(text, style);
  11751. var contentWidth = contentBlock.width;
  11752. var outerWidth = contentBlock.outerWidth;
  11753. var outerHeight = contentBlock.outerHeight;
  11754. var textPadding = style.padding;
  11755. var baseX = style.x || 0;
  11756. var baseY = style.y || 0;
  11757. var defaultStyle = this._defaultStyle;
  11758. var textAlign = style.align || defaultStyle.align;
  11759. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11760. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11761. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11762. var xLeft = boxX;
  11763. var lineTop = boxY;
  11764. if (textPadding) {
  11765. xLeft += textPadding[3];
  11766. lineTop += textPadding[0];
  11767. }
  11768. var xRight = xLeft + contentWidth;
  11769. if (needDrawBackground(style)) {
  11770. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11771. }
  11772. var bgColorDrawn = !!(style.backgroundColor);
  11773. for (var i = 0; i < contentBlock.lines.length; i++) {
  11774. var line = contentBlock.lines[i];
  11775. var tokens = line.tokens;
  11776. var tokenCount = tokens.length;
  11777. var lineHeight = line.lineHeight;
  11778. var remainedWidth = line.width;
  11779. var leftIndex = 0;
  11780. var lineXLeft = xLeft;
  11781. var lineXRight = xRight;
  11782. var rightIndex = tokenCount - 1;
  11783. var token = void 0;
  11784. while (leftIndex < tokenCount
  11785. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11786. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11787. remainedWidth -= token.width;
  11788. lineXLeft += token.width;
  11789. leftIndex++;
  11790. }
  11791. while (rightIndex >= 0
  11792. && (token = tokens[rightIndex], token.align === 'right')) {
  11793. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11794. remainedWidth -= token.width;
  11795. lineXRight -= token.width;
  11796. rightIndex--;
  11797. }
  11798. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11799. while (leftIndex <= rightIndex) {
  11800. token = tokens[leftIndex];
  11801. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11802. lineXLeft += token.width;
  11803. leftIndex++;
  11804. }
  11805. lineTop += lineHeight;
  11806. }
  11807. };
  11808. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11809. var tokenStyle = style.rich[token.styleName] || {};
  11810. tokenStyle.text = token.text;
  11811. var verticalAlign = token.verticalAlign;
  11812. var y = lineTop + lineHeight / 2;
  11813. if (verticalAlign === 'top') {
  11814. y = lineTop + token.height / 2;
  11815. }
  11816. else if (verticalAlign === 'bottom') {
  11817. y = lineTop + lineHeight - token.height / 2;
  11818. }
  11819. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11820. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11821. ? x - token.width
  11822. : textAlign === 'center'
  11823. ? x - token.width / 2
  11824. : x, y - token.height / 2, token.width, token.height);
  11825. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11826. var textPadding = token.textPadding;
  11827. if (textPadding) {
  11828. x = getTextXForPadding(x, textAlign, textPadding);
  11829. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11830. }
  11831. var el = this._getOrCreateChild(TSpan);
  11832. var subElStyle = el.createStyle();
  11833. el.useStyle(subElStyle);
  11834. var defaultStyle = this._defaultStyle;
  11835. var useDefaultFill = false;
  11836. var defaultLineWidth = 0;
  11837. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11838. : 'fill' in style ? style.fill
  11839. : (useDefaultFill = true, defaultStyle.fill));
  11840. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11841. : 'stroke' in style ? style.stroke
  11842. : (!bgColorDrawn
  11843. && !parentBgColorDrawn
  11844. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11845. : null);
  11846. var hasShadow = tokenStyle.textShadowBlur > 0
  11847. || style.textShadowBlur > 0;
  11848. subElStyle.text = token.text;
  11849. subElStyle.x = x;
  11850. subElStyle.y = y;
  11851. if (hasShadow) {
  11852. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11853. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11854. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11855. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11856. }
  11857. subElStyle.textAlign = textAlign;
  11858. subElStyle.textBaseline = 'middle';
  11859. subElStyle.font = token.font || DEFAULT_FONT;
  11860. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11861. setSeparateFont(subElStyle, tokenStyle);
  11862. if (textStroke) {
  11863. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11864. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11865. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11866. subElStyle.stroke = textStroke;
  11867. }
  11868. if (textFill) {
  11869. subElStyle.fill = textFill;
  11870. }
  11871. var textWidth = token.contentWidth;
  11872. var textHeight = token.contentHeight;
  11873. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY$1(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11874. };
  11875. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11876. var textBackgroundColor = style.backgroundColor;
  11877. var textBorderWidth = style.borderWidth;
  11878. var textBorderColor = style.borderColor;
  11879. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11880. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11881. var textBorderRadius = style.borderRadius;
  11882. var self = this;
  11883. var rectEl;
  11884. var imgEl;
  11885. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11886. rectEl = this._getOrCreateChild(Rect);
  11887. rectEl.useStyle(rectEl.createStyle());
  11888. rectEl.style.fill = null;
  11889. var rectShape = rectEl.shape;
  11890. rectShape.x = x;
  11891. rectShape.y = y;
  11892. rectShape.width = width;
  11893. rectShape.height = height;
  11894. rectShape.r = textBorderRadius;
  11895. rectEl.dirtyShape();
  11896. }
  11897. if (isPlainOrGradientBg) {
  11898. var rectStyle = rectEl.style;
  11899. rectStyle.fill = textBackgroundColor || null;
  11900. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11901. }
  11902. else if (isImageBg) {
  11903. imgEl = this._getOrCreateChild(ZRImage);
  11904. imgEl.onload = function () {
  11905. self.dirtyStyle();
  11906. };
  11907. var imgStyle = imgEl.style;
  11908. imgStyle.image = textBackgroundColor.image;
  11909. imgStyle.x = x;
  11910. imgStyle.y = y;
  11911. imgStyle.width = width;
  11912. imgStyle.height = height;
  11913. }
  11914. if (textBorderWidth && textBorderColor) {
  11915. var rectStyle = rectEl.style;
  11916. rectStyle.lineWidth = textBorderWidth;
  11917. rectStyle.stroke = textBorderColor;
  11918. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11919. rectStyle.lineDash = style.borderDash;
  11920. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11921. rectEl.strokeContainThreshold = 0;
  11922. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11923. rectStyle.strokeFirst = true;
  11924. rectStyle.lineWidth *= 2;
  11925. }
  11926. }
  11927. var commonStyle = (rectEl || imgEl).style;
  11928. commonStyle.shadowBlur = style.shadowBlur || 0;
  11929. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11930. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11931. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11932. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11933. };
  11934. ZRText.makeFont = function (style) {
  11935. var font = '';
  11936. if (hasSeparateFont(style)) {
  11937. font = [
  11938. style.fontStyle,
  11939. style.fontWeight,
  11940. parseFontSize(style.fontSize),
  11941. style.fontFamily || 'sans-serif'
  11942. ].join(' ');
  11943. }
  11944. return font && trim(font) || style.textFont || style.font;
  11945. };
  11946. return ZRText;
  11947. }(Displayable));
  11948. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11949. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11950. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  11951. function parseFontSize(fontSize) {
  11952. if (typeof fontSize === 'string'
  11953. && (fontSize.indexOf('px') !== -1
  11954. || fontSize.indexOf('rem') !== -1
  11955. || fontSize.indexOf('em') !== -1)) {
  11956. return fontSize;
  11957. }
  11958. else if (!isNaN(+fontSize)) {
  11959. return fontSize + 'px';
  11960. }
  11961. else {
  11962. return DEFAULT_FONT_SIZE + 'px';
  11963. }
  11964. }
  11965. function setSeparateFont(targetStyle, sourceStyle) {
  11966. for (var i = 0; i < FONT_PARTS.length; i++) {
  11967. var fontProp = FONT_PARTS[i];
  11968. var val = sourceStyle[fontProp];
  11969. if (val != null) {
  11970. targetStyle[fontProp] = val;
  11971. }
  11972. }
  11973. }
  11974. function hasSeparateFont(style) {
  11975. return style.fontSize != null || style.fontFamily || style.fontWeight;
  11976. }
  11977. function normalizeTextStyle(style) {
  11978. normalizeStyle(style);
  11979. each(style.rich, normalizeStyle);
  11980. return style;
  11981. }
  11982. function normalizeStyle(style) {
  11983. if (style) {
  11984. style.font = ZRText.makeFont(style);
  11985. var textAlign = style.align;
  11986. textAlign === 'middle' && (textAlign = 'center');
  11987. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11988. var verticalAlign = style.verticalAlign;
  11989. verticalAlign === 'center' && (verticalAlign = 'middle');
  11990. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11991. var textPadding = style.padding;
  11992. if (textPadding) {
  11993. style.padding = normalizeCssArray(style.padding);
  11994. }
  11995. }
  11996. }
  11997. function getStroke(stroke, lineWidth) {
  11998. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11999. ? null
  12000. : (stroke.image || stroke.colorStops)
  12001. ? '#000'
  12002. : stroke;
  12003. }
  12004. function getFill(fill) {
  12005. return (fill == null || fill === 'none')
  12006. ? null
  12007. : (fill.image || fill.colorStops)
  12008. ? '#000'
  12009. : fill;
  12010. }
  12011. function getTextXForPadding(x, textAlign, textPadding) {
  12012. return textAlign === 'right'
  12013. ? (x - textPadding[1])
  12014. : textAlign === 'center'
  12015. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  12016. : (x + textPadding[3]);
  12017. }
  12018. function getStyleText(style) {
  12019. var text = style.text;
  12020. text != null && (text += '');
  12021. return text;
  12022. }
  12023. function needDrawBackground(style) {
  12024. return !!(style.backgroundColor
  12025. || style.lineHeight
  12026. || (style.borderWidth && style.borderColor));
  12027. }
  12028. var getECData = makeInner();
  12029. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  12030. if (el) {
  12031. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  12032. // Useful in tooltip
  12033. ecData.dataIndex = dataIdx;
  12034. ecData.dataType = dataType;
  12035. ecData.seriesIndex = seriesIndex; // TODO: not store dataIndex on children.
  12036. if (el.type === 'group') {
  12037. el.traverse(function (child) {
  12038. var childECData = getECData(child);
  12039. childECData.seriesIndex = seriesIndex;
  12040. childECData.dataIndex = dataIdx;
  12041. childECData.dataType = dataType;
  12042. });
  12043. }
  12044. }
  12045. };
  12046. var _highlightNextDigit = 1;
  12047. var _highlightKeyMap = {};
  12048. var getSavedStates = makeInner();
  12049. var getComponentStates = makeInner();
  12050. var HOVER_STATE_NORMAL = 0;
  12051. var HOVER_STATE_BLUR = 1;
  12052. var HOVER_STATE_EMPHASIS = 2;
  12053. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  12054. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  12055. var Z2_EMPHASIS_LIFT = 10;
  12056. var Z2_SELECT_LIFT = 9;
  12057. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  12058. var DOWNPLAY_ACTION_TYPE = 'downplay';
  12059. var SELECT_ACTION_TYPE = 'select';
  12060. var UNSELECT_ACTION_TYPE = 'unselect';
  12061. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  12062. function hasFillOrStroke(fillOrStroke) {
  12063. return fillOrStroke != null && fillOrStroke !== 'none';
  12064. } // Most lifted color are duplicated.
  12065. var liftedColorCache = new LRU(100);
  12066. function liftColor(color$1) {
  12067. if (isString(color$1)) {
  12068. var liftedColor = liftedColorCache.get(color$1);
  12069. if (!liftedColor) {
  12070. liftedColor = lift(color$1, -0.1);
  12071. liftedColorCache.put(color$1, liftedColor);
  12072. }
  12073. return liftedColor;
  12074. } else if (isGradientObject(color$1)) {
  12075. var ret = extend({}, color$1);
  12076. ret.colorStops = map(color$1.colorStops, function (stop) {
  12077. return {
  12078. offset: stop.offset,
  12079. color: lift(stop.color, -0.1)
  12080. };
  12081. });
  12082. return ret;
  12083. } // Change nothing.
  12084. return color$1;
  12085. }
  12086. function doChangeHoverState(el, stateName, hoverStateEnum) {
  12087. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  12088. el.onHoverStateChange(stateName);
  12089. }
  12090. el.hoverState = hoverStateEnum;
  12091. }
  12092. function singleEnterEmphasis(el) {
  12093. // Only mark the flag.
  12094. // States will be applied in the echarts.ts in next frame.
  12095. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  12096. }
  12097. function singleLeaveEmphasis(el) {
  12098. // Only mark the flag.
  12099. // States will be applied in the echarts.ts in next frame.
  12100. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  12101. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12102. }
  12103. }
  12104. function singleEnterBlur(el) {
  12105. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  12106. }
  12107. function singleLeaveBlur(el) {
  12108. if (el.hoverState === HOVER_STATE_BLUR) {
  12109. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12110. }
  12111. }
  12112. function singleEnterSelect(el) {
  12113. el.selected = true;
  12114. }
  12115. function singleLeaveSelect(el) {
  12116. el.selected = false;
  12117. }
  12118. function updateElementState(el, updater, commonParam) {
  12119. updater(el, commonParam);
  12120. }
  12121. function traverseUpdateState(el, updater, commonParam) {
  12122. updateElementState(el, updater, commonParam);
  12123. el.isGroup && el.traverse(function (child) {
  12124. updateElementState(child, updater, commonParam);
  12125. });
  12126. }
  12127. function setStatesFlag(el, stateName) {
  12128. switch (stateName) {
  12129. case 'emphasis':
  12130. el.hoverState = HOVER_STATE_EMPHASIS;
  12131. break;
  12132. case 'normal':
  12133. el.hoverState = HOVER_STATE_NORMAL;
  12134. break;
  12135. case 'blur':
  12136. el.hoverState = HOVER_STATE_BLUR;
  12137. break;
  12138. case 'select':
  12139. el.selected = true;
  12140. }
  12141. }
  12142. function getFromStateStyle(el, props, toStateName, defaultValue) {
  12143. var style = el.style;
  12144. var fromState = {};
  12145. for (var i = 0; i < props.length; i++) {
  12146. var propName = props[i];
  12147. var val = style[propName];
  12148. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  12149. }
  12150. for (var i = 0; i < el.animators.length; i++) {
  12151. var animator = el.animators[i];
  12152. if (animator.__fromStateTransition // Don't consider the animation to emphasis state.
  12153. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  12154. animator.saveTo(fromState, props);
  12155. }
  12156. }
  12157. return fromState;
  12158. }
  12159. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  12160. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  12161. var cloned = false;
  12162. if (el instanceof Path) {
  12163. var store = getSavedStates(el);
  12164. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  12165. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  12166. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  12167. state = state || {};
  12168. var emphasisStyle = state.style || {}; // inherit case
  12169. if (emphasisStyle.fill === 'inherit') {
  12170. cloned = true;
  12171. state = extend({}, state);
  12172. emphasisStyle = extend({}, emphasisStyle);
  12173. emphasisStyle.fill = fromFill;
  12174. } // Apply default color lift
  12175. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  12176. cloned = true; // Not modify the original value.
  12177. state = extend({}, state);
  12178. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  12179. emphasisStyle.fill = liftColor(fromFill);
  12180. } // Not highlight stroke if fill has been highlighted.
  12181. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  12182. if (!cloned) {
  12183. state = extend({}, state);
  12184. emphasisStyle = extend({}, emphasisStyle);
  12185. }
  12186. emphasisStyle.stroke = liftColor(fromStroke);
  12187. }
  12188. state.style = emphasisStyle;
  12189. }
  12190. }
  12191. if (state) {
  12192. // TODO Share with textContent?
  12193. if (state.z2 == null) {
  12194. if (!cloned) {
  12195. state = extend({}, state);
  12196. }
  12197. var z2EmphasisLift = el.z2EmphasisLift;
  12198. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  12199. }
  12200. }
  12201. return state;
  12202. }
  12203. function createSelectDefaultState(el, stateName, state) {
  12204. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  12205. if (state) {
  12206. // TODO Share with textContent?
  12207. if (state.z2 == null) {
  12208. state = extend({}, state);
  12209. var z2SelectLift = el.z2SelectLift;
  12210. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  12211. }
  12212. }
  12213. return state;
  12214. }
  12215. function createBlurDefaultState(el, stateName, state) {
  12216. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  12217. var currentOpacity = el.style.opacity;
  12218. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  12219. opacity: 1
  12220. }) : null;
  12221. state = state || {};
  12222. var blurStyle = state.style || {};
  12223. if (blurStyle.opacity == null) {
  12224. // clone state
  12225. state = extend({}, state);
  12226. blurStyle = extend({
  12227. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  12228. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  12229. }, blurStyle);
  12230. state.style = blurStyle;
  12231. }
  12232. return state;
  12233. }
  12234. function elementStateProxy(stateName, targetStates) {
  12235. var state = this.states[stateName];
  12236. if (this.style) {
  12237. if (stateName === 'emphasis') {
  12238. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12239. } else if (stateName === 'blur') {
  12240. return createBlurDefaultState(this, stateName, state);
  12241. } else if (stateName === 'select') {
  12242. return createSelectDefaultState(this, stateName, state);
  12243. }
  12244. }
  12245. return state;
  12246. }
  12247. /**
  12248. * Set hover style (namely "emphasis style") of element.
  12249. * @param el Should not be `zrender/graphic/Group`.
  12250. * @param focus 'self' | 'selfInSeries' | 'series'
  12251. */
  12252. function setDefaultStateProxy(el) {
  12253. el.stateProxy = elementStateProxy;
  12254. var textContent = el.getTextContent();
  12255. var textGuide = el.getTextGuideLine();
  12256. if (textContent) {
  12257. textContent.stateProxy = elementStateProxy;
  12258. }
  12259. if (textGuide) {
  12260. textGuide.stateProxy = elementStateProxy;
  12261. }
  12262. }
  12263. function enterEmphasisWhenMouseOver(el, e) {
  12264. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12265. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12266. }
  12267. function leaveEmphasisWhenMouseOut(el, e) {
  12268. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12269. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12270. }
  12271. function enterEmphasis(el, highlightDigit) {
  12272. el.__highByOuter |= 1 << (highlightDigit || 0);
  12273. traverseUpdateState(el, singleEnterEmphasis);
  12274. }
  12275. function leaveEmphasis(el, highlightDigit) {
  12276. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12277. }
  12278. function enterBlur(el) {
  12279. traverseUpdateState(el, singleEnterBlur);
  12280. }
  12281. function leaveBlur(el) {
  12282. traverseUpdateState(el, singleLeaveBlur);
  12283. }
  12284. function enterSelect(el) {
  12285. traverseUpdateState(el, singleEnterSelect);
  12286. }
  12287. function leaveSelect(el) {
  12288. traverseUpdateState(el, singleLeaveSelect);
  12289. }
  12290. function shouldSilent(el, e) {
  12291. return el.__highDownSilentOnTouch && e.zrByTouch;
  12292. }
  12293. function allLeaveBlur(api) {
  12294. var model = api.getModel();
  12295. var leaveBlurredSeries = [];
  12296. var allComponentViews = [];
  12297. model.eachComponent(function (componentType, componentModel) {
  12298. var componentStates = getComponentStates(componentModel);
  12299. var isSeries = componentType === 'series';
  12300. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  12301. !isSeries && allComponentViews.push(view);
  12302. if (componentStates.isBlured) {
  12303. // Leave blur anyway
  12304. view.group.traverse(function (child) {
  12305. singleLeaveBlur(child);
  12306. });
  12307. isSeries && leaveBlurredSeries.push(componentModel);
  12308. }
  12309. componentStates.isBlured = false;
  12310. });
  12311. each(allComponentViews, function (view) {
  12312. if (view && view.toggleBlurSeries) {
  12313. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  12314. }
  12315. });
  12316. }
  12317. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12318. var ecModel = api.getModel();
  12319. blurScope = blurScope || 'coordinateSystem';
  12320. function leaveBlurOfIndices(data, dataIndices) {
  12321. for (var i = 0; i < dataIndices.length; i++) {
  12322. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12323. itemEl && leaveBlur(itemEl);
  12324. }
  12325. }
  12326. if (targetSeriesIndex == null) {
  12327. return;
  12328. }
  12329. if (!focus || focus === 'none') {
  12330. return;
  12331. }
  12332. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12333. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12334. if (targetCoordSys && targetCoordSys.master) {
  12335. targetCoordSys = targetCoordSys.master;
  12336. }
  12337. var blurredSeries = [];
  12338. ecModel.eachSeries(function (seriesModel) {
  12339. var sameSeries = targetSeriesModel === seriesModel;
  12340. var coordSys = seriesModel.coordinateSystem;
  12341. if (coordSys && coordSys.master) {
  12342. coordSys = coordSys.master;
  12343. }
  12344. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12345. if (!( // Not blur other series if blurScope series
  12346. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  12347. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  12348. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  12349. )) {
  12350. var view = api.getViewOfSeriesModel(seriesModel);
  12351. view.group.traverse(function (child) {
  12352. singleEnterBlur(child);
  12353. });
  12354. if (isArrayLike(focus)) {
  12355. leaveBlurOfIndices(seriesModel.getData(), focus);
  12356. } else if (isObject(focus)) {
  12357. var dataTypes = keys(focus);
  12358. for (var d = 0; d < dataTypes.length; d++) {
  12359. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12360. }
  12361. }
  12362. blurredSeries.push(seriesModel);
  12363. getComponentStates(seriesModel).isBlured = true;
  12364. }
  12365. });
  12366. ecModel.eachComponent(function (componentType, componentModel) {
  12367. if (componentType === 'series') {
  12368. return;
  12369. }
  12370. var view = api.getViewOfComponentModel(componentModel);
  12371. if (view && view.toggleBlurSeries) {
  12372. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12373. }
  12374. });
  12375. }
  12376. function blurComponent(componentMainType, componentIndex, api) {
  12377. if (componentMainType == null || componentIndex == null) {
  12378. return;
  12379. }
  12380. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12381. if (!componentModel) {
  12382. return;
  12383. }
  12384. getComponentStates(componentModel).isBlured = true;
  12385. var view = api.getViewOfComponentModel(componentModel);
  12386. if (!view || !view.focusBlurEnabled) {
  12387. return;
  12388. }
  12389. view.group.traverse(function (child) {
  12390. singleEnterBlur(child);
  12391. });
  12392. }
  12393. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12394. var seriesIndex = seriesModel.seriesIndex;
  12395. var data = seriesModel.getData(payload.dataType);
  12396. if (!data) {
  12397. if ("development" !== 'production') {
  12398. error("Unknown dataType " + payload.dataType);
  12399. }
  12400. return;
  12401. }
  12402. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  12403. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12404. var el = data.getItemGraphicEl(dataIndex);
  12405. if (!el) {
  12406. var count = data.count();
  12407. var current = 0; // If data on dataIndex is NaN.
  12408. while (!el && current < count) {
  12409. el = data.getItemGraphicEl(current++);
  12410. }
  12411. }
  12412. if (el) {
  12413. var ecData = getECData(el);
  12414. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12415. } else {
  12416. // If there is no element put on the data. Try getting it from raw option
  12417. // TODO Should put it on seriesModel?
  12418. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12419. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12420. if (focus_1 != null) {
  12421. blurSeries(seriesIndex, focus_1, blurScope, api);
  12422. }
  12423. }
  12424. }
  12425. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12426. var ret = {
  12427. focusSelf: false,
  12428. dispatchers: null
  12429. };
  12430. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12431. return ret;
  12432. }
  12433. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12434. if (!componentModel) {
  12435. return ret;
  12436. }
  12437. var view = api.getViewOfComponentModel(componentModel);
  12438. if (!view || !view.findHighDownDispatchers) {
  12439. return ret;
  12440. }
  12441. var dispatchers = view.findHighDownDispatchers(name); // At presnet, the component (like Geo) only blur inside itself.
  12442. // So we do not use `blurScope` in component.
  12443. var focusSelf;
  12444. for (var i = 0; i < dispatchers.length; i++) {
  12445. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12446. error('param should be highDownDispatcher');
  12447. }
  12448. if (getECData(dispatchers[i]).focus === 'self') {
  12449. focusSelf = true;
  12450. break;
  12451. }
  12452. }
  12453. return {
  12454. focusSelf: focusSelf,
  12455. dispatchers: dispatchers
  12456. };
  12457. }
  12458. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12459. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12460. error('param should be highDownDispatcher');
  12461. }
  12462. var ecData = getECData(dispatcher);
  12463. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12464. dispatchers = _a.dispatchers,
  12465. focusSelf = _a.focusSelf; // If `findHighDownDispatchers` is supported on the component,
  12466. // highlight/downplay elements with the same name.
  12467. if (dispatchers) {
  12468. if (focusSelf) {
  12469. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12470. }
  12471. each(dispatchers, function (dispatcher) {
  12472. return enterEmphasisWhenMouseOver(dispatcher, e);
  12473. });
  12474. } else {
  12475. // Try blur all in the related series. Then emphasis the hoverred.
  12476. // TODO. progressive mode.
  12477. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12478. if (ecData.focus === 'self') {
  12479. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12480. } // Other than series, component that not support `findHighDownDispatcher` will
  12481. // also use it. But in this case, highlight/downplay are only supported in
  12482. // mouse hover but not in dispatchAction.
  12483. enterEmphasisWhenMouseOver(dispatcher, e);
  12484. }
  12485. }
  12486. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12487. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12488. error('param should be highDownDispatcher');
  12489. }
  12490. allLeaveBlur(api);
  12491. var ecData = getECData(dispatcher);
  12492. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12493. if (dispatchers) {
  12494. each(dispatchers, function (dispatcher) {
  12495. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12496. });
  12497. } else {
  12498. leaveEmphasisWhenMouseOut(dispatcher, e);
  12499. }
  12500. }
  12501. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12502. if (!isSelectChangePayload(payload)) {
  12503. return;
  12504. }
  12505. var dataType = payload.dataType;
  12506. var data = seriesModel.getData(dataType);
  12507. var dataIndex = queryDataIndex(data, payload);
  12508. if (!isArray(dataIndex)) {
  12509. dataIndex = [dataIndex];
  12510. }
  12511. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12512. }
  12513. function updateSeriesElementSelection(seriesModel) {
  12514. var allData = seriesModel.getAllData();
  12515. each(allData, function (_a) {
  12516. var data = _a.data,
  12517. type = _a.type;
  12518. data.eachItemGraphicEl(function (el, idx) {
  12519. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12520. });
  12521. });
  12522. }
  12523. function getAllSelectedIndices(ecModel) {
  12524. var ret = [];
  12525. ecModel.eachSeries(function (seriesModel) {
  12526. var allData = seriesModel.getAllData();
  12527. each(allData, function (_a) {
  12528. var data = _a.data,
  12529. type = _a.type;
  12530. var dataIndices = seriesModel.getSelectedDataIndices();
  12531. if (dataIndices.length > 0) {
  12532. var item = {
  12533. dataIndex: dataIndices,
  12534. seriesIndex: seriesModel.seriesIndex
  12535. };
  12536. if (type != null) {
  12537. item.dataType = type;
  12538. }
  12539. ret.push(item);
  12540. }
  12541. });
  12542. });
  12543. return ret;
  12544. }
  12545. /**
  12546. * Enable the function that mouseover will trigger the emphasis state.
  12547. *
  12548. * NOTE:
  12549. * This function should be used on the element with dataIndex, seriesIndex.
  12550. *
  12551. */
  12552. function enableHoverEmphasis(el, focus, blurScope) {
  12553. setAsHighDownDispatcher(el, true);
  12554. traverseUpdateState(el, setDefaultStateProxy);
  12555. enableHoverFocus(el, focus, blurScope);
  12556. }
  12557. function disableHoverEmphasis(el) {
  12558. setAsHighDownDispatcher(el, false);
  12559. }
  12560. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12561. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12562. }
  12563. function enableHoverFocus(el, focus, blurScope) {
  12564. var ecData = getECData(el);
  12565. if (focus != null) {
  12566. // TODO dataIndex may be set after this function. This check is not useful.
  12567. // if (ecData.dataIndex == null) {
  12568. // if (__DEV__) {
  12569. // console.warn('focus can only been set on element with dataIndex');
  12570. // }
  12571. // }
  12572. // else {
  12573. ecData.focus = focus;
  12574. ecData.blurScope = blurScope; // }
  12575. } else if (ecData.focus) {
  12576. ecData.focus = null;
  12577. }
  12578. }
  12579. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12580. var defaultStyleGetterMap = {
  12581. itemStyle: 'getItemStyle',
  12582. lineStyle: 'getLineStyle',
  12583. areaStyle: 'getAreaStyle'
  12584. };
  12585. /**
  12586. * Set emphasis/blur/selected states of element.
  12587. */
  12588. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  12589. getter) {
  12590. styleType = styleType || 'itemStyle';
  12591. for (var i = 0; i < OTHER_STATES.length; i++) {
  12592. var stateName = OTHER_STATES[i];
  12593. var model = itemModel.getModel([stateName, styleType]);
  12594. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12595. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12596. }
  12597. }
  12598. /**
  12599. *
  12600. * Set element as highlight / downplay dispatcher.
  12601. * It will be checked when element received mouseover event or from highlight action.
  12602. * It's in change of all highlight/downplay behavior of it's children.
  12603. *
  12604. * @param el
  12605. * @param el.highDownSilentOnTouch
  12606. * In touch device, mouseover event will be trigger on touchstart event
  12607. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12608. * conveniently use hoverStyle when tap on touch screen without additional
  12609. * code for compatibility.
  12610. * But if the chart/component has select feature, which usually also use
  12611. * hoverStyle, there might be conflict between 'select-highlight' and
  12612. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12613. * In this case, `highDownSilentOnTouch` should be used to disable
  12614. * hover-highlight on touch device.
  12615. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12616. */
  12617. function setAsHighDownDispatcher(el, asDispatcher) {
  12618. var disable = asDispatcher === false;
  12619. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12620. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12621. if (el.highDownSilentOnTouch) {
  12622. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12623. } // Simple optimize, since this method might be
  12624. // called for each elements of a group in some cases.
  12625. if (!disable || extendedEl.__highDownDispatcher) {
  12626. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12627. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12628. // Also keep previous record.
  12629. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12630. extendedEl.__highDownDispatcher = !disable;
  12631. }
  12632. }
  12633. function isHighDownDispatcher(el) {
  12634. return !!(el && el.__highDownDispatcher);
  12635. }
  12636. /**
  12637. * Enable component highlight/downplay features:
  12638. * + hover link (within the same name)
  12639. * + focus blur in component
  12640. */
  12641. function enableComponentHighDownFeatures(el, componentModel, componentHighDownName) {
  12642. var ecData = getECData(el);
  12643. ecData.componentMainType = componentModel.mainType;
  12644. ecData.componentIndex = componentModel.componentIndex;
  12645. ecData.componentHighDownName = componentHighDownName;
  12646. }
  12647. /**
  12648. * Support highlight/downplay record on each elements.
  12649. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12650. * user triggered highlight/downplay should not conflict.
  12651. * Only all of the highlightDigit cleared, return to normal.
  12652. * @param {string} highlightKey
  12653. * @return {number} highlightDigit
  12654. */
  12655. function getHighlightDigit(highlightKey) {
  12656. var highlightDigit = _highlightKeyMap[highlightKey];
  12657. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12658. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12659. }
  12660. return highlightDigit;
  12661. }
  12662. function isSelectChangePayload(payload) {
  12663. var payloadType = payload.type;
  12664. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12665. }
  12666. function isHighDownPayload(payload) {
  12667. var payloadType = payload.type;
  12668. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12669. }
  12670. function savePathStates(el) {
  12671. var store = getSavedStates(el);
  12672. store.normalFill = el.style.fill;
  12673. store.normalStroke = el.style.stroke;
  12674. var selectState = el.states.select || {};
  12675. store.selectFill = selectState.style && selectState.style.fill || null;
  12676. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12677. }
  12678. var CMD$2 = PathProxy.CMD;
  12679. var points = [[], [], []];
  12680. var mathSqrt$1 = Math.sqrt;
  12681. var mathAtan2 = Math.atan2;
  12682. function transformPath(path, m) {
  12683. if (!m) {
  12684. return;
  12685. }
  12686. var data = path.data;
  12687. var len = path.len();
  12688. var cmd;
  12689. var nPoint;
  12690. var i;
  12691. var j;
  12692. var k;
  12693. var p;
  12694. var M = CMD$2.M;
  12695. var C = CMD$2.C;
  12696. var L = CMD$2.L;
  12697. var R = CMD$2.R;
  12698. var A = CMD$2.A;
  12699. var Q = CMD$2.Q;
  12700. for (i = 0, j = 0; i < len;) {
  12701. cmd = data[i++];
  12702. j = i;
  12703. nPoint = 0;
  12704. switch (cmd) {
  12705. case M:
  12706. nPoint = 1;
  12707. break;
  12708. case L:
  12709. nPoint = 1;
  12710. break;
  12711. case C:
  12712. nPoint = 3;
  12713. break;
  12714. case Q:
  12715. nPoint = 2;
  12716. break;
  12717. case A:
  12718. var x = m[4];
  12719. var y = m[5];
  12720. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  12721. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  12722. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12723. data[i] *= sx;
  12724. data[i++] += x;
  12725. data[i] *= sy;
  12726. data[i++] += y;
  12727. data[i++] *= sx;
  12728. data[i++] *= sy;
  12729. data[i++] += angle;
  12730. data[i++] += angle;
  12731. i += 2;
  12732. j = i;
  12733. break;
  12734. case R:
  12735. p[0] = data[i++];
  12736. p[1] = data[i++];
  12737. applyTransform(p, p, m);
  12738. data[j++] = p[0];
  12739. data[j++] = p[1];
  12740. p[0] += data[i++];
  12741. p[1] += data[i++];
  12742. applyTransform(p, p, m);
  12743. data[j++] = p[0];
  12744. data[j++] = p[1];
  12745. }
  12746. for (k = 0; k < nPoint; k++) {
  12747. var p_1 = points[k];
  12748. p_1[0] = data[i++];
  12749. p_1[1] = data[i++];
  12750. applyTransform(p_1, p_1, m);
  12751. data[j++] = p_1[0];
  12752. data[j++] = p_1[1];
  12753. }
  12754. }
  12755. path.increaseVersion();
  12756. }
  12757. var mathSqrt$2 = Math.sqrt;
  12758. var mathSin$2 = Math.sin;
  12759. var mathCos$2 = Math.cos;
  12760. var PI$1 = Math.PI;
  12761. function vMag(v) {
  12762. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12763. }
  12764. function vRatio(u, v) {
  12765. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12766. }
  12767. function vAngle(u, v) {
  12768. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12769. * Math.acos(vRatio(u, v));
  12770. }
  12771. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12772. var psi = psiDeg * (PI$1 / 180.0);
  12773. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12774. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12775. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12776. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12777. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12778. if (lambda > 1) {
  12779. rx *= mathSqrt$2(lambda);
  12780. ry *= mathSqrt$2(lambda);
  12781. }
  12782. var f = (fa === fs ? -1 : 1)
  12783. * mathSqrt$2((((rx * rx) * (ry * ry))
  12784. - ((rx * rx) * (yp * yp))
  12785. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12786. + (ry * ry) * (xp * xp))) || 0;
  12787. var cxp = f * rx * yp / ry;
  12788. var cyp = f * -ry * xp / rx;
  12789. var cx = (x1 + x2) / 2.0
  12790. + mathCos$2(psi) * cxp
  12791. - mathSin$2(psi) * cyp;
  12792. var cy = (y1 + y2) / 2.0
  12793. + mathSin$2(psi) * cxp
  12794. + mathCos$2(psi) * cyp;
  12795. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12796. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12797. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12798. var dTheta = vAngle(u, v);
  12799. if (vRatio(u, v) <= -1) {
  12800. dTheta = PI$1;
  12801. }
  12802. if (vRatio(u, v) >= 1) {
  12803. dTheta = 0;
  12804. }
  12805. if (dTheta < 0) {
  12806. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12807. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12808. }
  12809. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12810. }
  12811. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12812. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12813. function createPathProxyFromString(data) {
  12814. var path = new PathProxy();
  12815. if (!data) {
  12816. return path;
  12817. }
  12818. var cpx = 0;
  12819. var cpy = 0;
  12820. var subpathX = cpx;
  12821. var subpathY = cpy;
  12822. var prevCmd;
  12823. var CMD = PathProxy.CMD;
  12824. var cmdList = data.match(commandReg);
  12825. if (!cmdList) {
  12826. return path;
  12827. }
  12828. for (var l = 0; l < cmdList.length; l++) {
  12829. var cmdText = cmdList[l];
  12830. var cmdStr = cmdText.charAt(0);
  12831. var cmd = void 0;
  12832. var p = cmdText.match(numberReg) || [];
  12833. var pLen = p.length;
  12834. for (var i = 0; i < pLen; i++) {
  12835. p[i] = parseFloat(p[i]);
  12836. }
  12837. var off = 0;
  12838. while (off < pLen) {
  12839. var ctlPtx = void 0;
  12840. var ctlPty = void 0;
  12841. var rx = void 0;
  12842. var ry = void 0;
  12843. var psi = void 0;
  12844. var fa = void 0;
  12845. var fs = void 0;
  12846. var x1 = cpx;
  12847. var y1 = cpy;
  12848. var len = void 0;
  12849. var pathData = void 0;
  12850. switch (cmdStr) {
  12851. case 'l':
  12852. cpx += p[off++];
  12853. cpy += p[off++];
  12854. cmd = CMD.L;
  12855. path.addData(cmd, cpx, cpy);
  12856. break;
  12857. case 'L':
  12858. cpx = p[off++];
  12859. cpy = p[off++];
  12860. cmd = CMD.L;
  12861. path.addData(cmd, cpx, cpy);
  12862. break;
  12863. case 'm':
  12864. cpx += p[off++];
  12865. cpy += p[off++];
  12866. cmd = CMD.M;
  12867. path.addData(cmd, cpx, cpy);
  12868. subpathX = cpx;
  12869. subpathY = cpy;
  12870. cmdStr = 'l';
  12871. break;
  12872. case 'M':
  12873. cpx = p[off++];
  12874. cpy = p[off++];
  12875. cmd = CMD.M;
  12876. path.addData(cmd, cpx, cpy);
  12877. subpathX = cpx;
  12878. subpathY = cpy;
  12879. cmdStr = 'L';
  12880. break;
  12881. case 'h':
  12882. cpx += p[off++];
  12883. cmd = CMD.L;
  12884. path.addData(cmd, cpx, cpy);
  12885. break;
  12886. case 'H':
  12887. cpx = p[off++];
  12888. cmd = CMD.L;
  12889. path.addData(cmd, cpx, cpy);
  12890. break;
  12891. case 'v':
  12892. cpy += p[off++];
  12893. cmd = CMD.L;
  12894. path.addData(cmd, cpx, cpy);
  12895. break;
  12896. case 'V':
  12897. cpy = p[off++];
  12898. cmd = CMD.L;
  12899. path.addData(cmd, cpx, cpy);
  12900. break;
  12901. case 'C':
  12902. cmd = CMD.C;
  12903. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12904. cpx = p[off - 2];
  12905. cpy = p[off - 1];
  12906. break;
  12907. case 'c':
  12908. cmd = CMD.C;
  12909. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12910. cpx += p[off - 2];
  12911. cpy += p[off - 1];
  12912. break;
  12913. case 'S':
  12914. ctlPtx = cpx;
  12915. ctlPty = cpy;
  12916. len = path.len();
  12917. pathData = path.data;
  12918. if (prevCmd === CMD.C) {
  12919. ctlPtx += cpx - pathData[len - 4];
  12920. ctlPty += cpy - pathData[len - 3];
  12921. }
  12922. cmd = CMD.C;
  12923. x1 = p[off++];
  12924. y1 = p[off++];
  12925. cpx = p[off++];
  12926. cpy = p[off++];
  12927. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12928. break;
  12929. case 's':
  12930. ctlPtx = cpx;
  12931. ctlPty = cpy;
  12932. len = path.len();
  12933. pathData = path.data;
  12934. if (prevCmd === CMD.C) {
  12935. ctlPtx += cpx - pathData[len - 4];
  12936. ctlPty += cpy - pathData[len - 3];
  12937. }
  12938. cmd = CMD.C;
  12939. x1 = cpx + p[off++];
  12940. y1 = cpy + p[off++];
  12941. cpx += p[off++];
  12942. cpy += p[off++];
  12943. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12944. break;
  12945. case 'Q':
  12946. x1 = p[off++];
  12947. y1 = p[off++];
  12948. cpx = p[off++];
  12949. cpy = p[off++];
  12950. cmd = CMD.Q;
  12951. path.addData(cmd, x1, y1, cpx, cpy);
  12952. break;
  12953. case 'q':
  12954. x1 = p[off++] + cpx;
  12955. y1 = p[off++] + cpy;
  12956. cpx += p[off++];
  12957. cpy += p[off++];
  12958. cmd = CMD.Q;
  12959. path.addData(cmd, x1, y1, cpx, cpy);
  12960. break;
  12961. case 'T':
  12962. ctlPtx = cpx;
  12963. ctlPty = cpy;
  12964. len = path.len();
  12965. pathData = path.data;
  12966. if (prevCmd === CMD.Q) {
  12967. ctlPtx += cpx - pathData[len - 4];
  12968. ctlPty += cpy - pathData[len - 3];
  12969. }
  12970. cpx = p[off++];
  12971. cpy = p[off++];
  12972. cmd = CMD.Q;
  12973. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12974. break;
  12975. case 't':
  12976. ctlPtx = cpx;
  12977. ctlPty = cpy;
  12978. len = path.len();
  12979. pathData = path.data;
  12980. if (prevCmd === CMD.Q) {
  12981. ctlPtx += cpx - pathData[len - 4];
  12982. ctlPty += cpy - pathData[len - 3];
  12983. }
  12984. cpx += p[off++];
  12985. cpy += p[off++];
  12986. cmd = CMD.Q;
  12987. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12988. break;
  12989. case 'A':
  12990. rx = p[off++];
  12991. ry = p[off++];
  12992. psi = p[off++];
  12993. fa = p[off++];
  12994. fs = p[off++];
  12995. x1 = cpx, y1 = cpy;
  12996. cpx = p[off++];
  12997. cpy = p[off++];
  12998. cmd = CMD.A;
  12999. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13000. break;
  13001. case 'a':
  13002. rx = p[off++];
  13003. ry = p[off++];
  13004. psi = p[off++];
  13005. fa = p[off++];
  13006. fs = p[off++];
  13007. x1 = cpx, y1 = cpy;
  13008. cpx += p[off++];
  13009. cpy += p[off++];
  13010. cmd = CMD.A;
  13011. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13012. break;
  13013. }
  13014. }
  13015. if (cmdStr === 'z' || cmdStr === 'Z') {
  13016. cmd = CMD.Z;
  13017. path.addData(cmd);
  13018. cpx = subpathX;
  13019. cpy = subpathY;
  13020. }
  13021. prevCmd = cmd;
  13022. }
  13023. path.toStatic();
  13024. return path;
  13025. }
  13026. var SVGPath = (function (_super) {
  13027. __extends(SVGPath, _super);
  13028. function SVGPath() {
  13029. return _super !== null && _super.apply(this, arguments) || this;
  13030. }
  13031. SVGPath.prototype.applyTransform = function (m) { };
  13032. return SVGPath;
  13033. }(Path));
  13034. function isPathProxy(path) {
  13035. return path.setData != null;
  13036. }
  13037. function createPathOptions(str, opts) {
  13038. var pathProxy = createPathProxyFromString(str);
  13039. var innerOpts = extend({}, opts);
  13040. innerOpts.buildPath = function (path) {
  13041. if (isPathProxy(path)) {
  13042. path.setData(pathProxy.data);
  13043. var ctx = path.getContext();
  13044. if (ctx) {
  13045. path.rebuildPath(ctx, 1);
  13046. }
  13047. }
  13048. else {
  13049. var ctx = path;
  13050. pathProxy.rebuildPath(ctx, 1);
  13051. }
  13052. };
  13053. innerOpts.applyTransform = function (m) {
  13054. transformPath(pathProxy, m);
  13055. this.dirtyShape();
  13056. };
  13057. return innerOpts;
  13058. }
  13059. function createFromString(str, opts) {
  13060. return new SVGPath(createPathOptions(str, opts));
  13061. }
  13062. function extendFromString(str, defaultOpts) {
  13063. var innerOpts = createPathOptions(str, defaultOpts);
  13064. var Sub = (function (_super) {
  13065. __extends(Sub, _super);
  13066. function Sub(opts) {
  13067. var _this = _super.call(this, opts) || this;
  13068. _this.applyTransform = innerOpts.applyTransform;
  13069. _this.buildPath = innerOpts.buildPath;
  13070. return _this;
  13071. }
  13072. return Sub;
  13073. }(SVGPath));
  13074. return Sub;
  13075. }
  13076. function mergePath(pathEls, opts) {
  13077. var pathList = [];
  13078. var len = pathEls.length;
  13079. for (var i = 0; i < len; i++) {
  13080. var pathEl = pathEls[i];
  13081. pathList.push(pathEl.getUpdatedPathProxy(true));
  13082. }
  13083. var pathBundle = new Path(opts);
  13084. pathBundle.createPathProxy();
  13085. pathBundle.buildPath = function (path) {
  13086. if (isPathProxy(path)) {
  13087. path.appendPath(pathList);
  13088. var ctx = path.getContext();
  13089. if (ctx) {
  13090. path.rebuildPath(ctx, 1);
  13091. }
  13092. }
  13093. };
  13094. return pathBundle;
  13095. }
  13096. function clonePath(sourcePath, opts) {
  13097. opts = opts || {};
  13098. var path = new Path();
  13099. if (sourcePath.shape) {
  13100. path.setShape(sourcePath.shape);
  13101. }
  13102. path.setStyle(sourcePath.style);
  13103. if (opts.bakeTransform) {
  13104. transformPath(path.path, sourcePath.getComputedTransform());
  13105. }
  13106. else {
  13107. if (opts.toLocal) {
  13108. path.setLocalTransform(sourcePath.getComputedTransform());
  13109. }
  13110. else {
  13111. path.copyTransform(sourcePath);
  13112. }
  13113. }
  13114. path.buildPath = sourcePath.buildPath;
  13115. path.applyTransform = path.applyTransform;
  13116. path.z = sourcePath.z;
  13117. path.z2 = sourcePath.z2;
  13118. path.zlevel = sourcePath.zlevel;
  13119. return path;
  13120. }
  13121. var CircleShape = (function () {
  13122. function CircleShape() {
  13123. this.cx = 0;
  13124. this.cy = 0;
  13125. this.r = 0;
  13126. }
  13127. return CircleShape;
  13128. }());
  13129. var Circle = (function (_super) {
  13130. __extends(Circle, _super);
  13131. function Circle(opts) {
  13132. return _super.call(this, opts) || this;
  13133. }
  13134. Circle.prototype.getDefaultShape = function () {
  13135. return new CircleShape();
  13136. };
  13137. Circle.prototype.buildPath = function (ctx, shape) {
  13138. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13139. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  13140. };
  13141. return Circle;
  13142. }(Path));
  13143. Circle.prototype.type = 'circle';
  13144. var EllipseShape = (function () {
  13145. function EllipseShape() {
  13146. this.cx = 0;
  13147. this.cy = 0;
  13148. this.rx = 0;
  13149. this.ry = 0;
  13150. }
  13151. return EllipseShape;
  13152. }());
  13153. var Ellipse = (function (_super) {
  13154. __extends(Ellipse, _super);
  13155. function Ellipse(opts) {
  13156. return _super.call(this, opts) || this;
  13157. }
  13158. Ellipse.prototype.getDefaultShape = function () {
  13159. return new EllipseShape();
  13160. };
  13161. Ellipse.prototype.buildPath = function (ctx, shape) {
  13162. var k = 0.5522848;
  13163. var x = shape.cx;
  13164. var y = shape.cy;
  13165. var a = shape.rx;
  13166. var b = shape.ry;
  13167. var ox = a * k;
  13168. var oy = b * k;
  13169. ctx.moveTo(x - a, y);
  13170. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  13171. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  13172. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  13173. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  13174. ctx.closePath();
  13175. };
  13176. return Ellipse;
  13177. }(Path));
  13178. Ellipse.prototype.type = 'ellipse';
  13179. var PI$2 = Math.PI;
  13180. var PI2$5 = PI$2 * 2;
  13181. var mathSin$3 = Math.sin;
  13182. var mathCos$3 = Math.cos;
  13183. var mathACos = Math.acos;
  13184. var mathATan2 = Math.atan2;
  13185. var mathAbs$1 = Math.abs;
  13186. var mathSqrt$3 = Math.sqrt;
  13187. var mathMax$3 = Math.max;
  13188. var mathMin$3 = Math.min;
  13189. var e = 1e-4;
  13190. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  13191. var dx10 = x1 - x0;
  13192. var dy10 = y1 - y0;
  13193. var dx32 = x3 - x2;
  13194. var dy32 = y3 - y2;
  13195. var t = dy32 * dx10 - dx32 * dy10;
  13196. if (t * t < e) {
  13197. return;
  13198. }
  13199. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  13200. return [x0 + t * dx10, y0 + t * dy10];
  13201. }
  13202. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  13203. var x01 = x0 - x1;
  13204. var y01 = y0 - y1;
  13205. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  13206. var ox = lo * y01;
  13207. var oy = -lo * x01;
  13208. var x11 = x0 + ox;
  13209. var y11 = y0 + oy;
  13210. var x10 = x1 + ox;
  13211. var y10 = y1 + oy;
  13212. var x00 = (x11 + x10) / 2;
  13213. var y00 = (y11 + y10) / 2;
  13214. var dx = x10 - x11;
  13215. var dy = y10 - y11;
  13216. var d2 = dx * dx + dy * dy;
  13217. var r = radius - cr;
  13218. var s = x11 * y10 - x10 * y11;
  13219. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$3(0, r * r * d2 - s * s));
  13220. var cx0 = (s * dy - dx * d) / d2;
  13221. var cy0 = (-s * dx - dy * d) / d2;
  13222. var cx1 = (s * dy + dx * d) / d2;
  13223. var cy1 = (-s * dx + dy * d) / d2;
  13224. var dx0 = cx0 - x00;
  13225. var dy0 = cy0 - y00;
  13226. var dx1 = cx1 - x00;
  13227. var dy1 = cy1 - y00;
  13228. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  13229. cx0 = cx1;
  13230. cy0 = cy1;
  13231. }
  13232. return {
  13233. cx: cx0,
  13234. cy: cy0,
  13235. x0: -ox,
  13236. y0: -oy,
  13237. x1: cx0 * (radius / r - 1),
  13238. y1: cy0 * (radius / r - 1)
  13239. };
  13240. }
  13241. function normalizeCornerRadius(cr) {
  13242. var arr;
  13243. if (isArray(cr)) {
  13244. var len = cr.length;
  13245. if (!len) {
  13246. return cr;
  13247. }
  13248. if (len === 1) {
  13249. arr = [cr[0], cr[0], 0, 0];
  13250. }
  13251. else if (len === 2) {
  13252. arr = [cr[0], cr[0], cr[1], cr[1]];
  13253. }
  13254. else if (len === 3) {
  13255. arr = cr.concat(cr[2]);
  13256. }
  13257. else {
  13258. arr = cr;
  13259. }
  13260. }
  13261. else {
  13262. arr = [cr, cr, cr, cr];
  13263. }
  13264. return arr;
  13265. }
  13266. function buildPath$1(ctx, shape) {
  13267. var _a;
  13268. var radius = mathMax$3(shape.r, 0);
  13269. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  13270. var hasRadius = radius > 0;
  13271. var hasInnerRadius = innerRadius > 0;
  13272. if (!hasRadius && !hasInnerRadius) {
  13273. return;
  13274. }
  13275. if (!hasRadius) {
  13276. radius = innerRadius;
  13277. innerRadius = 0;
  13278. }
  13279. if (innerRadius > radius) {
  13280. var tmp = radius;
  13281. radius = innerRadius;
  13282. innerRadius = tmp;
  13283. }
  13284. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  13285. if (isNaN(startAngle) || isNaN(endAngle)) {
  13286. return;
  13287. }
  13288. var cx = shape.cx, cy = shape.cy;
  13289. var clockwise = !!shape.clockwise;
  13290. var arc = mathAbs$1(endAngle - startAngle);
  13291. var mod = arc > PI2$5 && arc % PI2$5;
  13292. mod > e && (arc = mod);
  13293. if (!(radius > e)) {
  13294. ctx.moveTo(cx, cy);
  13295. }
  13296. else if (arc > PI2$5 - e) {
  13297. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  13298. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13299. if (innerRadius > e) {
  13300. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  13301. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13302. }
  13303. }
  13304. else {
  13305. var icrStart = void 0;
  13306. var icrEnd = void 0;
  13307. var ocrStart = void 0;
  13308. var ocrEnd = void 0;
  13309. var ocrs = void 0;
  13310. var ocre = void 0;
  13311. var icrs = void 0;
  13312. var icre = void 0;
  13313. var ocrMax = void 0;
  13314. var icrMax = void 0;
  13315. var limitedOcrMax = void 0;
  13316. var limitedIcrMax = void 0;
  13317. var xre = void 0;
  13318. var yre = void 0;
  13319. var xirs = void 0;
  13320. var yirs = void 0;
  13321. var xrs = radius * mathCos$3(startAngle);
  13322. var yrs = radius * mathSin$3(startAngle);
  13323. var xire = innerRadius * mathCos$3(endAngle);
  13324. var yire = innerRadius * mathSin$3(endAngle);
  13325. var hasArc = arc > e;
  13326. if (hasArc) {
  13327. var cornerRadius = shape.cornerRadius;
  13328. if (cornerRadius) {
  13329. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  13330. }
  13331. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  13332. ocrs = mathMin$3(halfRd, ocrStart);
  13333. ocre = mathMin$3(halfRd, ocrEnd);
  13334. icrs = mathMin$3(halfRd, icrStart);
  13335. icre = mathMin$3(halfRd, icrEnd);
  13336. limitedOcrMax = ocrMax = mathMax$3(ocrs, ocre);
  13337. limitedIcrMax = icrMax = mathMax$3(icrs, icre);
  13338. if (ocrMax > e || icrMax > e) {
  13339. xre = radius * mathCos$3(endAngle);
  13340. yre = radius * mathSin$3(endAngle);
  13341. xirs = innerRadius * mathCos$3(startAngle);
  13342. yirs = innerRadius * mathSin$3(startAngle);
  13343. if (arc < PI$2) {
  13344. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13345. if (it_1) {
  13346. var x0 = xrs - it_1[0];
  13347. var y0 = yrs - it_1[1];
  13348. var x1 = xre - it_1[0];
  13349. var y1 = yre - it_1[1];
  13350. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  13351. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13352. limitedOcrMax = mathMin$3(ocrMax, (radius - b) / (a + 1));
  13353. limitedIcrMax = mathMin$3(icrMax, (innerRadius - b) / (a - 1));
  13354. }
  13355. }
  13356. }
  13357. }
  13358. if (!hasArc) {
  13359. ctx.moveTo(cx + xrs, cy + yrs);
  13360. }
  13361. else if (limitedOcrMax > e) {
  13362. var crStart = mathMin$3(ocrStart, limitedOcrMax);
  13363. var crEnd = mathMin$3(ocrEnd, limitedOcrMax);
  13364. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  13365. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  13366. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13367. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  13368. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13369. }
  13370. else {
  13371. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13372. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  13373. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13374. }
  13375. }
  13376. else {
  13377. ctx.moveTo(cx + xrs, cy + yrs);
  13378. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13379. }
  13380. if (!(innerRadius > e) || !hasArc) {
  13381. ctx.lineTo(cx + xire, cy + yire);
  13382. }
  13383. else if (limitedIcrMax > e) {
  13384. var crStart = mathMin$3(icrStart, limitedIcrMax);
  13385. var crEnd = mathMin$3(icrEnd, limitedIcrMax);
  13386. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  13387. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  13388. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13389. if (limitedIcrMax < icrMax && crStart === crEnd) {
  13390. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13391. }
  13392. else {
  13393. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13394. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  13395. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13396. }
  13397. }
  13398. else {
  13399. ctx.lineTo(cx + xire, cy + yire);
  13400. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13401. }
  13402. }
  13403. ctx.closePath();
  13404. }
  13405. var SectorShape = (function () {
  13406. function SectorShape() {
  13407. this.cx = 0;
  13408. this.cy = 0;
  13409. this.r0 = 0;
  13410. this.r = 0;
  13411. this.startAngle = 0;
  13412. this.endAngle = Math.PI * 2;
  13413. this.clockwise = true;
  13414. this.cornerRadius = 0;
  13415. }
  13416. return SectorShape;
  13417. }());
  13418. var Sector = (function (_super) {
  13419. __extends(Sector, _super);
  13420. function Sector(opts) {
  13421. return _super.call(this, opts) || this;
  13422. }
  13423. Sector.prototype.getDefaultShape = function () {
  13424. return new SectorShape();
  13425. };
  13426. Sector.prototype.buildPath = function (ctx, shape) {
  13427. buildPath$1(ctx, shape);
  13428. };
  13429. Sector.prototype.isZeroArea = function () {
  13430. return this.shape.startAngle === this.shape.endAngle
  13431. || this.shape.r === this.shape.r0;
  13432. };
  13433. return Sector;
  13434. }(Path));
  13435. Sector.prototype.type = 'sector';
  13436. var RingShape = (function () {
  13437. function RingShape() {
  13438. this.cx = 0;
  13439. this.cy = 0;
  13440. this.r = 0;
  13441. this.r0 = 0;
  13442. }
  13443. return RingShape;
  13444. }());
  13445. var Ring = (function (_super) {
  13446. __extends(Ring, _super);
  13447. function Ring(opts) {
  13448. return _super.call(this, opts) || this;
  13449. }
  13450. Ring.prototype.getDefaultShape = function () {
  13451. return new RingShape();
  13452. };
  13453. Ring.prototype.buildPath = function (ctx, shape) {
  13454. var x = shape.cx;
  13455. var y = shape.cy;
  13456. var PI2 = Math.PI * 2;
  13457. ctx.moveTo(x + shape.r, y);
  13458. ctx.arc(x, y, shape.r, 0, PI2, false);
  13459. ctx.moveTo(x + shape.r0, y);
  13460. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13461. };
  13462. return Ring;
  13463. }(Path));
  13464. Ring.prototype.type = 'ring';
  13465. function smoothBezier(points, smooth, isLoop, constraint) {
  13466. var cps = [];
  13467. var v = [];
  13468. var v1 = [];
  13469. var v2 = [];
  13470. var prevPoint;
  13471. var nextPoint;
  13472. var min$1;
  13473. var max$1;
  13474. if (constraint) {
  13475. min$1 = [Infinity, Infinity];
  13476. max$1 = [-Infinity, -Infinity];
  13477. for (var i = 0, len = points.length; i < len; i++) {
  13478. min(min$1, min$1, points[i]);
  13479. max(max$1, max$1, points[i]);
  13480. }
  13481. min(min$1, min$1, constraint[0]);
  13482. max(max$1, max$1, constraint[1]);
  13483. }
  13484. for (var i = 0, len = points.length; i < len; i++) {
  13485. var point = points[i];
  13486. if (isLoop) {
  13487. prevPoint = points[i ? i - 1 : len - 1];
  13488. nextPoint = points[(i + 1) % len];
  13489. }
  13490. else {
  13491. if (i === 0 || i === len - 1) {
  13492. cps.push(clone$1(points[i]));
  13493. continue;
  13494. }
  13495. else {
  13496. prevPoint = points[i - 1];
  13497. nextPoint = points[i + 1];
  13498. }
  13499. }
  13500. sub(v, nextPoint, prevPoint);
  13501. scale(v, v, smooth);
  13502. var d0 = distance(point, prevPoint);
  13503. var d1 = distance(point, nextPoint);
  13504. var sum = d0 + d1;
  13505. if (sum !== 0) {
  13506. d0 /= sum;
  13507. d1 /= sum;
  13508. }
  13509. scale(v1, v, -d0);
  13510. scale(v2, v, d1);
  13511. var cp0 = add([], point, v1);
  13512. var cp1 = add([], point, v2);
  13513. if (constraint) {
  13514. max(cp0, cp0, min$1);
  13515. min(cp0, cp0, max$1);
  13516. max(cp1, cp1, min$1);
  13517. min(cp1, cp1, max$1);
  13518. }
  13519. cps.push(cp0);
  13520. cps.push(cp1);
  13521. }
  13522. if (isLoop) {
  13523. cps.push(cps.shift());
  13524. }
  13525. return cps;
  13526. }
  13527. function buildPath$2(ctx, shape, closePath) {
  13528. var smooth = shape.smooth;
  13529. var points = shape.points;
  13530. if (points && points.length >= 2) {
  13531. if (smooth) {
  13532. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13533. ctx.moveTo(points[0][0], points[0][1]);
  13534. var len = points.length;
  13535. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13536. var cp1 = controlPoints[i * 2];
  13537. var cp2 = controlPoints[i * 2 + 1];
  13538. var p = points[(i + 1) % len];
  13539. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13540. }
  13541. }
  13542. else {
  13543. ctx.moveTo(points[0][0], points[0][1]);
  13544. for (var i = 1, l = points.length; i < l; i++) {
  13545. ctx.lineTo(points[i][0], points[i][1]);
  13546. }
  13547. }
  13548. closePath && ctx.closePath();
  13549. }
  13550. }
  13551. var PolygonShape = (function () {
  13552. function PolygonShape() {
  13553. this.points = null;
  13554. this.smooth = 0;
  13555. this.smoothConstraint = null;
  13556. }
  13557. return PolygonShape;
  13558. }());
  13559. var Polygon = (function (_super) {
  13560. __extends(Polygon, _super);
  13561. function Polygon(opts) {
  13562. return _super.call(this, opts) || this;
  13563. }
  13564. Polygon.prototype.getDefaultShape = function () {
  13565. return new PolygonShape();
  13566. };
  13567. Polygon.prototype.buildPath = function (ctx, shape) {
  13568. buildPath$2(ctx, shape, true);
  13569. };
  13570. return Polygon;
  13571. }(Path));
  13572. Polygon.prototype.type = 'polygon';
  13573. var PolylineShape = (function () {
  13574. function PolylineShape() {
  13575. this.points = null;
  13576. this.percent = 1;
  13577. this.smooth = 0;
  13578. this.smoothConstraint = null;
  13579. }
  13580. return PolylineShape;
  13581. }());
  13582. var Polyline = (function (_super) {
  13583. __extends(Polyline, _super);
  13584. function Polyline(opts) {
  13585. return _super.call(this, opts) || this;
  13586. }
  13587. Polyline.prototype.getDefaultStyle = function () {
  13588. return {
  13589. stroke: '#000',
  13590. fill: null
  13591. };
  13592. };
  13593. Polyline.prototype.getDefaultShape = function () {
  13594. return new PolylineShape();
  13595. };
  13596. Polyline.prototype.buildPath = function (ctx, shape) {
  13597. buildPath$2(ctx, shape, false);
  13598. };
  13599. return Polyline;
  13600. }(Path));
  13601. Polyline.prototype.type = 'polyline';
  13602. var subPixelOptimizeOutputShape$1 = {};
  13603. var LineShape = (function () {
  13604. function LineShape() {
  13605. this.x1 = 0;
  13606. this.y1 = 0;
  13607. this.x2 = 0;
  13608. this.y2 = 0;
  13609. this.percent = 1;
  13610. }
  13611. return LineShape;
  13612. }());
  13613. var Line = (function (_super) {
  13614. __extends(Line, _super);
  13615. function Line(opts) {
  13616. return _super.call(this, opts) || this;
  13617. }
  13618. Line.prototype.getDefaultStyle = function () {
  13619. return {
  13620. stroke: '#000',
  13621. fill: null
  13622. };
  13623. };
  13624. Line.prototype.getDefaultShape = function () {
  13625. return new LineShape();
  13626. };
  13627. Line.prototype.buildPath = function (ctx, shape) {
  13628. var x1;
  13629. var y1;
  13630. var x2;
  13631. var y2;
  13632. if (this.subPixelOptimize) {
  13633. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13634. x1 = optimizedShape.x1;
  13635. y1 = optimizedShape.y1;
  13636. x2 = optimizedShape.x2;
  13637. y2 = optimizedShape.y2;
  13638. }
  13639. else {
  13640. x1 = shape.x1;
  13641. y1 = shape.y1;
  13642. x2 = shape.x2;
  13643. y2 = shape.y2;
  13644. }
  13645. var percent = shape.percent;
  13646. if (percent === 0) {
  13647. return;
  13648. }
  13649. ctx.moveTo(x1, y1);
  13650. if (percent < 1) {
  13651. x2 = x1 * (1 - percent) + x2 * percent;
  13652. y2 = y1 * (1 - percent) + y2 * percent;
  13653. }
  13654. ctx.lineTo(x2, y2);
  13655. };
  13656. Line.prototype.pointAt = function (p) {
  13657. var shape = this.shape;
  13658. return [
  13659. shape.x1 * (1 - p) + shape.x2 * p,
  13660. shape.y1 * (1 - p) + shape.y2 * p
  13661. ];
  13662. };
  13663. return Line;
  13664. }(Path));
  13665. Line.prototype.type = 'line';
  13666. var out = [];
  13667. var BezierCurveShape = (function () {
  13668. function BezierCurveShape() {
  13669. this.x1 = 0;
  13670. this.y1 = 0;
  13671. this.x2 = 0;
  13672. this.y2 = 0;
  13673. this.cpx1 = 0;
  13674. this.cpy1 = 0;
  13675. this.percent = 1;
  13676. }
  13677. return BezierCurveShape;
  13678. }());
  13679. function someVectorAt(shape, t, isTangent) {
  13680. var cpx2 = shape.cpx2;
  13681. var cpy2 = shape.cpy2;
  13682. if (cpx2 != null || cpy2 != null) {
  13683. return [
  13684. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13685. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13686. ];
  13687. }
  13688. else {
  13689. return [
  13690. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13691. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13692. ];
  13693. }
  13694. }
  13695. var BezierCurve = (function (_super) {
  13696. __extends(BezierCurve, _super);
  13697. function BezierCurve(opts) {
  13698. return _super.call(this, opts) || this;
  13699. }
  13700. BezierCurve.prototype.getDefaultStyle = function () {
  13701. return {
  13702. stroke: '#000',
  13703. fill: null
  13704. };
  13705. };
  13706. BezierCurve.prototype.getDefaultShape = function () {
  13707. return new BezierCurveShape();
  13708. };
  13709. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13710. var x1 = shape.x1;
  13711. var y1 = shape.y1;
  13712. var x2 = shape.x2;
  13713. var y2 = shape.y2;
  13714. var cpx1 = shape.cpx1;
  13715. var cpy1 = shape.cpy1;
  13716. var cpx2 = shape.cpx2;
  13717. var cpy2 = shape.cpy2;
  13718. var percent = shape.percent;
  13719. if (percent === 0) {
  13720. return;
  13721. }
  13722. ctx.moveTo(x1, y1);
  13723. if (cpx2 == null || cpy2 == null) {
  13724. if (percent < 1) {
  13725. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13726. cpx1 = out[1];
  13727. x2 = out[2];
  13728. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13729. cpy1 = out[1];
  13730. y2 = out[2];
  13731. }
  13732. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13733. }
  13734. else {
  13735. if (percent < 1) {
  13736. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13737. cpx1 = out[1];
  13738. cpx2 = out[2];
  13739. x2 = out[3];
  13740. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13741. cpy1 = out[1];
  13742. cpy2 = out[2];
  13743. y2 = out[3];
  13744. }
  13745. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13746. }
  13747. };
  13748. BezierCurve.prototype.pointAt = function (t) {
  13749. return someVectorAt(this.shape, t, false);
  13750. };
  13751. BezierCurve.prototype.tangentAt = function (t) {
  13752. var p = someVectorAt(this.shape, t, true);
  13753. return normalize(p, p);
  13754. };
  13755. return BezierCurve;
  13756. }(Path));
  13757. BezierCurve.prototype.type = 'bezier-curve';
  13758. var ArcShape = (function () {
  13759. function ArcShape() {
  13760. this.cx = 0;
  13761. this.cy = 0;
  13762. this.r = 0;
  13763. this.startAngle = 0;
  13764. this.endAngle = Math.PI * 2;
  13765. this.clockwise = true;
  13766. }
  13767. return ArcShape;
  13768. }());
  13769. var Arc = (function (_super) {
  13770. __extends(Arc, _super);
  13771. function Arc(opts) {
  13772. return _super.call(this, opts) || this;
  13773. }
  13774. Arc.prototype.getDefaultStyle = function () {
  13775. return {
  13776. stroke: '#000',
  13777. fill: null
  13778. };
  13779. };
  13780. Arc.prototype.getDefaultShape = function () {
  13781. return new ArcShape();
  13782. };
  13783. Arc.prototype.buildPath = function (ctx, shape) {
  13784. var x = shape.cx;
  13785. var y = shape.cy;
  13786. var r = Math.max(shape.r, 0);
  13787. var startAngle = shape.startAngle;
  13788. var endAngle = shape.endAngle;
  13789. var clockwise = shape.clockwise;
  13790. var unitX = Math.cos(startAngle);
  13791. var unitY = Math.sin(startAngle);
  13792. ctx.moveTo(unitX * r + x, unitY * r + y);
  13793. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13794. };
  13795. return Arc;
  13796. }(Path));
  13797. Arc.prototype.type = 'arc';
  13798. var CompoundPath = (function (_super) {
  13799. __extends(CompoundPath, _super);
  13800. function CompoundPath() {
  13801. var _this = _super !== null && _super.apply(this, arguments) || this;
  13802. _this.type = 'compound';
  13803. return _this;
  13804. }
  13805. CompoundPath.prototype._updatePathDirty = function () {
  13806. var paths = this.shape.paths;
  13807. var dirtyPath = this.shapeChanged();
  13808. for (var i = 0; i < paths.length; i++) {
  13809. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13810. }
  13811. if (dirtyPath) {
  13812. this.dirtyShape();
  13813. }
  13814. };
  13815. CompoundPath.prototype.beforeBrush = function () {
  13816. this._updatePathDirty();
  13817. var paths = this.shape.paths || [];
  13818. var scale = this.getGlobalScale();
  13819. for (var i = 0; i < paths.length; i++) {
  13820. if (!paths[i].path) {
  13821. paths[i].createPathProxy();
  13822. }
  13823. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13824. }
  13825. };
  13826. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13827. var paths = shape.paths || [];
  13828. for (var i = 0; i < paths.length; i++) {
  13829. paths[i].buildPath(ctx, paths[i].shape, true);
  13830. }
  13831. };
  13832. CompoundPath.prototype.afterBrush = function () {
  13833. var paths = this.shape.paths || [];
  13834. for (var i = 0; i < paths.length; i++) {
  13835. paths[i].pathUpdated();
  13836. }
  13837. };
  13838. CompoundPath.prototype.getBoundingRect = function () {
  13839. this._updatePathDirty.call(this);
  13840. return Path.prototype.getBoundingRect.call(this);
  13841. };
  13842. return CompoundPath;
  13843. }(Path));
  13844. var Gradient = (function () {
  13845. function Gradient(colorStops) {
  13846. this.colorStops = colorStops || [];
  13847. }
  13848. Gradient.prototype.addColorStop = function (offset, color) {
  13849. this.colorStops.push({
  13850. offset: offset,
  13851. color: color
  13852. });
  13853. };
  13854. return Gradient;
  13855. }());
  13856. var LinearGradient = (function (_super) {
  13857. __extends(LinearGradient, _super);
  13858. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13859. var _this = _super.call(this, colorStops) || this;
  13860. _this.x = x == null ? 0 : x;
  13861. _this.y = y == null ? 0 : y;
  13862. _this.x2 = x2 == null ? 1 : x2;
  13863. _this.y2 = y2 == null ? 0 : y2;
  13864. _this.type = 'linear';
  13865. _this.global = globalCoord || false;
  13866. return _this;
  13867. }
  13868. return LinearGradient;
  13869. }(Gradient));
  13870. var RadialGradient = (function (_super) {
  13871. __extends(RadialGradient, _super);
  13872. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13873. var _this = _super.call(this, colorStops) || this;
  13874. _this.x = x == null ? 0.5 : x;
  13875. _this.y = y == null ? 0.5 : y;
  13876. _this.r = r == null ? 0.5 : r;
  13877. _this.type = 'radial';
  13878. _this.global = globalCoord || false;
  13879. return _this;
  13880. }
  13881. return RadialGradient;
  13882. }(Gradient));
  13883. var extent = [0, 0];
  13884. var extent2 = [0, 0];
  13885. var minTv$1 = new Point();
  13886. var maxTv$1 = new Point();
  13887. var OrientedBoundingRect = (function () {
  13888. function OrientedBoundingRect(rect, transform) {
  13889. this._corners = [];
  13890. this._axes = [];
  13891. this._origin = [0, 0];
  13892. for (var i = 0; i < 4; i++) {
  13893. this._corners[i] = new Point();
  13894. }
  13895. for (var i = 0; i < 2; i++) {
  13896. this._axes[i] = new Point();
  13897. }
  13898. if (rect) {
  13899. this.fromBoundingRect(rect, transform);
  13900. }
  13901. }
  13902. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13903. var corners = this._corners;
  13904. var axes = this._axes;
  13905. var x = rect.x;
  13906. var y = rect.y;
  13907. var x2 = x + rect.width;
  13908. var y2 = y + rect.height;
  13909. corners[0].set(x, y);
  13910. corners[1].set(x2, y);
  13911. corners[2].set(x2, y2);
  13912. corners[3].set(x, y2);
  13913. if (transform) {
  13914. for (var i = 0; i < 4; i++) {
  13915. corners[i].transform(transform);
  13916. }
  13917. }
  13918. Point.sub(axes[0], corners[1], corners[0]);
  13919. Point.sub(axes[1], corners[3], corners[0]);
  13920. axes[0].normalize();
  13921. axes[1].normalize();
  13922. for (var i = 0; i < 2; i++) {
  13923. this._origin[i] = axes[i].dot(corners[0]);
  13924. }
  13925. };
  13926. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13927. var overlapped = true;
  13928. var noMtv = !mtv;
  13929. minTv$1.set(Infinity, Infinity);
  13930. maxTv$1.set(0, 0);
  13931. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13932. overlapped = false;
  13933. if (noMtv) {
  13934. return overlapped;
  13935. }
  13936. }
  13937. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13938. overlapped = false;
  13939. if (noMtv) {
  13940. return overlapped;
  13941. }
  13942. }
  13943. if (!noMtv) {
  13944. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13945. }
  13946. return overlapped;
  13947. };
  13948. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13949. var overlapped = true;
  13950. for (var i = 0; i < 2; i++) {
  13951. var axis = this._axes[i];
  13952. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13953. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13954. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13955. overlapped = false;
  13956. if (noMtv) {
  13957. return overlapped;
  13958. }
  13959. var dist0 = Math.abs(extent2[0] - extent[1]);
  13960. var dist1 = Math.abs(extent[0] - extent2[1]);
  13961. if (Math.min(dist0, dist1) > maxTv.len()) {
  13962. if (dist0 < dist1) {
  13963. Point.scale(maxTv, axis, -dist0 * inverse);
  13964. }
  13965. else {
  13966. Point.scale(maxTv, axis, dist1 * inverse);
  13967. }
  13968. }
  13969. }
  13970. else if (minTv) {
  13971. var dist0 = Math.abs(extent2[0] - extent[1]);
  13972. var dist1 = Math.abs(extent[0] - extent2[1]);
  13973. if (Math.min(dist0, dist1) < minTv.len()) {
  13974. if (dist0 < dist1) {
  13975. Point.scale(minTv, axis, dist0 * inverse);
  13976. }
  13977. else {
  13978. Point.scale(minTv, axis, -dist1 * inverse);
  13979. }
  13980. }
  13981. }
  13982. }
  13983. return overlapped;
  13984. };
  13985. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13986. var axis = this._axes[dim];
  13987. var origin = this._origin;
  13988. var proj = corners[0].dot(axis) + origin[dim];
  13989. var min = proj;
  13990. var max = proj;
  13991. for (var i = 1; i < corners.length; i++) {
  13992. var proj_1 = corners[i].dot(axis) + origin[dim];
  13993. min = Math.min(proj_1, min);
  13994. max = Math.max(proj_1, max);
  13995. }
  13996. out[0] = min;
  13997. out[1] = max;
  13998. };
  13999. return OrientedBoundingRect;
  14000. }());
  14001. var m = [];
  14002. var IncrementalDisplayable = (function (_super) {
  14003. __extends(IncrementalDisplayable, _super);
  14004. function IncrementalDisplayable() {
  14005. var _this = _super !== null && _super.apply(this, arguments) || this;
  14006. _this.notClear = true;
  14007. _this.incremental = true;
  14008. _this._displayables = [];
  14009. _this._temporaryDisplayables = [];
  14010. _this._cursor = 0;
  14011. return _this;
  14012. }
  14013. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  14014. cb.call(context, this);
  14015. };
  14016. IncrementalDisplayable.prototype.useStyle = function () {
  14017. this.style = {};
  14018. };
  14019. IncrementalDisplayable.prototype.getCursor = function () {
  14020. return this._cursor;
  14021. };
  14022. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  14023. this._cursor = this._displayables.length;
  14024. };
  14025. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  14026. this._displayables = [];
  14027. this._temporaryDisplayables = [];
  14028. this._cursor = 0;
  14029. this.markRedraw();
  14030. this.notClear = false;
  14031. };
  14032. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  14033. this._temporaryDisplayables = [];
  14034. };
  14035. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  14036. if (notPersistent) {
  14037. this._temporaryDisplayables.push(displayable);
  14038. }
  14039. else {
  14040. this._displayables.push(displayable);
  14041. }
  14042. this.markRedraw();
  14043. };
  14044. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  14045. notPersistent = notPersistent || false;
  14046. for (var i = 0; i < displayables.length; i++) {
  14047. this.addDisplayable(displayables[i], notPersistent);
  14048. }
  14049. };
  14050. IncrementalDisplayable.prototype.getDisplayables = function () {
  14051. return this._displayables;
  14052. };
  14053. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  14054. return this._temporaryDisplayables;
  14055. };
  14056. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  14057. for (var i = this._cursor; i < this._displayables.length; i++) {
  14058. cb && cb(this._displayables[i]);
  14059. }
  14060. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14061. cb && cb(this._temporaryDisplayables[i]);
  14062. }
  14063. };
  14064. IncrementalDisplayable.prototype.update = function () {
  14065. this.updateTransform();
  14066. for (var i = this._cursor; i < this._displayables.length; i++) {
  14067. var displayable = this._displayables[i];
  14068. displayable.parent = this;
  14069. displayable.update();
  14070. displayable.parent = null;
  14071. }
  14072. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14073. var displayable = this._temporaryDisplayables[i];
  14074. displayable.parent = this;
  14075. displayable.update();
  14076. displayable.parent = null;
  14077. }
  14078. };
  14079. IncrementalDisplayable.prototype.getBoundingRect = function () {
  14080. if (!this._rect) {
  14081. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14082. for (var i = 0; i < this._displayables.length; i++) {
  14083. var displayable = this._displayables[i];
  14084. var childRect = displayable.getBoundingRect().clone();
  14085. if (displayable.needLocalTransform()) {
  14086. childRect.applyTransform(displayable.getLocalTransform(m));
  14087. }
  14088. rect.union(childRect);
  14089. }
  14090. this._rect = rect;
  14091. }
  14092. return this._rect;
  14093. };
  14094. IncrementalDisplayable.prototype.contain = function (x, y) {
  14095. var localPos = this.transformCoordToLocal(x, y);
  14096. var rect = this.getBoundingRect();
  14097. if (rect.contain(localPos[0], localPos[1])) {
  14098. for (var i = 0; i < this._displayables.length; i++) {
  14099. var displayable = this._displayables[i];
  14100. if (displayable.contain(x, y)) {
  14101. return true;
  14102. }
  14103. }
  14104. }
  14105. return false;
  14106. };
  14107. return IncrementalDisplayable;
  14108. }(Displayable));
  14109. var transitionStore = makeInner();
  14110. /**
  14111. * Return null if animation is disabled.
  14112. */
  14113. function getAnimationConfig(animationType, animatableModel, dataIndex, // Extra opts can override the option in animatable model.
  14114. extraOpts, // TODO It's only for pictorial bar now.
  14115. extraDelayParams) {
  14116. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  14117. // If animation is enabled. Will use this animation config in payload.
  14118. // If animation is disabled. Just ignore it.
  14119. if (animatableModel && animatableModel.ecModel) {
  14120. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  14121. animationPayload = updatePayload && updatePayload.animation;
  14122. }
  14123. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14124. var isUpdate = animationType === 'update';
  14125. if (animationEnabled) {
  14126. var duration = void 0;
  14127. var easing = void 0;
  14128. var delay = void 0;
  14129. if (extraOpts) {
  14130. duration = retrieve2(extraOpts.duration, 200);
  14131. easing = retrieve2(extraOpts.easing, 'cubicOut');
  14132. delay = 0;
  14133. } else {
  14134. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  14135. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  14136. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  14137. } // animation from payload has highest priority.
  14138. if (animationPayload) {
  14139. animationPayload.duration != null && (duration = animationPayload.duration);
  14140. animationPayload.easing != null && (easing = animationPayload.easing);
  14141. animationPayload.delay != null && (delay = animationPayload.delay);
  14142. }
  14143. if (isFunction(delay)) {
  14144. delay = delay(dataIndex, extraDelayParams);
  14145. }
  14146. if (isFunction(duration)) {
  14147. duration = duration(dataIndex);
  14148. }
  14149. var config = {
  14150. duration: duration || 0,
  14151. delay: delay,
  14152. easing: easing
  14153. };
  14154. return config;
  14155. } else {
  14156. return null;
  14157. }
  14158. }
  14159. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  14160. var isFrom = false;
  14161. var removeOpt;
  14162. if (isFunction(dataIndex)) {
  14163. during = cb;
  14164. cb = dataIndex;
  14165. dataIndex = null;
  14166. } else if (isObject(dataIndex)) {
  14167. cb = dataIndex.cb;
  14168. during = dataIndex.during;
  14169. isFrom = dataIndex.isFrom;
  14170. removeOpt = dataIndex.removeOpt;
  14171. dataIndex = dataIndex.dataIndex;
  14172. }
  14173. var isRemove = animationType === 'leave';
  14174. if (!isRemove) {
  14175. // Must stop the remove animation.
  14176. el.stopAnimation('leave');
  14177. }
  14178. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14179. if (animationConfig && animationConfig.duration > 0) {
  14180. var duration = animationConfig.duration;
  14181. var animationDelay = animationConfig.delay;
  14182. var animationEasing = animationConfig.easing;
  14183. var animateConfig = {
  14184. duration: duration,
  14185. delay: animationDelay || 0,
  14186. easing: animationEasing,
  14187. done: cb,
  14188. force: !!cb || !!during,
  14189. // Set to final state in update/init animation.
  14190. // So the post processing based on the path shape can be done correctly.
  14191. setToFinal: !isRemove,
  14192. scope: animationType,
  14193. during: during
  14194. };
  14195. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  14196. } else {
  14197. el.stopAnimation(); // If `isFrom`, the props is the "from" props.
  14198. !isFrom && el.attr(props); // Call during at least once.
  14199. during && during(1);
  14200. cb && cb();
  14201. }
  14202. }
  14203. /**
  14204. * Update graphic element properties with or without animation according to the
  14205. * configuration in series.
  14206. *
  14207. * Caution: this method will stop previous animation.
  14208. * So do not use this method to one element twice before
  14209. * animation starts, unless you know what you are doing.
  14210. * @example
  14211. * graphic.updateProps(el, {
  14212. * position: [100, 100]
  14213. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14214. * // Or
  14215. * graphic.updateProps(el, {
  14216. * position: [100, 100]
  14217. * }, seriesModel, function () { console.log('Animation done!'); });
  14218. */
  14219. function updateProps(el, props, // TODO: TYPE AnimatableModel
  14220. animatableModel, dataIndex, cb, during) {
  14221. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  14222. }
  14223. /**
  14224. * Init graphic element properties with or without animation according to the
  14225. * configuration in series.
  14226. *
  14227. * Caution: this method will stop previous animation.
  14228. * So do not use this method to one element twice before
  14229. * animation starts, unless you know what you are doing.
  14230. */
  14231. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  14232. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  14233. }
  14234. /**
  14235. * If element is removed.
  14236. * It can determine if element is having remove animation.
  14237. */
  14238. function isElementRemoved(el) {
  14239. if (!el.__zr) {
  14240. return true;
  14241. }
  14242. for (var i = 0; i < el.animators.length; i++) {
  14243. var animator = el.animators[i];
  14244. if (animator.scope === 'leave') {
  14245. return true;
  14246. }
  14247. }
  14248. return false;
  14249. }
  14250. /**
  14251. * Remove graphic element
  14252. */
  14253. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  14254. // Don't do remove animation twice.
  14255. if (isElementRemoved(el)) {
  14256. return;
  14257. }
  14258. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  14259. }
  14260. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  14261. el.removeTextContent();
  14262. el.removeTextGuideLine();
  14263. removeElement(el, {
  14264. style: {
  14265. opacity: 0
  14266. }
  14267. }, animatableModel, dataIndex, done);
  14268. }
  14269. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14270. function doRemove() {
  14271. el.parent && el.parent.remove(el);
  14272. } // Hide label and labelLine first
  14273. // TODO Also use fade out animation?
  14274. if (!el.isGroup) {
  14275. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14276. } else {
  14277. el.traverse(function (disp) {
  14278. if (!disp.isGroup) {
  14279. // Can invoke doRemove multiple times.
  14280. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14281. }
  14282. });
  14283. }
  14284. }
  14285. /**
  14286. * Save old style for style transition in universalTransition module.
  14287. * It's used when element will be reused in each render.
  14288. * For chart like map, heatmap, which will always create new element.
  14289. * We don't need to save this because universalTransition can get old style from the old element
  14290. */
  14291. function saveOldStyle(el) {
  14292. transitionStore(el).oldStyle = el.style;
  14293. }
  14294. function getOldStyle(el) {
  14295. return transitionStore(el).oldStyle;
  14296. }
  14297. var mathMax$4 = Math.max;
  14298. var mathMin$4 = Math.min;
  14299. var _customShapeMap = {};
  14300. /**
  14301. * Extend shape with parameters
  14302. */
  14303. function extendShape(opts) {
  14304. return Path.extend(opts);
  14305. }
  14306. var extendPathFromString = extendFromString;
  14307. /**
  14308. * Extend path
  14309. */
  14310. function extendPath(pathData, opts) {
  14311. return extendPathFromString(pathData, opts);
  14312. }
  14313. /**
  14314. * Register a user defined shape.
  14315. * The shape class can be fetched by `getShapeClass`
  14316. * This method will overwrite the registered shapes, including
  14317. * the registered built-in shapes, if using the same `name`.
  14318. * The shape can be used in `custom series` and
  14319. * `graphic component` by declaring `{type: name}`.
  14320. *
  14321. * @param name
  14322. * @param ShapeClass Can be generated by `extendShape`.
  14323. */
  14324. function registerShape(name, ShapeClass) {
  14325. _customShapeMap[name] = ShapeClass;
  14326. }
  14327. /**
  14328. * Find shape class registered by `registerShape`. Usually used in
  14329. * fetching user defined shape.
  14330. *
  14331. * [Caution]:
  14332. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14333. * to use user registered shapes.
  14334. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14335. * `registerShape` by default. That enables users to get both built-in
  14336. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14337. * the built-in shapes by using names like 'circle', 'rect' via calling
  14338. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14339. * in case that it is overwritten by users, except that some features, like
  14340. * `custom series`, `graphic component`, do it deliberately.
  14341. *
  14342. * (2) In the features like `custom series`, `graphic component`, the user input
  14343. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14344. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14345. * are reserved names, that is, if some user registers a shape named `'image'`,
  14346. * the shape will not be used. If we intending to add some more reserved names
  14347. * in feature, that might bring break changes (disable some existing user shape
  14348. * names). But that case probably rarely happens. So we don't make more mechanism
  14349. * to resolve this issue here.
  14350. *
  14351. * @param name
  14352. * @return The shape class. If not found, return nothing.
  14353. */
  14354. function getShapeClass(name) {
  14355. if (_customShapeMap.hasOwnProperty(name)) {
  14356. return _customShapeMap[name];
  14357. }
  14358. }
  14359. /**
  14360. * Create a path element from path data string
  14361. * @param pathData
  14362. * @param opts
  14363. * @param rect
  14364. * @param layout 'center' or 'cover' default to be cover
  14365. */
  14366. function makePath(pathData, opts, rect, layout) {
  14367. var path = createFromString(pathData, opts);
  14368. if (rect) {
  14369. if (layout === 'center') {
  14370. rect = centerGraphic(rect, path.getBoundingRect());
  14371. }
  14372. resizePath(path, rect);
  14373. }
  14374. return path;
  14375. }
  14376. /**
  14377. * Create a image element from image url
  14378. * @param imageUrl image url
  14379. * @param opts options
  14380. * @param rect constrain rect
  14381. * @param layout 'center' or 'cover'. Default to be 'cover'
  14382. */
  14383. function makeImage(imageUrl, rect, layout) {
  14384. var zrImg = new ZRImage({
  14385. style: {
  14386. image: imageUrl,
  14387. x: rect.x,
  14388. y: rect.y,
  14389. width: rect.width,
  14390. height: rect.height
  14391. },
  14392. onload: function (img) {
  14393. if (layout === 'center') {
  14394. var boundingRect = {
  14395. width: img.width,
  14396. height: img.height
  14397. };
  14398. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14399. }
  14400. }
  14401. });
  14402. return zrImg;
  14403. }
  14404. /**
  14405. * Get position of centered element in bounding box.
  14406. *
  14407. * @param rect element local bounding box
  14408. * @param boundingRect constraint bounding box
  14409. * @return element position containing x, y, width, and height
  14410. */
  14411. function centerGraphic(rect, boundingRect) {
  14412. // Set rect to center, keep width / height ratio.
  14413. var aspect = boundingRect.width / boundingRect.height;
  14414. var width = rect.height * aspect;
  14415. var height;
  14416. if (width <= rect.width) {
  14417. height = rect.height;
  14418. } else {
  14419. width = rect.width;
  14420. height = width / aspect;
  14421. }
  14422. var cx = rect.x + rect.width / 2;
  14423. var cy = rect.y + rect.height / 2;
  14424. return {
  14425. x: cx - width / 2,
  14426. y: cy - height / 2,
  14427. width: width,
  14428. height: height
  14429. };
  14430. }
  14431. var mergePath$1 = mergePath;
  14432. /**
  14433. * Resize a path to fit the rect
  14434. * @param path
  14435. * @param rect
  14436. */
  14437. function resizePath(path, rect) {
  14438. if (!path.applyTransform) {
  14439. return;
  14440. }
  14441. var pathRect = path.getBoundingRect();
  14442. var m = pathRect.calculateTransform(rect);
  14443. path.applyTransform(m);
  14444. }
  14445. /**
  14446. * Sub pixel optimize line for canvas
  14447. */
  14448. function subPixelOptimizeLine$1(shape, lineWidth) {
  14449. subPixelOptimizeLine(shape, shape, {
  14450. lineWidth: lineWidth
  14451. });
  14452. return shape;
  14453. }
  14454. /**
  14455. * Sub pixel optimize rect for canvas
  14456. */
  14457. function subPixelOptimizeRect$1(param) {
  14458. subPixelOptimizeRect(param.shape, param.shape, param.style);
  14459. return param;
  14460. }
  14461. /**
  14462. * Sub pixel optimize for canvas
  14463. *
  14464. * @param position Coordinate, such as x, y
  14465. * @param lineWidth Should be nonnegative integer.
  14466. * @param positiveOrNegative Default false (negative).
  14467. * @return Optimized position.
  14468. */
  14469. var subPixelOptimize$1 = subPixelOptimize;
  14470. /**
  14471. * Get transform matrix of target (param target),
  14472. * in coordinate of its ancestor (param ancestor)
  14473. *
  14474. * @param target
  14475. * @param [ancestor]
  14476. */
  14477. function getTransform(target, ancestor) {
  14478. var mat = identity([]);
  14479. while (target && target !== ancestor) {
  14480. mul$1(mat, target.getLocalTransform(), mat);
  14481. target = target.parent;
  14482. }
  14483. return mat;
  14484. }
  14485. /**
  14486. * Apply transform to an vertex.
  14487. * @param target [x, y]
  14488. * @param transform Can be:
  14489. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14490. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14491. * @param invert Whether use invert matrix.
  14492. * @return [x, y]
  14493. */
  14494. function applyTransform$1(target, transform, invert$1) {
  14495. if (transform && !isArrayLike(transform)) {
  14496. transform = Transformable.getLocalTransform(transform);
  14497. }
  14498. if (invert$1) {
  14499. transform = invert([], transform);
  14500. }
  14501. return applyTransform([], target, transform);
  14502. }
  14503. /**
  14504. * @param direction 'left' 'right' 'top' 'bottom'
  14505. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14506. * @param invert Whether use invert matrix.
  14507. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  14508. */
  14509. function transformDirection(direction, transform, invert) {
  14510. // Pick a base, ensure that transform result will not be (0, 0).
  14511. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14512. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14513. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14514. vertex = applyTransform$1(vertex, transform, invert);
  14515. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14516. }
  14517. function isNotGroup(el) {
  14518. return !el.isGroup;
  14519. }
  14520. function isPath(el) {
  14521. return el.shape != null;
  14522. }
  14523. /**
  14524. * Apply group transition animation from g1 to g2.
  14525. * If no animatableModel, no animation.
  14526. */
  14527. function groupTransition(g1, g2, animatableModel) {
  14528. if (!g1 || !g2) {
  14529. return;
  14530. }
  14531. function getElMap(g) {
  14532. var elMap = {};
  14533. g.traverse(function (el) {
  14534. if (isNotGroup(el) && el.anid) {
  14535. elMap[el.anid] = el;
  14536. }
  14537. });
  14538. return elMap;
  14539. }
  14540. function getAnimatableProps(el) {
  14541. var obj = {
  14542. x: el.x,
  14543. y: el.y,
  14544. rotation: el.rotation
  14545. };
  14546. if (isPath(el)) {
  14547. obj.shape = extend({}, el.shape);
  14548. }
  14549. return obj;
  14550. }
  14551. var elMap1 = getElMap(g1);
  14552. g2.traverse(function (el) {
  14553. if (isNotGroup(el) && el.anid) {
  14554. var oldEl = elMap1[el.anid];
  14555. if (oldEl) {
  14556. var newProp = getAnimatableProps(el);
  14557. el.attr(getAnimatableProps(oldEl));
  14558. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14559. }
  14560. }
  14561. });
  14562. }
  14563. function clipPointsByRect(points, rect) {
  14564. // FIXME: This way might be incorrect when graphic clipped by a corner
  14565. // and when element has a border.
  14566. return map(points, function (point) {
  14567. var x = point[0];
  14568. x = mathMax$4(x, rect.x);
  14569. x = mathMin$4(x, rect.x + rect.width);
  14570. var y = point[1];
  14571. y = mathMax$4(y, rect.y);
  14572. y = mathMin$4(y, rect.y + rect.height);
  14573. return [x, y];
  14574. });
  14575. }
  14576. /**
  14577. * Return a new clipped rect. If rect size are negative, return undefined.
  14578. */
  14579. function clipRectByRect(targetRect, rect) {
  14580. var x = mathMax$4(targetRect.x, rect.x);
  14581. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14582. var y = mathMax$4(targetRect.y, rect.y);
  14583. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14584. // should be painted. So return undefined.
  14585. if (x2 >= x && y2 >= y) {
  14586. return {
  14587. x: x,
  14588. y: y,
  14589. width: x2 - x,
  14590. height: y2 - y
  14591. };
  14592. }
  14593. }
  14594. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  14595. opt, rect) {
  14596. var innerOpts = extend({
  14597. rectHover: true
  14598. }, opt);
  14599. var style = innerOpts.style = {
  14600. strokeNoScale: true
  14601. };
  14602. rect = rect || {
  14603. x: -1,
  14604. y: -1,
  14605. width: 2,
  14606. height: 2
  14607. };
  14608. if (iconStr) {
  14609. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14610. }
  14611. }
  14612. /**
  14613. * Return `true` if the given line (line `a`) and the given polygon
  14614. * are intersect.
  14615. * Note that we do not count colinear as intersect here because no
  14616. * requirement for that. We could do that if required in future.
  14617. */
  14618. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14619. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14620. var p = points[i];
  14621. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14622. return true;
  14623. }
  14624. p2 = p;
  14625. }
  14626. }
  14627. /**
  14628. * Return `true` if the given two lines (line `a` and line `b`)
  14629. * are intersect.
  14630. * Note that we do not count colinear as intersect here because no
  14631. * requirement for that. We could do that if required in future.
  14632. */
  14633. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14634. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14635. var mx = a2x - a1x;
  14636. var my = a2y - a1y;
  14637. var nx = b2x - b1x;
  14638. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  14639. // existing `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14640. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14641. if (nearZero(nmCrossProduct)) {
  14642. return false;
  14643. } // `vec_m` and `vec_n` are intersect iff
  14644. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14645. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14646. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14647. var b1a1x = a1x - b1x;
  14648. var b1a1y = a1y - b1y;
  14649. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14650. if (q < 0 || q > 1) {
  14651. return false;
  14652. }
  14653. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14654. if (p < 0 || p > 1) {
  14655. return false;
  14656. }
  14657. return true;
  14658. }
  14659. /**
  14660. * Cross product of 2-dimension vector.
  14661. */
  14662. function crossProduct2d(x1, y1, x2, y2) {
  14663. return x1 * y2 - x2 * y1;
  14664. }
  14665. function nearZero(val) {
  14666. return val <= 1e-6 && val >= -1e-6;
  14667. }
  14668. function setTooltipConfig(opt) {
  14669. var itemTooltipOption = opt.itemTooltipOption;
  14670. var componentModel = opt.componentModel;
  14671. var itemName = opt.itemName;
  14672. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14673. formatter: itemTooltipOption
  14674. } : itemTooltipOption;
  14675. var mainType = componentModel.mainType;
  14676. var componentIndex = componentModel.componentIndex;
  14677. var formatterParams = {
  14678. componentType: mainType,
  14679. name: itemName,
  14680. $vars: ['name']
  14681. };
  14682. formatterParams[mainType + 'Index'] = componentIndex;
  14683. var formatterParamsExtra = opt.formatterParamsExtra;
  14684. if (formatterParamsExtra) {
  14685. each(keys(formatterParamsExtra), function (key) {
  14686. if (!hasOwn(formatterParams, key)) {
  14687. formatterParams[key] = formatterParamsExtra[key];
  14688. formatterParams.$vars.push(key);
  14689. }
  14690. });
  14691. }
  14692. var ecData = getECData(opt.el);
  14693. ecData.componentMainType = mainType;
  14694. ecData.componentIndex = componentIndex;
  14695. ecData.tooltipConfig = {
  14696. name: itemName,
  14697. option: defaults({
  14698. content: itemName,
  14699. formatterParams: formatterParams
  14700. }, itemTooltipOptionObj)
  14701. };
  14702. }
  14703. function traverseElement(el, cb) {
  14704. var stopped; // TODO
  14705. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  14706. if (el.isGroup) {
  14707. stopped = cb(el);
  14708. }
  14709. if (!stopped) {
  14710. el.traverse(cb);
  14711. }
  14712. }
  14713. function traverseElements(els, cb) {
  14714. if (els) {
  14715. if (isArray(els)) {
  14716. for (var i = 0; i < els.length; i++) {
  14717. traverseElement(els[i], cb);
  14718. }
  14719. } else {
  14720. traverseElement(els, cb);
  14721. }
  14722. }
  14723. } // Register built-in shapes. These shapes might be overwritten
  14724. // by users, although we do not recommend that.
  14725. registerShape('circle', Circle);
  14726. registerShape('ellipse', Ellipse);
  14727. registerShape('sector', Sector);
  14728. registerShape('ring', Ring);
  14729. registerShape('polygon', Polygon);
  14730. registerShape('polyline', Polyline);
  14731. registerShape('rect', Rect);
  14732. registerShape('line', Line);
  14733. registerShape('bezierCurve', BezierCurve);
  14734. registerShape('arc', Arc);
  14735. var graphic = /*#__PURE__*/Object.freeze({
  14736. __proto__: null,
  14737. updateProps: updateProps,
  14738. initProps: initProps,
  14739. removeElement: removeElement,
  14740. removeElementWithFadeOut: removeElementWithFadeOut,
  14741. isElementRemoved: isElementRemoved,
  14742. extendShape: extendShape,
  14743. extendPath: extendPath,
  14744. registerShape: registerShape,
  14745. getShapeClass: getShapeClass,
  14746. makePath: makePath,
  14747. makeImage: makeImage,
  14748. mergePath: mergePath$1,
  14749. resizePath: resizePath,
  14750. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14751. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14752. subPixelOptimize: subPixelOptimize$1,
  14753. getTransform: getTransform,
  14754. applyTransform: applyTransform$1,
  14755. transformDirection: transformDirection,
  14756. groupTransition: groupTransition,
  14757. clipPointsByRect: clipPointsByRect,
  14758. clipRectByRect: clipRectByRect,
  14759. createIcon: createIcon,
  14760. linePolygonIntersect: linePolygonIntersect,
  14761. lineLineIntersect: lineLineIntersect,
  14762. setTooltipConfig: setTooltipConfig,
  14763. traverseElements: traverseElements,
  14764. Group: Group,
  14765. Image: ZRImage,
  14766. Text: ZRText,
  14767. Circle: Circle,
  14768. Ellipse: Ellipse,
  14769. Sector: Sector,
  14770. Ring: Ring,
  14771. Polygon: Polygon,
  14772. Polyline: Polyline,
  14773. Rect: Rect,
  14774. Line: Line,
  14775. BezierCurve: BezierCurve,
  14776. Arc: Arc,
  14777. IncrementalDisplayable: IncrementalDisplayable,
  14778. CompoundPath: CompoundPath,
  14779. LinearGradient: LinearGradient,
  14780. RadialGradient: RadialGradient,
  14781. BoundingRect: BoundingRect,
  14782. OrientedBoundingRect: OrientedBoundingRect,
  14783. Point: Point,
  14784. Path: Path
  14785. });
  14786. var EMPTY_OBJ = {};
  14787. function setLabelText(label, labelTexts) {
  14788. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14789. var stateName = SPECIAL_STATES[i];
  14790. var text = labelTexts[stateName];
  14791. var state = label.ensureState(stateName);
  14792. state.style = state.style || {};
  14793. state.style.text = text;
  14794. }
  14795. var oldStates = label.currentStates.slice();
  14796. label.clearStates(true);
  14797. label.setStyle({
  14798. text: labelTexts.normal
  14799. });
  14800. label.useStates(oldStates, true);
  14801. }
  14802. function getLabelText(opt, stateModels, interpolatedValue) {
  14803. var labelFetcher = opt.labelFetcher;
  14804. var labelDataIndex = opt.labelDataIndex;
  14805. var labelDimIndex = opt.labelDimIndex;
  14806. var normalModel = stateModels.normal;
  14807. var baseText;
  14808. if (labelFetcher) {
  14809. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14810. interpolatedValue: interpolatedValue
  14811. } : null);
  14812. }
  14813. if (baseText == null) {
  14814. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14815. }
  14816. var statesText = {
  14817. normal: baseText
  14818. };
  14819. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14820. var stateName = SPECIAL_STATES[i];
  14821. var stateModel = stateModels[stateName];
  14822. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14823. }
  14824. return statesText;
  14825. }
  14826. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  14827. ) {
  14828. opt = opt || EMPTY_OBJ;
  14829. var isSetOnText = targetEl instanceof ZRText;
  14830. var needsCreateText = false;
  14831. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14832. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14833. if (stateModel && stateModel.getShallow('show')) {
  14834. needsCreateText = true;
  14835. break;
  14836. }
  14837. }
  14838. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14839. if (needsCreateText) {
  14840. if (!isSetOnText) {
  14841. // Reuse the previous
  14842. if (!textContent) {
  14843. textContent = new ZRText();
  14844. targetEl.setTextContent(textContent);
  14845. } // Use same state proxy
  14846. if (targetEl.stateProxy) {
  14847. textContent.stateProxy = targetEl.stateProxy;
  14848. }
  14849. }
  14850. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14851. var normalModel = labelStatesModels.normal;
  14852. var showNormal = !!normalModel.getShallow('show');
  14853. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14854. normalStyle.text = labelStatesTexts.normal;
  14855. if (!isSetOnText) {
  14856. // Always create new
  14857. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14858. }
  14859. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14860. var stateName = SPECIAL_STATES[i];
  14861. var stateModel = labelStatesModels[stateName];
  14862. if (stateModel) {
  14863. var stateObj = textContent.ensureState(stateName);
  14864. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14865. if (stateShow !== showNormal) {
  14866. stateObj.ignore = !stateShow;
  14867. }
  14868. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14869. stateObj.style.text = labelStatesTexts[stateName];
  14870. if (!isSetOnText) {
  14871. var targetElEmphasisState = targetEl.ensureState(stateName);
  14872. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14873. }
  14874. }
  14875. } // PENDING: if there is many requirements that emphasis position
  14876. // need to be different from normal position, we might consider
  14877. // auto silent is those cases.
  14878. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14879. if (textContent.style.x != null) {
  14880. normalStyle.x = textContent.style.x;
  14881. }
  14882. if (textContent.style.y != null) {
  14883. normalStyle.y = textContent.style.y;
  14884. }
  14885. textContent.ignore = !showNormal; // Always create new style.
  14886. textContent.useStyle(normalStyle);
  14887. textContent.dirty();
  14888. if (opt.enableTextSetter) {
  14889. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14890. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14891. setLabelText(textContent, labelStatesTexts);
  14892. };
  14893. }
  14894. } else if (textContent) {
  14895. // Not display rich text.
  14896. textContent.ignore = true;
  14897. }
  14898. targetEl.dirty();
  14899. }
  14900. function getLabelStatesModels(itemModel, labelName) {
  14901. labelName = labelName || 'label';
  14902. var statesModels = {
  14903. normal: itemModel.getModel(labelName)
  14904. };
  14905. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14906. var stateName = SPECIAL_STATES[i];
  14907. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14908. }
  14909. return statesModels;
  14910. }
  14911. /**
  14912. * Set basic textStyle properties.
  14913. */
  14914. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14915. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14916. ) {
  14917. var textStyle = {};
  14918. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14919. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14920. return textStyle;
  14921. }
  14922. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14923. opt = opt || {};
  14924. var textConfig = {};
  14925. var labelPosition;
  14926. var labelRotate = textStyleModel.getShallow('rotate');
  14927. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14928. var labelOffset = textStyleModel.getShallow('offset');
  14929. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14930. // in bar series, and magric type should be considered.
  14931. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14932. if (labelPosition != null) {
  14933. textConfig.position = labelPosition;
  14934. }
  14935. if (labelOffset != null) {
  14936. textConfig.offset = labelOffset;
  14937. }
  14938. if (labelRotate != null) {
  14939. labelRotate *= Math.PI / 180;
  14940. textConfig.rotation = labelRotate;
  14941. }
  14942. if (labelDistance != null) {
  14943. textConfig.distance = labelDistance;
  14944. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14945. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14946. return textConfig;
  14947. }
  14948. /**
  14949. * The uniform entry of set text style, that is, retrieve style definitions
  14950. * from `model` and set to `textStyle` object.
  14951. *
  14952. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14953. * properties will be set. (Consider the states of normal and emphasis and
  14954. * default value can be adopted, merge would make the logic too complicated
  14955. * to manage.)
  14956. */
  14957. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14958. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14959. opt = opt || EMPTY_OBJ;
  14960. var ecModel = textStyleModel.ecModel;
  14961. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14962. // {
  14963. // data: [{
  14964. // value: 12,
  14965. // label: {
  14966. // rich: {
  14967. // // no 'a' here but using parent 'a'.
  14968. // }
  14969. // }
  14970. // }],
  14971. // rich: {
  14972. // a: { ... }
  14973. // }
  14974. // }
  14975. var richItemNames = getRichItemNames(textStyleModel);
  14976. var richResult;
  14977. if (richItemNames) {
  14978. richResult = {};
  14979. for (var name_1 in richItemNames) {
  14980. if (richItemNames.hasOwnProperty(name_1)) {
  14981. // Cascade is supported in rich.
  14982. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14983. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14984. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14985. // That might confuses users. So probably we should put `textStyleModel` as the
  14986. // root ancestor of the `richTextStyle`. But that would be a break change.
  14987. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14988. }
  14989. }
  14990. }
  14991. if (richResult) {
  14992. textStyle.rich = richResult;
  14993. }
  14994. var overflow = textStyleModel.get('overflow');
  14995. if (overflow) {
  14996. textStyle.overflow = overflow;
  14997. }
  14998. var margin = textStyleModel.get('minMargin');
  14999. if (margin != null) {
  15000. textStyle.margin = margin;
  15001. }
  15002. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  15003. } // Consider case:
  15004. // {
  15005. // data: [{
  15006. // value: 12,
  15007. // label: {
  15008. // rich: {
  15009. // // no 'a' here but using parent 'a'.
  15010. // }
  15011. // }
  15012. // }],
  15013. // rich: {
  15014. // a: { ... }
  15015. // }
  15016. // }
  15017. // TODO TextStyleModel
  15018. function getRichItemNames(textStyleModel) {
  15019. // Use object to remove duplicated names.
  15020. var richItemNameMap;
  15021. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15022. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15023. if (rich) {
  15024. richItemNameMap = richItemNameMap || {};
  15025. var richKeys = keys(rich);
  15026. for (var i = 0; i < richKeys.length; i++) {
  15027. var richKey = richKeys[i];
  15028. richItemNameMap[richKey] = 1;
  15029. }
  15030. }
  15031. textStyleModel = textStyleModel.parentModel;
  15032. }
  15033. return richItemNameMap;
  15034. }
  15035. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  15036. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign'];
  15037. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  15038. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  15039. // In merge mode, default value should not be given.
  15040. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  15041. var inheritColor = opt && opt.inheritColor;
  15042. var fillColor = textStyleModel.getShallow('color');
  15043. var strokeColor = textStyleModel.getShallow('textBorderColor');
  15044. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  15045. if (fillColor === 'inherit' || fillColor === 'auto') {
  15046. if ("development" !== 'production') {
  15047. if (fillColor === 'auto') {
  15048. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15049. }
  15050. }
  15051. if (inheritColor) {
  15052. fillColor = inheritColor;
  15053. } else {
  15054. fillColor = null;
  15055. }
  15056. }
  15057. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  15058. if ("development" !== 'production') {
  15059. if (strokeColor === 'auto') {
  15060. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15061. }
  15062. }
  15063. if (inheritColor) {
  15064. strokeColor = inheritColor;
  15065. } else {
  15066. strokeColor = null;
  15067. }
  15068. }
  15069. if (!isAttached) {
  15070. // Only use default global textStyle.color if text is individual.
  15071. // Otherwise it will use the strategy of attached text color because text may be on a path.
  15072. fillColor = fillColor || globalTextStyle.color;
  15073. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  15074. }
  15075. if (fillColor != null) {
  15076. textStyle.fill = fillColor;
  15077. }
  15078. if (strokeColor != null) {
  15079. textStyle.stroke = strokeColor;
  15080. }
  15081. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  15082. if (textBorderWidth != null) {
  15083. textStyle.lineWidth = textBorderWidth;
  15084. }
  15085. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  15086. if (textBorderType != null) {
  15087. textStyle.lineDash = textBorderType;
  15088. }
  15089. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  15090. if (textBorderDashOffset != null) {
  15091. textStyle.lineDashOffset = textBorderDashOffset;
  15092. }
  15093. if (!isNotNormal && opacity == null && !inRich) {
  15094. opacity = opt && opt.defaultOpacity;
  15095. }
  15096. if (opacity != null) {
  15097. textStyle.opacity = opacity;
  15098. } // TODO
  15099. if (!isNotNormal && !isAttached) {
  15100. // Set default finally.
  15101. if (textStyle.fill == null && opt.inheritColor) {
  15102. textStyle.fill = opt.inheritColor;
  15103. }
  15104. } // Do not use `getFont` here, because merge should be supported, where
  15105. // part of these properties may be changed in emphasis style, and the
  15106. // others should remain their original value got from normal style.
  15107. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  15108. var key = TEXT_PROPS_WITH_GLOBAL[i];
  15109. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  15110. if (val != null) {
  15111. textStyle[key] = val;
  15112. }
  15113. }
  15114. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  15115. var key = TEXT_PROPS_SELF[i];
  15116. var val = textStyleModel.getShallow(key);
  15117. if (val != null) {
  15118. textStyle[key] = val;
  15119. }
  15120. }
  15121. if (textStyle.verticalAlign == null) {
  15122. var baseline = textStyleModel.getShallow('baseline');
  15123. if (baseline != null) {
  15124. textStyle.verticalAlign = baseline;
  15125. }
  15126. }
  15127. if (!isBlock || !opt.disableBox) {
  15128. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  15129. var key = TEXT_PROPS_BOX[i];
  15130. var val = textStyleModel.getShallow(key);
  15131. if (val != null) {
  15132. textStyle[key] = val;
  15133. }
  15134. }
  15135. var borderType = textStyleModel.getShallow('borderType');
  15136. if (borderType != null) {
  15137. textStyle.borderDash = borderType;
  15138. }
  15139. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  15140. if ("development" !== 'production') {
  15141. if (textStyle.backgroundColor === 'auto') {
  15142. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  15143. }
  15144. }
  15145. textStyle.backgroundColor = inheritColor;
  15146. }
  15147. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  15148. if ("development" !== 'production') {
  15149. if (textStyle.borderColor === 'auto') {
  15150. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  15151. }
  15152. }
  15153. textStyle.borderColor = inheritColor;
  15154. }
  15155. }
  15156. }
  15157. function getFont(opt, ecModel) {
  15158. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15159. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  15160. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '', opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '', (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px', opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'].join(' '));
  15161. }
  15162. var labelInner = makeInner();
  15163. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  15164. if (!label) {
  15165. return;
  15166. }
  15167. var obj = labelInner(label);
  15168. obj.prevValue = obj.value;
  15169. obj.value = value;
  15170. var normalLabelModel = labelStatesModels.normal;
  15171. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  15172. if (obj.valueAnimation) {
  15173. obj.precision = normalLabelModel.get('precision');
  15174. obj.defaultInterpolatedText = getDefaultText;
  15175. obj.statesModels = labelStatesModels;
  15176. }
  15177. }
  15178. function animateLabelValue(textEl, dataIndex, data, animatableModel, labelFetcher) {
  15179. var labelInnerStore = labelInner(textEl);
  15180. if (!labelInnerStore.valueAnimation || labelInnerStore.prevValue === labelInnerStore.value) {
  15181. // Value not changed, no new label animation
  15182. return;
  15183. }
  15184. var defaultInterpolatedText = labelInnerStore.defaultInterpolatedText; // Consider the case that being animating, do not use the `obj.value`,
  15185. // Otherwise it will jump to the `obj.value` when this new animation started.
  15186. var currValue = retrieve2(labelInnerStore.interpolatedValue, labelInnerStore.prevValue);
  15187. var targetValue = labelInnerStore.value;
  15188. function during(percent) {
  15189. var interpolated = interpolateRawValues(data, labelInnerStore.precision, currValue, targetValue, percent);
  15190. labelInnerStore.interpolatedValue = percent === 1 ? null : interpolated;
  15191. var labelText = getLabelText({
  15192. labelDataIndex: dataIndex,
  15193. labelFetcher: labelFetcher,
  15194. defaultText: defaultInterpolatedText ? defaultInterpolatedText(interpolated) : interpolated + ''
  15195. }, labelInnerStore.statesModels, interpolated);
  15196. setLabelText(textEl, labelText);
  15197. }
  15198. textEl.percent = 0;
  15199. (labelInnerStore.prevValue == null ? initProps : updateProps)(textEl, {
  15200. // percent is used to prevent animation from being aborted #15916
  15201. percent: 1
  15202. }, animatableModel, dataIndex, null, during);
  15203. }
  15204. var PATH_COLOR = ['textStyle', 'color'];
  15205. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow']; // TODO Performance improvement?
  15206. var tmpText = new ZRText();
  15207. var TextStyleMixin =
  15208. /** @class */
  15209. function () {
  15210. function TextStyleMixin() {}
  15211. /**
  15212. * Get color property or get color from option.textStyle.color
  15213. */
  15214. // TODO Callback
  15215. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  15216. var ecModel = this.ecModel;
  15217. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  15218. };
  15219. /**
  15220. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15221. * @return {string}
  15222. */
  15223. TextStyleMixin.prototype.getFont = function () {
  15224. return getFont({
  15225. fontStyle: this.getShallow('fontStyle'),
  15226. fontWeight: this.getShallow('fontWeight'),
  15227. fontSize: this.getShallow('fontSize'),
  15228. fontFamily: this.getShallow('fontFamily')
  15229. }, this.ecModel);
  15230. };
  15231. TextStyleMixin.prototype.getTextRect = function (text) {
  15232. var style = {
  15233. text: text,
  15234. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  15235. };
  15236. for (var i = 0; i < textStyleParams.length; i++) {
  15237. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  15238. }
  15239. tmpText.useStyle(style);
  15240. tmpText.update();
  15241. return tmpText.getBoundingRect();
  15242. };
  15243. return TextStyleMixin;
  15244. }();
  15245. var LINE_STYLE_KEY_MAP = [['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'type'], ['lineDashOffset', 'dashOffset'], ['lineCap', 'cap'], ['lineJoin', 'join'], ['miterLimit'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15246. // So do not transfer decal directly.
  15247. ];
  15248. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  15249. var LineStyleMixin =
  15250. /** @class */
  15251. function () {
  15252. function LineStyleMixin() {}
  15253. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  15254. return getLineStyle(this, excludes);
  15255. };
  15256. return LineStyleMixin;
  15257. }();
  15258. var ITEM_STYLE_KEY_MAP = [['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['lineDash', 'borderType'], ['lineDashOffset', 'borderDashOffset'], ['lineCap', 'borderCap'], ['lineJoin', 'borderJoin'], ['miterLimit', 'borderMiterLimit'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  15259. // So do not transfer decal directly.
  15260. ];
  15261. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  15262. var ItemStyleMixin =
  15263. /** @class */
  15264. function () {
  15265. function ItemStyleMixin() {}
  15266. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  15267. return getItemStyle(this, excludes, includes);
  15268. };
  15269. return ItemStyleMixin;
  15270. }();
  15271. var Model =
  15272. /** @class */
  15273. function () {
  15274. function Model(option, parentModel, ecModel) {
  15275. this.parentModel = parentModel;
  15276. this.ecModel = ecModel;
  15277. this.option = option; // Simple optimization
  15278. // if (this.init) {
  15279. // if (arguments.length <= 4) {
  15280. // this.init(option, parentModel, ecModel, extraOpt);
  15281. // }
  15282. // else {
  15283. // this.init.apply(this, arguments);
  15284. // }
  15285. // }
  15286. }
  15287. Model.prototype.init = function (option, parentModel, ecModel) {
  15288. var rest = [];
  15289. for (var _i = 3; _i < arguments.length; _i++) {
  15290. rest[_i - 3] = arguments[_i];
  15291. }
  15292. };
  15293. /**
  15294. * Merge the input option to me.
  15295. */
  15296. Model.prototype.mergeOption = function (option, ecModel) {
  15297. merge(this.option, option, true);
  15298. }; // `path` can be 'a.b.c', so the return value type have to be `ModelOption`
  15299. // TODO: TYPE strict key check?
  15300. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15301. Model.prototype.get = function (path, ignoreParent) {
  15302. if (path == null) {
  15303. return this.option;
  15304. }
  15305. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15306. };
  15307. Model.prototype.getShallow = function (key, ignoreParent) {
  15308. var option = this.option;
  15309. var val = option == null ? option : option[key];
  15310. if (val == null && !ignoreParent) {
  15311. var parentModel = this.parentModel;
  15312. if (parentModel) {
  15313. // FIXME:TS do not know how to make it works
  15314. val = parentModel.getShallow(key);
  15315. }
  15316. }
  15317. return val;
  15318. }; // `path` can be 'a.b.c', so the return value type have to be `Model<ModelOption>`
  15319. // getModel(path: string | string[], parentModel?: Model): Model;
  15320. // TODO 'a.b.c' is deprecated
  15321. Model.prototype.getModel = function (path, parentModel) {
  15322. var hasPath = path != null;
  15323. var pathFinal = hasPath ? this.parsePath(path) : null;
  15324. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15325. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15326. return new Model(obj, parentModel, this.ecModel);
  15327. };
  15328. /**
  15329. * If model has option
  15330. */
  15331. Model.prototype.isEmpty = function () {
  15332. return this.option == null;
  15333. };
  15334. Model.prototype.restoreData = function () {}; // Pending
  15335. Model.prototype.clone = function () {
  15336. var Ctor = this.constructor;
  15337. return new Ctor(clone(this.option));
  15338. }; // setReadOnly(properties): void {
  15339. // clazzUtil.setReadOnly(this, properties);
  15340. // }
  15341. // If path is null/undefined, return null/undefined.
  15342. Model.prototype.parsePath = function (path) {
  15343. if (typeof path === 'string') {
  15344. return path.split('.');
  15345. }
  15346. return path;
  15347. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  15348. // Default to be a identity resolver.
  15349. // Can be modified to a different resolver.
  15350. Model.prototype.resolveParentPath = function (path) {
  15351. return path;
  15352. }; // FIXME:TS check whether put this method here
  15353. Model.prototype.isAnimationEnabled = function () {
  15354. if (!env.node && this.option) {
  15355. if (this.option.animation != null) {
  15356. return !!this.option.animation;
  15357. } else if (this.parentModel) {
  15358. return this.parentModel.isAnimationEnabled();
  15359. }
  15360. }
  15361. };
  15362. Model.prototype._doGet = function (pathArr, parentModel) {
  15363. var obj = this.option;
  15364. if (!pathArr) {
  15365. return obj;
  15366. }
  15367. for (var i = 0; i < pathArr.length; i++) {
  15368. // Ignore empty
  15369. if (!pathArr[i]) {
  15370. continue;
  15371. } // obj could be number/string/... (like 0)
  15372. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15373. if (obj == null) {
  15374. break;
  15375. }
  15376. }
  15377. if (obj == null && parentModel) {
  15378. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15379. }
  15380. return obj;
  15381. };
  15382. return Model;
  15383. }();
  15384. enableClassExtend(Model);
  15385. enableClassCheck(Model);
  15386. mixin(Model, LineStyleMixin);
  15387. mixin(Model, ItemStyleMixin);
  15388. mixin(Model, AreaStyleMixin);
  15389. mixin(Model, TextStyleMixin);
  15390. var base = Math.round(Math.random() * 10);
  15391. /**
  15392. * @public
  15393. * @param {string} type
  15394. * @return {string}
  15395. */
  15396. function getUID(type) {
  15397. // Considering the case of crossing js context,
  15398. // use Math.random to make id as unique as possible.
  15399. return [type || '', base++].join('_');
  15400. }
  15401. /**
  15402. * Implements `SubTypeDefaulterManager` for `target`.
  15403. */
  15404. function enableSubTypeDefaulter(target) {
  15405. var subTypeDefaulters = {};
  15406. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  15407. var componentTypeInfo = parseClassType(componentType);
  15408. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  15409. };
  15410. target.determineSubType = function (componentType, option) {
  15411. var type = option.type;
  15412. if (!type) {
  15413. var componentTypeMain = parseClassType(componentType).main;
  15414. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15415. type = subTypeDefaulters[componentTypeMain](option);
  15416. }
  15417. }
  15418. return type;
  15419. };
  15420. }
  15421. /**
  15422. * Implements `TopologicalTravelable<any>` for `entity`.
  15423. *
  15424. * Topological travel on Activity Network (Activity On Vertices).
  15425. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15426. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15427. * If there is circular dependencey, Error will be thrown.
  15428. */
  15429. function enableTopologicalTravel(entity, dependencyGetter) {
  15430. /**
  15431. * @param targetNameList Target Component type list.
  15432. * Can be ['aa', 'bb', 'aa.xx']
  15433. * @param fullNameList By which we can build dependency graph.
  15434. * @param callback Params: componentType, dependencies.
  15435. * @param context Scope of callback.
  15436. */
  15437. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15438. if (!targetNameList.length) {
  15439. return;
  15440. }
  15441. var result = makeDepndencyGraph(fullNameList);
  15442. var graph = result.graph;
  15443. var noEntryList = result.noEntryList;
  15444. var targetNameSet = {};
  15445. each(targetNameList, function (name) {
  15446. targetNameSet[name] = true;
  15447. });
  15448. while (noEntryList.length) {
  15449. var currComponentType = noEntryList.pop();
  15450. var currVertex = graph[currComponentType];
  15451. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15452. if (isInTargetNameSet) {
  15453. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15454. delete targetNameSet[currComponentType];
  15455. }
  15456. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15457. }
  15458. each(targetNameSet, function () {
  15459. var errMsg = '';
  15460. if ("development" !== 'production') {
  15461. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  15462. }
  15463. throw new Error(errMsg);
  15464. });
  15465. function removeEdge(succComponentType) {
  15466. graph[succComponentType].entryCount--;
  15467. if (graph[succComponentType].entryCount === 0) {
  15468. noEntryList.push(succComponentType);
  15469. }
  15470. } // Consider this case: legend depends on series, and we call
  15471. // chart.setOption({series: [...]}), where only series is in option.
  15472. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15473. // not be called, but only sereis.mergeOption is called. Thus legend
  15474. // have no chance to update its local record about series (like which
  15475. // name of series is available in legend).
  15476. function removeEdgeAndAdd(succComponentType) {
  15477. targetNameSet[succComponentType] = true;
  15478. removeEdge(succComponentType);
  15479. }
  15480. };
  15481. function makeDepndencyGraph(fullNameList) {
  15482. var graph = {};
  15483. var noEntryList = [];
  15484. each(fullNameList, function (name) {
  15485. var thisItem = createDependencyGraphItem(graph, name);
  15486. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15487. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15488. thisItem.entryCount = availableDeps.length;
  15489. if (thisItem.entryCount === 0) {
  15490. noEntryList.push(name);
  15491. }
  15492. each(availableDeps, function (dependentName) {
  15493. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15494. thisItem.predecessor.push(dependentName);
  15495. }
  15496. var thatItem = createDependencyGraphItem(graph, dependentName);
  15497. if (indexOf(thatItem.successor, dependentName) < 0) {
  15498. thatItem.successor.push(name);
  15499. }
  15500. });
  15501. });
  15502. return {
  15503. graph: graph,
  15504. noEntryList: noEntryList
  15505. };
  15506. }
  15507. function createDependencyGraphItem(graph, name) {
  15508. if (!graph[name]) {
  15509. graph[name] = {
  15510. predecessor: [],
  15511. successor: []
  15512. };
  15513. }
  15514. return graph[name];
  15515. }
  15516. function getAvailableDependencies(originalDeps, fullNameList) {
  15517. var availableDeps = [];
  15518. each(originalDeps, function (dep) {
  15519. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15520. });
  15521. return availableDeps;
  15522. }
  15523. }
  15524. function inheritDefaultOption(superOption, subOption) {
  15525. // See also `model/Component.ts#getDefaultOption`
  15526. return merge(merge({}, superOption, true), subOption, true);
  15527. }
  15528. /*
  15529. * Licensed to the Apache Software Foundation (ASF) under one
  15530. * or more contributor license agreements. See the NOTICE file
  15531. * distributed with this work for additional information
  15532. * regarding copyright ownership. The ASF licenses this file
  15533. * to you under the Apache License, Version 2.0 (the
  15534. * "License"); you may not use this file except in compliance
  15535. * with the License. You may obtain a copy of the License at
  15536. *
  15537. * http://www.apache.org/licenses/LICENSE-2.0
  15538. *
  15539. * Unless required by applicable law or agreed to in writing,
  15540. * software distributed under the License is distributed on an
  15541. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15542. * KIND, either express or implied. See the License for the
  15543. * specific language governing permissions and limitations
  15544. * under the License.
  15545. */
  15546. /**
  15547. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15548. */
  15549. /*
  15550. * Licensed to the Apache Software Foundation (ASF) under one
  15551. * or more contributor license agreements. See the NOTICE file
  15552. * distributed with this work for additional information
  15553. * regarding copyright ownership. The ASF licenses this file
  15554. * to you under the Apache License, Version 2.0 (the
  15555. * "License"); you may not use this file except in compliance
  15556. * with the License. You may obtain a copy of the License at
  15557. *
  15558. * http://www.apache.org/licenses/LICENSE-2.0
  15559. *
  15560. * Unless required by applicable law or agreed to in writing,
  15561. * software distributed under the License is distributed on an
  15562. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15563. * KIND, either express or implied. See the License for the
  15564. * specific language governing permissions and limitations
  15565. * under the License.
  15566. */
  15567. /**
  15568. * Language: English.
  15569. */
  15570. var langEN = {
  15571. time: {
  15572. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  15573. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  15574. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  15575. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  15576. },
  15577. legend: {
  15578. selector: {
  15579. all: 'All',
  15580. inverse: 'Inv'
  15581. }
  15582. },
  15583. toolbox: {
  15584. brush: {
  15585. title: {
  15586. rect: 'Box Select',
  15587. polygon: 'Lasso Select',
  15588. lineX: 'Horizontally Select',
  15589. lineY: 'Vertically Select',
  15590. keep: 'Keep Selections',
  15591. clear: 'Clear Selections'
  15592. }
  15593. },
  15594. dataView: {
  15595. title: 'Data View',
  15596. lang: ['Data View', 'Close', 'Refresh']
  15597. },
  15598. dataZoom: {
  15599. title: {
  15600. zoom: 'Zoom',
  15601. back: 'Zoom Reset'
  15602. }
  15603. },
  15604. magicType: {
  15605. title: {
  15606. line: 'Switch to Line Chart',
  15607. bar: 'Switch to Bar Chart',
  15608. stack: 'Stack',
  15609. tiled: 'Tile'
  15610. }
  15611. },
  15612. restore: {
  15613. title: 'Restore'
  15614. },
  15615. saveAsImage: {
  15616. title: 'Save as Image',
  15617. lang: ['Right Click to Save Image']
  15618. }
  15619. },
  15620. series: {
  15621. typeNames: {
  15622. pie: 'Pie chart',
  15623. bar: 'Bar chart',
  15624. line: 'Line chart',
  15625. scatter: 'Scatter plot',
  15626. effectScatter: 'Ripple scatter plot',
  15627. radar: 'Radar chart',
  15628. tree: 'Tree',
  15629. treemap: 'Treemap',
  15630. boxplot: 'Boxplot',
  15631. candlestick: 'Candlestick',
  15632. k: 'K line chart',
  15633. heatmap: 'Heat map',
  15634. map: 'Map',
  15635. parallel: 'Parallel coordinate map',
  15636. lines: 'Line graph',
  15637. graph: 'Relationship graph',
  15638. sankey: 'Sankey diagram',
  15639. funnel: 'Funnel chart',
  15640. gauge: 'Gauge',
  15641. pictorialBar: 'Pictorial bar',
  15642. themeRiver: 'Theme River Map',
  15643. sunburst: 'Sunburst'
  15644. }
  15645. },
  15646. aria: {
  15647. general: {
  15648. withTitle: 'This is a chart about "{title}"',
  15649. withoutTitle: 'This is a chart'
  15650. },
  15651. series: {
  15652. single: {
  15653. prefix: '',
  15654. withName: ' with type {seriesType} named {seriesName}.',
  15655. withoutName: ' with type {seriesType}.'
  15656. },
  15657. multiple: {
  15658. prefix: '. It consists of {seriesCount} series count.',
  15659. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15660. withoutName: ' The {seriesId} series is a {seriesType}.',
  15661. separator: {
  15662. middle: '',
  15663. end: ''
  15664. }
  15665. }
  15666. },
  15667. data: {
  15668. allData: 'The data is as follows: ',
  15669. partialData: 'The first {displayCnt} items are: ',
  15670. withName: 'the data for {name} is {value}',
  15671. withoutName: '{value}',
  15672. separator: {
  15673. middle: ', ',
  15674. end: '. '
  15675. }
  15676. }
  15677. }
  15678. };
  15679. /*
  15680. * Licensed to the Apache Software Foundation (ASF) under one
  15681. * or more contributor license agreements. See the NOTICE file
  15682. * distributed with this work for additional information
  15683. * regarding copyright ownership. The ASF licenses this file
  15684. * to you under the Apache License, Version 2.0 (the
  15685. * "License"); you may not use this file except in compliance
  15686. * with the License. You may obtain a copy of the License at
  15687. *
  15688. * http://www.apache.org/licenses/LICENSE-2.0
  15689. *
  15690. * Unless required by applicable law or agreed to in writing,
  15691. * software distributed under the License is distributed on an
  15692. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15693. * KIND, either express or implied. See the License for the
  15694. * specific language governing permissions and limitations
  15695. * under the License.
  15696. */
  15697. /**
  15698. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15699. */
  15700. /*
  15701. * Licensed to the Apache Software Foundation (ASF) under one
  15702. * or more contributor license agreements. See the NOTICE file
  15703. * distributed with this work for additional information
  15704. * regarding copyright ownership. The ASF licenses this file
  15705. * to you under the Apache License, Version 2.0 (the
  15706. * "License"); you may not use this file except in compliance
  15707. * with the License. You may obtain a copy of the License at
  15708. *
  15709. * http://www.apache.org/licenses/LICENSE-2.0
  15710. *
  15711. * Unless required by applicable law or agreed to in writing,
  15712. * software distributed under the License is distributed on an
  15713. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15714. * KIND, either express or implied. See the License for the
  15715. * specific language governing permissions and limitations
  15716. * under the License.
  15717. */
  15718. var langZH = {
  15719. time: {
  15720. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15721. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15722. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15723. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15724. },
  15725. legend: {
  15726. selector: {
  15727. all: '全选',
  15728. inverse: '反选'
  15729. }
  15730. },
  15731. toolbox: {
  15732. brush: {
  15733. title: {
  15734. rect: '矩形选择',
  15735. polygon: '圈选',
  15736. lineX: '横向选择',
  15737. lineY: '纵向选择',
  15738. keep: '保持选择',
  15739. clear: '清除选择'
  15740. }
  15741. },
  15742. dataView: {
  15743. title: '数据视图',
  15744. lang: ['数据视图', '关闭', '刷新']
  15745. },
  15746. dataZoom: {
  15747. title: {
  15748. zoom: '区域缩放',
  15749. back: '区域缩放还原'
  15750. }
  15751. },
  15752. magicType: {
  15753. title: {
  15754. line: '切换为折线图',
  15755. bar: '切换为柱状图',
  15756. stack: '切换为堆叠',
  15757. tiled: '切换为平铺'
  15758. }
  15759. },
  15760. restore: {
  15761. title: '还原'
  15762. },
  15763. saveAsImage: {
  15764. title: '保存为图片',
  15765. lang: ['右键另存为图片']
  15766. }
  15767. },
  15768. series: {
  15769. typeNames: {
  15770. pie: '饼图',
  15771. bar: '柱状图',
  15772. line: '折线图',
  15773. scatter: '散点图',
  15774. effectScatter: '涟漪散点图',
  15775. radar: '雷达图',
  15776. tree: '树图',
  15777. treemap: '矩形树图',
  15778. boxplot: '箱型图',
  15779. candlestick: 'K线图',
  15780. k: 'K线图',
  15781. heatmap: '热力图',
  15782. map: '地图',
  15783. parallel: '平行坐标图',
  15784. lines: '线图',
  15785. graph: '关系图',
  15786. sankey: '桑基图',
  15787. funnel: '漏斗图',
  15788. gauge: '仪表盘图',
  15789. pictorialBar: '象形柱图',
  15790. themeRiver: '主题河流图',
  15791. sunburst: '旭日图'
  15792. }
  15793. },
  15794. aria: {
  15795. general: {
  15796. withTitle: '这是一个关于“{title}”的图表。',
  15797. withoutTitle: '这是一个图表,'
  15798. },
  15799. series: {
  15800. single: {
  15801. prefix: '',
  15802. withName: '图表类型是{seriesType},表示{seriesName}。',
  15803. withoutName: '图表类型是{seriesType}。'
  15804. },
  15805. multiple: {
  15806. prefix: '它由{seriesCount}个图表系列组成。',
  15807. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15808. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15809. separator: {
  15810. middle: ';',
  15811. end: '。'
  15812. }
  15813. }
  15814. },
  15815. data: {
  15816. allData: '其数据是——',
  15817. partialData: '其中,前{displayCnt}项是——',
  15818. withName: '{name}的数据是{value}',
  15819. withoutName: '{value}',
  15820. separator: {
  15821. middle: ',',
  15822. end: ''
  15823. }
  15824. }
  15825. }
  15826. };
  15827. var LOCALE_ZH = 'ZH';
  15828. var LOCALE_EN = 'EN';
  15829. var DEFAULT_LOCALE = LOCALE_EN;
  15830. var localeStorage = {};
  15831. var localeModels = {};
  15832. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15833. var langStr = (
  15834. /* eslint-disable-next-line */
  15835. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15836. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15837. }();
  15838. function registerLocale(locale, localeObj) {
  15839. locale = locale.toUpperCase();
  15840. localeModels[locale] = new Model(localeObj);
  15841. localeStorage[locale] = localeObj;
  15842. } // export function getLocale(locale: string) {
  15843. // return localeStorage[locale];
  15844. // }
  15845. function createLocaleObject(locale) {
  15846. if (isString(locale)) {
  15847. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15848. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15849. return clone(localeObj);
  15850. } else {
  15851. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15852. }
  15853. } else {
  15854. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15855. }
  15856. }
  15857. function getLocaleModel(lang) {
  15858. return localeModels[lang];
  15859. }
  15860. function getDefaultLocaleModel() {
  15861. return localeModels[DEFAULT_LOCALE];
  15862. } // Default locale
  15863. registerLocale(LOCALE_EN, langEN);
  15864. registerLocale(LOCALE_ZH, langZH);
  15865. var ONE_SECOND = 1000;
  15866. var ONE_MINUTE = ONE_SECOND * 60;
  15867. var ONE_HOUR = ONE_MINUTE * 60;
  15868. var ONE_DAY = ONE_HOUR * 24;
  15869. var ONE_YEAR = ONE_DAY * 365;
  15870. var defaultLeveledFormatter = {
  15871. year: '{yyyy}',
  15872. month: '{MMM}',
  15873. day: '{d}',
  15874. hour: '{HH}:{mm}',
  15875. minute: '{HH}:{mm}',
  15876. second: '{HH}:{mm}:{ss}',
  15877. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15878. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15879. };
  15880. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15881. var fullLeveledFormatter = {
  15882. year: '{yyyy}',
  15883. month: '{yyyy}-{MM}',
  15884. day: fullDayFormatter,
  15885. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15886. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15887. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15888. millisecond: defaultLeveledFormatter.none
  15889. };
  15890. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15891. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15892. function pad(str, len) {
  15893. str += '';
  15894. return '0000'.substr(0, len - str.length) + str;
  15895. }
  15896. function getPrimaryTimeUnit(timeUnit) {
  15897. switch (timeUnit) {
  15898. case 'half-year':
  15899. case 'quarter':
  15900. return 'month';
  15901. case 'week':
  15902. case 'half-week':
  15903. return 'day';
  15904. case 'half-day':
  15905. case 'quarter-day':
  15906. return 'hour';
  15907. default:
  15908. // year, minutes, second, milliseconds
  15909. return timeUnit;
  15910. }
  15911. }
  15912. function isPrimaryTimeUnit(timeUnit) {
  15913. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15914. }
  15915. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15916. switch (timeUnit) {
  15917. case 'year':
  15918. case 'month':
  15919. return 'day';
  15920. case 'millisecond':
  15921. return 'millisecond';
  15922. default:
  15923. // Also for day, hour, minute, second
  15924. return 'second';
  15925. }
  15926. }
  15927. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15928. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15929. time, template, isUTC, lang) {
  15930. var date = parseDate(time);
  15931. var y = date[fullYearGetterName(isUTC)]();
  15932. var M = date[monthGetterName(isUTC)]() + 1;
  15933. var q = Math.floor((M - 1) / 3) + 1;
  15934. var d = date[dateGetterName(isUTC)]();
  15935. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15936. var H = date[hoursGetterName(isUTC)]();
  15937. var h = (H - 1) % 12 + 1;
  15938. var m = date[minutesGetterName(isUTC)]();
  15939. var s = date[secondsGetterName(isUTC)]();
  15940. var S = date[millisecondsGetterName(isUTC)]();
  15941. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15942. var timeModel = localeModel.getModel('time');
  15943. var month = timeModel.get('month');
  15944. var monthAbbr = timeModel.get('monthAbbr');
  15945. var dayOfWeek = timeModel.get('dayOfWeek');
  15946. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15947. return (template || '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, y % 100 + '').replace(/{Q}/g, q + '').replace(/{MMMM}/g, month[M - 1]).replace(/{MMM}/g, monthAbbr[M - 1]).replace(/{MM}/g, pad(M, 2)).replace(/{M}/g, M + '').replace(/{dd}/g, pad(d, 2)).replace(/{d}/g, d + '').replace(/{eeee}/g, dayOfWeek[e]).replace(/{ee}/g, dayOfWeekAbbr[e]).replace(/{e}/g, e + '').replace(/{HH}/g, pad(H, 2)).replace(/{H}/g, H + '').replace(/{hh}/g, pad(h + '', 2)).replace(/{h}/g, h + '').replace(/{mm}/g, pad(m, 2)).replace(/{m}/g, m + '').replace(/{ss}/g, pad(s, 2)).replace(/{s}/g, s + '').replace(/{SSS}/g, pad(S, 3)).replace(/{S}/g, S + '');
  15948. }
  15949. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15950. var template = null;
  15951. if (isString(formatter)) {
  15952. // Single formatter for all units at all levels
  15953. template = formatter;
  15954. } else if (isFunction(formatter)) {
  15955. // Callback formatter
  15956. template = formatter(tick.value, idx, {
  15957. level: tick.level
  15958. });
  15959. } else {
  15960. var defaults$1 = extend({}, defaultLeveledFormatter);
  15961. if (tick.level > 0) {
  15962. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15963. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15964. }
  15965. }
  15966. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15967. : defaults(formatter, defaults$1) : defaults$1;
  15968. var unit = getUnitFromValue(tick.value, isUTC);
  15969. if (mergedFormatter[unit]) {
  15970. template = mergedFormatter[unit];
  15971. } else if (mergedFormatter.inherit) {
  15972. // Unit formatter is not defined and should inherit from bigger units
  15973. var targetId = timeUnits.indexOf(unit);
  15974. for (var i = targetId - 1; i >= 0; --i) {
  15975. if (mergedFormatter[unit]) {
  15976. template = mergedFormatter[unit];
  15977. break;
  15978. }
  15979. }
  15980. template = template || defaults$1.none;
  15981. }
  15982. if (isArray(template)) {
  15983. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15984. levelId = Math.min(levelId, template.length - 1);
  15985. template = template[levelId];
  15986. }
  15987. }
  15988. return format(new Date(tick.value), template, isUTC, lang);
  15989. }
  15990. function getUnitFromValue(value, isUTC) {
  15991. var date = parseDate(value);
  15992. var M = date[monthGetterName(isUTC)]() + 1;
  15993. var d = date[dateGetterName(isUTC)]();
  15994. var h = date[hoursGetterName(isUTC)]();
  15995. var m = date[minutesGetterName(isUTC)]();
  15996. var s = date[secondsGetterName(isUTC)]();
  15997. var S = date[millisecondsGetterName(isUTC)]();
  15998. var isSecond = S === 0;
  15999. var isMinute = isSecond && s === 0;
  16000. var isHour = isMinute && m === 0;
  16001. var isDay = isHour && h === 0;
  16002. var isMonth = isDay && d === 1;
  16003. var isYear = isMonth && M === 1;
  16004. if (isYear) {
  16005. return 'year';
  16006. } else if (isMonth) {
  16007. return 'month';
  16008. } else if (isDay) {
  16009. return 'day';
  16010. } else if (isHour) {
  16011. return 'hour';
  16012. } else if (isMinute) {
  16013. return 'minute';
  16014. } else if (isSecond) {
  16015. return 'second';
  16016. } else {
  16017. return 'millisecond';
  16018. }
  16019. }
  16020. function getUnitValue(value, unit, isUTC) {
  16021. var date = isNumber(value) ? parseDate(value) : value;
  16022. unit = unit || getUnitFromValue(value, isUTC);
  16023. switch (unit) {
  16024. case 'year':
  16025. return date[fullYearGetterName(isUTC)]();
  16026. case 'half-year':
  16027. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  16028. case 'quarter':
  16029. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  16030. case 'month':
  16031. return date[monthGetterName(isUTC)]();
  16032. case 'day':
  16033. return date[dateGetterName(isUTC)]();
  16034. case 'half-day':
  16035. return date[hoursGetterName(isUTC)]() / 24;
  16036. case 'hour':
  16037. return date[hoursGetterName(isUTC)]();
  16038. case 'minute':
  16039. return date[minutesGetterName(isUTC)]();
  16040. case 'second':
  16041. return date[secondsGetterName(isUTC)]();
  16042. case 'millisecond':
  16043. return date[millisecondsGetterName(isUTC)]();
  16044. }
  16045. }
  16046. function fullYearGetterName(isUTC) {
  16047. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  16048. }
  16049. function monthGetterName(isUTC) {
  16050. return isUTC ? 'getUTCMonth' : 'getMonth';
  16051. }
  16052. function dateGetterName(isUTC) {
  16053. return isUTC ? 'getUTCDate' : 'getDate';
  16054. }
  16055. function hoursGetterName(isUTC) {
  16056. return isUTC ? 'getUTCHours' : 'getHours';
  16057. }
  16058. function minutesGetterName(isUTC) {
  16059. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  16060. }
  16061. function secondsGetterName(isUTC) {
  16062. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  16063. }
  16064. function millisecondsGetterName(isUTC) {
  16065. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  16066. }
  16067. function fullYearSetterName(isUTC) {
  16068. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  16069. }
  16070. function monthSetterName(isUTC) {
  16071. return isUTC ? 'setUTCMonth' : 'setMonth';
  16072. }
  16073. function dateSetterName(isUTC) {
  16074. return isUTC ? 'setUTCDate' : 'setDate';
  16075. }
  16076. function hoursSetterName(isUTC) {
  16077. return isUTC ? 'setUTCHours' : 'setHours';
  16078. }
  16079. function minutesSetterName(isUTC) {
  16080. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  16081. }
  16082. function secondsSetterName(isUTC) {
  16083. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  16084. }
  16085. function millisecondsSetterName(isUTC) {
  16086. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  16087. }
  16088. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  16089. var textEl = new ZRText({
  16090. style: {
  16091. text: text,
  16092. font: font,
  16093. align: align,
  16094. verticalAlign: verticalAlign,
  16095. padding: padding,
  16096. rich: rich,
  16097. overflow: truncate ? 'truncate' : null,
  16098. lineHeight: lineHeight
  16099. }
  16100. });
  16101. return textEl.getBoundingRect();
  16102. }
  16103. /**
  16104. * Add a comma each three digit.
  16105. */
  16106. function addCommas(x) {
  16107. if (!isNumeric(x)) {
  16108. return isString(x) ? x : '-';
  16109. }
  16110. var parts = (x + '').split('.');
  16111. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  16112. }
  16113. function toCamelCase(str, upperCaseFirst) {
  16114. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16115. return group1.toUpperCase();
  16116. });
  16117. if (upperCaseFirst && str) {
  16118. str = str.charAt(0).toUpperCase() + str.slice(1);
  16119. }
  16120. return str;
  16121. }
  16122. var normalizeCssArray$1 = normalizeCssArray;
  16123. /**
  16124. * Make value user readable for tooltip and label.
  16125. * "User readable":
  16126. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  16127. * Avoid to display an empty string, which users can not recognize there is
  16128. * a value and it might look like a bug.
  16129. */
  16130. function makeValueReadable(value, valueType, useUTC) {
  16131. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}';
  16132. function stringToUserReadable(str) {
  16133. return str && trim(str) ? str : '-';
  16134. }
  16135. function isNumberUserReadable(num) {
  16136. return !!(num != null && !isNaN(num) && isFinite(num));
  16137. }
  16138. var isTypeTime = valueType === 'time';
  16139. var isValueDate = value instanceof Date;
  16140. if (isTypeTime || isValueDate) {
  16141. var date = isTypeTime ? parseDate(value) : value;
  16142. if (!isNaN(+date)) {
  16143. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  16144. } else if (isValueDate) {
  16145. return '-';
  16146. } // In other cases, continue to try to display the value in the following code.
  16147. }
  16148. if (valueType === 'ordinal') {
  16149. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  16150. } // By default.
  16151. var numericResult = numericToNumber(value);
  16152. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : typeof value === 'boolean' ? value + '' : '-';
  16153. }
  16154. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16155. var wrapVar = function (varName, seriesIdx) {
  16156. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16157. };
  16158. /**
  16159. * Template formatter
  16160. * @param {Array.<Object>|Object} paramsList
  16161. */
  16162. function formatTpl(tpl, paramsList, encode) {
  16163. if (!isArray(paramsList)) {
  16164. paramsList = [paramsList];
  16165. }
  16166. var seriesLen = paramsList.length;
  16167. if (!seriesLen) {
  16168. return '';
  16169. }
  16170. var $vars = paramsList[0].$vars || [];
  16171. for (var i = 0; i < $vars.length; i++) {
  16172. var alias = TPL_VAR_ALIAS[i];
  16173. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16174. }
  16175. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16176. for (var k = 0; k < $vars.length; k++) {
  16177. var val = paramsList[seriesIdx][$vars[k]];
  16178. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  16179. }
  16180. }
  16181. return tpl;
  16182. }
  16183. /**
  16184. * simple Template formatter
  16185. */
  16186. function formatTplSimple(tpl, param, encode) {
  16187. each(param, function (value, key) {
  16188. tpl = tpl.replace('{' + key + '}', encode ? encodeHTML(value) : value);
  16189. });
  16190. return tpl;
  16191. }
  16192. function getTooltipMarker(inOpt, extraCssText) {
  16193. var opt = isString(inOpt) ? {
  16194. color: inOpt,
  16195. extraCssText: extraCssText
  16196. } : inOpt || {};
  16197. var color = opt.color;
  16198. var type = opt.type;
  16199. extraCssText = opt.extraCssText;
  16200. var renderMode = opt.renderMode || 'html';
  16201. if (!color) {
  16202. return '';
  16203. }
  16204. if (renderMode === 'html') {
  16205. return type === 'subItem' ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;' + 'border-radius:4px;width:4px;height:4px;background-color:' // Only support string
  16206. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>' : '<span style="display:inline-block;margin-right:4px;' + 'border-radius:10px;width:10px;height:10px;background-color:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16207. } else {
  16208. // Should better not to auto generate style name by auto-increment number here.
  16209. // Because this util is usually called in tooltip formatter, which is probably
  16210. // called repeatedly when mouse move and the auto-increment number increases fast.
  16211. // Users can make their own style name by theirselves, make it unique and readable.
  16212. var markerId = opt.markerId || 'markerX';
  16213. return {
  16214. renderMode: renderMode,
  16215. content: '{' + markerId + '|} ',
  16216. style: type === 'subItem' ? {
  16217. width: 4,
  16218. height: 4,
  16219. borderRadius: 2,
  16220. backgroundColor: color
  16221. } : {
  16222. width: 10,
  16223. height: 10,
  16224. borderRadius: 5,
  16225. backgroundColor: color
  16226. }
  16227. };
  16228. }
  16229. }
  16230. /**
  16231. * @deprecated Use `time/format` instead.
  16232. * ISO Date format
  16233. * @param {string} tpl
  16234. * @param {number} value
  16235. * @param {boolean} [isUTC=false] Default in local time.
  16236. * see `module:echarts/scale/Time`
  16237. * and `module:echarts/util/number#parseDate`.
  16238. * @inner
  16239. */
  16240. function formatTime(tpl, value, isUTC) {
  16241. if ("development" !== 'production') {
  16242. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  16243. }
  16244. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  16245. tpl = 'MM-dd\nyyyy';
  16246. }
  16247. var date = parseDate(value);
  16248. var getUTC = isUTC ? 'getUTC' : 'get';
  16249. var y = date[getUTC + 'FullYear']();
  16250. var M = date[getUTC + 'Month']() + 1;
  16251. var d = date[getUTC + 'Date']();
  16252. var h = date[getUTC + 'Hours']();
  16253. var m = date[getUTC + 'Minutes']();
  16254. var s = date[getUTC + 'Seconds']();
  16255. var S = date[getUTC + 'Milliseconds']();
  16256. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', pad(y % 100 + '', 2)).replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
  16257. return tpl;
  16258. }
  16259. /**
  16260. * Capital first
  16261. * @param {string} str
  16262. * @return {string}
  16263. */
  16264. function capitalFirst(str) {
  16265. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16266. }
  16267. /**
  16268. * @return Never be null/undefined.
  16269. */
  16270. function convertToColorString(color, defaultColor) {
  16271. defaultColor = defaultColor || 'transparent';
  16272. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  16273. }
  16274. /**
  16275. * open new tab
  16276. * @param link url
  16277. * @param target blank or self
  16278. */
  16279. function windowOpen(link, target) {
  16280. /* global window */
  16281. if (target === '_blank' || target === 'blank') {
  16282. var blank = window.open();
  16283. blank.opener = null;
  16284. blank.location.href = link;
  16285. } else {
  16286. window.open(link, target);
  16287. }
  16288. }
  16289. var each$1 = each;
  16290. /**
  16291. * @public
  16292. */
  16293. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16294. /**
  16295. * @public
  16296. */
  16297. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16298. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16299. var x = 0;
  16300. var y = 0;
  16301. if (maxWidth == null) {
  16302. maxWidth = Infinity;
  16303. }
  16304. if (maxHeight == null) {
  16305. maxHeight = Infinity;
  16306. }
  16307. var currentLineMaxSize = 0;
  16308. group.eachChild(function (child, idx) {
  16309. var rect = child.getBoundingRect();
  16310. var nextChild = group.childAt(idx + 1);
  16311. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16312. var nextX;
  16313. var nextY;
  16314. if (orient === 'horizontal') {
  16315. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16316. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  16317. // FIXME compare before adding gap?
  16318. if (nextX > maxWidth || child.newline) {
  16319. x = 0;
  16320. nextX = moveX;
  16321. y += currentLineMaxSize + gap;
  16322. currentLineMaxSize = rect.height;
  16323. } else {
  16324. // FIXME: consider rect.y is not `0`?
  16325. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16326. }
  16327. } else {
  16328. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16329. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  16330. if (nextY > maxHeight || child.newline) {
  16331. x += currentLineMaxSize + gap;
  16332. y = 0;
  16333. nextY = moveY;
  16334. currentLineMaxSize = rect.width;
  16335. } else {
  16336. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16337. }
  16338. }
  16339. if (child.newline) {
  16340. return;
  16341. }
  16342. child.x = x;
  16343. child.y = y;
  16344. child.markRedraw();
  16345. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16346. });
  16347. }
  16348. /**
  16349. * VBox or HBox layouting
  16350. * @param {string} orient
  16351. * @param {module:zrender/graphic/Group} group
  16352. * @param {number} gap
  16353. * @param {number} [width=Infinity]
  16354. * @param {number} [height=Infinity]
  16355. */
  16356. var box = boxLayout;
  16357. /**
  16358. * VBox layouting
  16359. * @param {module:zrender/graphic/Group} group
  16360. * @param {number} gap
  16361. * @param {number} [width=Infinity]
  16362. * @param {number} [height=Infinity]
  16363. */
  16364. var vbox = curry(boxLayout, 'vertical');
  16365. /**
  16366. * HBox layouting
  16367. * @param {module:zrender/graphic/Group} group
  16368. * @param {number} gap
  16369. * @param {number} [width=Infinity]
  16370. * @param {number} [height=Infinity]
  16371. */
  16372. var hbox = curry(boxLayout, 'horizontal');
  16373. /**
  16374. * If x or x2 is not specified or 'center' 'left' 'right',
  16375. * the width would be as long as possible.
  16376. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16377. * the height would be as long as possible.
  16378. */
  16379. function getAvailableSize(positionInfo, containerRect, margin) {
  16380. var containerWidth = containerRect.width;
  16381. var containerHeight = containerRect.height;
  16382. var x = parsePercent$1(positionInfo.left, containerWidth);
  16383. var y = parsePercent$1(positionInfo.top, containerHeight);
  16384. var x2 = parsePercent$1(positionInfo.right, containerWidth);
  16385. var y2 = parsePercent$1(positionInfo.bottom, containerHeight);
  16386. (isNaN(x) || isNaN(parseFloat(positionInfo.left))) && (x = 0);
  16387. (isNaN(x2) || isNaN(parseFloat(positionInfo.right))) && (x2 = containerWidth);
  16388. (isNaN(y) || isNaN(parseFloat(positionInfo.top))) && (y = 0);
  16389. (isNaN(y2) || isNaN(parseFloat(positionInfo.bottom))) && (y2 = containerHeight);
  16390. margin = normalizeCssArray$1(margin || 0);
  16391. return {
  16392. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16393. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16394. };
  16395. }
  16396. /**
  16397. * Parse position info.
  16398. */
  16399. function getLayoutRect(positionInfo, containerRect, margin) {
  16400. margin = normalizeCssArray$1(margin || 0);
  16401. var containerWidth = containerRect.width;
  16402. var containerHeight = containerRect.height;
  16403. var left = parsePercent$1(positionInfo.left, containerWidth);
  16404. var top = parsePercent$1(positionInfo.top, containerHeight);
  16405. var right = parsePercent$1(positionInfo.right, containerWidth);
  16406. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16407. var width = parsePercent$1(positionInfo.width, containerWidth);
  16408. var height = parsePercent$1(positionInfo.height, containerHeight);
  16409. var verticalMargin = margin[2] + margin[0];
  16410. var horizontalMargin = margin[1] + margin[3];
  16411. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  16412. if (isNaN(width)) {
  16413. width = containerWidth - right - horizontalMargin - left;
  16414. }
  16415. if (isNaN(height)) {
  16416. height = containerHeight - bottom - verticalMargin - top;
  16417. }
  16418. if (aspect != null) {
  16419. // If width and height are not given
  16420. // 1. Graph should not exceeds the container
  16421. // 2. Aspect must be keeped
  16422. // 3. Graph should take the space as more as possible
  16423. // FIXME
  16424. // Margin is not considered, because there is no case that both
  16425. // using margin and aspect so far.
  16426. if (isNaN(width) && isNaN(height)) {
  16427. if (aspect > containerWidth / containerHeight) {
  16428. width = containerWidth * 0.8;
  16429. } else {
  16430. height = containerHeight * 0.8;
  16431. }
  16432. } // Calculate width or height with given aspect
  16433. if (isNaN(width)) {
  16434. width = aspect * height;
  16435. }
  16436. if (isNaN(height)) {
  16437. height = width / aspect;
  16438. }
  16439. } // If left is not specified, calculate left from right and width
  16440. if (isNaN(left)) {
  16441. left = containerWidth - right - width - horizontalMargin;
  16442. }
  16443. if (isNaN(top)) {
  16444. top = containerHeight - bottom - height - verticalMargin;
  16445. } // Align left and top
  16446. switch (positionInfo.left || positionInfo.right) {
  16447. case 'center':
  16448. left = containerWidth / 2 - width / 2 - margin[3];
  16449. break;
  16450. case 'right':
  16451. left = containerWidth - width - horizontalMargin;
  16452. break;
  16453. }
  16454. switch (positionInfo.top || positionInfo.bottom) {
  16455. case 'middle':
  16456. case 'center':
  16457. top = containerHeight / 2 - height / 2 - margin[0];
  16458. break;
  16459. case 'bottom':
  16460. top = containerHeight - height - verticalMargin;
  16461. break;
  16462. } // If something is wrong and left, top, width, height are calculated as NaN
  16463. left = left || 0;
  16464. top = top || 0;
  16465. if (isNaN(width)) {
  16466. // Width may be NaN if only one value is given except width
  16467. width = containerWidth - horizontalMargin - left - (right || 0);
  16468. }
  16469. if (isNaN(height)) {
  16470. // Height may be NaN if only one value is given except height
  16471. height = containerHeight - verticalMargin - top - (bottom || 0);
  16472. }
  16473. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16474. rect.margin = margin;
  16475. return rect;
  16476. }
  16477. /**
  16478. * Position a zr element in viewport
  16479. * Group position is specified by either
  16480. * {left, top}, {right, bottom}
  16481. * If all properties exists, right and bottom will be igonred.
  16482. *
  16483. * Logic:
  16484. * 1. Scale (against origin point in parent coord)
  16485. * 2. Rotate (against origin point in parent coord)
  16486. * 3. Translate (with el.position by this method)
  16487. * So this method only fixes the last step 'Translate', which does not affect
  16488. * scaling and rotating.
  16489. *
  16490. * If be called repeatedly with the same input el, the same result will be gotten.
  16491. *
  16492. * Return true if the layout happened.
  16493. *
  16494. * @param el Should have `getBoundingRect` method.
  16495. * @param positionInfo
  16496. * @param positionInfo.left
  16497. * @param positionInfo.top
  16498. * @param positionInfo.right
  16499. * @param positionInfo.bottom
  16500. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  16501. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  16502. * @param containerRect
  16503. * @param margin
  16504. * @param opt
  16505. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  16506. * @param opt.boundingMode
  16507. * Specify how to calculate boundingRect when locating.
  16508. * 'all': Position the boundingRect that is transformed and uioned
  16509. * both itself and its descendants.
  16510. * This mode simplies confine the elements in the bounding
  16511. * of their container (e.g., using 'right: 0').
  16512. * 'raw': Position the boundingRect that is not transformed and only itself.
  16513. * This mode is useful when you want a element can overflow its
  16514. * container. (Consider a rotated circle needs to be located in a corner.)
  16515. * In this mode positionInfo.width/height can only be number.
  16516. */
  16517. function positionElement(el, positionInfo, containerRect, margin, opt, out) {
  16518. var h = !opt || !opt.hv || opt.hv[0];
  16519. var v = !opt || !opt.hv || opt.hv[1];
  16520. var boundingMode = opt && opt.boundingMode || 'all';
  16521. out = out || el;
  16522. out.x = el.x;
  16523. out.y = el.y;
  16524. if (!h && !v) {
  16525. return false;
  16526. }
  16527. var rect;
  16528. if (boundingMode === 'raw') {
  16529. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  16530. } else {
  16531. rect = el.getBoundingRect();
  16532. if (el.needLocalTransform()) {
  16533. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  16534. // which should not be modified.
  16535. rect = rect.clone();
  16536. rect.applyTransform(transform);
  16537. }
  16538. } // The real width and height can not be specified but calculated by the given el.
  16539. var layoutRect = getLayoutRect(defaults({
  16540. width: rect.width,
  16541. height: rect.height
  16542. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  16543. // (see zrender/core/Transformable#getLocalTransform),
  16544. // we can just only modify el.position to get final result.
  16545. var dx = h ? layoutRect.x - rect.x : 0;
  16546. var dy = v ? layoutRect.y - rect.y : 0;
  16547. if (boundingMode === 'raw') {
  16548. out.x = dx;
  16549. out.y = dy;
  16550. } else {
  16551. out.x += dx;
  16552. out.y += dy;
  16553. }
  16554. if (out === el) {
  16555. el.markRedraw();
  16556. }
  16557. return true;
  16558. }
  16559. /**
  16560. * @param option Contains some of the properties in HV_NAMES.
  16561. * @param hvIdx 0: horizontal; 1: vertical.
  16562. */
  16563. function sizeCalculable(option, hvIdx) {
  16564. return option[HV_NAMES[hvIdx][0]] != null || option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null;
  16565. }
  16566. function fetchLayoutMode(ins) {
  16567. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  16568. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  16569. type: layoutMode
  16570. } : null;
  16571. }
  16572. /**
  16573. * Consider Case:
  16574. * When default option has {left: 0, width: 100}, and we set {right: 0}
  16575. * through setOption or media query, using normal zrUtil.merge will cause
  16576. * {right: 0} does not take effect.
  16577. *
  16578. * @example
  16579. * ComponentModel.extend({
  16580. * init: function () {
  16581. * ...
  16582. * let inputPositionParams = layout.getLayoutParams(option);
  16583. * this.mergeOption(inputPositionParams);
  16584. * },
  16585. * mergeOption: function (newOption) {
  16586. * newOption && zrUtil.merge(thisOption, newOption, true);
  16587. * layout.mergeLayoutParam(thisOption, newOption);
  16588. * }
  16589. * });
  16590. *
  16591. * @param targetOption
  16592. * @param newOption
  16593. * @param opt
  16594. */
  16595. function mergeLayoutParam(targetOption, newOption, opt) {
  16596. var ignoreSize = opt && opt.ignoreSize;
  16597. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16598. var hResult = merge(HV_NAMES[0], 0);
  16599. var vResult = merge(HV_NAMES[1], 1);
  16600. copy(HV_NAMES[0], targetOption, hResult);
  16601. copy(HV_NAMES[1], targetOption, vResult);
  16602. function merge(names, hvIdx) {
  16603. var newParams = {};
  16604. var newValueCount = 0;
  16605. var merged = {};
  16606. var mergedValueCount = 0;
  16607. var enoughParamNumber = 2;
  16608. each$1(names, function (name) {
  16609. merged[name] = targetOption[name];
  16610. });
  16611. each$1(names, function (name) {
  16612. // Consider case: newOption.width is null, which is
  16613. // set by user for removing width setting.
  16614. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16615. hasValue(newParams, name) && newValueCount++;
  16616. hasValue(merged, name) && mergedValueCount++;
  16617. });
  16618. if (ignoreSize[hvIdx]) {
  16619. // Only one of left/right is premitted to exist.
  16620. if (hasValue(newOption, names[1])) {
  16621. merged[names[2]] = null;
  16622. } else if (hasValue(newOption, names[2])) {
  16623. merged[names[1]] = null;
  16624. }
  16625. return merged;
  16626. } // Case: newOption: {width: ..., right: ...},
  16627. // or targetOption: {right: ...} and newOption: {width: ...},
  16628. // There is no conflict when merged only has params count
  16629. // little than enoughParamNumber.
  16630. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16631. return merged;
  16632. } // Case: newOption: {width: ..., right: ...},
  16633. // Than we can make sure user only want those two, and ignore
  16634. // all origin params in targetOption.
  16635. else if (newValueCount >= enoughParamNumber) {
  16636. return newParams;
  16637. } else {
  16638. // Chose another param from targetOption by priority.
  16639. for (var i = 0; i < names.length; i++) {
  16640. var name_1 = names[i];
  16641. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16642. newParams[name_1] = targetOption[name_1];
  16643. break;
  16644. }
  16645. }
  16646. return newParams;
  16647. }
  16648. }
  16649. function hasProp(obj, name) {
  16650. return obj.hasOwnProperty(name);
  16651. }
  16652. function hasValue(obj, name) {
  16653. return obj[name] != null && obj[name] !== 'auto';
  16654. }
  16655. function copy(names, target, source) {
  16656. each$1(names, function (name) {
  16657. target[name] = source[name];
  16658. });
  16659. }
  16660. }
  16661. /**
  16662. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16663. */
  16664. function getLayoutParams(source) {
  16665. return copyLayoutParams({}, source);
  16666. }
  16667. /**
  16668. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16669. * @param {Object} source
  16670. * @return {Object} Result contains those props.
  16671. */
  16672. function copyLayoutParams(target, source) {
  16673. source && target && each$1(LOCATION_PARAMS, function (name) {
  16674. source.hasOwnProperty(name) && (target[name] = source[name]);
  16675. });
  16676. return target;
  16677. }
  16678. var inner = makeInner();
  16679. var ComponentModel =
  16680. /** @class */
  16681. function (_super) {
  16682. __extends(ComponentModel, _super);
  16683. function ComponentModel(option, parentModel, ecModel) {
  16684. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16685. _this.uid = getUID('ec_cpt_model');
  16686. return _this;
  16687. }
  16688. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16689. this.mergeDefaultAndTheme(option, ecModel);
  16690. };
  16691. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16692. var layoutMode = fetchLayoutMode(this);
  16693. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16694. var themeModel = ecModel.getTheme();
  16695. merge(option, themeModel.get(this.mainType));
  16696. merge(option, this.getDefaultOption());
  16697. if (layoutMode) {
  16698. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16699. }
  16700. };
  16701. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16702. merge(this.option, option, true);
  16703. var layoutMode = fetchLayoutMode(this);
  16704. if (layoutMode) {
  16705. mergeLayoutParam(this.option, option, layoutMode);
  16706. }
  16707. };
  16708. /**
  16709. * Called immediately after `init` or `mergeOption` of this instance called.
  16710. */
  16711. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16712. /**
  16713. * [How to declare defaultOption]:
  16714. *
  16715. * (A) If using class declaration in typescript (since echarts 5):
  16716. * ```ts
  16717. * import {ComponentOption} from '../model/option.js';
  16718. * export interface XxxOption extends ComponentOption {
  16719. * aaa: number
  16720. * }
  16721. * export class XxxModel extends Component {
  16722. * static type = 'xxx';
  16723. * static defaultOption: XxxOption = {
  16724. * aaa: 123
  16725. * }
  16726. * }
  16727. * Component.registerClass(XxxModel);
  16728. * ```
  16729. * ```ts
  16730. * import {inheritDefaultOption} from '../util/component.js';
  16731. * import {XxxModel, XxxOption} from './XxxModel.js';
  16732. * export interface XxxSubOption extends XxxOption {
  16733. * bbb: number
  16734. * }
  16735. * class XxxSubModel extends XxxModel {
  16736. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16737. * bbb: 456
  16738. * })
  16739. * fn() {
  16740. * let opt = this.getDefaultOption();
  16741. * // opt is {aaa: 123, bbb: 456}
  16742. * }
  16743. * }
  16744. * ```
  16745. *
  16746. * (B) If using class extend (previous approach in echarts 3 & 4):
  16747. * ```js
  16748. * let XxxComponent = Component.extend({
  16749. * defaultOption: {
  16750. * xx: 123
  16751. * }
  16752. * })
  16753. * ```
  16754. * ```js
  16755. * let XxxSubComponent = XxxComponent.extend({
  16756. * defaultOption: {
  16757. * yy: 456
  16758. * },
  16759. * fn: function () {
  16760. * let opt = this.getDefaultOption();
  16761. * // opt is {xx: 123, yy: 456}
  16762. * }
  16763. * })
  16764. * ```
  16765. */
  16766. ComponentModel.prototype.getDefaultOption = function () {
  16767. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  16768. // in legacy env and auto merge defaultOption. So if using class
  16769. // declaration, defaultOption should be merged manually.
  16770. if (!isExtendedClass(ctor)) {
  16771. // When using ts class, defaultOption must be declared as static.
  16772. return ctor.defaultOption;
  16773. } // FIXME: remove this approach?
  16774. var fields = inner(this);
  16775. if (!fields.defaultOption) {
  16776. var optList = [];
  16777. var clz = ctor;
  16778. while (clz) {
  16779. var opt = clz.prototype.defaultOption;
  16780. opt && optList.push(opt);
  16781. clz = clz.superClass;
  16782. }
  16783. var defaultOption = {};
  16784. for (var i = optList.length - 1; i >= 0; i--) {
  16785. defaultOption = merge(defaultOption, optList[i], true);
  16786. }
  16787. fields.defaultOption = defaultOption;
  16788. }
  16789. return fields.defaultOption;
  16790. };
  16791. /**
  16792. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16793. * The same behavior as `modelUtil.parseFinder`.
  16794. *
  16795. * @param useDefault In many cases like series refer axis and axis refer grid,
  16796. * If axis index / axis id not specified, use the first target as default.
  16797. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16798. */
  16799. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16800. var indexKey = mainType + 'Index';
  16801. var idKey = mainType + 'Id';
  16802. return queryReferringComponents(this.ecModel, mainType, {
  16803. index: this.get(indexKey, true),
  16804. id: this.get(idKey, true)
  16805. }, opt);
  16806. };
  16807. ComponentModel.prototype.getBoxLayoutParams = function () {
  16808. // Consider itself having box layout configs.
  16809. var boxLayoutModel = this;
  16810. return {
  16811. left: boxLayoutModel.get('left'),
  16812. top: boxLayoutModel.get('top'),
  16813. right: boxLayoutModel.get('right'),
  16814. bottom: boxLayoutModel.get('bottom'),
  16815. width: boxLayoutModel.get('width'),
  16816. height: boxLayoutModel.get('height')
  16817. };
  16818. };
  16819. /**
  16820. * Get key for zlevel.
  16821. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  16822. * For example, lines with trail effect and progressive series will in an individual zlevel.
  16823. */
  16824. ComponentModel.prototype.getZLevelKey = function () {
  16825. return '';
  16826. };
  16827. ComponentModel.prototype.setZLevel = function (zlevel) {
  16828. this.option.zlevel = zlevel;
  16829. };
  16830. ComponentModel.protoInitialize = function () {
  16831. var proto = ComponentModel.prototype;
  16832. proto.type = 'component';
  16833. proto.id = '';
  16834. proto.name = '';
  16835. proto.mainType = '';
  16836. proto.subType = '';
  16837. proto.componentIndex = 0;
  16838. }();
  16839. return ComponentModel;
  16840. }(Model);
  16841. mountExtend(ComponentModel, Model);
  16842. enableClassManagement(ComponentModel);
  16843. enableSubTypeDefaulter(ComponentModel);
  16844. enableTopologicalTravel(ComponentModel, getDependencies);
  16845. function getDependencies(componentType) {
  16846. var deps = [];
  16847. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16848. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16849. }); // Ensure main type.
  16850. deps = map(deps, function (type) {
  16851. return parseClassType(type).main;
  16852. }); // Hack dataset for convenience.
  16853. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16854. deps.unshift('dataset');
  16855. }
  16856. return deps;
  16857. }
  16858. /*
  16859. * Licensed to the Apache Software Foundation (ASF) under one
  16860. * or more contributor license agreements. See the NOTICE file
  16861. * distributed with this work for additional information
  16862. * regarding copyright ownership. The ASF licenses this file
  16863. * to you under the Apache License, Version 2.0 (the
  16864. * "License"); you may not use this file except in compliance
  16865. * with the License. You may obtain a copy of the License at
  16866. *
  16867. * http://www.apache.org/licenses/LICENSE-2.0
  16868. *
  16869. * Unless required by applicable law or agreed to in writing,
  16870. * software distributed under the License is distributed on an
  16871. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16872. * KIND, either express or implied. See the License for the
  16873. * specific language governing permissions and limitations
  16874. * under the License.
  16875. */
  16876. /**
  16877. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16878. */
  16879. /*
  16880. * Licensed to the Apache Software Foundation (ASF) under one
  16881. * or more contributor license agreements. See the NOTICE file
  16882. * distributed with this work for additional information
  16883. * regarding copyright ownership. The ASF licenses this file
  16884. * to you under the Apache License, Version 2.0 (the
  16885. * "License"); you may not use this file except in compliance
  16886. * with the License. You may obtain a copy of the License at
  16887. *
  16888. * http://www.apache.org/licenses/LICENSE-2.0
  16889. *
  16890. * Unless required by applicable law or agreed to in writing,
  16891. * software distributed under the License is distributed on an
  16892. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16893. * KIND, either express or implied. See the License for the
  16894. * specific language governing permissions and limitations
  16895. * under the License.
  16896. */
  16897. var platform = ''; // Navigator not exists in node
  16898. if (typeof navigator !== 'undefined') {
  16899. /* global navigator */
  16900. platform = navigator.platform || '';
  16901. }
  16902. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16903. var globalDefault = {
  16904. darkMode: 'auto',
  16905. // backgroundColor: 'rgba(0,0,0,0)',
  16906. colorBy: 'series',
  16907. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16908. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16909. aria: {
  16910. decal: {
  16911. decals: [{
  16912. color: decalColor,
  16913. dashArrayX: [1, 0],
  16914. dashArrayY: [2, 5],
  16915. symbolSize: 1,
  16916. rotation: Math.PI / 6
  16917. }, {
  16918. color: decalColor,
  16919. symbol: 'circle',
  16920. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16921. dashArrayY: [6, 0],
  16922. symbolSize: 0.8
  16923. }, {
  16924. color: decalColor,
  16925. dashArrayX: [1, 0],
  16926. dashArrayY: [4, 3],
  16927. rotation: -Math.PI / 4
  16928. }, {
  16929. color: decalColor,
  16930. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16931. dashArrayY: [6, 0]
  16932. }, {
  16933. color: decalColor,
  16934. dashArrayX: [[1, 0], [1, 6]],
  16935. dashArrayY: [1, 0, 6, 0],
  16936. rotation: Math.PI / 4
  16937. }, {
  16938. color: decalColor,
  16939. symbol: 'triangle',
  16940. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16941. dashArrayY: [7, 2],
  16942. symbolSize: 0.75
  16943. }]
  16944. }
  16945. },
  16946. // If xAxis and yAxis declared, grid is created by default.
  16947. // grid: {},
  16948. textStyle: {
  16949. // color: '#000',
  16950. // decoration: 'none',
  16951. // PENDING
  16952. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16953. // fontFamily: 'Arial, Verdana, sans-serif',
  16954. fontSize: 12,
  16955. fontStyle: 'normal',
  16956. fontWeight: 'normal'
  16957. },
  16958. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16959. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16960. // Default is source-over
  16961. blendMode: null,
  16962. stateAnimation: {
  16963. duration: 300,
  16964. easing: 'cubicOut'
  16965. },
  16966. animation: 'auto',
  16967. animationDuration: 1000,
  16968. animationDurationUpdate: 500,
  16969. animationEasing: 'cubicInOut',
  16970. animationEasingUpdate: 'cubicInOut',
  16971. animationThreshold: 2000,
  16972. // Configuration for progressive/incremental rendering
  16973. progressiveThreshold: 3000,
  16974. progressive: 400,
  16975. // Threshold of if use single hover layer to optimize.
  16976. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16977. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16978. // which is unexpected.
  16979. // see example <echarts/test/heatmap-large.html>.
  16980. hoverLayerThreshold: 3000,
  16981. // See: module:echarts/scale/Time
  16982. useUTC: false
  16983. };
  16984. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'seriesName']);
  16985. var SOURCE_FORMAT_ORIGINAL = 'original';
  16986. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16987. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16988. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16989. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16990. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16991. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16992. var SERIES_LAYOUT_BY_ROW = 'row';
  16993. var BE_ORDINAL = {
  16994. Must: 1,
  16995. Might: 2,
  16996. Not: 3 // Other cases
  16997. };
  16998. var innerGlobalModel = makeInner();
  16999. /**
  17000. * MUST be called before mergeOption of all series.
  17001. */
  17002. function resetSourceDefaulter(ecModel) {
  17003. // `datasetMap` is used to make default encode.
  17004. innerGlobalModel(ecModel).datasetMap = createHashMap();
  17005. }
  17006. /**
  17007. * [The strategy of the arrengment of data dimensions for dataset]:
  17008. * "value way": all axes are non-category axes. So series one by one take
  17009. * several (the number is coordSysDims.length) dimensions from dataset.
  17010. * The result of data arrengment of data dimensions like:
  17011. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  17012. * "category way": at least one axis is category axis. So the the first data
  17013. * dimension is always mapped to the first category axis and shared by
  17014. * all of the series. The other data dimensions are taken by series like
  17015. * "value way" does.
  17016. * The result of data arrengment of data dimensions like:
  17017. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  17018. *
  17019. * @return encode Never be `null/undefined`.
  17020. */
  17021. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  17022. var encode = {};
  17023. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17024. if (!datasetModel || !coordDimensions) {
  17025. return encode;
  17026. }
  17027. var encodeItemName = [];
  17028. var encodeSeriesName = [];
  17029. var ecModel = seriesModel.ecModel;
  17030. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  17031. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  17032. var baseCategoryDimIndex;
  17033. var categoryWayValueDimStart;
  17034. coordDimensions = coordDimensions.slice();
  17035. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  17036. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  17037. name: coordDimInfoLoose
  17038. };
  17039. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  17040. baseCategoryDimIndex = coordDimIdx;
  17041. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  17042. }
  17043. encode[coordDimInfo.name] = [];
  17044. });
  17045. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  17046. categoryWayDim: categoryWayValueDimStart,
  17047. valueWayDim: 0
  17048. }); // TODO
  17049. // Auto detect first time axis and do arrangement.
  17050. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  17051. var coordDimName = coordDimInfo.name;
  17052. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  17053. if (baseCategoryDimIndex == null) {
  17054. var start = datasetRecord.valueWayDim;
  17055. pushDim(encode[coordDimName], start, count);
  17056. pushDim(encodeSeriesName, start, count);
  17057. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  17058. // especially when encode x y specified.
  17059. // consider: when multiple series share one dimension
  17060. // category axis, series name should better use
  17061. // the other dimension name. On the other hand, use
  17062. // both dimensions name.
  17063. } // In category way, the first category axis.
  17064. else if (baseCategoryDimIndex === coordDimIdx) {
  17065. pushDim(encode[coordDimName], 0, count);
  17066. pushDim(encodeItemName, 0, count);
  17067. } // In category way, the other axis.
  17068. else {
  17069. var start = datasetRecord.categoryWayDim;
  17070. pushDim(encode[coordDimName], start, count);
  17071. pushDim(encodeSeriesName, start, count);
  17072. datasetRecord.categoryWayDim += count;
  17073. }
  17074. });
  17075. function pushDim(dimIdxArr, idxFrom, idxCount) {
  17076. for (var i = 0; i < idxCount; i++) {
  17077. dimIdxArr.push(idxFrom + i);
  17078. }
  17079. }
  17080. function getDataDimCountOnCoordDim(coordDimInfo) {
  17081. var dimsDef = coordDimInfo.dimsDef;
  17082. return dimsDef ? dimsDef.length : 1;
  17083. }
  17084. encodeItemName.length && (encode.itemName = encodeItemName);
  17085. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17086. return encode;
  17087. }
  17088. /**
  17089. * Work for data like [{name: ..., value: ...}, ...].
  17090. *
  17091. * @return encode Never be `null/undefined`.
  17092. */
  17093. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  17094. var encode = {};
  17095. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17096. if (!datasetModel) {
  17097. return encode;
  17098. }
  17099. var sourceFormat = source.sourceFormat;
  17100. var dimensionsDefine = source.dimensionsDefine;
  17101. var potentialNameDimIndex;
  17102. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17103. each(dimensionsDefine, function (dim, idx) {
  17104. if ((isObject(dim) ? dim.name : dim) === 'name') {
  17105. potentialNameDimIndex = idx;
  17106. }
  17107. });
  17108. }
  17109. var idxResult = function () {
  17110. var idxRes0 = {};
  17111. var idxRes1 = {};
  17112. var guessRecords = []; // 5 is an experience value.
  17113. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  17114. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  17115. guessRecords.push(guessResult);
  17116. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  17117. // and then find a name dim with the priority:
  17118. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  17119. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  17120. idxRes0.v = i;
  17121. }
  17122. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  17123. idxRes0.n = i;
  17124. }
  17125. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  17126. return idxRes0;
  17127. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  17128. // find the first BE_ORDINAL.Might as the value dim,
  17129. // and then find a name dim with the priority:
  17130. // "other dim" > "the value dim itself".
  17131. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  17132. // treated as number.
  17133. if (!isPureNumber) {
  17134. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  17135. idxRes1.v = i;
  17136. }
  17137. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  17138. idxRes1.n = i;
  17139. }
  17140. }
  17141. }
  17142. function fulfilled(idxResult) {
  17143. return idxResult.v != null && idxResult.n != null;
  17144. }
  17145. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  17146. }();
  17147. if (idxResult) {
  17148. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  17149. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label uses itemName in charts.
  17150. // So we don't set encodeLabel here.
  17151. encode.itemName = [nameDimIndex];
  17152. encode.seriesName = [nameDimIndex];
  17153. }
  17154. return encode;
  17155. }
  17156. /**
  17157. * @return If return null/undefined, indicate that should not use datasetModel.
  17158. */
  17159. function querySeriesUpstreamDatasetModel(seriesModel) {
  17160. // Caution: consider the scenario:
  17161. // A dataset is declared and a series is not expected to use the dataset,
  17162. // and at the beginning `setOption({series: { noData })` (just prepare other
  17163. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17164. // the user should set an empty array to avoid that dataset is used by default.
  17165. var thisData = seriesModel.get('data', true);
  17166. if (!thisData) {
  17167. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  17168. index: seriesModel.get('datasetIndex', true),
  17169. id: seriesModel.get('datasetId', true)
  17170. }, SINGLE_REFERRING).models[0];
  17171. }
  17172. }
  17173. /**
  17174. * @return Always return an array event empty.
  17175. */
  17176. function queryDatasetUpstreamDatasetModels(datasetModel) {
  17177. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  17178. // Otherwise, no reference.
  17179. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  17180. return [];
  17181. }
  17182. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  17183. index: datasetModel.get('fromDatasetIndex', true),
  17184. id: datasetModel.get('fromDatasetId', true)
  17185. }, SINGLE_REFERRING).models;
  17186. }
  17187. /**
  17188. * The rule should not be complex, otherwise user might not
  17189. * be able to known where the data is wrong.
  17190. * The code is ugly, but how to make it neat?
  17191. */
  17192. function guessOrdinal(source, dimIndex) {
  17193. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  17194. } // dimIndex may be overflow source data.
  17195. // return {BE_ORDINAL}
  17196. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  17197. var result; // Experience value.
  17198. var maxLoop = 5;
  17199. if (isTypedArray(data)) {
  17200. return BE_ORDINAL.Not;
  17201. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17202. // always exists in source.
  17203. var dimName;
  17204. var dimType;
  17205. if (dimensionsDefine) {
  17206. var dimDefItem = dimensionsDefine[dimIndex];
  17207. if (isObject(dimDefItem)) {
  17208. dimName = dimDefItem.name;
  17209. dimType = dimDefItem.type;
  17210. } else if (isString(dimDefItem)) {
  17211. dimName = dimDefItem;
  17212. }
  17213. }
  17214. if (dimType != null) {
  17215. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  17216. }
  17217. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17218. var dataArrayRows = data;
  17219. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17220. var sample = dataArrayRows[dimIndex];
  17221. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17222. if ((result = detectValue(sample[startIndex + i])) != null) {
  17223. return result;
  17224. }
  17225. }
  17226. } else {
  17227. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  17228. var row = dataArrayRows[startIndex + i];
  17229. if (row && (result = detectValue(row[dimIndex])) != null) {
  17230. return result;
  17231. }
  17232. }
  17233. }
  17234. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17235. var dataObjectRows = data;
  17236. if (!dimName) {
  17237. return BE_ORDINAL.Not;
  17238. }
  17239. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  17240. var item = dataObjectRows[i];
  17241. if (item && (result = detectValue(item[dimName])) != null) {
  17242. return result;
  17243. }
  17244. }
  17245. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17246. var dataKeyedColumns = data;
  17247. if (!dimName) {
  17248. return BE_ORDINAL.Not;
  17249. }
  17250. var sample = dataKeyedColumns[dimName];
  17251. if (!sample || isTypedArray(sample)) {
  17252. return BE_ORDINAL.Not;
  17253. }
  17254. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17255. if ((result = detectValue(sample[i])) != null) {
  17256. return result;
  17257. }
  17258. }
  17259. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17260. var dataOriginal = data;
  17261. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  17262. var item = dataOriginal[i];
  17263. var val = getDataItemValue(item);
  17264. if (!isArray(val)) {
  17265. return BE_ORDINAL.Not;
  17266. }
  17267. if ((result = detectValue(val[dimIndex])) != null) {
  17268. return result;
  17269. }
  17270. }
  17271. }
  17272. function detectValue(val) {
  17273. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  17274. // `isFinit('')` get `true`.
  17275. if (val != null && isFinite(val) && val !== '') {
  17276. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  17277. } else if (beStr && val !== '-') {
  17278. return BE_ORDINAL.Must;
  17279. }
  17280. }
  17281. return BE_ORDINAL.Not;
  17282. }
  17283. var internalOptionCreatorMap = createHashMap();
  17284. function registerInternalOptionCreator(mainType, creator) {
  17285. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  17286. internalOptionCreatorMap.set(mainType, creator);
  17287. }
  17288. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  17289. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  17290. if (!internalOptionCreator) {
  17291. return newCmptOptionList;
  17292. }
  17293. var internalOptions = internalOptionCreator(ecModel);
  17294. if (!internalOptions) {
  17295. return newCmptOptionList;
  17296. }
  17297. if ("development" !== 'production') {
  17298. for (var i = 0; i < internalOptions.length; i++) {
  17299. assert(isComponentIdInternal(internalOptions[i]));
  17300. }
  17301. }
  17302. return newCmptOptionList.concat(internalOptions);
  17303. }
  17304. var innerColor = makeInner();
  17305. var innerDecal = makeInner();
  17306. var PaletteMixin =
  17307. /** @class */
  17308. function () {
  17309. function PaletteMixin() {}
  17310. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  17311. var defaultPalette = normalizeToArray(this.get('color', true));
  17312. var layeredPalette = this.get('colorLayer', true);
  17313. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  17314. };
  17315. PaletteMixin.prototype.clearColorPalette = function () {
  17316. clearPalette(this, innerColor);
  17317. };
  17318. return PaletteMixin;
  17319. }();
  17320. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  17321. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  17322. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  17323. }
  17324. function getNearestPalette(palettes, requestColorNum) {
  17325. var paletteNum = palettes.length; // TODO palettes must be in order
  17326. for (var i = 0; i < paletteNum; i++) {
  17327. if (palettes[i].length > requestColorNum) {
  17328. return palettes[i];
  17329. }
  17330. }
  17331. return palettes[paletteNum - 1];
  17332. }
  17333. /**
  17334. * @param name MUST NOT be null/undefined. Otherwise call this function
  17335. * twise with the same parameters will get different result.
  17336. * @param scope default this.
  17337. * @return Can be null/undefined
  17338. */
  17339. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  17340. scope = scope || that;
  17341. var scopeFields = inner(scope);
  17342. var paletteIdx = scopeFields.paletteIdx || 0;
  17343. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17344. if (paletteNameMap.hasOwnProperty(name)) {
  17345. return paletteNameMap[name];
  17346. }
  17347. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  17348. palette = palette || defaultPalette;
  17349. if (!palette || !palette.length) {
  17350. return;
  17351. }
  17352. var pickedPaletteItem = palette[paletteIdx];
  17353. if (name) {
  17354. paletteNameMap[name] = pickedPaletteItem;
  17355. }
  17356. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  17357. return pickedPaletteItem;
  17358. }
  17359. function clearPalette(that, inner) {
  17360. inner(that).paletteIdx = 0;
  17361. inner(that).paletteNameMap = {};
  17362. }
  17363. // Internal method names:
  17364. // -----------------------
  17365. var reCreateSeriesIndices;
  17366. var assertSeriesInitialized;
  17367. var initBase;
  17368. var OPTION_INNER_KEY = '\0_ec_inner';
  17369. var OPTION_INNER_VALUE = 1;
  17370. var BUITIN_COMPONENTS_MAP = {
  17371. grid: 'GridComponent',
  17372. polar: 'PolarComponent',
  17373. geo: 'GeoComponent',
  17374. singleAxis: 'SingleAxisComponent',
  17375. parallel: 'ParallelComponent',
  17376. calendar: 'CalendarComponent',
  17377. graphic: 'GraphicComponent',
  17378. toolbox: 'ToolboxComponent',
  17379. tooltip: 'TooltipComponent',
  17380. axisPointer: 'AxisPointerComponent',
  17381. brush: 'BrushComponent',
  17382. title: 'TitleComponent',
  17383. timeline: 'TimelineComponent',
  17384. markPoint: 'MarkPointComponent',
  17385. markLine: 'MarkLineComponent',
  17386. markArea: 'MarkAreaComponent',
  17387. legend: 'LegendComponent',
  17388. dataZoom: 'DataZoomComponent',
  17389. visualMap: 'VisualMapComponent',
  17390. // aria: 'AriaComponent',
  17391. // dataset: 'DatasetComponent',
  17392. // Dependencies
  17393. xAxis: 'GridComponent',
  17394. yAxis: 'GridComponent',
  17395. angleAxis: 'PolarComponent',
  17396. radiusAxis: 'PolarComponent'
  17397. };
  17398. var BUILTIN_CHARTS_MAP = {
  17399. line: 'LineChart',
  17400. bar: 'BarChart',
  17401. pie: 'PieChart',
  17402. scatter: 'ScatterChart',
  17403. radar: 'RadarChart',
  17404. map: 'MapChart',
  17405. tree: 'TreeChart',
  17406. treemap: 'TreemapChart',
  17407. graph: 'GraphChart',
  17408. gauge: 'GaugeChart',
  17409. funnel: 'FunnelChart',
  17410. parallel: 'ParallelChart',
  17411. sankey: 'SankeyChart',
  17412. boxplot: 'BoxplotChart',
  17413. candlestick: 'CandlestickChart',
  17414. effectScatter: 'EffectScatterChart',
  17415. lines: 'LinesChart',
  17416. heatmap: 'HeatmapChart',
  17417. pictorialBar: 'PictorialBarChart',
  17418. themeRiver: 'ThemeRiverChart',
  17419. sunburst: 'SunburstChart',
  17420. custom: 'CustomChart'
  17421. };
  17422. var componetsMissingLogPrinted = {};
  17423. function checkMissingComponents(option) {
  17424. each(option, function (componentOption, mainType) {
  17425. if (!ComponentModel.hasClass(mainType)) {
  17426. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  17427. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  17428. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  17429. componetsMissingLogPrinted[componentImportName] = true;
  17430. }
  17431. }
  17432. });
  17433. }
  17434. var GlobalModel =
  17435. /** @class */
  17436. function (_super) {
  17437. __extends(GlobalModel, _super);
  17438. function GlobalModel() {
  17439. return _super !== null && _super.apply(this, arguments) || this;
  17440. }
  17441. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  17442. theme = theme || {};
  17443. this.option = null; // Mark as not initialized.
  17444. this._theme = new Model(theme);
  17445. this._locale = new Model(locale);
  17446. this._optionManager = optionManager;
  17447. };
  17448. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  17449. if ("development" !== 'production') {
  17450. assert(option != null, 'option is null/undefined');
  17451. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  17452. }
  17453. var innerOpt = normalizeSetOptionInput(opts);
  17454. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  17455. this._resetOption(null, innerOpt);
  17456. };
  17457. /**
  17458. * @param type null/undefined: reset all.
  17459. * 'recreate': force recreate all.
  17460. * 'timeline': only reset timeline option
  17461. * 'media': only reset media query option
  17462. * @return Whether option changed.
  17463. */
  17464. GlobalModel.prototype.resetOption = function (type, opt) {
  17465. return this._resetOption(type, normalizeSetOptionInput(opt));
  17466. };
  17467. GlobalModel.prototype._resetOption = function (type, opt) {
  17468. var optionChanged = false;
  17469. var optionManager = this._optionManager;
  17470. if (!type || type === 'recreate') {
  17471. var baseOption = optionManager.mountOption(type === 'recreate');
  17472. if ("development" !== 'production') {
  17473. checkMissingComponents(baseOption);
  17474. }
  17475. if (!this.option || type === 'recreate') {
  17476. initBase(this, baseOption);
  17477. } else {
  17478. this.restoreData();
  17479. this._mergeOption(baseOption, opt);
  17480. }
  17481. optionChanged = true;
  17482. }
  17483. if (type === 'timeline' || type === 'media') {
  17484. this.restoreData();
  17485. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  17486. // it should better not have the same props with `MediaUnit['option']`.
  17487. // Because either `option2` or `MediaUnit['option']` will be always merged to "current option"
  17488. // rather than original "baseOption". If they both override a prop, the result might be
  17489. // unexpected when media state changed after `setOption` called.
  17490. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  17491. // (`{baseOption, media}`) in `setOption`.
  17492. // For `timeline`, the case is the same.
  17493. if (!type || type === 'recreate' || type === 'timeline') {
  17494. var timelineOption = optionManager.getTimelineOption(this);
  17495. if (timelineOption) {
  17496. optionChanged = true;
  17497. this._mergeOption(timelineOption, opt);
  17498. }
  17499. }
  17500. if (!type || type === 'recreate' || type === 'media') {
  17501. var mediaOptions = optionManager.getMediaOption(this);
  17502. if (mediaOptions.length) {
  17503. each(mediaOptions, function (mediaOption) {
  17504. optionChanged = true;
  17505. this._mergeOption(mediaOption, opt);
  17506. }, this);
  17507. }
  17508. }
  17509. return optionChanged;
  17510. };
  17511. GlobalModel.prototype.mergeOption = function (option) {
  17512. this._mergeOption(option, null);
  17513. };
  17514. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  17515. var option = this.option;
  17516. var componentsMap = this._componentsMap;
  17517. var componentsCount = this._componentsCount;
  17518. var newCmptTypes = [];
  17519. var newCmptTypeMap = createHashMap();
  17520. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  17521. resetSourceDefaulter(this); // If no component class, merge directly.
  17522. // For example: color, animaiton options, etc.
  17523. each(newOption, function (componentOption, mainType) {
  17524. if (componentOption == null) {
  17525. return;
  17526. }
  17527. if (!ComponentModel.hasClass(mainType)) {
  17528. // globalSettingTask.dirty();
  17529. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17530. } else if (mainType) {
  17531. newCmptTypes.push(mainType);
  17532. newCmptTypeMap.set(mainType, true);
  17533. }
  17534. });
  17535. if (replaceMergeMainTypeMap) {
  17536. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  17537. // we trade it as it is declared in option as `{xxx: []}`. Because:
  17538. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  17539. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  17540. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  17541. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  17542. newCmptTypes.push(mainTypeInReplaceMerge);
  17543. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  17544. }
  17545. });
  17546. }
  17547. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17548. function visitComponent(mainType) {
  17549. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  17550. var oldCmptList = componentsMap.get(mainType);
  17551. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  17552. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  17553. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  17554. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  17555. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  17556. // components, which is probably incorrect logic.
  17557. option[mainType] = null;
  17558. componentsMap.set(mainType, null);
  17559. componentsCount.set(mainType, 0);
  17560. var optionsByMainType = [];
  17561. var cmptsByMainType = [];
  17562. var cmptsCountByMainType = 0;
  17563. var tooltipExists;
  17564. var tooltipWarningLogged;
  17565. each(mappingResult, function (resultItem, index) {
  17566. var componentModel = resultItem.existing;
  17567. var newCmptOption = resultItem.newOption;
  17568. if (!newCmptOption) {
  17569. if (componentModel) {
  17570. // Consider where is no new option and should be merged using {},
  17571. // see removeEdgeAndAdd in topologicalTravel and
  17572. // ComponentModel.getAllClassMainTypes.
  17573. componentModel.mergeOption({}, this);
  17574. componentModel.optionUpdated({}, false);
  17575. } // If no both `resultItem.exist` and `resultItem.option`,
  17576. // either it is in `replaceMerge` and not matched by any id,
  17577. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  17578. } else {
  17579. var isSeriesType = mainType === 'series';
  17580. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  17581. );
  17582. if (!ComponentModelClass) {
  17583. if ("development" !== 'production') {
  17584. var subType = resultItem.keyInfo.subType;
  17585. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  17586. if (!componetsMissingLogPrinted[subType]) {
  17587. componetsMissingLogPrinted[subType] = true;
  17588. if (seriesImportName) {
  17589. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  17590. } else {
  17591. error("Unknown series " + subType);
  17592. }
  17593. }
  17594. }
  17595. return;
  17596. } // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  17597. if (mainType === 'tooltip') {
  17598. if (tooltipExists) {
  17599. if ("development" !== 'production') {
  17600. if (!tooltipWarningLogged) {
  17601. warn('Currently only one tooltip component is allowed.');
  17602. tooltipWarningLogged = true;
  17603. }
  17604. }
  17605. return;
  17606. }
  17607. tooltipExists = true;
  17608. }
  17609. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17610. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  17611. componentModel.mergeOption(newCmptOption, this);
  17612. componentModel.optionUpdated(newCmptOption, false);
  17613. } else {
  17614. // PENDING Global as parent ?
  17615. var extraOpt = extend({
  17616. componentIndex: index
  17617. }, resultItem.keyInfo);
  17618. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  17619. extend(componentModel, extraOpt);
  17620. if (resultItem.brandNew) {
  17621. componentModel.__requireNewView = true;
  17622. }
  17623. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  17624. // newCmptOption has been used as componentModel.option
  17625. // and may be merged with theme and default, so pass null
  17626. // to avoid confusion.
  17627. componentModel.optionUpdated(null, true);
  17628. }
  17629. }
  17630. if (componentModel) {
  17631. optionsByMainType.push(componentModel.option);
  17632. cmptsByMainType.push(componentModel);
  17633. cmptsCountByMainType++;
  17634. } else {
  17635. // Always do assign to avoid elided item in array.
  17636. optionsByMainType.push(void 0);
  17637. cmptsByMainType.push(void 0);
  17638. }
  17639. }, this);
  17640. option[mainType] = optionsByMainType;
  17641. componentsMap.set(mainType, cmptsByMainType);
  17642. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  17643. if (mainType === 'series') {
  17644. reCreateSeriesIndices(this);
  17645. }
  17646. } // If no series declared, ensure `_seriesIndices` initialized.
  17647. if (!this._seriesIndices) {
  17648. reCreateSeriesIndices(this);
  17649. }
  17650. };
  17651. /**
  17652. * Get option for output (cloned option and inner info removed)
  17653. */
  17654. GlobalModel.prototype.getOption = function () {
  17655. var option = clone(this.option);
  17656. each(option, function (optInMainType, mainType) {
  17657. if (ComponentModel.hasClass(mainType)) {
  17658. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  17659. // Inner cmpts might not be at last since ec5.0, but still
  17660. // compatible for users: if inner cmpt at last, splice the returned array.
  17661. var realLen = opts.length;
  17662. var metNonInner = false;
  17663. for (var i = realLen - 1; i >= 0; i--) {
  17664. // Remove options with inner id.
  17665. if (opts[i] && !isComponentIdInternal(opts[i])) {
  17666. metNonInner = true;
  17667. } else {
  17668. opts[i] = null;
  17669. !metNonInner && realLen--;
  17670. }
  17671. }
  17672. opts.length = realLen;
  17673. option[mainType] = opts;
  17674. }
  17675. });
  17676. delete option[OPTION_INNER_KEY];
  17677. return option;
  17678. };
  17679. GlobalModel.prototype.getTheme = function () {
  17680. return this._theme;
  17681. };
  17682. GlobalModel.prototype.getLocaleModel = function () {
  17683. return this._locale;
  17684. };
  17685. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17686. this._payload = payload;
  17687. };
  17688. GlobalModel.prototype.getUpdatePayload = function () {
  17689. return this._payload;
  17690. };
  17691. /**
  17692. * @param idx If not specified, return the first one.
  17693. */
  17694. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17695. var list = this._componentsMap.get(mainType);
  17696. if (list) {
  17697. var cmpt = list[idx || 0];
  17698. if (cmpt) {
  17699. return cmpt;
  17700. } else if (idx == null) {
  17701. for (var i = 0; i < list.length; i++) {
  17702. if (list[i]) {
  17703. return list[i];
  17704. }
  17705. }
  17706. }
  17707. }
  17708. };
  17709. /**
  17710. * @return Never be null/undefined.
  17711. */
  17712. GlobalModel.prototype.queryComponents = function (condition) {
  17713. var mainType = condition.mainType;
  17714. if (!mainType) {
  17715. return [];
  17716. }
  17717. var index = condition.index;
  17718. var id = condition.id;
  17719. var name = condition.name;
  17720. var cmpts = this._componentsMap.get(mainType);
  17721. if (!cmpts || !cmpts.length) {
  17722. return [];
  17723. }
  17724. var result;
  17725. if (index != null) {
  17726. result = [];
  17727. each(normalizeToArray(index), function (idx) {
  17728. cmpts[idx] && result.push(cmpts[idx]);
  17729. });
  17730. } else if (id != null) {
  17731. result = queryByIdOrName('id', id, cmpts);
  17732. } else if (name != null) {
  17733. result = queryByIdOrName('name', name, cmpts);
  17734. } else {
  17735. // Return all non-empty components in that mainType
  17736. result = filter(cmpts, function (cmpt) {
  17737. return !!cmpt;
  17738. });
  17739. }
  17740. return filterBySubType(result, condition);
  17741. };
  17742. /**
  17743. * The interface is different from queryComponents,
  17744. * which is convenient for inner usage.
  17745. *
  17746. * @usage
  17747. * let result = findComponents(
  17748. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17749. * );
  17750. * let result = findComponents(
  17751. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17752. * );
  17753. * let result = findComponents(
  17754. * {mainType: 'series',
  17755. * filter: function (model, index) {...}}
  17756. * );
  17757. * // result like [component0, componnet1, ...]
  17758. */
  17759. GlobalModel.prototype.findComponents = function (condition) {
  17760. var query = condition.query;
  17761. var mainType = condition.mainType;
  17762. var queryCond = getQueryCond(query);
  17763. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  17764. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17765. return !!cmpt;
  17766. });
  17767. return doFilter(filterBySubType(result, condition));
  17768. function getQueryCond(q) {
  17769. var indexAttr = mainType + 'Index';
  17770. var idAttr = mainType + 'Id';
  17771. var nameAttr = mainType + 'Name';
  17772. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17773. mainType: mainType,
  17774. // subType will be filtered finally.
  17775. index: q[indexAttr],
  17776. id: q[idAttr],
  17777. name: q[nameAttr]
  17778. } : null;
  17779. }
  17780. function doFilter(res) {
  17781. return condition.filter ? filter(res, condition.filter) : res;
  17782. }
  17783. };
  17784. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17785. var componentsMap = this._componentsMap;
  17786. if (isFunction(mainType)) {
  17787. var ctxForAll_1 = cb;
  17788. var cbForAll_1 = mainType;
  17789. componentsMap.each(function (cmpts, componentType) {
  17790. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17791. var cmpt = cmpts[i];
  17792. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17793. }
  17794. });
  17795. } else {
  17796. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17797. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17798. var cmpt = cmpts[i];
  17799. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17800. }
  17801. }
  17802. };
  17803. /**
  17804. * Get series list before filtered by name.
  17805. */
  17806. GlobalModel.prototype.getSeriesByName = function (name) {
  17807. var nameStr = convertOptionIdName(name, null);
  17808. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17809. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17810. });
  17811. };
  17812. /**
  17813. * Get series list before filtered by index.
  17814. */
  17815. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17816. return this._componentsMap.get('series')[seriesIndex];
  17817. };
  17818. /**
  17819. * Get series list before filtered by type.
  17820. * FIXME: rename to getRawSeriesByType?
  17821. */
  17822. GlobalModel.prototype.getSeriesByType = function (subType) {
  17823. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17824. return !!oneSeries && oneSeries.subType === subType;
  17825. });
  17826. };
  17827. /**
  17828. * Get all series before filtered.
  17829. */
  17830. GlobalModel.prototype.getSeries = function () {
  17831. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17832. return !!oneSeries;
  17833. });
  17834. };
  17835. /**
  17836. * Count series before filtered.
  17837. */
  17838. GlobalModel.prototype.getSeriesCount = function () {
  17839. return this._componentsCount.get('series');
  17840. };
  17841. /**
  17842. * After filtering, series may be different
  17843. * from raw series.
  17844. */
  17845. GlobalModel.prototype.eachSeries = function (cb, context) {
  17846. assertSeriesInitialized(this);
  17847. each(this._seriesIndices, function (rawSeriesIndex) {
  17848. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17849. cb.call(context, series, rawSeriesIndex);
  17850. }, this);
  17851. };
  17852. /**
  17853. * Iterate raw series before filtered.
  17854. *
  17855. * @param {Function} cb
  17856. * @param {*} context
  17857. */
  17858. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17859. each(this._componentsMap.get('series'), function (series) {
  17860. series && cb.call(context, series, series.componentIndex);
  17861. });
  17862. };
  17863. /**
  17864. * After filtering, series may be different.
  17865. * from raw series.
  17866. */
  17867. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17868. assertSeriesInitialized(this);
  17869. each(this._seriesIndices, function (rawSeriesIndex) {
  17870. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17871. if (series.subType === subType) {
  17872. cb.call(context, series, rawSeriesIndex);
  17873. }
  17874. }, this);
  17875. };
  17876. /**
  17877. * Iterate raw series before filtered of given type.
  17878. */
  17879. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17880. return each(this.getSeriesByType(subType), cb, context);
  17881. };
  17882. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17883. assertSeriesInitialized(this);
  17884. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17885. };
  17886. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17887. return (this._seriesIndices || []).slice();
  17888. };
  17889. GlobalModel.prototype.filterSeries = function (cb, context) {
  17890. assertSeriesInitialized(this);
  17891. var newSeriesIndices = [];
  17892. each(this._seriesIndices, function (seriesRawIdx) {
  17893. var series = this._componentsMap.get('series')[seriesRawIdx];
  17894. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17895. }, this);
  17896. this._seriesIndices = newSeriesIndices;
  17897. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17898. };
  17899. GlobalModel.prototype.restoreData = function (payload) {
  17900. reCreateSeriesIndices(this);
  17901. var componentsMap = this._componentsMap;
  17902. var componentTypes = [];
  17903. componentsMap.each(function (components, componentType) {
  17904. if (ComponentModel.hasClass(componentType)) {
  17905. componentTypes.push(componentType);
  17906. }
  17907. });
  17908. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17909. each(componentsMap.get(componentType), function (component) {
  17910. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17911. component.restoreData();
  17912. }
  17913. });
  17914. });
  17915. };
  17916. GlobalModel.internalField = function () {
  17917. reCreateSeriesIndices = function (ecModel) {
  17918. var seriesIndices = ecModel._seriesIndices = [];
  17919. each(ecModel._componentsMap.get('series'), function (series) {
  17920. // series may have been removed by `replaceMerge`.
  17921. series && seriesIndices.push(series.componentIndex);
  17922. });
  17923. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17924. };
  17925. assertSeriesInitialized = function (ecModel) {
  17926. // Components that use _seriesIndices should depends on series component,
  17927. // which make sure that their initialization is after series.
  17928. if ("development" !== 'production') {
  17929. if (!ecModel._seriesIndices) {
  17930. throw new Error('Option should contains series.');
  17931. }
  17932. }
  17933. };
  17934. initBase = function (ecModel, baseOption) {
  17935. // Using OPTION_INNER_KEY to mark that this option cannot be used outside,
  17936. // i.e. `chart.setOption(chart.getModel().option);` is forbidden.
  17937. ecModel.option = {};
  17938. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  17939. // before series initialized.
  17940. ecModel._componentsMap = createHashMap({
  17941. series: []
  17942. });
  17943. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  17944. // performed before theme and globalDefault merge.
  17945. var airaOption = baseOption.aria;
  17946. if (isObject(airaOption) && airaOption.enabled == null) {
  17947. airaOption.enabled = true;
  17948. }
  17949. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  17950. merge(baseOption, globalDefault, false);
  17951. ecModel._mergeOption(baseOption, null);
  17952. };
  17953. }();
  17954. return GlobalModel;
  17955. }(Model);
  17956. function isNotTargetSeries(seriesModel, payload) {
  17957. if (payload) {
  17958. var index = payload.seriesIndex;
  17959. var id = payload.seriesId;
  17960. var name_1 = payload.seriesName;
  17961. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17962. }
  17963. }
  17964. function mergeTheme(option, theme) {
  17965. // PENDING
  17966. // NOT use `colorLayer` in theme if option has `color`
  17967. var notMergeColorLayer = option.color && !option.colorLayer;
  17968. each(theme, function (themeItem, name) {
  17969. if (name === 'colorLayer' && notMergeColorLayer) {
  17970. return;
  17971. } // If it is component model mainType, the model handles that merge later.
  17972. // otherwise, merge them here.
  17973. if (!ComponentModel.hasClass(name)) {
  17974. if (typeof themeItem === 'object') {
  17975. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17976. } else {
  17977. if (option[name] == null) {
  17978. option[name] = themeItem;
  17979. }
  17980. }
  17981. }
  17982. });
  17983. }
  17984. function queryByIdOrName(attr, idOrName, cmpts) {
  17985. // Here is a break from echarts4: string and number are
  17986. // treated as equal.
  17987. if (isArray(idOrName)) {
  17988. var keyMap_1 = createHashMap();
  17989. each(idOrName, function (idOrNameItem) {
  17990. if (idOrNameItem != null) {
  17991. var idName = convertOptionIdName(idOrNameItem, null);
  17992. idName != null && keyMap_1.set(idOrNameItem, true);
  17993. }
  17994. });
  17995. return filter(cmpts, function (cmpt) {
  17996. return cmpt && keyMap_1.get(cmpt[attr]);
  17997. });
  17998. } else {
  17999. var idName_1 = convertOptionIdName(idOrName, null);
  18000. return filter(cmpts, function (cmpt) {
  18001. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  18002. });
  18003. }
  18004. }
  18005. function filterBySubType(components, condition) {
  18006. // Using hasOwnProperty for restrict. Consider
  18007. // subType is undefined in user payload.
  18008. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  18009. return cmpt && cmpt.subType === condition.subType;
  18010. }) : components;
  18011. }
  18012. function normalizeSetOptionInput(opts) {
  18013. var replaceMergeMainTypeMap = createHashMap();
  18014. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  18015. if ("development" !== 'production') {
  18016. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  18017. }
  18018. replaceMergeMainTypeMap.set(mainType, true);
  18019. });
  18020. return {
  18021. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  18022. };
  18023. }
  18024. mixin(GlobalModel, PaletteMixin);
  18025. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  18026. 'getOption', // 'getViewOfComponentModel',
  18027. // 'getViewOfSeriesModel',
  18028. 'getId', 'updateLabelLayout'];
  18029. var ExtensionAPI =
  18030. /** @class */
  18031. function () {
  18032. function ExtensionAPI(ecInstance) {
  18033. each(availableMethods, function (methodName) {
  18034. this[methodName] = bind(ecInstance[methodName], ecInstance);
  18035. }, this);
  18036. }
  18037. return ExtensionAPI;
  18038. }();
  18039. var coordinateSystemCreators = {};
  18040. var CoordinateSystemManager =
  18041. /** @class */
  18042. function () {
  18043. function CoordinateSystemManager() {
  18044. this._coordinateSystems = [];
  18045. }
  18046. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  18047. var coordinateSystems = [];
  18048. each(coordinateSystemCreators, function (creator, type) {
  18049. var list = creator.create(ecModel, api);
  18050. coordinateSystems = coordinateSystems.concat(list || []);
  18051. });
  18052. this._coordinateSystems = coordinateSystems;
  18053. };
  18054. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  18055. each(this._coordinateSystems, function (coordSys) {
  18056. coordSys.update && coordSys.update(ecModel, api);
  18057. });
  18058. };
  18059. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  18060. return this._coordinateSystems.slice();
  18061. };
  18062. CoordinateSystemManager.register = function (type, creator) {
  18063. coordinateSystemCreators[type] = creator;
  18064. };
  18065. CoordinateSystemManager.get = function (type) {
  18066. return coordinateSystemCreators[type];
  18067. };
  18068. return CoordinateSystemManager;
  18069. }();
  18070. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  18071. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  18072. /**
  18073. * TERM EXPLANATIONS:
  18074. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  18075. */
  18076. var OptionManager =
  18077. /** @class */
  18078. function () {
  18079. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18080. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18081. // rawOption cloned and backuped when timeline changed, which does no
  18082. // good to performance. What's more, that both timeline and setOption
  18083. // method supply 'notMerge' brings complex and some problems.
  18084. // Consider this case:
  18085. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18086. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18087. function OptionManager(api) {
  18088. this._timelineOptions = [];
  18089. this._mediaList = [];
  18090. /**
  18091. * -1, means default.
  18092. * empty means no media.
  18093. */
  18094. this._currentMediaIndices = [];
  18095. this._api = api;
  18096. }
  18097. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  18098. if (rawOption) {
  18099. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18100. each(normalizeToArray(rawOption.series), function (series) {
  18101. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18102. });
  18103. each(normalizeToArray(rawOption.dataset), function (dataset) {
  18104. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  18105. });
  18106. } // Caution: some series modify option data, if do not clone,
  18107. // it should ensure that the repeat modify correctly
  18108. // (create a new object when modify itself).
  18109. rawOption = clone(rawOption); // FIXME
  18110. // If some property is set in timeline options or media option but
  18111. // not set in baseOption, a warning should be given.
  18112. var optionBackup = this._optionBackup;
  18113. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  18114. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  18115. if (optionBackup) {
  18116. // FIXME
  18117. // the restore merge solution is essentially incorrect.
  18118. // the mapping can not be 100% consistent with ecModel, which probably brings
  18119. // potential bug!
  18120. // The first merge is delayed, because in most cases, users do not call `setOption` twice.
  18121. // let fakeCmptsMap = this._fakeCmptsMap;
  18122. // if (!fakeCmptsMap) {
  18123. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  18124. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  18125. // }
  18126. // mergeToBackupOption(
  18127. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  18128. // );
  18129. // For simplicity, timeline options and media options do not support merge,
  18130. // that is, if you `setOption` twice and both has timeline options, the latter
  18131. // timeline options will not be merged to the former, but just substitute them.
  18132. if (newParsedOption.timelineOptions.length) {
  18133. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  18134. }
  18135. if (newParsedOption.mediaList.length) {
  18136. optionBackup.mediaList = newParsedOption.mediaList;
  18137. }
  18138. if (newParsedOption.mediaDefault) {
  18139. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  18140. }
  18141. } else {
  18142. this._optionBackup = newParsedOption;
  18143. }
  18144. };
  18145. OptionManager.prototype.mountOption = function (isRecreate) {
  18146. var optionBackup = this._optionBackup;
  18147. this._timelineOptions = optionBackup.timelineOptions;
  18148. this._mediaList = optionBackup.mediaList;
  18149. this._mediaDefault = optionBackup.mediaDefault;
  18150. this._currentMediaIndices = [];
  18151. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  18152. // called, and is merged into every new option by inner method `mergeToBackupOption`
  18153. // each time `setOption` called, can be only used in `isRecreate`, because
  18154. // its reliability is under suspicion. In other cases option merge is
  18155. // performed by `model.mergeOption`.
  18156. ? optionBackup.baseOption : this._newBaseOption);
  18157. };
  18158. OptionManager.prototype.getTimelineOption = function (ecModel) {
  18159. var option;
  18160. var timelineOptions = this._timelineOptions;
  18161. if (timelineOptions.length) {
  18162. // getTimelineOption can only be called after ecModel inited,
  18163. // so we can get currentIndex from timelineModel.
  18164. var timelineModel = ecModel.getComponent('timeline');
  18165. if (timelineModel) {
  18166. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  18167. timelineOptions[timelineModel.getCurrentIndex()]);
  18168. }
  18169. }
  18170. return option;
  18171. };
  18172. OptionManager.prototype.getMediaOption = function (ecModel) {
  18173. var ecWidth = this._api.getWidth();
  18174. var ecHeight = this._api.getHeight();
  18175. var mediaList = this._mediaList;
  18176. var mediaDefault = this._mediaDefault;
  18177. var indices = [];
  18178. var result = []; // No media defined.
  18179. if (!mediaList.length && !mediaDefault) {
  18180. return result;
  18181. } // Multi media may be applied, the latter defined media has higher priority.
  18182. for (var i = 0, len = mediaList.length; i < len; i++) {
  18183. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18184. indices.push(i);
  18185. }
  18186. } // FIXME
  18187. // Whether mediaDefault should force users to provide? Otherwise
  18188. // the change by media query can not be recorvered.
  18189. if (!indices.length && mediaDefault) {
  18190. indices = [-1];
  18191. }
  18192. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18193. result = map(indices, function (index) {
  18194. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  18195. });
  18196. } // Otherwise return nothing.
  18197. this._currentMediaIndices = indices;
  18198. return result;
  18199. };
  18200. return OptionManager;
  18201. }();
  18202. /**
  18203. * [RAW_OPTION_PATTERNS]
  18204. * (Note: "series: []" represents all other props in `ECUnitOption`)
  18205. *
  18206. * (1) No prop "baseOption" declared:
  18207. * Root option is used as "baseOption" (except prop "options" and "media").
  18208. * ```js
  18209. * option = {
  18210. * series: [],
  18211. * timeline: {},
  18212. * options: [],
  18213. * };
  18214. * option = {
  18215. * series: [],
  18216. * media: {},
  18217. * };
  18218. * option = {
  18219. * series: [],
  18220. * timeline: {},
  18221. * options: [],
  18222. * media: {},
  18223. * }
  18224. * ```
  18225. *
  18226. * (2) Prop "baseOption" declared:
  18227. * If "baseOption" declared, `ECUnitOption` props can only be declared
  18228. * inside "baseOption" except prop "timeline" (compat ec2).
  18229. * ```js
  18230. * option = {
  18231. * baseOption: {
  18232. * timeline: {},
  18233. * series: [],
  18234. * },
  18235. * options: []
  18236. * };
  18237. * option = {
  18238. * baseOption: {
  18239. * series: [],
  18240. * },
  18241. * media: []
  18242. * };
  18243. * option = {
  18244. * baseOption: {
  18245. * timeline: {},
  18246. * series: [],
  18247. * },
  18248. * options: []
  18249. * media: []
  18250. * };
  18251. * option = {
  18252. * // ec3 compat ec2: allow (only) `timeline` declared
  18253. * // outside baseOption. Keep this setting for compat.
  18254. * timeline: {},
  18255. * baseOption: {
  18256. * series: [],
  18257. * },
  18258. * options: [],
  18259. * media: []
  18260. * };
  18261. * ```
  18262. */
  18263. function parseRawOption( // `rawOption` May be modified
  18264. rawOption, optionPreprocessorFuncs, isNew) {
  18265. var mediaList = [];
  18266. var mediaDefault;
  18267. var baseOption;
  18268. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  18269. var timelineOnRoot = rawOption.timeline;
  18270. var timelineOptionsOnRoot = rawOption.options;
  18271. var mediaOnRoot = rawOption.media;
  18272. var hasMedia = !!rawOption.media;
  18273. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  18274. if (declaredBaseOption) {
  18275. baseOption = declaredBaseOption; // For merge option.
  18276. if (!baseOption.timeline) {
  18277. baseOption.timeline = timelineOnRoot;
  18278. }
  18279. } // For convenience, enable to use the root option as the `baseOption`:
  18280. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  18281. else {
  18282. if (hasTimeline || hasMedia) {
  18283. rawOption.options = rawOption.media = null;
  18284. }
  18285. baseOption = rawOption;
  18286. }
  18287. if (hasMedia) {
  18288. if (isArray(mediaOnRoot)) {
  18289. each(mediaOnRoot, function (singleMedia) {
  18290. if ("development" !== 'production') {
  18291. // Real case of wrong config.
  18292. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  18293. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  18294. }
  18295. }
  18296. if (singleMedia && singleMedia.option) {
  18297. if (singleMedia.query) {
  18298. mediaList.push(singleMedia);
  18299. } else if (!mediaDefault) {
  18300. // Use the first media default.
  18301. mediaDefault = singleMedia;
  18302. }
  18303. }
  18304. });
  18305. } else {
  18306. if ("development" !== 'production') {
  18307. // Real case of wrong config.
  18308. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  18309. }
  18310. }
  18311. }
  18312. doPreprocess(baseOption);
  18313. each(timelineOptionsOnRoot, function (option) {
  18314. return doPreprocess(option);
  18315. });
  18316. each(mediaList, function (media) {
  18317. return doPreprocess(media.option);
  18318. });
  18319. function doPreprocess(option) {
  18320. each(optionPreprocessorFuncs, function (preProcess) {
  18321. preProcess(option, isNew);
  18322. });
  18323. }
  18324. return {
  18325. baseOption: baseOption,
  18326. timelineOptions: timelineOptionsOnRoot || [],
  18327. mediaDefault: mediaDefault,
  18328. mediaList: mediaList
  18329. };
  18330. }
  18331. /**
  18332. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18333. * Support: width, height, aspectRatio
  18334. * Can use max or min as prefix.
  18335. */
  18336. function applyMediaQuery(query, ecWidth, ecHeight) {
  18337. var realMap = {
  18338. width: ecWidth,
  18339. height: ecHeight,
  18340. aspectratio: ecWidth / ecHeight // lower case for convenience.
  18341. };
  18342. var applicable = true;
  18343. each(query, function (value, attr) {
  18344. var matched = attr.match(QUERY_REG);
  18345. if (!matched || !matched[1] || !matched[2]) {
  18346. return;
  18347. }
  18348. var operator = matched[1];
  18349. var realAttr = matched[2].toLowerCase();
  18350. if (!compare(realMap[realAttr], value, operator)) {
  18351. applicable = false;
  18352. }
  18353. });
  18354. return applicable;
  18355. }
  18356. function compare(real, expect, operator) {
  18357. if (operator === 'min') {
  18358. return real >= expect;
  18359. } else if (operator === 'max') {
  18360. return real <= expect;
  18361. } else {
  18362. // Equals
  18363. return real === expect;
  18364. }
  18365. }
  18366. function indicesEquals(indices1, indices2) {
  18367. // indices is always order by asc and has only finite number.
  18368. return indices1.join(',') === indices2.join(',');
  18369. }
  18370. var each$2 = each;
  18371. var isObject$1 = isObject;
  18372. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18373. function compatEC2ItemStyle(opt) {
  18374. var itemStyleOpt = opt && opt.itemStyle;
  18375. if (!itemStyleOpt) {
  18376. return;
  18377. }
  18378. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18379. var styleName = POSSIBLE_STYLES[i];
  18380. var normalItemStyleOpt = itemStyleOpt.normal;
  18381. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18382. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18383. if ("development" !== 'production') {
  18384. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  18385. }
  18386. opt[styleName] = opt[styleName] || {};
  18387. if (!opt[styleName].normal) {
  18388. opt[styleName].normal = normalItemStyleOpt[styleName];
  18389. } else {
  18390. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18391. }
  18392. normalItemStyleOpt[styleName] = null;
  18393. }
  18394. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18395. if ("development" !== 'production') {
  18396. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  18397. }
  18398. opt[styleName] = opt[styleName] || {};
  18399. if (!opt[styleName].emphasis) {
  18400. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18401. } else {
  18402. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18403. }
  18404. emphasisItemStyleOpt[styleName] = null;
  18405. }
  18406. }
  18407. }
  18408. function convertNormalEmphasis(opt, optType, useExtend) {
  18409. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18410. var normalOpt = opt[optType].normal;
  18411. var emphasisOpt = opt[optType].emphasis;
  18412. if (normalOpt) {
  18413. if ("development" !== 'production') {
  18414. // eslint-disable-next-line max-len
  18415. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  18416. } // Timeline controlStyle has other properties besides normal and emphasis
  18417. if (useExtend) {
  18418. opt[optType].normal = opt[optType].emphasis = null;
  18419. defaults(opt[optType], normalOpt);
  18420. } else {
  18421. opt[optType] = normalOpt;
  18422. }
  18423. }
  18424. if (emphasisOpt) {
  18425. if ("development" !== 'production') {
  18426. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  18427. }
  18428. opt.emphasis = opt.emphasis || {};
  18429. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  18430. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  18431. if (emphasisOpt.focus) {
  18432. opt.emphasis.focus = emphasisOpt.focus;
  18433. }
  18434. if (emphasisOpt.blurScope) {
  18435. opt.emphasis.blurScope = emphasisOpt.blurScope;
  18436. }
  18437. }
  18438. }
  18439. }
  18440. function removeEC3NormalStatus(opt) {
  18441. convertNormalEmphasis(opt, 'itemStyle');
  18442. convertNormalEmphasis(opt, 'lineStyle');
  18443. convertNormalEmphasis(opt, 'areaStyle');
  18444. convertNormalEmphasis(opt, 'label');
  18445. convertNormalEmphasis(opt, 'labelLine'); // treemap
  18446. convertNormalEmphasis(opt, 'upperLabel'); // graph
  18447. convertNormalEmphasis(opt, 'edgeLabel');
  18448. }
  18449. function compatTextStyle(opt, propName) {
  18450. // Check whether is not object (string\null\undefined ...)
  18451. var labelOptSingle = isObject$1(opt) && opt[propName];
  18452. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  18453. if (textStyle) {
  18454. if ("development" !== 'production') {
  18455. // eslint-disable-next-line max-len
  18456. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  18457. }
  18458. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18459. var textPropName = TEXT_STYLE_OPTIONS[i];
  18460. if (textStyle.hasOwnProperty(textPropName)) {
  18461. labelOptSingle[textPropName] = textStyle[textPropName];
  18462. }
  18463. }
  18464. }
  18465. }
  18466. function compatEC3CommonStyles(opt) {
  18467. if (opt) {
  18468. removeEC3NormalStatus(opt);
  18469. compatTextStyle(opt, 'label');
  18470. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18471. }
  18472. }
  18473. function processSeries(seriesOpt) {
  18474. if (!isObject$1(seriesOpt)) {
  18475. return;
  18476. }
  18477. compatEC2ItemStyle(seriesOpt);
  18478. removeEC3NormalStatus(seriesOpt);
  18479. compatTextStyle(seriesOpt, 'label'); // treemap
  18480. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  18481. compatTextStyle(seriesOpt, 'edgeLabel');
  18482. if (seriesOpt.emphasis) {
  18483. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  18484. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  18485. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18486. }
  18487. var markPoint = seriesOpt.markPoint;
  18488. if (markPoint) {
  18489. compatEC2ItemStyle(markPoint);
  18490. compatEC3CommonStyles(markPoint);
  18491. }
  18492. var markLine = seriesOpt.markLine;
  18493. if (markLine) {
  18494. compatEC2ItemStyle(markLine);
  18495. compatEC3CommonStyles(markLine);
  18496. }
  18497. var markArea = seriesOpt.markArea;
  18498. if (markArea) {
  18499. compatEC3CommonStyles(markArea);
  18500. }
  18501. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  18502. // then the backward compat based on option type will not be performed.
  18503. if (seriesOpt.type === 'graph') {
  18504. data = data || seriesOpt.nodes;
  18505. var edgeData = seriesOpt.links || seriesOpt.edges;
  18506. if (edgeData && !isTypedArray(edgeData)) {
  18507. for (var i = 0; i < edgeData.length; i++) {
  18508. compatEC3CommonStyles(edgeData[i]);
  18509. }
  18510. }
  18511. each(seriesOpt.categories, function (opt) {
  18512. removeEC3NormalStatus(opt);
  18513. });
  18514. }
  18515. if (data && !isTypedArray(data)) {
  18516. for (var i = 0; i < data.length; i++) {
  18517. compatEC3CommonStyles(data[i]);
  18518. }
  18519. } // mark point data
  18520. markPoint = seriesOpt.markPoint;
  18521. if (markPoint && markPoint.data) {
  18522. var mpData = markPoint.data;
  18523. for (var i = 0; i < mpData.length; i++) {
  18524. compatEC3CommonStyles(mpData[i]);
  18525. }
  18526. } // mark line data
  18527. markLine = seriesOpt.markLine;
  18528. if (markLine && markLine.data) {
  18529. var mlData = markLine.data;
  18530. for (var i = 0; i < mlData.length; i++) {
  18531. if (isArray(mlData[i])) {
  18532. compatEC3CommonStyles(mlData[i][0]);
  18533. compatEC3CommonStyles(mlData[i][1]);
  18534. } else {
  18535. compatEC3CommonStyles(mlData[i]);
  18536. }
  18537. }
  18538. } // Series
  18539. if (seriesOpt.type === 'gauge') {
  18540. compatTextStyle(seriesOpt, 'axisLabel');
  18541. compatTextStyle(seriesOpt, 'title');
  18542. compatTextStyle(seriesOpt, 'detail');
  18543. } else if (seriesOpt.type === 'treemap') {
  18544. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18545. each(seriesOpt.levels, function (opt) {
  18546. removeEC3NormalStatus(opt);
  18547. });
  18548. } else if (seriesOpt.type === 'tree') {
  18549. removeEC3NormalStatus(seriesOpt.leaves);
  18550. } // sunburst starts from ec4, so it does not need to compat levels.
  18551. }
  18552. function toArr(o) {
  18553. return isArray(o) ? o : o ? [o] : [];
  18554. }
  18555. function toObj(o) {
  18556. return (isArray(o) ? o[0] : o) || {};
  18557. }
  18558. function globalCompatStyle(option, isTheme) {
  18559. each$2(toArr(option.series), function (seriesOpt) {
  18560. isObject$1(seriesOpt) && processSeries(seriesOpt);
  18561. });
  18562. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18563. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18564. each$2(axes, function (axisName) {
  18565. each$2(toArr(option[axisName]), function (axisOpt) {
  18566. if (axisOpt) {
  18567. compatTextStyle(axisOpt, 'axisLabel');
  18568. compatTextStyle(axisOpt.axisPointer, 'label');
  18569. }
  18570. });
  18571. });
  18572. each$2(toArr(option.parallel), function (parallelOpt) {
  18573. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18574. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18575. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18576. });
  18577. each$2(toArr(option.calendar), function (calendarOpt) {
  18578. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18579. compatTextStyle(calendarOpt, 'dayLabel');
  18580. compatTextStyle(calendarOpt, 'monthLabel');
  18581. compatTextStyle(calendarOpt, 'yearLabel');
  18582. }); // radar.name.textStyle
  18583. each$2(toArr(option.radar), function (radarOpt) {
  18584. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  18585. if (radarOpt.name && radarOpt.axisName == null) {
  18586. radarOpt.axisName = radarOpt.name;
  18587. delete radarOpt.name;
  18588. if ("development" !== 'production') {
  18589. deprecateLog('name property in radar component has been changed to axisName');
  18590. }
  18591. }
  18592. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  18593. radarOpt.axisNameGap = radarOpt.nameGap;
  18594. delete radarOpt.nameGap;
  18595. if ("development" !== 'production') {
  18596. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  18597. }
  18598. }
  18599. if ("development" !== 'production') {
  18600. each$2(radarOpt.indicator, function (indicatorOpt) {
  18601. if (indicatorOpt.text) {
  18602. deprecateReplaceLog('text', 'name', 'radar.indicator');
  18603. }
  18604. });
  18605. }
  18606. });
  18607. each$2(toArr(option.geo), function (geoOpt) {
  18608. if (isObject$1(geoOpt)) {
  18609. compatEC3CommonStyles(geoOpt);
  18610. each$2(toArr(geoOpt.regions), function (regionObj) {
  18611. compatEC3CommonStyles(regionObj);
  18612. });
  18613. }
  18614. });
  18615. each$2(toArr(option.timeline), function (timelineOpt) {
  18616. compatEC3CommonStyles(timelineOpt);
  18617. convertNormalEmphasis(timelineOpt, 'label');
  18618. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18619. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18620. var data = timelineOpt.data;
  18621. isArray(data) && each(data, function (item) {
  18622. if (isObject(item)) {
  18623. convertNormalEmphasis(item, 'label');
  18624. convertNormalEmphasis(item, 'itemStyle');
  18625. }
  18626. });
  18627. });
  18628. each$2(toArr(option.toolbox), function (toolboxOpt) {
  18629. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18630. each$2(toolboxOpt.feature, function (featureOpt) {
  18631. convertNormalEmphasis(featureOpt, 'iconStyle');
  18632. });
  18633. });
  18634. compatTextStyle(toObj(option.axisPointer), 'label');
  18635. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  18636. // storedLogs = {};
  18637. }
  18638. function get(opt, path) {
  18639. var pathArr = path.split(',');
  18640. var obj = opt;
  18641. for (var i = 0; i < pathArr.length; i++) {
  18642. obj = obj && obj[pathArr[i]];
  18643. if (obj == null) {
  18644. break;
  18645. }
  18646. }
  18647. return obj;
  18648. }
  18649. function set$1(opt, path, val, overwrite) {
  18650. var pathArr = path.split(',');
  18651. var obj = opt;
  18652. var key;
  18653. var i = 0;
  18654. for (; i < pathArr.length - 1; i++) {
  18655. key = pathArr[i];
  18656. if (obj[key] == null) {
  18657. obj[key] = {};
  18658. }
  18659. obj = obj[key];
  18660. }
  18661. if (overwrite || obj[pathArr[i]] == null) {
  18662. obj[pathArr[i]] = val;
  18663. }
  18664. }
  18665. function compatLayoutProperties(option) {
  18666. option && each(LAYOUT_PROPERTIES, function (prop) {
  18667. if (prop[0] in option && !(prop[1] in option)) {
  18668. option[prop[1]] = option[prop[0]];
  18669. }
  18670. });
  18671. }
  18672. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18673. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18674. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  18675. function compatBarItemStyle(option) {
  18676. var itemStyle = option && option.itemStyle;
  18677. if (itemStyle) {
  18678. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  18679. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  18680. var newName = BAR_ITEM_STYLE_MAP[i][0];
  18681. if (itemStyle[oldName] != null) {
  18682. itemStyle[newName] = itemStyle[oldName];
  18683. if ("development" !== 'production') {
  18684. deprecateReplaceLog(oldName, newName);
  18685. }
  18686. }
  18687. }
  18688. }
  18689. }
  18690. function compatPieLabel(option) {
  18691. if (!option) {
  18692. return;
  18693. }
  18694. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18695. if ("development" !== 'production') {
  18696. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18697. }
  18698. option.edgeDistance = option.margin;
  18699. }
  18700. }
  18701. function compatSunburstState(option) {
  18702. if (!option) {
  18703. return;
  18704. }
  18705. if (option.downplay && !option.blur) {
  18706. option.blur = option.downplay;
  18707. if ("development" !== 'production') {
  18708. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18709. }
  18710. }
  18711. }
  18712. function compatGraphFocus(option) {
  18713. if (!option) {
  18714. return;
  18715. }
  18716. if (option.focusNodeAdjacency != null) {
  18717. option.emphasis = option.emphasis || {};
  18718. if (option.emphasis.focus == null) {
  18719. if ("development" !== 'production') {
  18720. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18721. }
  18722. option.emphasis.focus = 'adjacency';
  18723. }
  18724. }
  18725. }
  18726. function traverseTree(data, cb) {
  18727. if (data) {
  18728. for (var i = 0; i < data.length; i++) {
  18729. cb(data[i]);
  18730. data[i] && traverseTree(data[i].children, cb);
  18731. }
  18732. }
  18733. }
  18734. function globalBackwardCompat(option, isTheme) {
  18735. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  18736. option.series = normalizeToArray(option.series);
  18737. each(option.series, function (seriesOpt) {
  18738. if (!isObject(seriesOpt)) {
  18739. return;
  18740. }
  18741. var seriesType = seriesOpt.type;
  18742. if (seriesType === 'line') {
  18743. if (seriesOpt.clipOverflow != null) {
  18744. seriesOpt.clip = seriesOpt.clipOverflow;
  18745. if ("development" !== 'production') {
  18746. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18747. }
  18748. }
  18749. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18750. if (seriesOpt.clockWise != null) {
  18751. seriesOpt.clockwise = seriesOpt.clockWise;
  18752. if ("development" !== 'production') {
  18753. deprecateReplaceLog('clockWise', 'clockwise');
  18754. }
  18755. }
  18756. compatPieLabel(seriesOpt.label);
  18757. var data = seriesOpt.data;
  18758. if (data && !isTypedArray(data)) {
  18759. for (var i = 0; i < data.length; i++) {
  18760. compatPieLabel(data[i]);
  18761. }
  18762. }
  18763. if (seriesOpt.hoverOffset != null) {
  18764. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18765. if (seriesOpt.emphasis.scaleSize = null) {
  18766. if ("development" !== 'production') {
  18767. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18768. }
  18769. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18770. }
  18771. }
  18772. } else if (seriesType === 'gauge') {
  18773. var pointerColor = get(seriesOpt, 'pointer.color');
  18774. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18775. } else if (seriesType === 'bar') {
  18776. compatBarItemStyle(seriesOpt);
  18777. compatBarItemStyle(seriesOpt.backgroundStyle);
  18778. compatBarItemStyle(seriesOpt.emphasis);
  18779. var data = seriesOpt.data;
  18780. if (data && !isTypedArray(data)) {
  18781. for (var i = 0; i < data.length; i++) {
  18782. if (typeof data[i] === 'object') {
  18783. compatBarItemStyle(data[i]);
  18784. compatBarItemStyle(data[i] && data[i].emphasis);
  18785. }
  18786. }
  18787. }
  18788. } else if (seriesType === 'sunburst') {
  18789. var highlightPolicy = seriesOpt.highlightPolicy;
  18790. if (highlightPolicy) {
  18791. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18792. if (!seriesOpt.emphasis.focus) {
  18793. seriesOpt.emphasis.focus = highlightPolicy;
  18794. if ("development" !== 'production') {
  18795. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18796. }
  18797. }
  18798. }
  18799. compatSunburstState(seriesOpt);
  18800. traverseTree(seriesOpt.data, compatSunburstState);
  18801. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18802. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  18803. } else if (seriesType === 'map') {
  18804. if (seriesOpt.mapType && !seriesOpt.map) {
  18805. if ("development" !== 'production') {
  18806. deprecateReplaceLog('mapType', 'map', 'map');
  18807. }
  18808. seriesOpt.map = seriesOpt.mapType;
  18809. }
  18810. if (seriesOpt.mapLocation) {
  18811. if ("development" !== 'production') {
  18812. deprecateLog('`mapLocation` is not used anymore.');
  18813. }
  18814. defaults(seriesOpt, seriesOpt.mapLocation);
  18815. }
  18816. }
  18817. if (seriesOpt.hoverAnimation != null) {
  18818. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18819. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18820. if ("development" !== 'production') {
  18821. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18822. }
  18823. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18824. }
  18825. }
  18826. compatLayoutProperties(seriesOpt);
  18827. }); // dataRange has changed to visualMap
  18828. if (option.dataRange) {
  18829. option.visualMap = option.dataRange;
  18830. }
  18831. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18832. var options = option[componentName];
  18833. if (options) {
  18834. if (!isArray(options)) {
  18835. options = [options];
  18836. }
  18837. each(options, function (option) {
  18838. compatLayoutProperties(option);
  18839. });
  18840. }
  18841. });
  18842. }
  18843. // data processing stage is blocked in stream.
  18844. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18845. // (2) Only register once when import repeatedly.
  18846. // Should be executed after series is filtered and before stack calculation.
  18847. function dataStack(ecModel) {
  18848. var stackInfoMap = createHashMap();
  18849. ecModel.eachSeries(function (seriesModel) {
  18850. var stack = seriesModel.get('stack'); // Compatible: when `stack` is set as '', do not stack.
  18851. if (stack) {
  18852. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18853. var data = seriesModel.getData();
  18854. var stackInfo = {
  18855. // Used for calculate axis extent automatically.
  18856. // TODO: Type getCalculationInfo return more specific type?
  18857. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18858. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18859. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18860. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18861. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18862. data: data,
  18863. seriesModel: seriesModel
  18864. }; // If stacked on axis that do not support data stack.
  18865. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18866. return;
  18867. }
  18868. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18869. stackInfoList.push(stackInfo);
  18870. }
  18871. });
  18872. stackInfoMap.each(calculateStack);
  18873. }
  18874. function calculateStack(stackInfoList) {
  18875. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18876. var resultVal = [];
  18877. var resultNaN = [NaN, NaN];
  18878. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18879. var targetData = targetStackInfo.data;
  18880. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18881. var stackStrategy = targetStackInfo.seriesModel.get('stackStrategy') || 'samesign'; // Should not write on raw data, because stack series model list changes
  18882. // depending on legend selection.
  18883. targetData.modify(dims, function (v0, v1, dataIndex) {
  18884. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18885. // should also be NaN, to draw a appropriate belt area.
  18886. if (isNaN(sum)) {
  18887. return resultNaN;
  18888. }
  18889. var byValue;
  18890. var stackedDataRawIndex;
  18891. if (isStackedByIndex) {
  18892. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18893. } else {
  18894. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18895. } // If stackOver is NaN, chart view will render point on value start.
  18896. var stackedOver = NaN;
  18897. for (var j = idxInStack - 1; j >= 0; j--) {
  18898. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18899. if (!isStackedByIndex) {
  18900. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18901. }
  18902. if (stackedDataRawIndex >= 0) {
  18903. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18904. if (stackStrategy === 'all' // single stack group
  18905. || stackStrategy === 'positive' && val > 0 || stackStrategy === 'negative' && val < 0 || stackStrategy === 'samesign' && sum >= 0 && val > 0 // All positive stack
  18906. || stackStrategy === 'samesign' && sum <= 0 && val < 0 // All negative stack
  18907. ) {
  18908. // The sum has to be very small to be affected by the
  18909. // floating arithmetic problem. An incorrect result will probably
  18910. // cause axis min/max to be filtered incorrectly.
  18911. sum = addSafe(sum, val);
  18912. stackedOver = val;
  18913. break;
  18914. }
  18915. }
  18916. }
  18917. resultVal[0] = sum;
  18918. resultVal[1] = stackedOver;
  18919. return resultVal;
  18920. });
  18921. });
  18922. }
  18923. var SourceImpl =
  18924. /** @class */
  18925. function () {
  18926. function SourceImpl(fields) {
  18927. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18928. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  18929. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18930. this.startIndex = fields.startIndex || 0;
  18931. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18932. this.metaRawOption = fields.metaRawOption;
  18933. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  18934. if (dimensionsDefine) {
  18935. for (var i = 0; i < dimensionsDefine.length; i++) {
  18936. var dim = dimensionsDefine[i];
  18937. if (dim.type == null) {
  18938. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  18939. dim.type = 'ordinal';
  18940. }
  18941. }
  18942. }
  18943. }
  18944. }
  18945. return SourceImpl;
  18946. }();
  18947. function isSourceInstance(val) {
  18948. return val instanceof SourceImpl;
  18949. }
  18950. /**
  18951. * Create a source from option.
  18952. * NOTE: Created source is immutable. Don't change any properties in it.
  18953. */
  18954. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  18955. sourceFormat) {
  18956. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18957. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18958. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18959. var source = new SourceImpl({
  18960. data: sourceData,
  18961. sourceFormat: sourceFormat,
  18962. seriesLayoutBy: seriesLayoutBy,
  18963. dimensionsDefine: determined.dimensionsDefine,
  18964. startIndex: determined.startIndex,
  18965. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18966. metaRawOption: clone(thisMetaRawOption)
  18967. });
  18968. return source;
  18969. }
  18970. /**
  18971. * Wrap original series data for some compatibility cases.
  18972. */
  18973. function createSourceFromSeriesDataOption(data) {
  18974. return new SourceImpl({
  18975. data: data,
  18976. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18977. });
  18978. }
  18979. /**
  18980. * Clone source but excludes source data.
  18981. */
  18982. function cloneSourceShallow(source) {
  18983. return new SourceImpl({
  18984. data: source.data,
  18985. sourceFormat: source.sourceFormat,
  18986. seriesLayoutBy: source.seriesLayoutBy,
  18987. dimensionsDefine: clone(source.dimensionsDefine),
  18988. startIndex: source.startIndex,
  18989. dimensionsDetectedCount: source.dimensionsDetectedCount
  18990. });
  18991. }
  18992. /**
  18993. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18994. */
  18995. function detectSourceFormat(data) {
  18996. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18997. if (isTypedArray(data)) {
  18998. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18999. } else if (isArray(data)) {
  19000. // FIXME Whether tolerate null in top level array?
  19001. if (data.length === 0) {
  19002. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  19003. }
  19004. for (var i = 0, len = data.length; i < len; i++) {
  19005. var item = data[i];
  19006. if (item == null) {
  19007. continue;
  19008. } else if (isArray(item)) {
  19009. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  19010. break;
  19011. } else if (isObject(item)) {
  19012. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  19013. break;
  19014. }
  19015. }
  19016. } else if (isObject(data)) {
  19017. for (var key in data) {
  19018. if (hasOwn(data, key) && isArrayLike(data[key])) {
  19019. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  19020. break;
  19021. }
  19022. }
  19023. }
  19024. return sourceFormat;
  19025. }
  19026. /**
  19027. * Determine the source definitions from data standalone dimensions definitions
  19028. * are not specified.
  19029. */
  19030. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  19031. // {
  19032. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  19033. // }
  19034. // in `dataset` or `series`
  19035. dimensionsDefine) {
  19036. var dimensionsDetectedCount;
  19037. var startIndex; // PENDING: Could data be null/undefined here?
  19038. // currently, if `dataset.source` not specified, error thrown.
  19039. // if `series.data` not specified, nothing rendered without error thrown.
  19040. // Should test these cases.
  19041. if (!data) {
  19042. return {
  19043. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19044. startIndex: startIndex,
  19045. dimensionsDetectedCount: dimensionsDetectedCount
  19046. };
  19047. }
  19048. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19049. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  19050. // Caution: consider a line with 5 string and 1 number,
  19051. // it still can not be sure it is a head, because the
  19052. // 5 string may be 5 values of category columns.
  19053. if (sourceHeader === 'auto' || sourceHeader == null) {
  19054. arrayRowsTravelFirst(function (val) {
  19055. // '-' is regarded as null/undefined.
  19056. if (val != null && val !== '-') {
  19057. if (isString(val)) {
  19058. startIndex == null && (startIndex = 1);
  19059. } else {
  19060. startIndex = 0;
  19061. }
  19062. } // 10 is an experience number, avoid long loop.
  19063. }, seriesLayoutBy, dataArrayRows, 10);
  19064. } else {
  19065. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  19066. }
  19067. if (!dimensionsDefine && startIndex === 1) {
  19068. dimensionsDefine = [];
  19069. arrayRowsTravelFirst(function (val, index) {
  19070. dimensionsDefine[index] = val != null ? val + '' : '';
  19071. }, seriesLayoutBy, dataArrayRows, Infinity);
  19072. }
  19073. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  19074. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19075. if (!dimensionsDefine) {
  19076. dimensionsDefine = objectRowsCollectDimensions(data);
  19077. }
  19078. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  19079. if (!dimensionsDefine) {
  19080. dimensionsDefine = [];
  19081. each(data, function (colArr, key) {
  19082. dimensionsDefine.push(key);
  19083. });
  19084. }
  19085. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19086. var value0 = getDataItemValue(data[0]);
  19087. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  19088. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19089. if ("development" !== 'production') {
  19090. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  19091. }
  19092. }
  19093. return {
  19094. startIndex: startIndex,
  19095. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19096. dimensionsDetectedCount: dimensionsDetectedCount
  19097. };
  19098. }
  19099. function objectRowsCollectDimensions(data) {
  19100. var firstIndex = 0;
  19101. var obj;
  19102. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  19103. if (obj) {
  19104. return keys(obj);
  19105. }
  19106. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  19107. // which is reasonable. But dimension name is duplicated.
  19108. // Returns undefined or an array contains only object without null/undefined or string.
  19109. function normalizeDimensionsOption(dimensionsDefine) {
  19110. if (!dimensionsDefine) {
  19111. // The meaning of null/undefined is different from empty array.
  19112. return;
  19113. }
  19114. var nameMap = createHashMap();
  19115. return map(dimensionsDefine, function (rawItem, index) {
  19116. rawItem = isObject(rawItem) ? rawItem : {
  19117. name: rawItem
  19118. }; // Other fields will be discarded.
  19119. var item = {
  19120. name: rawItem.name,
  19121. displayName: rawItem.displayName,
  19122. type: rawItem.type
  19123. }; // User can set null in dimensions.
  19124. // We don't auto specify name, otherwise a given name may
  19125. // cause it to be referred unexpectedly.
  19126. if (item.name == null) {
  19127. return item;
  19128. } // Also consider number form like 2012.
  19129. item.name += ''; // User may also specify displayName.
  19130. // displayName will always exists except user not
  19131. // specified or dim name is not specified or detected.
  19132. // (A auto generated dim name will not be used as
  19133. // displayName).
  19134. if (item.displayName == null) {
  19135. item.displayName = item.name;
  19136. }
  19137. var exist = nameMap.get(item.name);
  19138. if (!exist) {
  19139. nameMap.set(item.name, {
  19140. count: 1
  19141. });
  19142. } else {
  19143. item.name += '-' + exist.count++;
  19144. }
  19145. return item;
  19146. });
  19147. }
  19148. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  19149. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  19150. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19151. cb(data[i] ? data[i][0] : null, i);
  19152. }
  19153. } else {
  19154. var value0 = data[0] || [];
  19155. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  19156. cb(value0[i], i);
  19157. }
  19158. }
  19159. }
  19160. function shouldRetrieveDataByName(source) {
  19161. var sourceFormat = source.sourceFormat;
  19162. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  19163. }
  19164. /*
  19165. * Licensed to the Apache Software Foundation (ASF) under one
  19166. * or more contributor license agreements. See the NOTICE file
  19167. * distributed with this work for additional information
  19168. * regarding copyright ownership. The ASF licenses this file
  19169. * to you under the Apache License, Version 2.0 (the
  19170. * "License"); you may not use this file except in compliance
  19171. * with the License. You may obtain a copy of the License at
  19172. *
  19173. * http://www.apache.org/licenses/LICENSE-2.0
  19174. *
  19175. * Unless required by applicable law or agreed to in writing,
  19176. * software distributed under the License is distributed on an
  19177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19178. * KIND, either express or implied. See the License for the
  19179. * specific language governing permissions and limitations
  19180. * under the License.
  19181. */
  19182. /**
  19183. * AUTO-GENERATED FILE. DO NOT MODIFY.
  19184. */
  19185. /*
  19186. * Licensed to the Apache Software Foundation (ASF) under one
  19187. * or more contributor license agreements. See the NOTICE file
  19188. * distributed with this work for additional information
  19189. * regarding copyright ownership. The ASF licenses this file
  19190. * to you under the Apache License, Version 2.0 (the
  19191. * "License"); you may not use this file except in compliance
  19192. * with the License. You may obtain a copy of the License at
  19193. *
  19194. * http://www.apache.org/licenses/LICENSE-2.0
  19195. *
  19196. * Unless required by applicable law or agreed to in writing,
  19197. * software distributed under the License is distributed on an
  19198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19199. * KIND, either express or implied. See the License for the
  19200. * specific language governing permissions and limitations
  19201. * under the License.
  19202. */
  19203. var _a, _b, _c; // TODO
  19204. var providerMethods;
  19205. var mountMethods;
  19206. /**
  19207. * If normal array used, mutable chunk size is supported.
  19208. * If typed array used, chunk size must be fixed.
  19209. */
  19210. var DefaultDataProvider =
  19211. /** @class */
  19212. function () {
  19213. function DefaultDataProvider(sourceParam, dimSize) {
  19214. // let source: Source;
  19215. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  19216. this._source = source;
  19217. var data = this._data = source.data; // Typed array. TODO IE10+?
  19218. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19219. if ("development" !== 'production') {
  19220. if (dimSize == null) {
  19221. throw new Error('Typed array data must specify dimension size');
  19222. }
  19223. }
  19224. this._offset = 0;
  19225. this._dimSize = dimSize;
  19226. this._data = data;
  19227. }
  19228. mountMethods(this, data, source);
  19229. }
  19230. DefaultDataProvider.prototype.getSource = function () {
  19231. return this._source;
  19232. };
  19233. DefaultDataProvider.prototype.count = function () {
  19234. return 0;
  19235. };
  19236. DefaultDataProvider.prototype.getItem = function (idx, out) {
  19237. return;
  19238. };
  19239. DefaultDataProvider.prototype.appendData = function (newData) {};
  19240. DefaultDataProvider.prototype.clean = function () {};
  19241. DefaultDataProvider.protoInitialize = function () {
  19242. // PENDING: To avoid potential incompat (e.g., prototype
  19243. // is visited somewhere), still init them on prototype.
  19244. var proto = DefaultDataProvider.prototype;
  19245. proto.pure = false;
  19246. proto.persistent = true;
  19247. }();
  19248. DefaultDataProvider.internalField = function () {
  19249. var _a;
  19250. mountMethods = function (provider, data, source) {
  19251. var sourceFormat = source.sourceFormat;
  19252. var seriesLayoutBy = source.seriesLayoutBy;
  19253. var startIndex = source.startIndex;
  19254. var dimsDef = source.dimensionsDefine;
  19255. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19256. if ("development" !== 'production') {
  19257. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19258. }
  19259. extend(provider, methods);
  19260. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19261. provider.getItem = getItemForTypedArray;
  19262. provider.count = countForTypedArray;
  19263. provider.fillStorage = fillStorageForTypedArray;
  19264. } else {
  19265. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  19266. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  19267. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  19268. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  19269. }
  19270. };
  19271. var getItemForTypedArray = function (idx, out) {
  19272. idx = idx - this._offset;
  19273. out = out || [];
  19274. var data = this._data;
  19275. var dimSize = this._dimSize;
  19276. var offset = dimSize * idx;
  19277. for (var i = 0; i < dimSize; i++) {
  19278. out[i] = data[offset + i];
  19279. }
  19280. return out;
  19281. };
  19282. var fillStorageForTypedArray = function (start, end, storage, extent) {
  19283. var data = this._data;
  19284. var dimSize = this._dimSize;
  19285. for (var dim = 0; dim < dimSize; dim++) {
  19286. var dimExtent = extent[dim];
  19287. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  19288. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  19289. var count = end - start;
  19290. var arr = storage[dim];
  19291. for (var i = 0; i < count; i++) {
  19292. // appendData with TypedArray will always do replace in provider.
  19293. var val = data[i * dimSize + dim];
  19294. arr[start + i] = val;
  19295. val < min && (min = val);
  19296. val > max && (max = val);
  19297. }
  19298. dimExtent[0] = min;
  19299. dimExtent[1] = max;
  19300. }
  19301. };
  19302. var countForTypedArray = function () {
  19303. return this._data ? this._data.length / this._dimSize : 0;
  19304. };
  19305. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  19306. pure: true,
  19307. appendData: appendDataSimply
  19308. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  19309. pure: true,
  19310. appendData: function () {
  19311. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19312. }
  19313. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  19314. pure: true,
  19315. appendData: appendDataSimply
  19316. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  19317. pure: true,
  19318. appendData: function (newData) {
  19319. var data = this._data;
  19320. each(newData, function (newCol, key) {
  19321. var oldCol = data[key] || (data[key] = []);
  19322. for (var i = 0; i < (newCol || []).length; i++) {
  19323. oldCol.push(newCol[i]);
  19324. }
  19325. });
  19326. }
  19327. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  19328. appendData: appendDataSimply
  19329. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  19330. persistent: false,
  19331. pure: true,
  19332. appendData: function (newData) {
  19333. if ("development" !== 'production') {
  19334. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  19335. }
  19336. this._data = newData;
  19337. },
  19338. // Clean self if data is already used.
  19339. clean: function () {
  19340. // PENDING
  19341. this._offset += this.count();
  19342. this._data = null;
  19343. }
  19344. }, _a);
  19345. function appendDataSimply(newData) {
  19346. for (var i = 0; i < newData.length; i++) {
  19347. this._data.push(newData[i]);
  19348. }
  19349. }
  19350. }();
  19351. return DefaultDataProvider;
  19352. }();
  19353. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  19354. return rawData[idx];
  19355. };
  19356. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  19357. return rawData[idx + startIndex];
  19358. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  19359. idx += startIndex;
  19360. var item = out || [];
  19361. var data = rawData;
  19362. for (var i = 0; i < data.length; i++) {
  19363. var row = data[i];
  19364. item[i] = row ? row[idx] : null;
  19365. }
  19366. return item;
  19367. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  19368. var item = out || [];
  19369. for (var i = 0; i < dimsDef.length; i++) {
  19370. var dimName = dimsDef[i].name;
  19371. if ("development" !== 'production') {
  19372. if (dimName == null) {
  19373. throw new Error();
  19374. }
  19375. }
  19376. var col = rawData[dimName];
  19377. item[i] = col ? col[idx] : null;
  19378. }
  19379. return item;
  19380. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  19381. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  19382. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19383. if ("development" !== 'production') {
  19384. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19385. }
  19386. return method;
  19387. }
  19388. var countSimply = function (rawData, startIndex, dimsDef) {
  19389. return rawData.length;
  19390. };
  19391. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  19392. return Math.max(0, rawData.length - startIndex);
  19393. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  19394. var row = rawData[0];
  19395. return row ? Math.max(0, row.length - startIndex) : 0;
  19396. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  19397. var dimName = dimsDef[0].name;
  19398. if ("development" !== 'production') {
  19399. if (dimName == null) {
  19400. throw new Error();
  19401. }
  19402. }
  19403. var col = rawData[dimName];
  19404. return col ? col.length : 0;
  19405. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  19406. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  19407. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19408. if ("development" !== 'production') {
  19409. assert(method, 'Do not support count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19410. }
  19411. return method;
  19412. }
  19413. var getRawValueSimply = function (dataItem, dimIndex, property) {
  19414. return dataItem[dimIndex];
  19415. };
  19416. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  19417. return dataItem[property];
  19418. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  19419. // FIXME: In some case (markpoint in geo (geo-map.html)),
  19420. // dataItem is {coord: [...]}
  19421. var value = getDataItemValue(dataItem);
  19422. return !(value instanceof Array) ? value : value[dimIndex];
  19423. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  19424. function getRawSourceValueGetter(sourceFormat) {
  19425. var method = rawSourceValueGetterMap[sourceFormat];
  19426. if ("development" !== 'production') {
  19427. assert(method, 'Do not support get value on "' + sourceFormat + '".');
  19428. }
  19429. return method;
  19430. }
  19431. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  19432. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  19433. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19434. // Consider persistent.
  19435. // Caution: why use raw value to display on label or tooltip?
  19436. // A reason is to avoid format. For example time value we do not know
  19437. // how to format is expected. More over, if stack is used, calculated
  19438. // value may be 0.91000000001, which have brings trouble to display.
  19439. // TODO: consider how to treat null/undefined/NaN when display?
  19440. function retrieveRawValue(data, dataIndex, // If dimIndex is null/undefined, return OptionDataItem.
  19441. // Otherwise, return OptionDataValue.
  19442. dim) {
  19443. if (!data) {
  19444. return;
  19445. } // Consider data may be not persistent.
  19446. var dataItem = data.getRawDataItem(dataIndex);
  19447. if (dataItem == null) {
  19448. return;
  19449. }
  19450. var store = data.getStore();
  19451. var sourceFormat = store.getSource().sourceFormat;
  19452. if (dim != null) {
  19453. var dimIndex = data.getDimensionIndex(dim);
  19454. var property = store.getDimensionProperty(dimIndex);
  19455. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  19456. } else {
  19457. var result = dataItem;
  19458. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19459. result = getDataItemValue(dataItem);
  19460. }
  19461. return result;
  19462. }
  19463. }
  19464. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19465. var DataFormatMixin =
  19466. /** @class */
  19467. function () {
  19468. function DataFormatMixin() {}
  19469. /**
  19470. * Get params for formatter
  19471. */
  19472. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  19473. var data = this.getData(dataType);
  19474. var rawValue = this.getRawValue(dataIndex, dataType);
  19475. var rawDataIndex = data.getRawIndex(dataIndex);
  19476. var name = data.getName(dataIndex);
  19477. var itemOpt = data.getRawDataItem(dataIndex);
  19478. var style = data.getItemVisual(dataIndex, 'style');
  19479. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  19480. var borderColor = style && style.stroke;
  19481. var mainType = this.mainType;
  19482. var isSeries = mainType === 'series';
  19483. var userOutput = data.userOutput && data.userOutput.get();
  19484. return {
  19485. componentType: mainType,
  19486. componentSubType: this.subType,
  19487. componentIndex: this.componentIndex,
  19488. seriesType: isSeries ? this.subType : null,
  19489. seriesIndex: this.seriesIndex,
  19490. seriesId: isSeries ? this.id : null,
  19491. seriesName: isSeries ? this.name : null,
  19492. name: name,
  19493. dataIndex: rawDataIndex,
  19494. data: itemOpt,
  19495. dataType: dataType,
  19496. value: rawValue,
  19497. color: color,
  19498. borderColor: borderColor,
  19499. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  19500. encode: userOutput ? userOutput.encode : null,
  19501. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19502. $vars: ['seriesName', 'name', 'value']
  19503. };
  19504. };
  19505. /**
  19506. * Format label
  19507. * @param dataIndex
  19508. * @param status 'normal' by default
  19509. * @param dataType
  19510. * @param labelDimIndex Only used in some chart that
  19511. * use formatter in different dimensions, like radar.
  19512. * @param formatter Formatter given outside.
  19513. * @return return null/undefined if no formatter
  19514. */
  19515. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  19516. status = status || 'normal';
  19517. var data = this.getData(dataType);
  19518. var params = this.getDataParams(dataIndex, dataType);
  19519. if (extendParams) {
  19520. params.value = extendParams.interpolatedValue;
  19521. }
  19522. if (labelDimIndex != null && isArray(params.value)) {
  19523. params.value = params.value[labelDimIndex];
  19524. }
  19525. if (!formatter) {
  19526. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  19527. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  19528. }
  19529. if (isFunction(formatter)) {
  19530. params.status = status;
  19531. params.dimensionIndex = labelDimIndex;
  19532. return formatter(params);
  19533. } else if (isString(formatter)) {
  19534. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  19535. // Do not support '}' in dim name util have to.
  19536. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  19537. var len = dimStr.length;
  19538. var dimLoose = dimStr;
  19539. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  19540. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  19541. if ("development" !== 'production') {
  19542. if (isNaN(dimLoose)) {
  19543. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  19544. }
  19545. }
  19546. }
  19547. var val = retrieveRawValue(data, dataIndex, dimLoose);
  19548. if (extendParams && isArray(extendParams.interpolatedValue)) {
  19549. var dimIndex = data.getDimensionIndex(dimLoose);
  19550. if (dimIndex >= 0) {
  19551. val = extendParams.interpolatedValue[dimIndex];
  19552. }
  19553. }
  19554. return val != null ? val + '' : '';
  19555. });
  19556. }
  19557. };
  19558. /**
  19559. * Get raw value in option
  19560. */
  19561. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  19562. return retrieveRawValue(this.getData(dataType), idx);
  19563. };
  19564. /**
  19565. * Should be implemented.
  19566. * @param {number} dataIndex
  19567. * @param {boolean} [multipleSeries=false]
  19568. * @param {string} [dataType]
  19569. */
  19570. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19571. // Empty function
  19572. return;
  19573. };
  19574. return DataFormatMixin;
  19575. }();
  19576. // but guess little chance has been used outside. Do we need to backward
  19577. // compat it?
  19578. // type TooltipFormatResultLegacyObject = {
  19579. // // `html` means the markup language text, either in 'html' or 'richText'.
  19580. // // The name `html` is not appropriate because in 'richText' it is not a HTML
  19581. // // string. But still support it for backward compatibility.
  19582. // html: string;
  19583. // markers: Dictionary<ColorString>;
  19584. // };
  19585. /**
  19586. * For backward compat, normalize the return from `formatTooltip`.
  19587. */
  19588. function normalizeTooltipFormatResult(result) {
  19589. var markupText; // let markers: Dictionary<ColorString>;
  19590. var markupFragment;
  19591. if (isObject(result)) {
  19592. if (result.type) {
  19593. markupFragment = result;
  19594. } else {
  19595. if ("development" !== 'production') {
  19596. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  19597. }
  19598. } // else {
  19599. // markupText = (result as TooltipFormatResultLegacyObject).html;
  19600. // markers = (result as TooltipFormatResultLegacyObject).markers;
  19601. // if (markersExisting) {
  19602. // markers = zrUtil.merge(markersExisting, markers);
  19603. // }
  19604. // }
  19605. } else {
  19606. markupText = result;
  19607. }
  19608. return {
  19609. text: markupText,
  19610. // markers: markers || markersExisting,
  19611. frag: markupFragment
  19612. };
  19613. }
  19614. /**
  19615. * @param {Object} define
  19616. * @return See the return of `createTask`.
  19617. */
  19618. function createTask(define) {
  19619. return new Task(define);
  19620. }
  19621. var Task =
  19622. /** @class */
  19623. function () {
  19624. function Task(define) {
  19625. define = define || {};
  19626. this._reset = define.reset;
  19627. this._plan = define.plan;
  19628. this._count = define.count;
  19629. this._onDirty = define.onDirty;
  19630. this._dirty = true;
  19631. }
  19632. /**
  19633. * @param step Specified step.
  19634. * @param skip Skip customer perform call.
  19635. * @param modBy Sampling window size.
  19636. * @param modDataCount Sampling count.
  19637. * @return whether unfinished.
  19638. */
  19639. Task.prototype.perform = function (performArgs) {
  19640. var upTask = this._upstream;
  19641. var skip = performArgs && performArgs.skip; // TODO some refactor.
  19642. // Pull data. Must pull data each time, because context.data
  19643. // may be updated by Series.setData.
  19644. if (this._dirty && upTask) {
  19645. var context = this.context;
  19646. context.data = context.outputData = upTask.context.outputData;
  19647. }
  19648. if (this.__pipeline) {
  19649. this.__pipeline.currentTask = this;
  19650. }
  19651. var planResult;
  19652. if (this._plan && !skip) {
  19653. planResult = this._plan(this.context);
  19654. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19655. // elements uniformed distributed when progress, especially when moving or zooming.
  19656. var lastModBy = normalizeModBy(this._modBy);
  19657. var lastModDataCount = this._modDataCount || 0;
  19658. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19659. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19660. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19661. planResult = 'reset';
  19662. }
  19663. function normalizeModBy(val) {
  19664. !(val >= 1) && (val = 1); // jshint ignore:line
  19665. return val;
  19666. }
  19667. var forceFirstProgress;
  19668. if (this._dirty || planResult === 'reset') {
  19669. this._dirty = false;
  19670. forceFirstProgress = this._doReset(skip);
  19671. }
  19672. this._modBy = modBy;
  19673. this._modDataCount = modDataCount;
  19674. var step = performArgs && performArgs.step;
  19675. if (upTask) {
  19676. if ("development" !== 'production') {
  19677. assert(upTask._outputDueEnd != null);
  19678. }
  19679. this._dueEnd = upTask._outputDueEnd;
  19680. } // DataTask or overallTask
  19681. else {
  19682. if ("development" !== 'production') {
  19683. assert(!this._progress || this._count);
  19684. }
  19685. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19686. } // Note: Stubs, that its host overall task let it has progress, has progress.
  19687. // If no progress, pass index from upstream to downstream each time plan called.
  19688. if (this._progress) {
  19689. var start = this._dueIndex;
  19690. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19691. if (!skip && (forceFirstProgress || start < end)) {
  19692. var progress = this._progress;
  19693. if (isArray(progress)) {
  19694. for (var i = 0; i < progress.length; i++) {
  19695. this._doProgress(progress[i], start, end, modBy, modDataCount);
  19696. }
  19697. } else {
  19698. this._doProgress(progress, start, end, modBy, modDataCount);
  19699. }
  19700. }
  19701. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  19702. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19703. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19704. if ("development" !== 'production') {
  19705. // ??? Can not rollback.
  19706. assert(outputDueEnd >= this._outputDueEnd);
  19707. }
  19708. this._outputDueEnd = outputDueEnd;
  19709. } else {
  19710. // (1) Some overall task has no progress.
  19711. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19712. // This should always be performed so it can be passed to downstream.
  19713. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19714. }
  19715. return this.unfinished();
  19716. };
  19717. Task.prototype.dirty = function () {
  19718. this._dirty = true;
  19719. this._onDirty && this._onDirty(this.context);
  19720. };
  19721. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19722. iterator.reset(start, end, modBy, modDataCount);
  19723. this._callingProgress = progress;
  19724. this._callingProgress({
  19725. start: start,
  19726. end: end,
  19727. count: end - start,
  19728. next: iterator.next
  19729. }, this.context);
  19730. };
  19731. Task.prototype._doReset = function (skip) {
  19732. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19733. this._settedOutputEnd = null;
  19734. var progress;
  19735. var forceFirstProgress;
  19736. if (!skip && this._reset) {
  19737. progress = this._reset(this.context);
  19738. if (progress && progress.progress) {
  19739. forceFirstProgress = progress.forceFirstProgress;
  19740. progress = progress.progress;
  19741. } // To simplify no progress checking, array must has item.
  19742. if (isArray(progress) && !progress.length) {
  19743. progress = null;
  19744. }
  19745. }
  19746. this._progress = progress;
  19747. this._modBy = this._modDataCount = null;
  19748. var downstream = this._downstream;
  19749. downstream && downstream.dirty();
  19750. return forceFirstProgress;
  19751. };
  19752. Task.prototype.unfinished = function () {
  19753. return this._progress && this._dueIndex < this._dueEnd;
  19754. };
  19755. /**
  19756. * @param downTask The downstream task.
  19757. * @return The downstream task.
  19758. */
  19759. Task.prototype.pipe = function (downTask) {
  19760. if ("development" !== 'production') {
  19761. assert(downTask && !downTask._disposed && downTask !== this);
  19762. } // If already downstream, do not dirty downTask.
  19763. if (this._downstream !== downTask || this._dirty) {
  19764. this._downstream = downTask;
  19765. downTask._upstream = this;
  19766. downTask.dirty();
  19767. }
  19768. };
  19769. Task.prototype.dispose = function () {
  19770. if (this._disposed) {
  19771. return;
  19772. }
  19773. this._upstream && (this._upstream._downstream = null);
  19774. this._downstream && (this._downstream._upstream = null);
  19775. this._dirty = false;
  19776. this._disposed = true;
  19777. };
  19778. Task.prototype.getUpstream = function () {
  19779. return this._upstream;
  19780. };
  19781. Task.prototype.getDownstream = function () {
  19782. return this._downstream;
  19783. };
  19784. Task.prototype.setOutputEnd = function (end) {
  19785. // This only happens in dataTask, dataZoom, map, currently.
  19786. // where dataZoom do not set end each time, but only set
  19787. // when reset. So we should record the set end, in case
  19788. // that the stub of dataZoom perform again and earse the
  19789. // set end by upstream.
  19790. this._outputDueEnd = this._settedOutputEnd = end;
  19791. };
  19792. return Task;
  19793. }();
  19794. var iterator = function () {
  19795. var end;
  19796. var current;
  19797. var modBy;
  19798. var modDataCount;
  19799. var winCount;
  19800. var it = {
  19801. reset: function (s, e, sStep, sCount) {
  19802. current = s;
  19803. end = e;
  19804. modBy = sStep;
  19805. modDataCount = sCount;
  19806. winCount = Math.ceil(modDataCount / modBy);
  19807. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19808. }
  19809. };
  19810. return it;
  19811. function sequentialNext() {
  19812. return current < end ? current++ : null;
  19813. }
  19814. function modNext() {
  19815. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19816. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19817. // Use normal linear rendering mode.
  19818. : current;
  19819. current++;
  19820. return result;
  19821. }
  19822. }(); // -----------------------------------------------------------------------------
  19823. // For stream debug (Should be commented out after used!)
  19824. // @usage: printTask(this, 'begin');
  19825. // @usage: printTask(this, null, {someExtraProp});
  19826. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19827. //
  19828. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19829. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19830. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19831. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19832. // let props = [];
  19833. // if (task.__pipeline) {
  19834. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19835. // props.push({text: '__idxInPipeline/total', value: val});
  19836. // } else {
  19837. // let stubCount = 0;
  19838. // task.agentStubMap.each(() => stubCount++);
  19839. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19840. // }
  19841. // props.push({text: 'uid', value: task.uidDebug});
  19842. // if (task.__pipeline) {
  19843. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19844. // task.agent && props.push(
  19845. // {text: 'stubFor', value: task.agent.uidDebug}
  19846. // );
  19847. // }
  19848. // props.push(
  19849. // {text: 'dirty', value: task._dirty},
  19850. // {text: 'dueIndex', value: task._dueIndex},
  19851. // {text: 'dueEnd', value: task._dueEnd},
  19852. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19853. // );
  19854. // if (extra) {
  19855. // Object.keys(extra).forEach(key => {
  19856. // props.push({text: key, value: extra[key]});
  19857. // });
  19858. // }
  19859. // let args = ['color: blue'];
  19860. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19861. // args.push('color: green', 'color: red'),
  19862. // `${item.text}: %c${item.value}`
  19863. // )).join('%c, ');
  19864. // console.log.apply(console, [msg].concat(args));
  19865. // // console.log(this);
  19866. // };
  19867. // window.printPipeline = function (task: any, prefix: string) {
  19868. // const pipeline = task.__pipeline;
  19869. // let currTask = pipeline.head;
  19870. // while (currTask) {
  19871. // window.printTask(currTask, prefix);
  19872. // currTask = currTask._downstream;
  19873. // }
  19874. // };
  19875. // window.showChain = function (chainHeadTask) {
  19876. // var chain = [];
  19877. // var task = chainHeadTask;
  19878. // while (task) {
  19879. // chain.push({
  19880. // task: task,
  19881. // up: task._upstream,
  19882. // down: task._downstream,
  19883. // idxInPipeline: task.__idxInPipeline
  19884. // });
  19885. // task = task._downstream;
  19886. // }
  19887. // return chain;
  19888. // };
  19889. // window.findTaskInChain = function (task, chainHeadTask) {
  19890. // let chain = window.showChain(chainHeadTask);
  19891. // let result = [];
  19892. // for (let i = 0; i < chain.length; i++) {
  19893. // let chainItem = chain[i];
  19894. // if (chainItem.task === task) {
  19895. // result.push(i);
  19896. // }
  19897. // }
  19898. // return result;
  19899. // };
  19900. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19901. // let chainA = window.showChain(chainHeadTaskA);
  19902. // for (let i = 0; i < chainA.length; i++) {
  19903. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19904. // }
  19905. // };
  19906. /**
  19907. * Convert raw the value in to inner value in List.
  19908. *
  19909. * [Performance sensitive]
  19910. *
  19911. * [Caution]: this is the key logic of user value parser.
  19912. * For backward compatibility, do not modify it until you have to!
  19913. */
  19914. function parseDataValue(value, // For high performance, do not omit the second param.
  19915. opt) {
  19916. // Performance sensitive.
  19917. var dimType = opt && opt.type;
  19918. if (dimType === 'ordinal') {
  19919. // If given value is a category string
  19920. return value;
  19921. }
  19922. if (dimType === 'time' // spead up when using timestamp
  19923. && !isNumber(value) && value != null && value !== '-') {
  19924. value = +parseDate(value);
  19925. } // dimType defaults 'number'.
  19926. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19927. // parse to NaN.
  19928. // number-like string (like ' 123 ') can be converted to a number.
  19929. // where null/undefined or other string will be converted to NaN.
  19930. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19931. // If object, also parse to NaN
  19932. : +value;
  19933. }
  19934. var valueParserMap = createHashMap({
  19935. 'number': function (val) {
  19936. // Do not use `numericToNumber` here. We have `numericToNumber` by default.
  19937. // Here the number parser can have loose rule:
  19938. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19939. return parseFloat(val);
  19940. },
  19941. 'time': function (val) {
  19942. // return timestamp.
  19943. return +parseDate(val);
  19944. },
  19945. 'trim': function (val) {
  19946. return isString(val) ? trim(val) : val;
  19947. }
  19948. });
  19949. function getRawValueParser(type) {
  19950. return valueParserMap.get(type);
  19951. }
  19952. var ORDER_COMPARISON_OP_MAP = {
  19953. lt: function (lval, rval) {
  19954. return lval < rval;
  19955. },
  19956. lte: function (lval, rval) {
  19957. return lval <= rval;
  19958. },
  19959. gt: function (lval, rval) {
  19960. return lval > rval;
  19961. },
  19962. gte: function (lval, rval) {
  19963. return lval >= rval;
  19964. }
  19965. };
  19966. var FilterOrderComparator =
  19967. /** @class */
  19968. function () {
  19969. function FilterOrderComparator(op, rval) {
  19970. if (!isNumber(rval)) {
  19971. var errMsg = '';
  19972. if ("development" !== 'production') {
  19973. errMsg = 'rvalue of "<", ">", "<=", ">=" can only be number in filter.';
  19974. }
  19975. throwError(errMsg);
  19976. }
  19977. this._opFn = ORDER_COMPARISON_OP_MAP[op];
  19978. this._rvalFloat = numericToNumber(rval);
  19979. } // Performance sensitive.
  19980. FilterOrderComparator.prototype.evaluate = function (lval) {
  19981. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19982. return isNumber(lval) ? this._opFn(lval, this._rvalFloat) : this._opFn(numericToNumber(lval), this._rvalFloat);
  19983. };
  19984. return FilterOrderComparator;
  19985. }();
  19986. var SortOrderComparator =
  19987. /** @class */
  19988. function () {
  19989. /**
  19990. * @param order by default: 'asc'
  19991. * @param incomparable by default: Always on the tail.
  19992. * That is, if 'asc' => 'max', if 'desc' => 'min'
  19993. * See the definition of "incomparable" in [SORT_COMPARISON_RULE].
  19994. */
  19995. function SortOrderComparator(order, incomparable) {
  19996. var isDesc = order === 'desc';
  19997. this._resultLT = isDesc ? 1 : -1;
  19998. if (incomparable == null) {
  19999. incomparable = isDesc ? 'min' : 'max';
  20000. }
  20001. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  20002. } // See [SORT_COMPARISON_RULE].
  20003. // Performance sensitive.
  20004. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  20005. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  20006. var lvalFloat = isNumber(lval) ? lval : numericToNumber(lval);
  20007. var rvalFloat = isNumber(rval) ? rval : numericToNumber(rval);
  20008. var lvalNotNumeric = isNaN(lvalFloat);
  20009. var rvalNotNumeric = isNaN(rvalFloat);
  20010. if (lvalNotNumeric) {
  20011. lvalFloat = this._incomparable;
  20012. }
  20013. if (rvalNotNumeric) {
  20014. rvalFloat = this._incomparable;
  20015. }
  20016. if (lvalNotNumeric && rvalNotNumeric) {
  20017. var lvalIsStr = isString(lval);
  20018. var rvalIsStr = isString(rval);
  20019. if (lvalIsStr) {
  20020. lvalFloat = rvalIsStr ? lval : 0;
  20021. }
  20022. if (rvalIsStr) {
  20023. rvalFloat = lvalIsStr ? rval : 0;
  20024. }
  20025. }
  20026. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  20027. };
  20028. return SortOrderComparator;
  20029. }();
  20030. var FilterEqualityComparator =
  20031. /** @class */
  20032. function () {
  20033. function FilterEqualityComparator(isEq, rval) {
  20034. this._rval = rval;
  20035. this._isEQ = isEq;
  20036. this._rvalTypeof = typeof rval;
  20037. this._rvalFloat = numericToNumber(rval);
  20038. } // Performance sensitive.
  20039. FilterEqualityComparator.prototype.evaluate = function (lval) {
  20040. var eqResult = lval === this._rval;
  20041. if (!eqResult) {
  20042. var lvalTypeof = typeof lval;
  20043. if (lvalTypeof !== this._rvalTypeof && (lvalTypeof === 'number' || this._rvalTypeof === 'number')) {
  20044. eqResult = numericToNumber(lval) === this._rvalFloat;
  20045. }
  20046. }
  20047. return this._isEQ ? eqResult : !eqResult;
  20048. };
  20049. return FilterEqualityComparator;
  20050. }();
  20051. /**
  20052. * [FILTER_COMPARISON_RULE]
  20053. * `lt`|`lte`|`gt`|`gte`:
  20054. * + rval must be a number. And lval will be converted to number (`numericToNumber`) to compare.
  20055. * `eq`:
  20056. * + If same type, compare with `===`.
  20057. * + If there is one number, convert to number (`numericToNumber`) to compare.
  20058. * + Else return `false`.
  20059. * `ne`:
  20060. * + Not `eq`.
  20061. *
  20062. *
  20063. * [SORT_COMPARISON_RULE]
  20064. * All the values are grouped into three categories:
  20065. * + "numeric" (number and numeric string)
  20066. * + "non-numeric-string" (string that excluding numeric string)
  20067. * + "others"
  20068. * "numeric" vs "numeric": values are ordered by number order.
  20069. * "non-numeric-string" vs "non-numeric-string": values are ordered by ES spec (#sec-abstract-relational-comparison).
  20070. * "others" vs "others": do not change order (always return 0).
  20071. * "numeric" vs "non-numeric-string": "non-numeric-string" is treated as "incomparable".
  20072. * "number" vs "others": "others" is treated as "incomparable".
  20073. * "non-numeric-string" vs "others": "others" is treated as "incomparable".
  20074. * "incomparable" will be seen as -Infinity or Infinity (depends on the settings).
  20075. * MEMO:
  20076. * Non-numeric string sort makes sense when we need to put the items with the same tag together.
  20077. * But if we support string sort, we still need to avoid the misleading like `'2' > '12'`,
  20078. * So we treat "numeric-string" sorted by number order rather than string comparison.
  20079. *
  20080. *
  20081. * [CHECK_LIST_OF_THE_RULE_DESIGN]
  20082. * + Do not support string comparison until required. And also need to
  20083. * avoid the misleading of "2" > "12".
  20084. * + Should avoid the misleading case:
  20085. * `" 22 " gte "22"` is `true` but `" 22 " eq "22"` is `false`.
  20086. * + JS bad case should be avoided: null <= 0, [] <= 0, ' ' <= 0, ...
  20087. * + Only "numeric" can be converted to comparable number, otherwise converted to NaN.
  20088. * See `util/number.ts#numericToNumber`.
  20089. *
  20090. * @return If `op` is not `RelationalOperator`, return null;
  20091. */
  20092. function createFilterComparator(op, rval) {
  20093. return op === 'eq' || op === 'ne' ? new FilterEqualityComparator(op === 'eq', rval) : hasOwn(ORDER_COMPARISON_OP_MAP, op) ? new FilterOrderComparator(op, rval) : null;
  20094. }
  20095. /**
  20096. * TODO: disable writable.
  20097. * This structure will be exposed to users.
  20098. */
  20099. var ExternalSource =
  20100. /** @class */
  20101. function () {
  20102. function ExternalSource() {}
  20103. ExternalSource.prototype.getRawData = function () {
  20104. // Only built-in transform available.
  20105. throw new Error('not supported');
  20106. };
  20107. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  20108. // Only built-in transform available.
  20109. throw new Error('not supported');
  20110. };
  20111. ExternalSource.prototype.cloneRawData = function () {
  20112. return;
  20113. };
  20114. /**
  20115. * @return If dimension not found, return null/undefined.
  20116. */
  20117. ExternalSource.prototype.getDimensionInfo = function (dim) {
  20118. return;
  20119. };
  20120. /**
  20121. * dimensions defined if and only if either:
  20122. * (a) dataset.dimensions are declared.
  20123. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  20124. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  20125. * the defined dimensions.
  20126. * Otherwise, `dimensionInfoAll` is determined by data columns.
  20127. * @return Always return an array (even empty array).
  20128. */
  20129. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  20130. return;
  20131. };
  20132. ExternalSource.prototype.count = function () {
  20133. return;
  20134. };
  20135. /**
  20136. * Only support by dimension index.
  20137. * No need to support by dimension name in transform function,
  20138. * because transform function is not case-specific, no need to use name literally.
  20139. */
  20140. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  20141. return;
  20142. };
  20143. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  20144. return;
  20145. };
  20146. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  20147. return parseDataValue(rawVal, dimInfo);
  20148. };
  20149. return ExternalSource;
  20150. }();
  20151. function createExternalSource(internalSource, externalTransform) {
  20152. var extSource = new ExternalSource();
  20153. var data = internalSource.data;
  20154. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  20155. var sourceHeaderCount = internalSource.startIndex;
  20156. var errMsg = '';
  20157. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  20158. // For the logic simplicity in transformer, only 'culumn' is
  20159. // supported in data transform. Otherwise, the `dimensionsDefine`
  20160. // might be detected by 'row', which probably confuses users.
  20161. if ("development" !== 'production') {
  20162. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  20163. }
  20164. throwError(errMsg);
  20165. } // [MEMO]
  20166. // Create a new dimensions structure for exposing.
  20167. // Do not expose all dimension info to users directly.
  20168. // Because the dimension is probably auto detected from data and not might reliable.
  20169. // Should not lead the transformers to think that is reliable and return it.
  20170. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20171. var dimensions = [];
  20172. var dimsByName = {};
  20173. var dimsDef = internalSource.dimensionsDefine;
  20174. if (dimsDef) {
  20175. each(dimsDef, function (dimDef, idx) {
  20176. var name = dimDef.name;
  20177. var dimDefExt = {
  20178. index: idx,
  20179. name: name,
  20180. displayName: dimDef.displayName
  20181. };
  20182. dimensions.push(dimDefExt); // Users probably do not specify dimension name. For simplicity, data transform
  20183. // does not generate dimension name.
  20184. if (name != null) {
  20185. // Dimension name should not be duplicated.
  20186. // For simplicity, data transform forbids name duplication, do not generate
  20187. // new name like module `completeDimensions.ts` did, but just tell users.
  20188. var errMsg_1 = '';
  20189. if (hasOwn(dimsByName, name)) {
  20190. if ("development" !== 'production') {
  20191. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  20192. }
  20193. throwError(errMsg_1);
  20194. }
  20195. dimsByName[name] = dimDefExt;
  20196. }
  20197. });
  20198. } // If dimension definitions are not defined and can not be detected.
  20199. // e.g., pure data `[[11, 22], ...]`.
  20200. else {
  20201. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  20202. // Do not generete name or anything others. The consequence process in
  20203. // `transform` or `series` probably have there own name generation strategry.
  20204. dimensions.push({
  20205. index: i
  20206. });
  20207. }
  20208. } // Implement public methods:
  20209. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20210. if (externalTransform.__isBuiltIn) {
  20211. extSource.getRawDataItem = function (dataIndex) {
  20212. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20213. };
  20214. extSource.getRawData = bind(getRawData, null, internalSource);
  20215. }
  20216. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  20217. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20218. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  20219. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  20220. extSource.retrieveValue = function (dataIndex, dimIndex) {
  20221. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20222. return retrieveValueFromItem(rawItem, dimIndex);
  20223. };
  20224. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  20225. if (dataItem == null) {
  20226. return;
  20227. }
  20228. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  20229. if (dimDef) {
  20230. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  20231. }
  20232. };
  20233. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  20234. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  20235. return extSource;
  20236. }
  20237. function getRawData(upstream) {
  20238. var sourceFormat = upstream.sourceFormat;
  20239. if (!isSupportedSourceFormat(sourceFormat)) {
  20240. var errMsg = '';
  20241. if ("development" !== 'production') {
  20242. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  20243. }
  20244. throwError(errMsg);
  20245. }
  20246. return upstream.data;
  20247. }
  20248. function cloneRawData(upstream) {
  20249. var sourceFormat = upstream.sourceFormat;
  20250. var data = upstream.data;
  20251. if (!isSupportedSourceFormat(sourceFormat)) {
  20252. var errMsg = '';
  20253. if ("development" !== 'production') {
  20254. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  20255. }
  20256. throwError(errMsg);
  20257. }
  20258. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  20259. var result = [];
  20260. for (var i = 0, len = data.length; i < len; i++) {
  20261. // Not strictly clone for performance
  20262. result.push(data[i].slice());
  20263. }
  20264. return result;
  20265. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  20266. var result = [];
  20267. for (var i = 0, len = data.length; i < len; i++) {
  20268. // Not strictly clone for performance
  20269. result.push(extend({}, data[i]));
  20270. }
  20271. return result;
  20272. }
  20273. }
  20274. function getDimensionInfo(dimensions, dimsByName, dim) {
  20275. if (dim == null) {
  20276. return;
  20277. } // Keep the same logic as `List::getDimension` did.
  20278. if (isNumber(dim) // If being a number-like string but not being defined a dimension name.
  20279. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  20280. return dimensions[dim];
  20281. } else if (hasOwn(dimsByName, dim)) {
  20282. return dimsByName[dim];
  20283. }
  20284. }
  20285. function cloneAllDimensionInfo(dimensions) {
  20286. return clone(dimensions);
  20287. }
  20288. var externalTransformMap = createHashMap();
  20289. function registerExternalTransform(externalTransform) {
  20290. externalTransform = clone(externalTransform);
  20291. var type = externalTransform.type;
  20292. var errMsg = '';
  20293. if (!type) {
  20294. if ("development" !== 'production') {
  20295. errMsg = 'Must have a `type` when `registerTransform`.';
  20296. }
  20297. throwError(errMsg);
  20298. }
  20299. var typeParsed = type.split(':');
  20300. if (typeParsed.length !== 2) {
  20301. if ("development" !== 'production') {
  20302. errMsg = 'Name must include namespace like "ns:regression".';
  20303. }
  20304. throwError(errMsg);
  20305. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  20306. // be called directly via 'xxx' rather than 'echarts:xxx'.
  20307. var isBuiltIn = false;
  20308. if (typeParsed[0] === 'echarts') {
  20309. type = typeParsed[1];
  20310. isBuiltIn = true;
  20311. }
  20312. externalTransform.__isBuiltIn = isBuiltIn;
  20313. externalTransformMap.set(type, externalTransform);
  20314. }
  20315. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  20316. var pipedTransOption = normalizeToArray(rawTransOption);
  20317. var pipeLen = pipedTransOption.length;
  20318. var errMsg = '';
  20319. if (!pipeLen) {
  20320. if ("development" !== 'production') {
  20321. errMsg = 'If `transform` declared, it should at least contain one transform.';
  20322. }
  20323. throwError(errMsg);
  20324. }
  20325. for (var i = 0, len = pipeLen; i < len; i++) {
  20326. var transOption = pipedTransOption[i];
  20327. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  20328. // piped transform only support single output, except the last one.
  20329. if (i !== len - 1) {
  20330. sourceList.length = Math.max(sourceList.length, 1);
  20331. }
  20332. }
  20333. return sourceList;
  20334. }
  20335. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  20336. pipeIndex) {
  20337. var errMsg = '';
  20338. if (!upSourceList.length) {
  20339. if ("development" !== 'production') {
  20340. errMsg = 'Must have at least one upstream dataset.';
  20341. }
  20342. throwError(errMsg);
  20343. }
  20344. if (!isObject(transOption)) {
  20345. if ("development" !== 'production') {
  20346. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  20347. }
  20348. throwError(errMsg);
  20349. }
  20350. var transType = transOption.type;
  20351. var externalTransform = externalTransformMap.get(transType);
  20352. if (!externalTransform) {
  20353. if ("development" !== 'production') {
  20354. errMsg = 'Can not find transform on type "' + transType + '".';
  20355. }
  20356. throwError(errMsg);
  20357. } // Prepare source
  20358. var extUpSourceList = map(upSourceList, function (upSource) {
  20359. return createExternalSource(upSource, externalTransform);
  20360. });
  20361. var resultList = normalizeToArray(externalTransform.transform({
  20362. upstream: extUpSourceList[0],
  20363. upstreamList: extUpSourceList,
  20364. config: clone(transOption.config)
  20365. }));
  20366. if ("development" !== 'production') {
  20367. if (transOption.print) {
  20368. var printStrArr = map(resultList, function (extSource) {
  20369. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  20370. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  20371. }).join('\n');
  20372. log(printStrArr);
  20373. }
  20374. }
  20375. return map(resultList, function (result, resultIndex) {
  20376. var errMsg = '';
  20377. if (!isObject(result)) {
  20378. if ("development" !== 'production') {
  20379. errMsg = 'A transform should not return some empty results.';
  20380. }
  20381. throwError(errMsg);
  20382. }
  20383. if (!result.data) {
  20384. if ("development" !== 'production') {
  20385. errMsg = 'Transform result data should be not be null or undefined';
  20386. }
  20387. throwError(errMsg);
  20388. }
  20389. var sourceFormat = detectSourceFormat(result.data);
  20390. if (!isSupportedSourceFormat(sourceFormat)) {
  20391. if ("development" !== 'production') {
  20392. errMsg = 'Transform result data should be array rows or object rows.';
  20393. }
  20394. throwError(errMsg);
  20395. }
  20396. var resultMetaRawOption;
  20397. var firstUpSource = upSourceList[0];
  20398. /**
  20399. * Intuitively, the end users known the content of the original `dataset.source`,
  20400. * calucating the transform result in mind.
  20401. * Suppose the original `dataset.source` is:
  20402. * ```js
  20403. * [
  20404. * ['product', '2012', '2013', '2014', '2015'],
  20405. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  20406. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  20407. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  20408. * ]
  20409. * ```
  20410. * The dimension info have to be detected from the source data.
  20411. * Some of the transformers (like filter, sort) will follow the dimension info
  20412. * of upstream, while others use new dimensions (like aggregate).
  20413. * Transformer can output a field `dimensions` to define the its own output dimensions.
  20414. * We also allow transformers to ignore the output `dimensions` field, and
  20415. * inherit the upstream dimensions definition. It can reduce the burden of handling
  20416. * dimensions in transformers.
  20417. *
  20418. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20419. */
  20420. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  20421. // dimensions definitions. We do not inherit anything from upstream.
  20422. && !result.dimensions) {
  20423. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result, because:
  20424. // (1) The returned data always does not contain header line and can not be used
  20425. // as dimension-detection. In this case we can not use "detected dimensions" of
  20426. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  20427. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  20428. // So the original detected header should be add to the result, otherwise they can not be read.
  20429. if (startIndex) {
  20430. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  20431. }
  20432. resultMetaRawOption = {
  20433. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20434. sourceHeader: startIndex,
  20435. dimensions: firstUpSource.metaRawOption.dimensions
  20436. };
  20437. } else {
  20438. resultMetaRawOption = {
  20439. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20440. sourceHeader: 0,
  20441. dimensions: result.dimensions
  20442. };
  20443. }
  20444. return createSource(result.data, resultMetaRawOption, null);
  20445. });
  20446. }
  20447. function isSupportedSourceFormat(sourceFormat) {
  20448. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  20449. }
  20450. var UNDEFINED = 'undefined';
  20451. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  20452. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  20453. // different from the Ctor of typed array.
  20454. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  20455. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  20456. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  20457. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  20458. /**
  20459. * Multi dimensional data store
  20460. */
  20461. var dataCtors = {
  20462. 'float': CtorFloat64Array,
  20463. 'int': CtorInt32Array,
  20464. // Ordinal data type can be string or int
  20465. 'ordinal': Array,
  20466. 'number': Array,
  20467. 'time': CtorFloat64Array
  20468. };
  20469. var defaultDimValueGetters;
  20470. function getIndicesCtor(rawCount) {
  20471. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  20472. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  20473. }
  20474. function getInitialExtent() {
  20475. return [Infinity, -Infinity];
  20476. }
  20477. function cloneChunk(originalChunk) {
  20478. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  20479. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  20480. }
  20481. function prepareStore(store, dimIdx, dimType, end, append) {
  20482. var DataCtor = dataCtors[dimType || 'float'];
  20483. if (append) {
  20484. var oldStore = store[dimIdx];
  20485. var oldLen = oldStore && oldStore.length;
  20486. if (!(oldLen === end)) {
  20487. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  20488. // within the initial chunkSize.
  20489. for (var j = 0; j < oldLen; j++) {
  20490. newStore[j] = oldStore[j];
  20491. }
  20492. store[dimIdx] = newStore;
  20493. }
  20494. } else {
  20495. store[dimIdx] = new DataCtor(end);
  20496. }
  20497. }
  20498. /**
  20499. * Basically, DataStore API keep immutable.
  20500. */
  20501. var DataStore =
  20502. /** @class */
  20503. function () {
  20504. function DataStore() {
  20505. this._chunks = []; // It will not be calculated until needed.
  20506. this._rawExtent = [];
  20507. this._extent = [];
  20508. this._count = 0;
  20509. this._rawCount = 0;
  20510. this._calcDimNameToIdx = createHashMap();
  20511. }
  20512. /**
  20513. * Initialize from data
  20514. */
  20515. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  20516. if ("development" !== 'production') {
  20517. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Invalid data provider.');
  20518. }
  20519. this._provider = provider; // Clear
  20520. this._chunks = [];
  20521. this._indices = null;
  20522. this.getRawIndex = this._getRawIdxIdentity;
  20523. var source = provider.getSource();
  20524. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat]; // Default dim value getter
  20525. this._dimValueGetter = dimValueGetter || defaultGetter; // Reset raw extent.
  20526. this._rawExtent = [];
  20527. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  20528. this._dimensions = map(inputDimensions, function (dim) {
  20529. if ("development" !== 'production') {
  20530. if (willRetrieveDataByName) {
  20531. assert(dim.property != null);
  20532. }
  20533. }
  20534. return {
  20535. // Only pick these two props. Not leak other properties like orderMeta.
  20536. type: dim.type,
  20537. property: dim.property
  20538. };
  20539. });
  20540. this._initDataFromProvider(0, provider.count());
  20541. };
  20542. DataStore.prototype.getProvider = function () {
  20543. return this._provider;
  20544. };
  20545. /**
  20546. * Caution: even when a `source` instance owned by a series, the created data store
  20547. * may still be shared by different sereis (the source hash does not use all `source`
  20548. * props, see `sourceManager`). In this case, the `source` props that are not used in
  20549. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  20550. * thus should not be fetch here.
  20551. */
  20552. DataStore.prototype.getSource = function () {
  20553. return this._provider.getSource();
  20554. };
  20555. /**
  20556. * @caution Only used in dataStack.
  20557. */
  20558. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  20559. var calcDimNameToIdx = this._calcDimNameToIdx;
  20560. var dimensions = this._dimensions;
  20561. var calcDimIdx = calcDimNameToIdx.get(dimName);
  20562. if (calcDimIdx != null) {
  20563. if (dimensions[calcDimIdx].type === type) {
  20564. return calcDimIdx;
  20565. }
  20566. } else {
  20567. calcDimIdx = dimensions.length;
  20568. }
  20569. dimensions[calcDimIdx] = {
  20570. type: type
  20571. };
  20572. calcDimNameToIdx.set(dimName, calcDimIdx);
  20573. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  20574. this._rawExtent[calcDimIdx] = getInitialExtent();
  20575. return calcDimIdx;
  20576. };
  20577. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  20578. var chunk = this._chunks[dimIdx];
  20579. var dim = this._dimensions[dimIdx];
  20580. var rawExtents = this._rawExtent;
  20581. var offset = dim.ordinalOffset || 0;
  20582. var len = chunk.length;
  20583. if (offset === 0) {
  20584. // We need to reset the rawExtent if collect is from start.
  20585. // Because this dimension may be guessed as number and calcuating a wrong extent.
  20586. rawExtents[dimIdx] = getInitialExtent();
  20587. }
  20588. var dimRawExtent = rawExtents[dimIdx]; // Parse from previous data offset. len may be changed after appendData
  20589. for (var i = offset; i < len; i++) {
  20590. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  20591. if (!isNaN(val)) {
  20592. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  20593. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  20594. }
  20595. }
  20596. dim.ordinalMeta = ordinalMeta;
  20597. dim.ordinalOffset = len;
  20598. dim.type = 'ordinal'; // Force to be ordinal
  20599. };
  20600. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  20601. var dimInfo = this._dimensions[dimIdx];
  20602. var ordinalMeta = dimInfo.ordinalMeta;
  20603. return ordinalMeta;
  20604. };
  20605. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  20606. var item = this._dimensions[dimIndex];
  20607. return item && item.property;
  20608. };
  20609. /**
  20610. * Caution: Can be only called on raw data (before `this._indices` created).
  20611. */
  20612. DataStore.prototype.appendData = function (data) {
  20613. if ("development" !== 'production') {
  20614. assert(!this._indices, 'appendData can only be called on raw data.');
  20615. }
  20616. var provider = this._provider;
  20617. var start = this.count();
  20618. provider.appendData(data);
  20619. var end = provider.count();
  20620. if (!provider.persistent) {
  20621. end += start;
  20622. }
  20623. if (start < end) {
  20624. this._initDataFromProvider(start, end, true);
  20625. }
  20626. return [start, end];
  20627. };
  20628. DataStore.prototype.appendValues = function (values, minFillLen) {
  20629. var chunks = this._chunks;
  20630. var dimensions = this._dimensions;
  20631. var dimLen = dimensions.length;
  20632. var rawExtent = this._rawExtent;
  20633. var start = this.count();
  20634. var end = start + Math.max(values.length, minFillLen || 0);
  20635. for (var i = 0; i < dimLen; i++) {
  20636. var dim = dimensions[i];
  20637. prepareStore(chunks, i, dim.type, end, true);
  20638. }
  20639. var emptyDataItem = [];
  20640. for (var idx = start; idx < end; idx++) {
  20641. var sourceIdx = idx - start; // Store the data by dimensions
  20642. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20643. var dim = dimensions[dimIdx];
  20644. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  20645. chunks[dimIdx][idx] = val;
  20646. var dimRawExtent = rawExtent[dimIdx];
  20647. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20648. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20649. }
  20650. }
  20651. this._rawCount = this._count = end;
  20652. return {
  20653. start: start,
  20654. end: end
  20655. };
  20656. };
  20657. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  20658. var provider = this._provider;
  20659. var chunks = this._chunks;
  20660. var dimensions = this._dimensions;
  20661. var dimLen = dimensions.length;
  20662. var rawExtent = this._rawExtent;
  20663. var dimNames = map(dimensions, function (dim) {
  20664. return dim.property;
  20665. });
  20666. for (var i = 0; i < dimLen; i++) {
  20667. var dim = dimensions[i];
  20668. if (!rawExtent[i]) {
  20669. rawExtent[i] = getInitialExtent();
  20670. }
  20671. prepareStore(chunks, i, dim.type, end, append);
  20672. }
  20673. if (provider.fillStorage) {
  20674. provider.fillStorage(start, end, chunks, rawExtent);
  20675. } else {
  20676. var dataItem = [];
  20677. for (var idx = start; idx < end; idx++) {
  20678. // NOTICE: Try not to write things into dataItem
  20679. dataItem = provider.getItem(idx, dataItem); // Each data item is value
  20680. // [1, 2]
  20681. // 2
  20682. // Bar chart, line chart which uses category axis
  20683. // only gives the 'y' value. 'x' value is the indices of category
  20684. // Use a tempValue to normalize the value to be a (x, y) value
  20685. // Store the data by dimensions
  20686. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20687. var dimStorage = chunks[dimIdx]; // PENDING NULL is empty or zero
  20688. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  20689. dimStorage[idx] = val;
  20690. var dimRawExtent = rawExtent[dimIdx];
  20691. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20692. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20693. }
  20694. }
  20695. }
  20696. if (!provider.persistent && provider.clean) {
  20697. // Clean unused data if data source is typed array.
  20698. provider.clean();
  20699. }
  20700. this._rawCount = this._count = end; // Reset data extent
  20701. this._extent = [];
  20702. };
  20703. DataStore.prototype.count = function () {
  20704. return this._count;
  20705. };
  20706. /**
  20707. * Get value. Return NaN if idx is out of range.
  20708. */
  20709. DataStore.prototype.get = function (dim, idx) {
  20710. if (!(idx >= 0 && idx < this._count)) {
  20711. return NaN;
  20712. }
  20713. var dimStore = this._chunks[dim];
  20714. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  20715. };
  20716. DataStore.prototype.getValues = function (dimensions, idx) {
  20717. var values = [];
  20718. var dimArr = [];
  20719. if (idx == null) {
  20720. idx = dimensions; // TODO get all from store?
  20721. dimensions = []; // All dimensions
  20722. for (var i = 0; i < this._dimensions.length; i++) {
  20723. dimArr.push(i);
  20724. }
  20725. } else {
  20726. dimArr = dimensions;
  20727. }
  20728. for (var i = 0, len = dimArr.length; i < len; i++) {
  20729. values.push(this.get(dimArr[i], idx));
  20730. }
  20731. return values;
  20732. };
  20733. /**
  20734. * @param dim concrete dim
  20735. */
  20736. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  20737. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  20738. return NaN;
  20739. }
  20740. var dimStore = this._chunks[dim];
  20741. return dimStore ? dimStore[rawIdx] : NaN;
  20742. };
  20743. /**
  20744. * Get sum of data in one dimension
  20745. */
  20746. DataStore.prototype.getSum = function (dim) {
  20747. var dimData = this._chunks[dim];
  20748. var sum = 0;
  20749. if (dimData) {
  20750. for (var i = 0, len = this.count(); i < len; i++) {
  20751. var value = this.get(dim, i);
  20752. if (!isNaN(value)) {
  20753. sum += value;
  20754. }
  20755. }
  20756. }
  20757. return sum;
  20758. };
  20759. /**
  20760. * Get median of data in one dimension
  20761. */
  20762. DataStore.prototype.getMedian = function (dim) {
  20763. var dimDataArray = []; // map all data of one dimension
  20764. this.each([dim], function (val) {
  20765. if (!isNaN(val)) {
  20766. dimDataArray.push(val);
  20767. }
  20768. }); // TODO
  20769. // Use quick select?
  20770. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  20771. return a - b;
  20772. });
  20773. var len = this.count(); // calculate median
  20774. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  20775. };
  20776. /**
  20777. * Retrieve the index with given raw data index.
  20778. */
  20779. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  20780. if (rawIndex >= this._rawCount || rawIndex < 0) {
  20781. return -1;
  20782. }
  20783. if (!this._indices) {
  20784. return rawIndex;
  20785. } // Indices are ascending
  20786. var indices = this._indices; // If rawIndex === dataIndex
  20787. var rawDataIndex = indices[rawIndex];
  20788. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  20789. return rawIndex;
  20790. }
  20791. var left = 0;
  20792. var right = this._count - 1;
  20793. while (left <= right) {
  20794. var mid = (left + right) / 2 | 0;
  20795. if (indices[mid] < rawIndex) {
  20796. left = mid + 1;
  20797. } else if (indices[mid] > rawIndex) {
  20798. right = mid - 1;
  20799. } else {
  20800. return mid;
  20801. }
  20802. }
  20803. return -1;
  20804. };
  20805. /**
  20806. * Retrieve the index of nearest value.
  20807. * @param dim
  20808. * @param value
  20809. * @param [maxDistance=Infinity]
  20810. * @return If and only if multiple indices have
  20811. * the same value, they are put to the result.
  20812. */
  20813. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  20814. var chunks = this._chunks;
  20815. var dimData = chunks[dim];
  20816. var nearestIndices = [];
  20817. if (!dimData) {
  20818. return nearestIndices;
  20819. }
  20820. if (maxDistance == null) {
  20821. maxDistance = Infinity;
  20822. }
  20823. var minDist = Infinity;
  20824. var minDiff = -1;
  20825. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/SeriesData.js`.
  20826. for (var i = 0, len = this.count(); i < len; i++) {
  20827. var dataIndex = this.getRawIndex(i);
  20828. var diff = value - dimData[dataIndex];
  20829. var dist = Math.abs(diff);
  20830. if (dist <= maxDistance) {
  20831. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  20832. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  20833. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  20834. // So we choose the one that `diff >= 0` in this case.
  20835. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  20836. // should be push to `nearestIndices`.
  20837. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  20838. minDist = dist;
  20839. minDiff = diff;
  20840. nearestIndicesLen = 0;
  20841. }
  20842. if (diff === minDiff) {
  20843. nearestIndices[nearestIndicesLen++] = i;
  20844. }
  20845. }
  20846. }
  20847. nearestIndices.length = nearestIndicesLen;
  20848. return nearestIndices;
  20849. };
  20850. DataStore.prototype.getIndices = function () {
  20851. var newIndices;
  20852. var indices = this._indices;
  20853. if (indices) {
  20854. var Ctor = indices.constructor;
  20855. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  20856. if (Ctor === Array) {
  20857. newIndices = new Ctor(thisCount);
  20858. for (var i = 0; i < thisCount; i++) {
  20859. newIndices[i] = indices[i];
  20860. }
  20861. } else {
  20862. newIndices = new Ctor(indices.buffer, 0, thisCount);
  20863. }
  20864. } else {
  20865. var Ctor = getIndicesCtor(this._rawCount);
  20866. newIndices = new Ctor(this.count());
  20867. for (var i = 0; i < newIndices.length; i++) {
  20868. newIndices[i] = i;
  20869. }
  20870. }
  20871. return newIndices;
  20872. };
  20873. /**
  20874. * Data filter.
  20875. */
  20876. DataStore.prototype.filter = function (dims, cb) {
  20877. if (!this._count) {
  20878. return this;
  20879. }
  20880. var newStore = this.clone();
  20881. var count = newStore.count();
  20882. var Ctor = getIndicesCtor(newStore._rawCount);
  20883. var newIndices = new Ctor(count);
  20884. var value = [];
  20885. var dimSize = dims.length;
  20886. var offset = 0;
  20887. var dim0 = dims[0];
  20888. var chunks = newStore._chunks;
  20889. for (var i = 0; i < count; i++) {
  20890. var keep = void 0;
  20891. var rawIdx = newStore.getRawIndex(i); // Simple optimization
  20892. if (dimSize === 0) {
  20893. keep = cb(i);
  20894. } else if (dimSize === 1) {
  20895. var val = chunks[dim0][rawIdx];
  20896. keep = cb(val, i);
  20897. } else {
  20898. var k = 0;
  20899. for (; k < dimSize; k++) {
  20900. value[k] = chunks[dims[k]][rawIdx];
  20901. }
  20902. value[k] = i;
  20903. keep = cb.apply(null, value);
  20904. }
  20905. if (keep) {
  20906. newIndices[offset++] = rawIdx;
  20907. }
  20908. } // Set indices after filtered.
  20909. if (offset < count) {
  20910. newStore._indices = newIndices;
  20911. }
  20912. newStore._count = offset; // Reset data extent
  20913. newStore._extent = [];
  20914. newStore._updateGetRawIdx();
  20915. return newStore;
  20916. };
  20917. /**
  20918. * Select data in range. (For optimization of filter)
  20919. * (Manually inline code, support 5 million data filtering in data zoom.)
  20920. */
  20921. DataStore.prototype.selectRange = function (range) {
  20922. var newStore = this.clone();
  20923. var len = newStore._count;
  20924. if (!len) {
  20925. return this;
  20926. }
  20927. var dims = keys(range);
  20928. var dimSize = dims.length;
  20929. if (!dimSize) {
  20930. return this;
  20931. }
  20932. var originalCount = newStore.count();
  20933. var Ctor = getIndicesCtor(newStore._rawCount);
  20934. var newIndices = new Ctor(originalCount);
  20935. var offset = 0;
  20936. var dim0 = dims[0];
  20937. var min = range[dim0][0];
  20938. var max = range[dim0][1];
  20939. var storeArr = newStore._chunks;
  20940. var quickFinished = false;
  20941. if (!newStore._indices) {
  20942. // Extreme optimization for common case. About 2x faster in chrome.
  20943. var idx = 0;
  20944. if (dimSize === 1) {
  20945. var dimStorage = storeArr[dims[0]];
  20946. for (var i = 0; i < len; i++) {
  20947. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  20948. // value indicates the line should be broken. But for the case like
  20949. // scatter plot, a data item with empty value will not be rendered,
  20950. // but the axis extent may be effected if some other dim of the data
  20951. // item has value. Fortunately it is not a significant negative effect.
  20952. if (val >= min && val <= max || isNaN(val)) {
  20953. newIndices[offset++] = idx;
  20954. }
  20955. idx++;
  20956. }
  20957. quickFinished = true;
  20958. } else if (dimSize === 2) {
  20959. var dimStorage = storeArr[dims[0]];
  20960. var dimStorage2 = storeArr[dims[1]];
  20961. var min2 = range[dims[1]][0];
  20962. var max2 = range[dims[1]][1];
  20963. for (var i = 0; i < len; i++) {
  20964. var val = dimStorage[i];
  20965. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  20966. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  20967. newIndices[offset++] = idx;
  20968. }
  20969. idx++;
  20970. }
  20971. quickFinished = true;
  20972. }
  20973. }
  20974. if (!quickFinished) {
  20975. if (dimSize === 1) {
  20976. for (var i = 0; i < originalCount; i++) {
  20977. var rawIndex = newStore.getRawIndex(i);
  20978. var val = storeArr[dims[0]][rawIndex]; // Do not filter NaN, see comment above.
  20979. if (val >= min && val <= max || isNaN(val)) {
  20980. newIndices[offset++] = rawIndex;
  20981. }
  20982. }
  20983. } else {
  20984. for (var i = 0; i < originalCount; i++) {
  20985. var keep = true;
  20986. var rawIndex = newStore.getRawIndex(i);
  20987. for (var k = 0; k < dimSize; k++) {
  20988. var dimk = dims[k];
  20989. var val = storeArr[dimk][rawIndex]; // Do not filter NaN, see comment above.
  20990. if (val < range[dimk][0] || val > range[dimk][1]) {
  20991. keep = false;
  20992. }
  20993. }
  20994. if (keep) {
  20995. newIndices[offset++] = newStore.getRawIndex(i);
  20996. }
  20997. }
  20998. }
  20999. } // Set indices after filtered.
  21000. if (offset < originalCount) {
  21001. newStore._indices = newIndices;
  21002. }
  21003. newStore._count = offset; // Reset data extent
  21004. newStore._extent = [];
  21005. newStore._updateGetRawIdx();
  21006. return newStore;
  21007. }; // /**
  21008. // * Data mapping to a plain array
  21009. // */
  21010. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  21011. // const result: any[] = [];
  21012. // this.each(dims, function () {
  21013. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  21014. // });
  21015. // return result;
  21016. // }
  21017. /**
  21018. * Data mapping to a new List with given dimensions
  21019. */
  21020. DataStore.prototype.map = function (dims, cb) {
  21021. // TODO only clone picked chunks.
  21022. var target = this.clone(dims);
  21023. this._updateDims(target, dims, cb);
  21024. return target;
  21025. };
  21026. /**
  21027. * @caution Danger!! Only used in dataStack.
  21028. */
  21029. DataStore.prototype.modify = function (dims, cb) {
  21030. this._updateDims(this, dims, cb);
  21031. };
  21032. DataStore.prototype._updateDims = function (target, dims, cb) {
  21033. var targetChunks = target._chunks;
  21034. var tmpRetValue = [];
  21035. var dimSize = dims.length;
  21036. var dataCount = target.count();
  21037. var values = [];
  21038. var rawExtent = target._rawExtent;
  21039. for (var i = 0; i < dims.length; i++) {
  21040. rawExtent[dims[i]] = getInitialExtent();
  21041. }
  21042. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  21043. var rawIndex = target.getRawIndex(dataIndex);
  21044. for (var k = 0; k < dimSize; k++) {
  21045. values[k] = targetChunks[dims[k]][rawIndex];
  21046. }
  21047. values[dimSize] = dataIndex;
  21048. var retValue = cb && cb.apply(null, values);
  21049. if (retValue != null) {
  21050. // a number or string (in oridinal dimension)?
  21051. if (typeof retValue !== 'object') {
  21052. tmpRetValue[0] = retValue;
  21053. retValue = tmpRetValue;
  21054. }
  21055. for (var i = 0; i < retValue.length; i++) {
  21056. var dim = dims[i];
  21057. var val = retValue[i];
  21058. var rawExtentOnDim = rawExtent[dim];
  21059. var dimStore = targetChunks[dim];
  21060. if (dimStore) {
  21061. dimStore[rawIndex] = val;
  21062. }
  21063. if (val < rawExtentOnDim[0]) {
  21064. rawExtentOnDim[0] = val;
  21065. }
  21066. if (val > rawExtentOnDim[1]) {
  21067. rawExtentOnDim[1] = val;
  21068. }
  21069. }
  21070. }
  21071. }
  21072. };
  21073. /**
  21074. * Large data down sampling using largest-triangle-three-buckets
  21075. * @param {string} valueDimension
  21076. * @param {number} targetCount
  21077. */
  21078. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  21079. var target = this.clone([valueDimension], true);
  21080. var targetStorage = target._chunks;
  21081. var dimStore = targetStorage[valueDimension];
  21082. var len = this.count();
  21083. var sampledIndex = 0;
  21084. var frameSize = Math.floor(1 / rate);
  21085. var currentRawIndex = this.getRawIndex(0);
  21086. var maxArea;
  21087. var area;
  21088. var nextRawIndex;
  21089. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len)); // First frame use the first data.
  21090. newIndices[sampledIndex++] = currentRawIndex;
  21091. for (var i = 1; i < len - 1; i += frameSize) {
  21092. var nextFrameStart = Math.min(i + frameSize, len - 1);
  21093. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  21094. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  21095. var avgY = 0;
  21096. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  21097. var rawIndex = this.getRawIndex(idx);
  21098. var y = dimStore[rawIndex];
  21099. if (isNaN(y)) {
  21100. continue;
  21101. }
  21102. avgY += y;
  21103. }
  21104. avgY /= nextFrameEnd - nextFrameStart;
  21105. var frameStart = i;
  21106. var frameEnd = Math.min(i + frameSize, len);
  21107. var pointAX = i - 1;
  21108. var pointAY = dimStore[currentRawIndex];
  21109. maxArea = -1;
  21110. nextRawIndex = frameStart;
  21111. var firstNaNIndex = -1;
  21112. var countNaN = 0; // Find a point from current frame that construct a triangle with largest area with previous selected point
  21113. // And the average of next frame.
  21114. for (var idx = frameStart; idx < frameEnd; idx++) {
  21115. var rawIndex = this.getRawIndex(idx);
  21116. var y = dimStore[rawIndex];
  21117. if (isNaN(y)) {
  21118. countNaN++;
  21119. if (firstNaNIndex < 0) {
  21120. firstNaNIndex = rawIndex;
  21121. }
  21122. continue;
  21123. } // Calculate triangle area over three buckets
  21124. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  21125. if (area > maxArea) {
  21126. maxArea = area;
  21127. nextRawIndex = rawIndex; // Next a is this b
  21128. }
  21129. }
  21130. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  21131. // Append first NaN point in every bucket.
  21132. // It is necessary to ensure the correct order of indices.
  21133. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  21134. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  21135. }
  21136. newIndices[sampledIndex++] = nextRawIndex;
  21137. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  21138. } // First frame use the last data.
  21139. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  21140. target._count = sampledIndex;
  21141. target._indices = newIndices;
  21142. target.getRawIndex = this._getRawIdx;
  21143. return target;
  21144. };
  21145. /**
  21146. * Large data down sampling on given dimension
  21147. * @param sampleIndex Sample index for name and id
  21148. */
  21149. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  21150. var target = this.clone([dimension], true);
  21151. var targetStorage = target._chunks;
  21152. var frameValues = [];
  21153. var frameSize = Math.floor(1 / rate);
  21154. var dimStore = targetStorage[dimension];
  21155. var len = this.count();
  21156. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  21157. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  21158. var offset = 0;
  21159. for (var i = 0; i < len; i += frameSize) {
  21160. // Last frame
  21161. if (frameSize > len - i) {
  21162. frameSize = len - i;
  21163. frameValues.length = frameSize;
  21164. }
  21165. for (var k = 0; k < frameSize; k++) {
  21166. var dataIdx = this.getRawIndex(i + k);
  21167. frameValues[k] = dimStore[dataIdx];
  21168. }
  21169. var value = sampleValue(frameValues);
  21170. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  21171. dimStore[sampleFrameIdx] = value;
  21172. if (value < rawExtentOnDim[0]) {
  21173. rawExtentOnDim[0] = value;
  21174. }
  21175. if (value > rawExtentOnDim[1]) {
  21176. rawExtentOnDim[1] = value;
  21177. }
  21178. newIndices[offset++] = sampleFrameIdx;
  21179. }
  21180. target._count = offset;
  21181. target._indices = newIndices;
  21182. target._updateGetRawIdx();
  21183. return target;
  21184. };
  21185. /**
  21186. * Data iteration
  21187. * @param ctx default this
  21188. * @example
  21189. * list.each('x', function (x, idx) {});
  21190. * list.each(['x', 'y'], function (x, y, idx) {});
  21191. * list.each(function (idx) {})
  21192. */
  21193. DataStore.prototype.each = function (dims, cb) {
  21194. if (!this._count) {
  21195. return;
  21196. }
  21197. var dimSize = dims.length;
  21198. var chunks = this._chunks;
  21199. for (var i = 0, len = this.count(); i < len; i++) {
  21200. var rawIdx = this.getRawIndex(i); // Simple optimization
  21201. switch (dimSize) {
  21202. case 0:
  21203. cb(i);
  21204. break;
  21205. case 1:
  21206. cb(chunks[dims[0]][rawIdx], i);
  21207. break;
  21208. case 2:
  21209. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  21210. break;
  21211. default:
  21212. var k = 0;
  21213. var value = [];
  21214. for (; k < dimSize; k++) {
  21215. value[k] = chunks[dims[k]][rawIdx];
  21216. } // Index
  21217. value[k] = i;
  21218. cb.apply(null, value);
  21219. }
  21220. }
  21221. };
  21222. /**
  21223. * Get extent of data in one dimension
  21224. */
  21225. DataStore.prototype.getDataExtent = function (dim) {
  21226. // Make sure use concrete dim as cache name.
  21227. var dimData = this._chunks[dim];
  21228. var initialExtent = getInitialExtent();
  21229. if (!dimData) {
  21230. return initialExtent;
  21231. } // Make more strict checkings to ensure hitting cache.
  21232. var currEnd = this.count(); // Consider the most cases when using data zoom, `getDataExtent`
  21233. // happened before filtering. We cache raw extent, which is not
  21234. // necessary to be cleared and recalculated when restore data.
  21235. var useRaw = !this._indices;
  21236. var dimExtent;
  21237. if (useRaw) {
  21238. return this._rawExtent[dim].slice();
  21239. }
  21240. dimExtent = this._extent[dim];
  21241. if (dimExtent) {
  21242. return dimExtent.slice();
  21243. }
  21244. dimExtent = initialExtent;
  21245. var min = dimExtent[0];
  21246. var max = dimExtent[1];
  21247. for (var i = 0; i < currEnd; i++) {
  21248. var rawIdx = this.getRawIndex(i);
  21249. var value = dimData[rawIdx];
  21250. value < min && (min = value);
  21251. value > max && (max = value);
  21252. }
  21253. dimExtent = [min, max];
  21254. this._extent[dim] = dimExtent;
  21255. return dimExtent;
  21256. };
  21257. /**
  21258. * Get raw data item
  21259. */
  21260. DataStore.prototype.getRawDataItem = function (idx) {
  21261. var rawIdx = this.getRawIndex(idx);
  21262. if (!this._provider.persistent) {
  21263. var val = [];
  21264. var chunks = this._chunks;
  21265. for (var i = 0; i < chunks.length; i++) {
  21266. val.push(chunks[i][rawIdx]);
  21267. }
  21268. return val;
  21269. } else {
  21270. return this._provider.getItem(rawIdx);
  21271. }
  21272. };
  21273. /**
  21274. * Clone shallow.
  21275. *
  21276. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  21277. */
  21278. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  21279. var target = new DataStore();
  21280. var chunks = this._chunks;
  21281. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  21282. obj[dimIdx] = true;
  21283. return obj;
  21284. }, {});
  21285. if (clonedDimsMap) {
  21286. for (var i = 0; i < chunks.length; i++) {
  21287. // Not clone if dim is not picked.
  21288. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  21289. }
  21290. } else {
  21291. target._chunks = chunks;
  21292. }
  21293. this._copyCommonProps(target);
  21294. if (!ignoreIndices) {
  21295. target._indices = this._cloneIndices();
  21296. }
  21297. target._updateGetRawIdx();
  21298. return target;
  21299. };
  21300. DataStore.prototype._copyCommonProps = function (target) {
  21301. target._count = this._count;
  21302. target._rawCount = this._rawCount;
  21303. target._provider = this._provider;
  21304. target._dimensions = this._dimensions;
  21305. target._extent = clone(this._extent);
  21306. target._rawExtent = clone(this._rawExtent);
  21307. };
  21308. DataStore.prototype._cloneIndices = function () {
  21309. if (this._indices) {
  21310. var Ctor = this._indices.constructor;
  21311. var indices = void 0;
  21312. if (Ctor === Array) {
  21313. var thisCount = this._indices.length;
  21314. indices = new Ctor(thisCount);
  21315. for (var i = 0; i < thisCount; i++) {
  21316. indices[i] = this._indices[i];
  21317. }
  21318. } else {
  21319. indices = new Ctor(this._indices);
  21320. }
  21321. return indices;
  21322. }
  21323. return null;
  21324. };
  21325. DataStore.prototype._getRawIdxIdentity = function (idx) {
  21326. return idx;
  21327. };
  21328. DataStore.prototype._getRawIdx = function (idx) {
  21329. if (idx < this._count && idx >= 0) {
  21330. return this._indices[idx];
  21331. }
  21332. return -1;
  21333. };
  21334. DataStore.prototype._updateGetRawIdx = function () {
  21335. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  21336. };
  21337. DataStore.internalField = function () {
  21338. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  21339. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  21340. }
  21341. defaultDimValueGetters = {
  21342. arrayRows: getDimValueSimply,
  21343. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  21344. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  21345. },
  21346. keyedColumns: getDimValueSimply,
  21347. original: function (dataItem, property, dataIndex, dimIndex) {
  21348. // Performance sensitive, do not use modelUtil.getDataItemValue.
  21349. // If dataItem is an plain object with no value field, the let `value`
  21350. // will be assigned with the object, but it will be tread correctly
  21351. // in the `convertValue`.
  21352. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  21353. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  21354. : value, this._dimensions[dimIndex]);
  21355. },
  21356. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  21357. return dataItem[dimIndex];
  21358. }
  21359. };
  21360. }();
  21361. return DataStore;
  21362. }();
  21363. /**
  21364. * [REQUIREMENT_MEMO]:
  21365. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  21366. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  21367. * `root-dataset`. Them on `series` has higher priority.
  21368. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  21369. * confuse users: whether those props indicate how to visit the upstream source or visit
  21370. * the transform result source, and some transforms has nothing to do with these props,
  21371. * and some transforms might have multiple upstream.
  21372. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  21373. * declared in `root-dataset`.
  21374. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  21375. * That is for reducing complexity in transforms.
  21376. * PENDING: Whether to provide transposition transform?
  21377. *
  21378. * [IMPLEMENTAION_MEMO]:
  21379. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  21380. * They will not be calculated until `source` is about to be visited (to prevent from
  21381. * duplicate calcuation). `source` is visited only in series and input to transforms.
  21382. *
  21383. * [DIMENSION_INHERIT_RULE]:
  21384. * By default the dimensions are inherited from ancestors, unless a transform return
  21385. * a new dimensions definition.
  21386. * Consider the case:
  21387. * ```js
  21388. * dataset: [{
  21389. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  21390. * }, {
  21391. * transform: { type: 'filter', ... }
  21392. * }]
  21393. * dataset: [{
  21394. * dimension: ['Product', 'Sales', 'Prise'],
  21395. * source: [ ['Cookies', 321, 44.21], ...]
  21396. * }, {
  21397. * transform: { type: 'filter', ... }
  21398. * }]
  21399. * ```
  21400. * The two types of option should have the same behavior after transform.
  21401. *
  21402. *
  21403. * [SCENARIO]:
  21404. * (1) Provide source data directly:
  21405. * ```js
  21406. * series: {
  21407. * encode: {...},
  21408. * dimensions: [...]
  21409. * seriesLayoutBy: 'row',
  21410. * data: [[...]]
  21411. * }
  21412. * ```
  21413. * (2) Series refer to dataset.
  21414. * ```js
  21415. * series: [{
  21416. * encode: {...}
  21417. * // Ignore datasetIndex means `datasetIndex: 0`
  21418. * // and the dimensions defination in dataset is used
  21419. * }, {
  21420. * encode: {...},
  21421. * seriesLayoutBy: 'column',
  21422. * datasetIndex: 1
  21423. * }]
  21424. * ```
  21425. * (3) dataset transform
  21426. * ```js
  21427. * dataset: [{
  21428. * source: [...]
  21429. * }, {
  21430. * source: [...]
  21431. * }, {
  21432. * // By default from 0.
  21433. * transform: { type: 'filter', config: {...} }
  21434. * }, {
  21435. * // Piped.
  21436. * transform: [
  21437. * { type: 'filter', config: {...} },
  21438. * { type: 'sort', config: {...} }
  21439. * ]
  21440. * }, {
  21441. * id: 'regressionData',
  21442. * fromDatasetIndex: 1,
  21443. * // Third-party transform
  21444. * transform: { type: 'ecStat:regression', config: {...} }
  21445. * }, {
  21446. * // retrieve the extra result.
  21447. * id: 'regressionFormula',
  21448. * fromDatasetId: 'regressionData',
  21449. * fromTransformResult: 1
  21450. * }]
  21451. * ```
  21452. */
  21453. var SourceManager =
  21454. /** @class */
  21455. function () {
  21456. function SourceManager(sourceHost) {
  21457. // Cached source. Do not repeat calculating if not dirty.
  21458. this._sourceList = [];
  21459. this._storeList = []; // version sign of each upstream source manager.
  21460. this._upstreamSignList = [];
  21461. this._versionSignBase = 0;
  21462. this._dirty = true;
  21463. this._sourceHost = sourceHost;
  21464. }
  21465. /**
  21466. * Mark dirty.
  21467. */
  21468. SourceManager.prototype.dirty = function () {
  21469. this._setLocalSource([], []);
  21470. this._storeList = [];
  21471. this._dirty = true;
  21472. };
  21473. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  21474. this._sourceList = sourceList;
  21475. this._upstreamSignList = upstreamSignList;
  21476. this._versionSignBase++;
  21477. if (this._versionSignBase > 9e10) {
  21478. this._versionSignBase = 0;
  21479. }
  21480. };
  21481. /**
  21482. * For detecting whether the upstream source is dirty, so that
  21483. * the local cached source (in `_sourceList`) should be discarded.
  21484. */
  21485. SourceManager.prototype._getVersionSign = function () {
  21486. return this._sourceHost.uid + '_' + this._versionSignBase;
  21487. };
  21488. /**
  21489. * Always return a source instance. Otherwise throw error.
  21490. */
  21491. SourceManager.prototype.prepareSource = function () {
  21492. // For the case that call `setOption` multiple time but no data changed,
  21493. // cache the result source to prevent from repeating transform.
  21494. if (this._isDirty()) {
  21495. this._createSource();
  21496. this._dirty = false;
  21497. }
  21498. };
  21499. SourceManager.prototype._createSource = function () {
  21500. this._setLocalSource([], []);
  21501. var sourceHost = this._sourceHost;
  21502. var upSourceMgrList = this._getUpstreamSourceManagers();
  21503. var hasUpstream = !!upSourceMgrList.length;
  21504. var resultSourceList;
  21505. var upstreamSignList;
  21506. if (isSeries(sourceHost)) {
  21507. var seriesModel = sourceHost;
  21508. var data = void 0;
  21509. var sourceFormat = void 0;
  21510. var upSource = void 0; // Has upstream dataset
  21511. if (hasUpstream) {
  21512. var upSourceMgr = upSourceMgrList[0];
  21513. upSourceMgr.prepareSource();
  21514. upSource = upSourceMgr.getSource();
  21515. data = upSource.data;
  21516. sourceFormat = upSource.sourceFormat;
  21517. upstreamSignList = [upSourceMgr._getVersionSign()];
  21518. } // Series data is from own.
  21519. else {
  21520. data = seriesModel.get('data', true);
  21521. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  21522. upstreamSignList = [];
  21523. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  21524. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  21525. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  21526. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  21527. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader); // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  21528. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  21529. // but series need `seriesLayoutBy: 'row'`.
  21530. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions); // We share source with dataset as much as possible
  21531. // to avoid extra memory cost of high dimensional data.
  21532. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  21533. resultSourceList = needsCreateSource ? [createSource(data, {
  21534. seriesLayoutBy: seriesLayoutBy,
  21535. sourceHeader: sourceHeader,
  21536. dimensions: dimensions
  21537. }, sourceFormat)] : [];
  21538. } else {
  21539. var datasetModel = sourceHost; // Has upstream dataset.
  21540. if (hasUpstream) {
  21541. var result = this._applyTransform(upSourceMgrList);
  21542. resultSourceList = result.sourceList;
  21543. upstreamSignList = result.upstreamSignList;
  21544. } // Is root dataset.
  21545. else {
  21546. var sourceData = datasetModel.get('source', true);
  21547. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  21548. upstreamSignList = [];
  21549. }
  21550. }
  21551. if ("development" !== 'production') {
  21552. assert(resultSourceList && upstreamSignList);
  21553. }
  21554. this._setLocalSource(resultSourceList, upstreamSignList);
  21555. };
  21556. SourceManager.prototype._applyTransform = function (upMgrList) {
  21557. var datasetModel = this._sourceHost;
  21558. var transformOption = datasetModel.get('transform', true);
  21559. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  21560. if ("development" !== 'production') {
  21561. assert(fromTransformResult != null || transformOption != null);
  21562. }
  21563. if (fromTransformResult != null) {
  21564. var errMsg = '';
  21565. if (upMgrList.length !== 1) {
  21566. if ("development" !== 'production') {
  21567. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  21568. }
  21569. doThrow(errMsg);
  21570. }
  21571. }
  21572. var sourceList;
  21573. var upSourceList = [];
  21574. var upstreamSignList = [];
  21575. each(upMgrList, function (upMgr) {
  21576. upMgr.prepareSource();
  21577. var upSource = upMgr.getSource(fromTransformResult || 0);
  21578. var errMsg = '';
  21579. if (fromTransformResult != null && !upSource) {
  21580. if ("development" !== 'production') {
  21581. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  21582. }
  21583. doThrow(errMsg);
  21584. }
  21585. upSourceList.push(upSource);
  21586. upstreamSignList.push(upMgr._getVersionSign());
  21587. });
  21588. if (transformOption) {
  21589. sourceList = applyDataTransform(transformOption, upSourceList, {
  21590. datasetIndex: datasetModel.componentIndex
  21591. });
  21592. } else if (fromTransformResult != null) {
  21593. sourceList = [cloneSourceShallow(upSourceList[0])];
  21594. }
  21595. return {
  21596. sourceList: sourceList,
  21597. upstreamSignList: upstreamSignList
  21598. };
  21599. };
  21600. SourceManager.prototype._isDirty = function () {
  21601. if (this._dirty) {
  21602. return true;
  21603. } // All sourceList is from the some upstream.
  21604. var upSourceMgrList = this._getUpstreamSourceManagers();
  21605. for (var i = 0; i < upSourceMgrList.length; i++) {
  21606. var upSrcMgr = upSourceMgrList[i];
  21607. if ( // Consider the case that there is ancestor diry, call it recursively.
  21608. // The performance is probably not an issue because usually the chain is not long.
  21609. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  21610. return true;
  21611. }
  21612. }
  21613. };
  21614. /**
  21615. * @param sourceIndex By default 0, means "main source".
  21616. * In most cases there is only one source.
  21617. */
  21618. SourceManager.prototype.getSource = function (sourceIndex) {
  21619. sourceIndex = sourceIndex || 0;
  21620. var source = this._sourceList[sourceIndex];
  21621. if (!source) {
  21622. // Series may share source instance with dataset.
  21623. var upSourceMgrList = this._getUpstreamSourceManagers();
  21624. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  21625. }
  21626. return source;
  21627. };
  21628. /**
  21629. *
  21630. * Get a data store which can be shared across series.
  21631. * Only available for series.
  21632. *
  21633. * @param seriesDimRequest Dimensions that are generated in series.
  21634. * Should have been sorted by `storeDimIndex` asc.
  21635. */
  21636. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  21637. if ("development" !== 'production') {
  21638. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  21639. }
  21640. var schema = seriesDimRequest.makeStoreSchema();
  21641. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  21642. };
  21643. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  21644. // TODO Can use other sourceIndex?
  21645. var sourceIndex = 0;
  21646. var storeList = this._storeList;
  21647. var cachedStoreMap = storeList[sourceIndex];
  21648. if (!cachedStoreMap) {
  21649. cachedStoreMap = storeList[sourceIndex] = {};
  21650. }
  21651. var cachedStore = cachedStoreMap[sourceReadKey];
  21652. if (!cachedStore) {
  21653. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  21654. if (isSeries(this._sourceHost) && upSourceMgr) {
  21655. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  21656. } else {
  21657. cachedStore = new DataStore(); // Always create store from source of series.
  21658. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  21659. }
  21660. cachedStoreMap[sourceReadKey] = cachedStore;
  21661. }
  21662. return cachedStore;
  21663. };
  21664. /**
  21665. * PENDING: Is it fast enough?
  21666. * If no upstream, return empty array.
  21667. */
  21668. SourceManager.prototype._getUpstreamSourceManagers = function () {
  21669. // Always get the relationship from the raw option.
  21670. // Do not cache the link of the dependency graph, so that
  21671. // there is no need to update them when change happens.
  21672. var sourceHost = this._sourceHost;
  21673. if (isSeries(sourceHost)) {
  21674. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  21675. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  21676. } else {
  21677. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  21678. return datasetModel.getSourceManager();
  21679. });
  21680. }
  21681. };
  21682. SourceManager.prototype._getSourceMetaRawOption = function () {
  21683. var sourceHost = this._sourceHost;
  21684. var seriesLayoutBy;
  21685. var sourceHeader;
  21686. var dimensions;
  21687. if (isSeries(sourceHost)) {
  21688. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  21689. sourceHeader = sourceHost.get('sourceHeader', true);
  21690. dimensions = sourceHost.get('dimensions', true);
  21691. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  21692. else if (!this._getUpstreamSourceManagers().length) {
  21693. var model = sourceHost;
  21694. seriesLayoutBy = model.get('seriesLayoutBy', true);
  21695. sourceHeader = model.get('sourceHeader', true);
  21696. dimensions = model.get('dimensions', true);
  21697. }
  21698. return {
  21699. seriesLayoutBy: seriesLayoutBy,
  21700. sourceHeader: sourceHeader,
  21701. dimensions: dimensions
  21702. };
  21703. };
  21704. return SourceManager;
  21705. }();
  21706. // disable the transform merge, but do not disable transform clone from rawOption.
  21707. function disableTransformOptionMerge(datasetModel) {
  21708. var transformOption = datasetModel.option.transform;
  21709. transformOption && setAsPrimitive(datasetModel.option.transform);
  21710. }
  21711. function isSeries(sourceHost) {
  21712. // Avoid circular dependency with Series.ts
  21713. return sourceHost.mainType === 'series';
  21714. }
  21715. function doThrow(errMsg) {
  21716. throw new Error(errMsg);
  21717. }
  21718. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1'; // TODO: more textStyle option
  21719. function getTooltipTextStyle(textStyle, renderMode) {
  21720. var nameFontColor = textStyle.color || '#6e7079';
  21721. var nameFontSize = textStyle.fontSize || 12;
  21722. var nameFontWeight = textStyle.fontWeight || '400';
  21723. var valueFontColor = textStyle.color || '#464646';
  21724. var valueFontSize = textStyle.fontSize || 14;
  21725. var valueFontWeight = textStyle.fontWeight || '900';
  21726. if (renderMode === 'html') {
  21727. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  21728. return {
  21729. // eslint-disable-next-line max-len
  21730. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  21731. // eslint-disable-next-line max-len
  21732. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  21733. };
  21734. } else {
  21735. return {
  21736. nameStyle: {
  21737. fontSize: nameFontSize,
  21738. fill: nameFontColor,
  21739. fontWeight: nameFontWeight
  21740. },
  21741. valueStyle: {
  21742. fontSize: valueFontSize,
  21743. fill: valueFontColor,
  21744. fontWeight: valueFontWeight
  21745. }
  21746. };
  21747. }
  21748. } // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  21749. // (value from UI design)
  21750. var HTML_GAPS = [0, 10, 20, 30];
  21751. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n']; // eslint-disable-next-line max-len
  21752. function createTooltipMarkup(type, option) {
  21753. option.type = type;
  21754. return option;
  21755. }
  21756. function isSectionFragment(frag) {
  21757. return frag.type === 'section';
  21758. }
  21759. function getBuilder(frag) {
  21760. return isSectionFragment(frag) ? buildSection : buildNameValue;
  21761. }
  21762. function getBlockGapLevel(frag) {
  21763. if (isSectionFragment(frag)) {
  21764. var gapLevel_1 = 0;
  21765. var subBlockLen = frag.blocks.length;
  21766. var hasInnerGap_1 = subBlockLen > 1 || subBlockLen > 0 && !frag.noHeader;
  21767. each(frag.blocks, function (subBlock) {
  21768. var subGapLevel = getBlockGapLevel(subBlock); // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  21769. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  21770. if (subGapLevel >= gapLevel_1) {
  21771. gapLevel_1 = subGapLevel + +(hasInnerGap_1 && ( // 0 always can not be readable gap level.
  21772. !subGapLevel // If no header, always keep the sub gap level. Otherwise
  21773. // look weird in case `multipleSeries`.
  21774. || isSectionFragment(subBlock) && !subBlock.noHeader));
  21775. }
  21776. });
  21777. return gapLevel_1;
  21778. }
  21779. return 0;
  21780. }
  21781. function buildSection(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21782. var noHeader = fragment.noHeader;
  21783. var gaps = getGap(getBlockGapLevel(fragment));
  21784. var subMarkupTextList = [];
  21785. var subBlocks = fragment.blocks || [];
  21786. assert(!subBlocks || isArray(subBlocks));
  21787. subBlocks = subBlocks || [];
  21788. var orderMode = ctx.orderMode;
  21789. if (fragment.sortBlocks && orderMode) {
  21790. subBlocks = subBlocks.slice();
  21791. var orderMap = {
  21792. valueAsc: 'asc',
  21793. valueDesc: 'desc'
  21794. };
  21795. if (hasOwn(orderMap, orderMode)) {
  21796. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  21797. subBlocks.sort(function (a, b) {
  21798. return comparator_1.evaluate(a.sortParam, b.sortParam);
  21799. });
  21800. } // FIXME 'seriesDesc' necessary?
  21801. else if (orderMode === 'seriesDesc') {
  21802. subBlocks.reverse();
  21803. }
  21804. }
  21805. each(subBlocks, function (subBlock, idx) {
  21806. var valueFormatter = fragment.valueFormatter;
  21807. var subMarkupText = getBuilder(subBlock)( // Inherit valueFormatter
  21808. valueFormatter ? extend(extend({}, ctx), {
  21809. valueFormatter: valueFormatter
  21810. }) : ctx, subBlock, idx > 0 ? gaps.html : 0, toolTipTextStyle);
  21811. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  21812. });
  21813. var subMarkupText = ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), noHeader ? topMarginForOuterGap : gaps.html);
  21814. if (noHeader) {
  21815. return subMarkupText;
  21816. }
  21817. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  21818. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  21819. if (ctx.renderMode === 'richText') {
  21820. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  21821. } else {
  21822. return wrapBlockHTML("<div style=\"" + nameStyle + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  21823. }
  21824. }
  21825. function buildNameValue(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21826. var renderMode = ctx.renderMode;
  21827. var noName = fragment.noName;
  21828. var noValue = fragment.noValue;
  21829. var noMarker = !fragment.markerType;
  21830. var name = fragment.name;
  21831. var useUTC = ctx.useUTC;
  21832. var valueFormatter = fragment.valueFormatter || ctx.valueFormatter || function (value) {
  21833. value = isArray(value) ? value : [value];
  21834. return map(value, function (val, idx) {
  21835. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  21836. });
  21837. };
  21838. if (noName && noValue) {
  21839. return;
  21840. }
  21841. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  21842. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  21843. var valueTypeOption = fragment.valueType;
  21844. var readableValueList = noValue ? [] : valueFormatter(fragment.value);
  21845. var valueAlignRight = !noMarker || !noName; // It little weird if only value next to marker but far from marker.
  21846. var valueCloseToMarker = !noMarker && noName;
  21847. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  21848. nameStyle = _a.nameStyle,
  21849. valueStyle = _a.valueStyle;
  21850. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle)) // Value has commas inside, so use ' ' as delimiter for multiple values.
  21851. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  21852. }
  21853. /**
  21854. * @return markupText. null/undefined means no content.
  21855. */
  21856. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  21857. if (!fragment) {
  21858. return;
  21859. }
  21860. var builder = getBuilder(fragment);
  21861. var ctx = {
  21862. useUTC: useUTC,
  21863. renderMode: renderMode,
  21864. orderMode: orderMode,
  21865. markupStyleCreator: markupStyleCreator,
  21866. valueFormatter: fragment.valueFormatter
  21867. };
  21868. return builder(ctx, fragment, 0, toolTipTextStyle);
  21869. }
  21870. function getGap(gapLevel) {
  21871. return {
  21872. html: HTML_GAPS[gapLevel],
  21873. richText: RICH_TEXT_GAPS[gapLevel]
  21874. };
  21875. }
  21876. function wrapBlockHTML(encodedContent, topGap) {
  21877. var clearfix = '<div style="clear:both"></div>';
  21878. var marginCSS = "margin: " + topGap + "px 0 0";
  21879. return "<div style=\"" + marginCSS + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodedContent + clearfix + '</div>';
  21880. }
  21881. function wrapInlineNameHTML(name, leftHasMarker, style) {
  21882. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  21883. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  21884. }
  21885. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  21886. // Do not too close to marker, considering there are multiple values separated by spaces.
  21887. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  21888. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  21889. valueList = isArray(valueList) ? valueList : [valueList];
  21890. return "<span style=\"" + alignCSS + ";" + style + "\">" // Value has commas inside, so use ' ' as delimiter for multiple values.
  21891. + map(valueList, function (value) {
  21892. return encodeHTML(value);
  21893. }).join('&nbsp;&nbsp;') + '</span>';
  21894. }
  21895. function wrapInlineNameRichText(ctx, name, style) {
  21896. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  21897. }
  21898. function wrapInlineValueRichText(ctx, values, alignRight, valueCloseToMarker, style) {
  21899. var styles = [style];
  21900. var paddingLeft = valueCloseToMarker ? 10 : 20;
  21901. alignRight && styles.push({
  21902. padding: [0, 0, 0, paddingLeft],
  21903. align: 'right'
  21904. }); // Value has commas inside, so use ' ' as delimiter for multiple values.
  21905. return ctx.markupStyleCreator.wrapRichTextStyle(isArray(values) ? values.join(' ') : values, styles);
  21906. }
  21907. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  21908. var style = series.getData().getItemVisual(dataIndex, 'style');
  21909. var color = style[series.visualDrawType];
  21910. return convertToColorString(color);
  21911. }
  21912. function getPaddingFromTooltipModel(model, renderMode) {
  21913. var padding = model.get('padding');
  21914. return padding != null ? padding // We give slightly different to look pretty.
  21915. : renderMode === 'richText' ? [8, 10] : 10;
  21916. }
  21917. /**
  21918. * The major feature is generate styles for `renderMode: 'richText'`.
  21919. * But it also serves `renderMode: 'html'` to provide
  21920. * "renderMode-independent" API.
  21921. */
  21922. var TooltipMarkupStyleCreator =
  21923. /** @class */
  21924. function () {
  21925. function TooltipMarkupStyleCreator() {
  21926. this.richTextStyles = {}; // Notice that "generate a style name" usually happens repeatedly when mouse is moving and
  21927. // a tooltip is displayed. So we put the `_nextStyleNameId` as a member of each creator
  21928. // rather than static shared by all creators (which will cause it increase to fast).
  21929. this._nextStyleNameId = getRandomIdBase();
  21930. }
  21931. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  21932. return '__EC_aUTo_' + this._nextStyleNameId++;
  21933. };
  21934. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  21935. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  21936. var marker = getTooltipMarker({
  21937. color: colorStr,
  21938. type: markerType,
  21939. renderMode: renderMode,
  21940. markerId: markerId
  21941. });
  21942. if (isString(marker)) {
  21943. return marker;
  21944. } else {
  21945. if ("development" !== 'production') {
  21946. assert(markerId);
  21947. }
  21948. this.richTextStyles[markerId] = marker.style;
  21949. return marker.content;
  21950. }
  21951. };
  21952. /**
  21953. * @usage
  21954. * ```ts
  21955. * const styledText = markupStyleCreator.wrapRichTextStyle([
  21956. * // The styles will be auto merged.
  21957. * {
  21958. * fontSize: 12,
  21959. * color: 'blue'
  21960. * },
  21961. * {
  21962. * padding: 20
  21963. * }
  21964. * ]);
  21965. * ```
  21966. */
  21967. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  21968. var finalStl = {};
  21969. if (isArray(styles)) {
  21970. each(styles, function (stl) {
  21971. return extend(finalStl, stl);
  21972. });
  21973. } else {
  21974. extend(finalStl, styles);
  21975. }
  21976. var styleName = this._generateStyleName();
  21977. this.richTextStyles[styleName] = finalStl;
  21978. return "{" + styleName + "|" + text + "}";
  21979. };
  21980. return TooltipMarkupStyleCreator;
  21981. }();
  21982. function defaultSeriesFormatTooltip(opt) {
  21983. var series = opt.series;
  21984. var dataIndex = opt.dataIndex;
  21985. var multipleSeries = opt.multipleSeries;
  21986. var data = series.getData();
  21987. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  21988. var tooltipDimLen = tooltipDims.length;
  21989. var value = series.getRawValue(dataIndex);
  21990. var isValueArr = isArray(value);
  21991. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  21992. var inlineValue;
  21993. var inlineValueType;
  21994. var subBlocks;
  21995. var sortParam;
  21996. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  21997. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  21998. inlineValue = formatArrResult.inlineValues;
  21999. inlineValueType = formatArrResult.inlineValueTypes;
  22000. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  22001. sortParam = formatArrResult.inlineValues[0];
  22002. } else if (tooltipDimLen) {
  22003. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  22004. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  22005. inlineValueType = dimInfo.type;
  22006. } else {
  22007. sortParam = inlineValue = isValueArr ? value[0] : value;
  22008. } // Do not show generated series name. It might not be readable.
  22009. var seriesNameSpecified = isNameSpecified(series);
  22010. var seriesName = seriesNameSpecified && series.name || '';
  22011. var itemName = data.getName(dataIndex);
  22012. var inlineName = multipleSeries ? seriesName : itemName;
  22013. return createTooltipMarkup('section', {
  22014. header: seriesName,
  22015. // When series name is not specified, do not show a header line with only '-'.
  22016. // This case always happens in tooltip.trigger: 'item'.
  22017. noHeader: multipleSeries || !seriesNameSpecified,
  22018. sortParam: sortParam,
  22019. blocks: [createTooltipMarkup('nameValue', {
  22020. markerType: 'item',
  22021. markerColor: markerColor,
  22022. // Do not mix display seriesName and itemName in one tooltip,
  22023. // which might confuses users.
  22024. name: inlineName,
  22025. // name dimension might be auto assigned, where the name might
  22026. // be not readable. So we check trim here.
  22027. noName: !trim(inlineName),
  22028. value: inlineValue,
  22029. valueType: inlineValueType
  22030. })].concat(subBlocks || [])
  22031. });
  22032. }
  22033. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  22034. // check: category-no-encode-has-axis-data in dataset.html
  22035. var data = series.getData();
  22036. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  22037. var dimItem = data.getDimensionInfo(idx);
  22038. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  22039. }, false);
  22040. var inlineValues = [];
  22041. var inlineValueTypes = [];
  22042. var blocks = [];
  22043. tooltipDims.length ? each(tooltipDims, function (dim) {
  22044. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  22045. }) // By default, all dims is used on tooltip.
  22046. : each(value, setEachItem);
  22047. function setEachItem(val, dim) {
  22048. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  22049. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  22050. return;
  22051. }
  22052. if (isValueMultipleLine) {
  22053. blocks.push(createTooltipMarkup('nameValue', {
  22054. markerType: 'subItem',
  22055. markerColor: colorStr,
  22056. name: dimInfo.displayName,
  22057. value: val,
  22058. valueType: dimInfo.type
  22059. }));
  22060. } else {
  22061. inlineValues.push(val);
  22062. inlineValueTypes.push(dimInfo.type);
  22063. }
  22064. }
  22065. return {
  22066. inlineValues: inlineValues,
  22067. inlineValueTypes: inlineValueTypes,
  22068. blocks: blocks
  22069. };
  22070. }
  22071. var inner$1 = makeInner();
  22072. function getSelectionKey(data, dataIndex) {
  22073. return data.getName(dataIndex) || data.getId(dataIndex);
  22074. }
  22075. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  22076. var SeriesModel =
  22077. /** @class */
  22078. function (_super) {
  22079. __extends(SeriesModel, _super);
  22080. function SeriesModel() {
  22081. // [Caution]: Because this class or desecendants can be used as `XXX.extend(subProto)`,
  22082. // the class members must not be initialized in constructor or declaration place.
  22083. // Otherwise there is bad case:
  22084. // class A {xxx = 1;}
  22085. // enableClassExtend(A);
  22086. // class B extends A {}
  22087. // var C = B.extend({xxx: 5});
  22088. // var c = new C();
  22089. // console.log(c.xxx); // expect 5 but always 1.
  22090. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  22091. // Props about data selection
  22092. // ---------------------------------------
  22093. _this._selectedDataIndicesMap = {};
  22094. return _this;
  22095. }
  22096. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  22097. this.seriesIndex = this.componentIndex;
  22098. this.dataTask = createTask({
  22099. count: dataTaskCount,
  22100. reset: dataTaskReset
  22101. });
  22102. this.dataTask.context = {
  22103. model: this
  22104. };
  22105. this.mergeDefaultAndTheme(option, ecModel);
  22106. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  22107. sourceManager.prepareSource();
  22108. var data = this.getInitialData(option, ecModel);
  22109. wrapData(data, this);
  22110. this.dataTask.context.data = data;
  22111. if ("development" !== 'production') {
  22112. assert(data, 'getInitialData returned invalid data.');
  22113. }
  22114. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  22115. // dataBeforeProcessed by cloneShallow), cloneShallow will
  22116. // cause data.graph.data !== data when using
  22117. // module:echarts/data/Graph or module:echarts/data/Tree.
  22118. // See module:echarts/data/helper/linkSeriesData
  22119. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  22120. // init or merge stage, because the data can be restored. So we do not `restoreData`
  22121. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  22122. // Call `seriesModel.getRawData()` instead.
  22123. // this.restoreData();
  22124. autoSeriesName(this);
  22125. this._initSelectedMapFromData(data);
  22126. };
  22127. /**
  22128. * Util for merge default and theme to option
  22129. */
  22130. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  22131. var layoutMode = fetchLayoutMode(this);
  22132. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  22133. // But if name duplicate between series subType
  22134. // (for example: parallel) add component mainType,
  22135. // add suffix 'Series'.
  22136. var themeSubType = this.subType;
  22137. if (ComponentModel.hasClass(themeSubType)) {
  22138. themeSubType += 'Series';
  22139. }
  22140. merge(option, ecModel.getTheme().get(this.subType));
  22141. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  22142. defaultEmphasis(option, 'label', ['show']);
  22143. this.fillDataTextStyle(option.data);
  22144. if (layoutMode) {
  22145. mergeLayoutParam(option, inputPositionParams, layoutMode);
  22146. }
  22147. };
  22148. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  22149. // this.settingTask.dirty();
  22150. newSeriesOption = merge(this.option, newSeriesOption, true);
  22151. this.fillDataTextStyle(newSeriesOption.data);
  22152. var layoutMode = fetchLayoutMode(this);
  22153. if (layoutMode) {
  22154. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  22155. }
  22156. var sourceManager = inner$1(this).sourceManager;
  22157. sourceManager.dirty();
  22158. sourceManager.prepareSource();
  22159. var data = this.getInitialData(newSeriesOption, ecModel);
  22160. wrapData(data, this);
  22161. this.dataTask.dirty();
  22162. this.dataTask.context.data = data;
  22163. inner$1(this).dataBeforeProcessed = data;
  22164. autoSeriesName(this);
  22165. this._initSelectedMapFromData(data);
  22166. };
  22167. SeriesModel.prototype.fillDataTextStyle = function (data) {
  22168. // Default data label emphasis `show`
  22169. // FIXME Tree structure data ?
  22170. // FIXME Performance ?
  22171. if (data && !isTypedArray(data)) {
  22172. var props = ['show'];
  22173. for (var i = 0; i < data.length; i++) {
  22174. if (data[i] && data[i].label) {
  22175. defaultEmphasis(data[i], 'label', props);
  22176. }
  22177. }
  22178. }
  22179. };
  22180. /**
  22181. * Init a data structure from data related option in series
  22182. * Must be overridden.
  22183. */
  22184. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  22185. return;
  22186. };
  22187. /**
  22188. * Append data to list
  22189. */
  22190. SeriesModel.prototype.appendData = function (params) {
  22191. // FIXME ???
  22192. // (1) If data from dataset, forbidden append.
  22193. // (2) support append data of dataset.
  22194. var data = this.getRawData();
  22195. data.appendData(params.data);
  22196. };
  22197. /**
  22198. * Consider some method like `filter`, `map` need make new data,
  22199. * We should make sure that `seriesModel.getData()` get correct
  22200. * data in the stream procedure. So we fetch data from upstream
  22201. * each time `task.perform` called.
  22202. */
  22203. SeriesModel.prototype.getData = function (dataType) {
  22204. var task = getCurrentTask(this);
  22205. if (task) {
  22206. var data = task.context.data;
  22207. return dataType == null ? data : data.getLinkedData(dataType);
  22208. } else {
  22209. // When series is not alive (that may happen when click toolbox
  22210. // restore or setOption with not merge mode), series data may
  22211. // be still need to judge animation or something when graphic
  22212. // elements want to know whether fade out.
  22213. return inner$1(this).data;
  22214. }
  22215. };
  22216. SeriesModel.prototype.getAllData = function () {
  22217. var mainData = this.getData();
  22218. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  22219. data: mainData
  22220. }];
  22221. };
  22222. SeriesModel.prototype.setData = function (data) {
  22223. var task = getCurrentTask(this);
  22224. if (task) {
  22225. var context = task.context; // Consider case: filter, data sample.
  22226. // FIXME:TS never used, so comment it
  22227. // if (context.data !== data && task.modifyOutputEnd) {
  22228. // task.setOutputEnd(data.count());
  22229. // }
  22230. context.outputData = data; // Caution: setData should update context.data,
  22231. // Because getData may be called multiply in a
  22232. // single stage and expect to get the data just
  22233. // set. (For example, AxisProxy, x y both call
  22234. // getData and setDate sequentially).
  22235. // So the context.data should be fetched from
  22236. // upstream each time when a stage starts to be
  22237. // performed.
  22238. if (task !== this.dataTask) {
  22239. context.data = data;
  22240. }
  22241. }
  22242. inner$1(this).data = data;
  22243. };
  22244. SeriesModel.prototype.getEncode = function () {
  22245. var encode = this.get('encode', true);
  22246. if (encode) {
  22247. return createHashMap(encode);
  22248. }
  22249. };
  22250. SeriesModel.prototype.getSourceManager = function () {
  22251. return inner$1(this).sourceManager;
  22252. };
  22253. SeriesModel.prototype.getSource = function () {
  22254. return this.getSourceManager().getSource();
  22255. };
  22256. /**
  22257. * Get data before processed
  22258. */
  22259. SeriesModel.prototype.getRawData = function () {
  22260. return inner$1(this).dataBeforeProcessed;
  22261. };
  22262. SeriesModel.prototype.getColorBy = function () {
  22263. var colorBy = this.get('colorBy');
  22264. return colorBy || 'series';
  22265. };
  22266. SeriesModel.prototype.isColorBySeries = function () {
  22267. return this.getColorBy() === 'series';
  22268. };
  22269. /**
  22270. * Get base axis if has coordinate system and has axis.
  22271. * By default use coordSys.getBaseAxis();
  22272. * Can be overridden for some chart.
  22273. * @return {type} description
  22274. */
  22275. SeriesModel.prototype.getBaseAxis = function () {
  22276. var coordSys = this.coordinateSystem; // @ts-ignore
  22277. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  22278. };
  22279. /**
  22280. * Default tooltip formatter
  22281. *
  22282. * @param dataIndex
  22283. * @param multipleSeries
  22284. * @param dataType
  22285. * @param renderMode valid values: 'html'(by default) and 'richText'.
  22286. * 'html' is used for rendering tooltip in extra DOM form, and the result
  22287. * string is used as DOM HTML content.
  22288. * 'richText' is used for rendering tooltip in rich text form, for those where
  22289. * DOM operation is not supported.
  22290. * @return formatted tooltip with `html` and `markers`
  22291. * Notice: The override method can also return string
  22292. */
  22293. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  22294. return defaultSeriesFormatTooltip({
  22295. series: this,
  22296. dataIndex: dataIndex,
  22297. multipleSeries: multipleSeries
  22298. });
  22299. };
  22300. SeriesModel.prototype.isAnimationEnabled = function () {
  22301. var ecModel = this.ecModel; // Disable animation if using echarts in node but not give ssr flag.
  22302. // In ssr mode, renderToString will generate svg with css animation.
  22303. if (env.node && !(ecModel && ecModel.ssr)) {
  22304. return false;
  22305. }
  22306. var animationEnabled = this.getShallow('animation');
  22307. if (animationEnabled) {
  22308. if (this.getData().count() > this.getShallow('animationThreshold')) {
  22309. animationEnabled = false;
  22310. }
  22311. }
  22312. return !!animationEnabled;
  22313. };
  22314. SeriesModel.prototype.restoreData = function () {
  22315. this.dataTask.dirty();
  22316. };
  22317. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  22318. var ecModel = this.ecModel; // PENDING
  22319. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  22320. if (!color) {
  22321. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  22322. }
  22323. return color;
  22324. };
  22325. /**
  22326. * Use `data.mapDimensionsAll(coordDim)` instead.
  22327. * @deprecated
  22328. */
  22329. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  22330. return this.getRawData().mapDimensionsAll(coordDim);
  22331. };
  22332. /**
  22333. * Get progressive rendering count each step
  22334. */
  22335. SeriesModel.prototype.getProgressive = function () {
  22336. return this.get('progressive');
  22337. };
  22338. /**
  22339. * Get progressive rendering count each step
  22340. */
  22341. SeriesModel.prototype.getProgressiveThreshold = function () {
  22342. return this.get('progressiveThreshold');
  22343. }; // PENGING If selectedMode is null ?
  22344. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  22345. this._innerSelect(this.getData(dataType), innerDataIndices);
  22346. };
  22347. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  22348. var selectedMap = this.option.selectedMap;
  22349. if (!selectedMap) {
  22350. return;
  22351. }
  22352. var selectedMode = this.option.selectedMode;
  22353. var data = this.getData(dataType);
  22354. if (selectedMode === 'series' || selectedMap === 'all') {
  22355. this.option.selectedMap = {};
  22356. this._selectedDataIndicesMap = {};
  22357. return;
  22358. }
  22359. for (var i = 0; i < innerDataIndices.length; i++) {
  22360. var dataIndex = innerDataIndices[i];
  22361. var nameOrId = getSelectionKey(data, dataIndex);
  22362. selectedMap[nameOrId] = false;
  22363. this._selectedDataIndicesMap[nameOrId] = -1;
  22364. }
  22365. };
  22366. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  22367. var tmpArr = [];
  22368. for (var i = 0; i < innerDataIndices.length; i++) {
  22369. tmpArr[0] = innerDataIndices[i];
  22370. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  22371. }
  22372. };
  22373. SeriesModel.prototype.getSelectedDataIndices = function () {
  22374. if (this.option.selectedMap === 'all') {
  22375. return [].slice.call(this.getData().getIndices());
  22376. }
  22377. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  22378. var nameOrIds = keys(selectedDataIndicesMap);
  22379. var dataIndices = [];
  22380. for (var i = 0; i < nameOrIds.length; i++) {
  22381. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  22382. if (dataIndex >= 0) {
  22383. dataIndices.push(dataIndex);
  22384. }
  22385. }
  22386. return dataIndices;
  22387. };
  22388. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  22389. var selectedMap = this.option.selectedMap;
  22390. if (!selectedMap) {
  22391. return false;
  22392. }
  22393. var data = this.getData(dataType);
  22394. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  22395. };
  22396. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  22397. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  22398. return true;
  22399. }
  22400. var universalTransitionOpt = this.option.universalTransition; // Quick reject
  22401. if (!universalTransitionOpt) {
  22402. return false;
  22403. }
  22404. if (universalTransitionOpt === true) {
  22405. return true;
  22406. } // Can be simply 'universalTransition: true'
  22407. return universalTransitionOpt && universalTransitionOpt.enabled;
  22408. };
  22409. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  22410. var _a, _b;
  22411. var option = this.option;
  22412. var selectedMode = option.selectedMode;
  22413. var len = innerDataIndices.length;
  22414. if (!selectedMode || !len) {
  22415. return;
  22416. }
  22417. if (selectedMode === 'series') {
  22418. option.selectedMap = 'all';
  22419. } else if (selectedMode === 'multiple') {
  22420. if (!isObject(option.selectedMap)) {
  22421. option.selectedMap = {};
  22422. }
  22423. var selectedMap = option.selectedMap;
  22424. for (var i = 0; i < len; i++) {
  22425. var dataIndex = innerDataIndices[i]; // TODO different types of data share same object.
  22426. var nameOrId = getSelectionKey(data, dataIndex);
  22427. selectedMap[nameOrId] = true;
  22428. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  22429. }
  22430. } else if (selectedMode === 'single' || selectedMode === true) {
  22431. var lastDataIndex = innerDataIndices[len - 1];
  22432. var nameOrId = getSelectionKey(data, lastDataIndex);
  22433. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  22434. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  22435. }
  22436. };
  22437. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  22438. // Ignore select info in data if selectedMap exists.
  22439. // NOTE It's only for legacy usage. edge data is not supported.
  22440. if (this.option.selectedMap) {
  22441. return;
  22442. }
  22443. var dataIndices = [];
  22444. if (data.hasItemOption) {
  22445. data.each(function (idx) {
  22446. var rawItem = data.getRawDataItem(idx);
  22447. if (rawItem && rawItem.selected) {
  22448. dataIndices.push(idx);
  22449. }
  22450. });
  22451. }
  22452. if (dataIndices.length > 0) {
  22453. this._innerSelect(data, dataIndices);
  22454. }
  22455. }; // /**
  22456. // * @see {module:echarts/stream/Scheduler}
  22457. // */
  22458. // abstract pipeTask: null
  22459. SeriesModel.registerClass = function (clz) {
  22460. return ComponentModel.registerClass(clz);
  22461. };
  22462. SeriesModel.protoInitialize = function () {
  22463. var proto = SeriesModel.prototype;
  22464. proto.type = 'series.__base__';
  22465. proto.seriesIndex = 0;
  22466. proto.ignoreStyleOnData = false;
  22467. proto.hasSymbolVisual = false;
  22468. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  22469. proto.visualStyleAccessPath = 'itemStyle';
  22470. proto.visualDrawType = 'fill';
  22471. }();
  22472. return SeriesModel;
  22473. }(ComponentModel);
  22474. mixin(SeriesModel, DataFormatMixin);
  22475. mixin(SeriesModel, PaletteMixin);
  22476. mountExtend(SeriesModel, ComponentModel);
  22477. /**
  22478. * MUST be called after `prepareSource` called
  22479. * Here we need to make auto series, especially for auto legend. But we
  22480. * do not modify series.name in option to avoid side effects.
  22481. */
  22482. function autoSeriesName(seriesModel) {
  22483. // User specified name has higher priority, otherwise it may cause
  22484. // series can not be queried unexpectedly.
  22485. var name = seriesModel.name;
  22486. if (!isNameSpecified(seriesModel)) {
  22487. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  22488. }
  22489. }
  22490. function getSeriesAutoName(seriesModel) {
  22491. var data = seriesModel.getRawData();
  22492. var dataDims = data.mapDimensionsAll('seriesName');
  22493. var nameArr = [];
  22494. each(dataDims, function (dataDim) {
  22495. var dimInfo = data.getDimensionInfo(dataDim);
  22496. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  22497. });
  22498. return nameArr.join(' ');
  22499. }
  22500. function dataTaskCount(context) {
  22501. return context.model.getRawData().count();
  22502. }
  22503. function dataTaskReset(context) {
  22504. var seriesModel = context.model;
  22505. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  22506. return dataTaskProgress;
  22507. }
  22508. function dataTaskProgress(param, context) {
  22509. // Avoid repeat cloneShallow when data just created in reset.
  22510. if (context.outputData && param.end > context.outputData.count()) {
  22511. context.model.getRawData().cloneShallow(context.outputData);
  22512. }
  22513. } // TODO refactor
  22514. function wrapData(data, seriesModel) {
  22515. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  22516. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  22517. });
  22518. }
  22519. function onDataChange(seriesModel, newList) {
  22520. var task = getCurrentTask(seriesModel);
  22521. if (task) {
  22522. // Consider case: filter, selectRange
  22523. task.setOutputEnd((newList || this).count());
  22524. }
  22525. return newList;
  22526. }
  22527. function getCurrentTask(seriesModel) {
  22528. var scheduler = (seriesModel.ecModel || {}).scheduler;
  22529. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  22530. if (pipeline) {
  22531. // When pipline finished, the currrentTask keep the last
  22532. // task (renderTask).
  22533. var task = pipeline.currentTask;
  22534. if (task) {
  22535. var agentStubMap = task.agentStubMap;
  22536. if (agentStubMap) {
  22537. task = agentStubMap.get(seriesModel.uid);
  22538. }
  22539. }
  22540. return task;
  22541. }
  22542. }
  22543. var ComponentView =
  22544. /** @class */
  22545. function () {
  22546. function ComponentView() {
  22547. this.group = new Group();
  22548. this.uid = getUID('viewComponent');
  22549. }
  22550. ComponentView.prototype.init = function (ecModel, api) {};
  22551. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  22552. ComponentView.prototype.dispose = function (ecModel, api) {};
  22553. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  22554. };
  22555. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  22556. };
  22557. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  22558. };
  22559. /**
  22560. * Hook for toggle blur target series.
  22561. * Can be used in marker for blur or leave blur the markers
  22562. */
  22563. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {// Do nothing;
  22564. };
  22565. /**
  22566. * Traverse the new rendered elements.
  22567. *
  22568. * It will traverse the new added element in progressive rendering.
  22569. * And traverse all in normal rendering.
  22570. */
  22571. ComponentView.prototype.eachRendered = function (cb) {
  22572. var group = this.group;
  22573. if (group) {
  22574. group.traverse(cb);
  22575. }
  22576. };
  22577. return ComponentView;
  22578. }();
  22579. enableClassExtend(ComponentView);
  22580. enableClassManagement(ComponentView);
  22581. /**
  22582. * @return {string} If large mode changed, return string 'reset';
  22583. */
  22584. function createRenderPlanner() {
  22585. var inner = makeInner();
  22586. return function (seriesModel) {
  22587. var fields = inner(seriesModel);
  22588. var pipelineContext = seriesModel.pipelineContext;
  22589. var originalLarge = !!fields.large;
  22590. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  22591. // exists. See #11611 . Probably we need to modify this structure, see the comment
  22592. // on `performRawSeries` in `Schedular.js`.
  22593. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  22594. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  22595. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  22596. };
  22597. }
  22598. var inner$2 = makeInner();
  22599. var renderPlanner = createRenderPlanner();
  22600. var ChartView =
  22601. /** @class */
  22602. function () {
  22603. function ChartView() {
  22604. this.group = new Group();
  22605. this.uid = getUID('viewChart');
  22606. this.renderTask = createTask({
  22607. plan: renderTaskPlan,
  22608. reset: renderTaskReset
  22609. });
  22610. this.renderTask.context = {
  22611. view: this
  22612. };
  22613. }
  22614. ChartView.prototype.init = function (ecModel, api) {};
  22615. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  22616. if ("development" !== 'production') {
  22617. throw new Error('render method must been implemented');
  22618. }
  22619. };
  22620. /**
  22621. * Highlight series or specified data item.
  22622. */
  22623. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  22624. var data = seriesModel.getData(payload && payload.dataType);
  22625. if (!data) {
  22626. if ("development" !== 'production') {
  22627. error("Unknown dataType " + payload.dataType);
  22628. }
  22629. return;
  22630. }
  22631. toggleHighlight(data, payload, 'emphasis');
  22632. };
  22633. /**
  22634. * Downplay series or specified data item.
  22635. */
  22636. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  22637. var data = seriesModel.getData(payload && payload.dataType);
  22638. if (!data) {
  22639. if ("development" !== 'production') {
  22640. error("Unknown dataType " + payload.dataType);
  22641. }
  22642. return;
  22643. }
  22644. toggleHighlight(data, payload, 'normal');
  22645. };
  22646. /**
  22647. * Remove self.
  22648. */
  22649. ChartView.prototype.remove = function (ecModel, api) {
  22650. this.group.removeAll();
  22651. };
  22652. /**
  22653. * Dispose self.
  22654. */
  22655. ChartView.prototype.dispose = function (ecModel, api) {};
  22656. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  22657. this.render(seriesModel, ecModel, api, payload);
  22658. }; // FIXME never used?
  22659. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  22660. this.render(seriesModel, ecModel, api, payload);
  22661. }; // FIXME never used?
  22662. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  22663. this.render(seriesModel, ecModel, api, payload);
  22664. };
  22665. /**
  22666. * Traverse the new rendered elements.
  22667. *
  22668. * It will traverse the new added element in progressive rendering.
  22669. * And traverse all in normal rendering.
  22670. */
  22671. ChartView.prototype.eachRendered = function (cb) {
  22672. traverseElements(this.group, cb);
  22673. };
  22674. ChartView.markUpdateMethod = function (payload, methodName) {
  22675. inner$2(payload).updateMethod = methodName;
  22676. };
  22677. ChartView.protoInitialize = function () {
  22678. var proto = ChartView.prototype;
  22679. proto.type = 'chart';
  22680. }();
  22681. return ChartView;
  22682. }();
  22683. /**
  22684. * Set state of single element
  22685. */
  22686. function elSetState(el, state, highlightDigit) {
  22687. if (el && isHighDownDispatcher(el)) {
  22688. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  22689. }
  22690. }
  22691. function toggleHighlight(data, payload, state) {
  22692. var dataIndex = queryDataIndex(data, payload);
  22693. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  22694. if (dataIndex != null) {
  22695. each(normalizeToArray(dataIndex), function (dataIdx) {
  22696. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22697. });
  22698. } else {
  22699. data.eachItemGraphicEl(function (el) {
  22700. elSetState(el, state, highlightDigit);
  22701. });
  22702. }
  22703. }
  22704. enableClassExtend(ChartView, ['dispose']);
  22705. enableClassManagement(ChartView);
  22706. function renderTaskPlan(context) {
  22707. return renderPlanner(context.model);
  22708. }
  22709. function renderTaskReset(context) {
  22710. var seriesModel = context.model;
  22711. var ecModel = context.ecModel;
  22712. var api = context.api;
  22713. var payload = context.payload; // FIXME: remove updateView updateVisual
  22714. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22715. var view = context.view;
  22716. var updateMethod = payload && inner$2(payload).updateMethod;
  22717. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  22718. // is less than progressive threshold.
  22719. : 'render';
  22720. if (methodName !== 'render') {
  22721. view[methodName](seriesModel, ecModel, api, payload);
  22722. }
  22723. return progressMethodMap[methodName];
  22724. }
  22725. var progressMethodMap = {
  22726. incrementalPrepareRender: {
  22727. progress: function (params, context) {
  22728. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  22729. }
  22730. },
  22731. render: {
  22732. // Put view.render in `progress` to support appendData. But in this case
  22733. // view.render should not be called in reset, otherwise it will be called
  22734. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22735. // in any cases.
  22736. forceFirstProgress: true,
  22737. progress: function (params, context) {
  22738. context.view.render(context.model, context.ecModel, context.api, context.payload);
  22739. }
  22740. }
  22741. };
  22742. /*
  22743. * Licensed to the Apache Software Foundation (ASF) under one
  22744. * or more contributor license agreements. See the NOTICE file
  22745. * distributed with this work for additional information
  22746. * regarding copyright ownership. The ASF licenses this file
  22747. * to you under the Apache License, Version 2.0 (the
  22748. * "License"); you may not use this file except in compliance
  22749. * with the License. You may obtain a copy of the License at
  22750. *
  22751. * http://www.apache.org/licenses/LICENSE-2.0
  22752. *
  22753. * Unless required by applicable law or agreed to in writing,
  22754. * software distributed under the License is distributed on an
  22755. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22756. * KIND, either express or implied. See the License for the
  22757. * specific language governing permissions and limitations
  22758. * under the License.
  22759. */
  22760. /**
  22761. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22762. */
  22763. /*
  22764. * Licensed to the Apache Software Foundation (ASF) under one
  22765. * or more contributor license agreements. See the NOTICE file
  22766. * distributed with this work for additional information
  22767. * regarding copyright ownership. The ASF licenses this file
  22768. * to you under the Apache License, Version 2.0 (the
  22769. * "License"); you may not use this file except in compliance
  22770. * with the License. You may obtain a copy of the License at
  22771. *
  22772. * http://www.apache.org/licenses/LICENSE-2.0
  22773. *
  22774. * Unless required by applicable law or agreed to in writing,
  22775. * software distributed under the License is distributed on an
  22776. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22777. * KIND, either express or implied. See the License for the
  22778. * specific language governing permissions and limitations
  22779. * under the License.
  22780. */
  22781. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22782. var RATE = '\0__throttleRate';
  22783. var THROTTLE_TYPE = '\0__throttleType';
  22784. /**
  22785. * @public
  22786. * @param {(Function)} fn
  22787. * @param {number} [delay=0] Unit: ms.
  22788. * @param {boolean} [debounce=false]
  22789. * true: If call interval less than `delay`, only the last call works.
  22790. * false: If call interval less than `delay, call works on fixed rate.
  22791. * @return {(Function)} throttled fn.
  22792. */
  22793. function throttle(fn, delay, debounce) {
  22794. var currCall;
  22795. var lastCall = 0;
  22796. var lastExec = 0;
  22797. var timer = null;
  22798. var diff;
  22799. var scope;
  22800. var args;
  22801. var debounceNextCall;
  22802. delay = delay || 0;
  22803. function exec() {
  22804. lastExec = new Date().getTime();
  22805. timer = null;
  22806. fn.apply(scope, args || []);
  22807. }
  22808. var cb = function () {
  22809. var cbArgs = [];
  22810. for (var _i = 0; _i < arguments.length; _i++) {
  22811. cbArgs[_i] = arguments[_i];
  22812. }
  22813. currCall = new Date().getTime();
  22814. scope = this;
  22815. args = cbArgs;
  22816. var thisDelay = debounceNextCall || delay;
  22817. var thisDebounce = debounceNextCall || debounce;
  22818. debounceNextCall = null;
  22819. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22820. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  22821. // than a new call of `cb`, that is, preserving the command order. Consider
  22822. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22823. // happens, either the `exec` is called dierectly, or the call is delayed.
  22824. // But the delayed call should never be later than next call of `cb`. Under
  22825. // this assurance, we can simply update view state each time `dispatchAction`
  22826. // triggered by user roaming, but not need to add extra code to avoid the
  22827. // state being "rolled-back".
  22828. if (thisDebounce) {
  22829. timer = setTimeout(exec, thisDelay);
  22830. } else {
  22831. if (diff >= 0) {
  22832. exec();
  22833. } else {
  22834. timer = setTimeout(exec, -diff);
  22835. }
  22836. }
  22837. lastCall = currCall;
  22838. };
  22839. /**
  22840. * Clear throttle.
  22841. * @public
  22842. */
  22843. cb.clear = function () {
  22844. if (timer) {
  22845. clearTimeout(timer);
  22846. timer = null;
  22847. }
  22848. };
  22849. /**
  22850. * Enable debounce once.
  22851. */
  22852. cb.debounceNextCall = function (debounceDelay) {
  22853. debounceNextCall = debounceDelay;
  22854. };
  22855. return cb;
  22856. }
  22857. /**
  22858. * Create throttle method or update throttle rate.
  22859. *
  22860. * @example
  22861. * ComponentView.prototype.render = function () {
  22862. * ...
  22863. * throttle.createOrUpdate(
  22864. * this,
  22865. * '_dispatchAction',
  22866. * this.model.get('throttle'),
  22867. * 'fixRate'
  22868. * );
  22869. * };
  22870. * ComponentView.prototype.remove = function () {
  22871. * throttle.clear(this, '_dispatchAction');
  22872. * };
  22873. * ComponentView.prototype.dispose = function () {
  22874. * throttle.clear(this, '_dispatchAction');
  22875. * };
  22876. *
  22877. */
  22878. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22879. var fn = obj[fnAttr];
  22880. if (!fn) {
  22881. return;
  22882. }
  22883. var originFn = fn[ORIGIN_METHOD] || fn;
  22884. var lastThrottleType = fn[THROTTLE_TYPE];
  22885. var lastRate = fn[RATE];
  22886. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22887. if (rate == null || !throttleType) {
  22888. return obj[fnAttr] = originFn;
  22889. }
  22890. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  22891. fn[ORIGIN_METHOD] = originFn;
  22892. fn[THROTTLE_TYPE] = throttleType;
  22893. fn[RATE] = rate;
  22894. }
  22895. return fn;
  22896. }
  22897. /**
  22898. * Clear throttle. Example see throttle.createOrUpdate.
  22899. */
  22900. function clear(obj, fnAttr) {
  22901. var fn = obj[fnAttr];
  22902. if (fn && fn[ORIGIN_METHOD]) {
  22903. // Clear throttle
  22904. fn.clear && fn.clear();
  22905. obj[fnAttr] = fn[ORIGIN_METHOD];
  22906. }
  22907. }
  22908. var inner$3 = makeInner();
  22909. var defaultStyleMappers = {
  22910. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  22911. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  22912. };
  22913. var defaultColorKey = {
  22914. lineStyle: 'stroke',
  22915. itemStyle: 'fill'
  22916. };
  22917. function getStyleMapper(seriesModel, stylePath) {
  22918. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  22919. if (!styleMapper) {
  22920. console.warn("Unknown style type '" + stylePath + "'.");
  22921. return defaultStyleMappers.itemStyle;
  22922. }
  22923. return styleMapper;
  22924. }
  22925. function getDefaultColorKey(seriesModel, stylePath) {
  22926. // return defaultColorKey[stylePath] ||
  22927. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  22928. if (!colorKey) {
  22929. console.warn("Unknown style type '" + stylePath + "'.");
  22930. return 'fill';
  22931. }
  22932. return colorKey;
  22933. }
  22934. var seriesStyleTask = {
  22935. createOnAllSeries: true,
  22936. performRawSeries: true,
  22937. reset: function (seriesModel, ecModel) {
  22938. var data = seriesModel.getData();
  22939. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22940. var styleModel = seriesModel.getModel(stylePath);
  22941. var getStyle = getStyleMapper(seriesModel, stylePath);
  22942. var globalStyle = getStyle(styleModel);
  22943. var decalOption = styleModel.getShallow('decal');
  22944. if (decalOption) {
  22945. data.setVisual('decal', decalOption);
  22946. decalOption.dirty = true;
  22947. } // TODO
  22948. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22949. var color = globalStyle[colorKey]; // TODO style callback
  22950. var colorCallback = isFunction(color) ? color : null;
  22951. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto'; // Get from color palette by default.
  22952. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  22953. // Note: If some series has color specified (e.g., by itemStyle.color), we DO NOT
  22954. // make it effect palette. Because some scenarios users need to make some series
  22955. // transparent or as background, which should better not effect the palette.
  22956. var colorPalette = seriesModel.getColorFromPalette( // TODO series count changed.
  22957. seriesModel.name, null, ecModel.getSeriesCount());
  22958. if (!globalStyle[colorKey]) {
  22959. globalStyle[colorKey] = colorPalette;
  22960. data.setVisual('colorFromPalette', true);
  22961. }
  22962. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  22963. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  22964. }
  22965. data.setVisual('style', globalStyle);
  22966. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  22967. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  22968. data.setVisual('colorFromPalette', false);
  22969. return {
  22970. dataEach: function (data, idx) {
  22971. var dataParams = seriesModel.getDataParams(idx);
  22972. var itemStyle = extend({}, globalStyle);
  22973. itemStyle[colorKey] = colorCallback(dataParams);
  22974. data.setItemVisual(idx, 'style', itemStyle);
  22975. }
  22976. };
  22977. }
  22978. }
  22979. };
  22980. var sharedModel = new Model();
  22981. var dataStyleTask = {
  22982. createOnAllSeries: true,
  22983. performRawSeries: true,
  22984. reset: function (seriesModel, ecModel) {
  22985. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  22986. return;
  22987. }
  22988. var data = seriesModel.getData();
  22989. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22990. var getStyle = getStyleMapper(seriesModel, stylePath);
  22991. var colorKey = data.getVisual('drawType');
  22992. return {
  22993. dataEach: data.hasItemOption ? function (data, idx) {
  22994. // Not use getItemModel for performance considuration
  22995. var rawItem = data.getRawDataItem(idx);
  22996. if (rawItem && rawItem[stylePath]) {
  22997. sharedModel.option = rawItem[stylePath];
  22998. var style = getStyle(sharedModel);
  22999. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  23000. extend(existsStyle, style);
  23001. if (sharedModel.option.decal) {
  23002. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  23003. sharedModel.option.decal.dirty = true;
  23004. }
  23005. if (colorKey in style) {
  23006. data.setItemVisual(idx, 'colorFromPalette', false);
  23007. }
  23008. }
  23009. } : null
  23010. };
  23011. }
  23012. }; // Pick color from palette for the data which has not been set with color yet.
  23013. // Note: do not support stream rendering. No such cases yet.
  23014. var dataColorPaletteTask = {
  23015. performRawSeries: true,
  23016. overallReset: function (ecModel) {
  23017. // Each type of series uses one scope.
  23018. // Pie and funnel are using different scopes.
  23019. var paletteScopeGroupByType = createHashMap();
  23020. ecModel.eachSeries(function (seriesModel) {
  23021. var colorBy = seriesModel.getColorBy();
  23022. if (seriesModel.isColorBySeries()) {
  23023. return;
  23024. }
  23025. var key = seriesModel.type + '-' + colorBy;
  23026. var colorScope = paletteScopeGroupByType.get(key);
  23027. if (!colorScope) {
  23028. colorScope = {};
  23029. paletteScopeGroupByType.set(key, colorScope);
  23030. }
  23031. inner$3(seriesModel).scope = colorScope;
  23032. });
  23033. ecModel.eachSeries(function (seriesModel) {
  23034. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  23035. return;
  23036. }
  23037. var dataAll = seriesModel.getRawData();
  23038. var idxMap = {};
  23039. var data = seriesModel.getData();
  23040. var colorScope = inner$3(seriesModel).scope;
  23041. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  23042. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  23043. data.each(function (idx) {
  23044. var rawIdx = data.getRawIndex(idx);
  23045. idxMap[rawIdx] = idx;
  23046. }); // Iterate on data before filtered. To make sure color from palette can be
  23047. // Consistent when toggling legend.
  23048. dataAll.each(function (rawIdx) {
  23049. var idx = idxMap[rawIdx];
  23050. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  23051. // also picked from color palette. So following situation is not in the case:
  23052. // 1. series.itemStyle.color is set
  23053. // 2. color is encoded by visualMap
  23054. if (fromPalette) {
  23055. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  23056. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  23057. var dataCount = dataAll.count();
  23058. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  23059. }
  23060. });
  23061. });
  23062. }
  23063. };
  23064. var PI$3 = Math.PI;
  23065. /**
  23066. * @param {module:echarts/ExtensionAPI} api
  23067. * @param {Object} [opts]
  23068. * @param {string} [opts.text]
  23069. * @param {string} [opts.color]
  23070. * @param {string} [opts.textColor]
  23071. * @return {module:zrender/Element}
  23072. */
  23073. function defaultLoading(api, opts) {
  23074. opts = opts || {};
  23075. defaults(opts, {
  23076. text: 'loading',
  23077. textColor: '#000',
  23078. fontSize: 12,
  23079. fontWeight: 'normal',
  23080. fontStyle: 'normal',
  23081. fontFamily: 'sans-serif',
  23082. maskColor: 'rgba(255, 255, 255, 0.8)',
  23083. showSpinner: true,
  23084. color: '#5470c6',
  23085. spinnerRadius: 10,
  23086. lineWidth: 5,
  23087. zlevel: 0
  23088. });
  23089. var group = new Group();
  23090. var mask = new Rect({
  23091. style: {
  23092. fill: opts.maskColor
  23093. },
  23094. zlevel: opts.zlevel,
  23095. z: 10000
  23096. });
  23097. group.add(mask);
  23098. var textContent = new ZRText({
  23099. style: {
  23100. text: opts.text,
  23101. fill: opts.textColor,
  23102. fontSize: opts.fontSize,
  23103. fontWeight: opts.fontWeight,
  23104. fontStyle: opts.fontStyle,
  23105. fontFamily: opts.fontFamily
  23106. },
  23107. zlevel: opts.zlevel,
  23108. z: 10001
  23109. });
  23110. var labelRect = new Rect({
  23111. style: {
  23112. fill: 'none'
  23113. },
  23114. textContent: textContent,
  23115. textConfig: {
  23116. position: 'right',
  23117. distance: 10
  23118. },
  23119. zlevel: opts.zlevel,
  23120. z: 10001
  23121. });
  23122. group.add(labelRect);
  23123. var arc;
  23124. if (opts.showSpinner) {
  23125. arc = new Arc({
  23126. shape: {
  23127. startAngle: -PI$3 / 2,
  23128. endAngle: -PI$3 / 2 + 0.1,
  23129. r: opts.spinnerRadius
  23130. },
  23131. style: {
  23132. stroke: opts.color,
  23133. lineCap: 'round',
  23134. lineWidth: opts.lineWidth
  23135. },
  23136. zlevel: opts.zlevel,
  23137. z: 10001
  23138. });
  23139. arc.animateShape(true).when(1000, {
  23140. endAngle: PI$3 * 3 / 2
  23141. }).start('circularInOut');
  23142. arc.animateShape(true).when(1000, {
  23143. startAngle: PI$3 * 3 / 2
  23144. }).delay(300).start('circularInOut');
  23145. group.add(arc);
  23146. } // Inject resize
  23147. group.resize = function () {
  23148. var textWidth = textContent.getBoundingRect().width;
  23149. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  23150. // textDistance needs to be calculated when both animation and text exist
  23151. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  23152. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  23153. + (textWidth ? 0 : r);
  23154. var cy = api.getHeight() / 2;
  23155. opts.showSpinner && arc.setShape({
  23156. cx: cx,
  23157. cy: cy
  23158. });
  23159. labelRect.setShape({
  23160. x: cx - r,
  23161. y: cy - r,
  23162. width: r * 2,
  23163. height: r * 2
  23164. });
  23165. mask.setShape({
  23166. x: 0,
  23167. y: 0,
  23168. width: api.getWidth(),
  23169. height: api.getHeight()
  23170. });
  23171. };
  23172. group.resize();
  23173. return group;
  23174. }
  23175. var Scheduler =
  23176. /** @class */
  23177. function () {
  23178. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  23179. // key: handlerUID
  23180. this._stageTaskMap = createHashMap();
  23181. this.ecInstance = ecInstance;
  23182. this.api = api; // Fix current processors in case that in some rear cases that
  23183. // processors might be registered after echarts instance created.
  23184. // Register processors incrementally for a echarts instance is
  23185. // not supported by this stream architecture.
  23186. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  23187. visualHandlers = this._visualHandlers = visualHandlers.slice();
  23188. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  23189. }
  23190. Scheduler.prototype.restoreData = function (ecModel, payload) {
  23191. // TODO: Only restore needed series and components, but not all components.
  23192. // Currently `restoreData` of all of the series and component will be called.
  23193. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  23194. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  23195. // and some components like coordinate system, axes, dataZoom, visualMap only
  23196. // need their target series refresh.
  23197. // (1) If we are implementing this feature some day, we should consider these cases:
  23198. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  23199. // on the settings of `dataZoom`), it should be re-performed if the component
  23200. // is modified by `setOption`.
  23201. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  23202. // it should be re-performed when the result array of `getTargetSeries` changed.
  23203. // We use `dependencies` to cover these issues.
  23204. // (3) How to update target series when coordinate system related components modified.
  23205. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  23206. // and this case all of the tasks will be set as dirty.
  23207. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  23208. // depends on all of the series.
  23209. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  23210. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  23211. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  23212. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  23213. // probably cause state chaos (consider `dataZoomProcessor`).
  23214. this._stageTaskMap.each(function (taskRecord) {
  23215. var overallTask = taskRecord.overallTask;
  23216. overallTask && overallTask.dirty();
  23217. });
  23218. }; // If seriesModel provided, incremental threshold is check by series data.
  23219. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  23220. // For overall task
  23221. if (!task.__pipeline) {
  23222. return;
  23223. }
  23224. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  23225. var pCtx = pipeline.context;
  23226. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  23227. var step = incremental ? pipeline.step : null;
  23228. var modDataCount = pCtx && pCtx.modDataCount;
  23229. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  23230. return {
  23231. step: step,
  23232. modBy: modBy,
  23233. modDataCount: modDataCount
  23234. };
  23235. };
  23236. Scheduler.prototype.getPipeline = function (pipelineId) {
  23237. return this._pipelineMap.get(pipelineId);
  23238. };
  23239. /**
  23240. * Current, progressive rendering starts from visual and layout.
  23241. * Always detect render mode in the same stage, avoiding that incorrect
  23242. * detection caused by data filtering.
  23243. * Caution:
  23244. * `updateStreamModes` use `seriesModel.getData()`.
  23245. */
  23246. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  23247. var pipeline = this._pipelineMap.get(seriesModel.uid);
  23248. var data = seriesModel.getData();
  23249. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  23250. // animation frame. Note that some types of series do not provide
  23251. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  23252. // use the term `incremental` but not `progressive` to describe the
  23253. // case that `chart.appendData`.
  23254. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  23255. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  23256. // see `test/candlestick-large3.html`
  23257. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  23258. seriesModel.pipelineContext = pipeline.context = {
  23259. progressiveRender: progressiveRender,
  23260. modDataCount: modDataCount,
  23261. large: large
  23262. };
  23263. };
  23264. Scheduler.prototype.restorePipelines = function (ecModel) {
  23265. var scheduler = this;
  23266. var pipelineMap = scheduler._pipelineMap = createHashMap();
  23267. ecModel.eachSeries(function (seriesModel) {
  23268. var progressive = seriesModel.getProgressive();
  23269. var pipelineId = seriesModel.uid;
  23270. pipelineMap.set(pipelineId, {
  23271. id: pipelineId,
  23272. head: null,
  23273. tail: null,
  23274. threshold: seriesModel.getProgressiveThreshold(),
  23275. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  23276. blockIndex: -1,
  23277. step: Math.round(progressive || 700),
  23278. count: 0
  23279. });
  23280. scheduler._pipe(seriesModel, seriesModel.dataTask);
  23281. });
  23282. };
  23283. Scheduler.prototype.prepareStageTasks = function () {
  23284. var stageTaskMap = this._stageTaskMap;
  23285. var ecModel = this.api.getModel();
  23286. var api = this.api;
  23287. each(this._allHandlers, function (handler) {
  23288. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  23289. var errMsg = '';
  23290. if ("development" !== 'production') {
  23291. // Currently do not need to support to sepecify them both.
  23292. errMsg = '"reset" and "overallReset" must not be both specified.';
  23293. }
  23294. assert(!(handler.reset && handler.overallReset), errMsg);
  23295. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  23296. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  23297. }, this);
  23298. };
  23299. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  23300. var renderTask = view.renderTask;
  23301. var context = renderTask.context;
  23302. context.model = model;
  23303. context.ecModel = ecModel;
  23304. context.api = api;
  23305. renderTask.__block = !view.incrementalPrepareRender;
  23306. this._pipe(model, renderTask);
  23307. };
  23308. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  23309. // If we do not use `block` here, it should be considered when to update modes.
  23310. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  23311. block: true
  23312. });
  23313. };
  23314. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  23315. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  23316. };
  23317. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  23318. opt = opt || {};
  23319. var unfinished = false;
  23320. var scheduler = this;
  23321. each(stageHandlers, function (stageHandler, idx) {
  23322. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  23323. return;
  23324. }
  23325. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  23326. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23327. var overallTask = stageHandlerRecord.overallTask;
  23328. if (overallTask) {
  23329. var overallNeedDirty_1;
  23330. var agentStubMap = overallTask.agentStubMap;
  23331. agentStubMap.each(function (stub) {
  23332. if (needSetDirty(opt, stub)) {
  23333. stub.dirty();
  23334. overallNeedDirty_1 = true;
  23335. }
  23336. });
  23337. overallNeedDirty_1 && overallTask.dirty();
  23338. scheduler.updatePayload(overallTask, payload);
  23339. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  23340. // then execute the overall task. And stub will call seriesModel.setData,
  23341. // which ensures that in the overallTask seriesModel.getData() will not
  23342. // return incorrect data.
  23343. agentStubMap.each(function (stub) {
  23344. stub.perform(performArgs_1);
  23345. });
  23346. if (overallTask.perform(performArgs_1)) {
  23347. unfinished = true;
  23348. }
  23349. } else if (seriesTaskMap) {
  23350. seriesTaskMap.each(function (task, pipelineId) {
  23351. if (needSetDirty(opt, task)) {
  23352. task.dirty();
  23353. }
  23354. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  23355. // if intending to declare `performRawSeries` in handlers, only
  23356. // stream-independent (specifically, data item independent) operations can be
  23357. // performed. Because if a series is filtered, most of the tasks will not
  23358. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23359. // Perhaps we should not provide a separate callback for this case instead
  23360. // of providing the config `performRawSeries`. The stream-dependent operations
  23361. // and stream-independent operations should better not be mixed.
  23362. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  23363. scheduler.updatePayload(task, payload);
  23364. if (task.perform(performArgs)) {
  23365. unfinished = true;
  23366. }
  23367. });
  23368. }
  23369. });
  23370. function needSetDirty(opt, task) {
  23371. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23372. }
  23373. this.unfinished = unfinished || this.unfinished;
  23374. };
  23375. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  23376. var unfinished;
  23377. ecModel.eachSeries(function (seriesModel) {
  23378. // Progress to the end for dataInit and dataRestore.
  23379. unfinished = seriesModel.dataTask.perform() || unfinished;
  23380. });
  23381. this.unfinished = unfinished || this.unfinished;
  23382. };
  23383. Scheduler.prototype.plan = function () {
  23384. // Travel pipelines, check block.
  23385. this._pipelineMap.each(function (pipeline) {
  23386. var task = pipeline.tail;
  23387. do {
  23388. if (task.__block) {
  23389. pipeline.blockIndex = task.__idxInPipeline;
  23390. break;
  23391. }
  23392. task = task.getUpstream();
  23393. } while (task);
  23394. });
  23395. };
  23396. Scheduler.prototype.updatePayload = function (task, payload) {
  23397. payload !== 'remain' && (task.context.payload = payload);
  23398. };
  23399. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23400. var scheduler = this;
  23401. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  23402. // do not need to reuse the map.
  23403. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  23404. var seriesType = stageHandler.seriesType;
  23405. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23406. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23407. // it works but it may cause other irrelevant charts blocked.
  23408. if (stageHandler.createOnAllSeries) {
  23409. ecModel.eachRawSeries(create);
  23410. } else if (seriesType) {
  23411. ecModel.eachRawSeriesByType(seriesType, create);
  23412. } else if (getTargetSeries) {
  23413. getTargetSeries(ecModel, api).each(create);
  23414. }
  23415. function create(seriesModel) {
  23416. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  23417. // Reuse original task instance.
  23418. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  23419. plan: seriesTaskPlan,
  23420. reset: seriesTaskReset,
  23421. count: seriesTaskCount
  23422. }));
  23423. task.context = {
  23424. model: seriesModel,
  23425. ecModel: ecModel,
  23426. api: api,
  23427. // PENDING: `useClearVisual` not used?
  23428. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23429. plan: stageHandler.plan,
  23430. reset: stageHandler.reset,
  23431. scheduler: scheduler
  23432. };
  23433. scheduler._pipe(seriesModel, task);
  23434. }
  23435. };
  23436. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23437. var scheduler = this;
  23438. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  23439. || createTask({
  23440. reset: overallTaskReset
  23441. });
  23442. overallTask.context = {
  23443. ecModel: ecModel,
  23444. api: api,
  23445. overallReset: stageHandler.overallReset,
  23446. scheduler: scheduler
  23447. };
  23448. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  23449. // do not need to reuse the map.
  23450. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  23451. var seriesType = stageHandler.seriesType;
  23452. var getTargetSeries = stageHandler.getTargetSeries;
  23453. var overallProgress = true;
  23454. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  23455. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  23456. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23457. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23458. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23459. // we set the pipeline block.
  23460. var errMsg = '';
  23461. if ("development" !== 'production') {
  23462. errMsg = '"createOnAllSeries" is not supported for "overallReset", ' + 'because it will block all streams.';
  23463. }
  23464. assert(!stageHandler.createOnAllSeries, errMsg);
  23465. if (seriesType) {
  23466. ecModel.eachRawSeriesByType(seriesType, createStub);
  23467. } else if (getTargetSeries) {
  23468. getTargetSeries(ecModel, api).each(createStub);
  23469. } // Otherwise, (usually it is legacy case), the overall task will only be
  23470. // executed when upstream is dirty. Otherwise the progressive rendering of all
  23471. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23472. // dirty info from upstream.
  23473. else {
  23474. overallProgress = false;
  23475. each(ecModel.getSeries(), createStub);
  23476. }
  23477. function createStub(seriesModel) {
  23478. var pipelineId = seriesModel.uid;
  23479. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  23480. // should be set as dirty and re-performed.
  23481. shouldOverallTaskDirty = true, createTask({
  23482. reset: stubReset,
  23483. onDirty: stubOnDirty
  23484. })));
  23485. stub.context = {
  23486. model: seriesModel,
  23487. overallProgress: overallProgress // FIXME:TS never used, so comment it
  23488. // modifyOutputEnd: modifyOutputEnd
  23489. };
  23490. stub.agent = overallTask;
  23491. stub.__block = overallProgress;
  23492. scheduler._pipe(seriesModel, stub);
  23493. }
  23494. if (shouldOverallTaskDirty) {
  23495. overallTask.dirty();
  23496. }
  23497. };
  23498. Scheduler.prototype._pipe = function (seriesModel, task) {
  23499. var pipelineId = seriesModel.uid;
  23500. var pipeline = this._pipelineMap.get(pipelineId);
  23501. !pipeline.head && (pipeline.head = task);
  23502. pipeline.tail && pipeline.tail.pipe(task);
  23503. pipeline.tail = task;
  23504. task.__idxInPipeline = pipeline.count++;
  23505. task.__pipeline = pipeline;
  23506. };
  23507. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23508. if (isFunction(stageHandler)) {
  23509. stageHandler = {
  23510. overallReset: stageHandler,
  23511. seriesType: detectSeriseType(stageHandler)
  23512. };
  23513. }
  23514. stageHandler.uid = getUID('stageHandler');
  23515. visualType && (stageHandler.visualType = visualType);
  23516. return stageHandler;
  23517. };
  23518. return Scheduler;
  23519. }();
  23520. function overallTaskReset(context) {
  23521. context.overallReset(context.ecModel, context.api, context.payload);
  23522. }
  23523. function stubReset(context) {
  23524. return context.overallProgress && stubProgress;
  23525. }
  23526. function stubProgress() {
  23527. this.agent.dirty();
  23528. this.getDownstream().dirty();
  23529. }
  23530. function stubOnDirty() {
  23531. this.agent && this.agent.dirty();
  23532. }
  23533. function seriesTaskPlan(context) {
  23534. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  23535. }
  23536. function seriesTaskReset(context) {
  23537. if (context.useClearVisual) {
  23538. context.data.clearAllVisual();
  23539. }
  23540. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  23541. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  23542. return makeSeriesTaskProgress(idx);
  23543. }) : singleSeriesTaskProgress;
  23544. }
  23545. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23546. function makeSeriesTaskProgress(resetDefineIdx) {
  23547. return function (params, context) {
  23548. var data = context.data;
  23549. var resetDefine = context.resetDefines[resetDefineIdx];
  23550. if (resetDefine && resetDefine.dataEach) {
  23551. for (var i = params.start; i < params.end; i++) {
  23552. resetDefine.dataEach(data, i);
  23553. }
  23554. } else if (resetDefine && resetDefine.progress) {
  23555. resetDefine.progress(params, data);
  23556. }
  23557. };
  23558. }
  23559. function seriesTaskCount(context) {
  23560. return context.data.count();
  23561. }
  23562. /**
  23563. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23564. * To ensure that they can work normally, they should work in block mode, that is,
  23565. * they should not be started util the previous tasks finished. So they cause the
  23566. * progressive rendering disabled. We try to detect the series type, to narrow down
  23567. * the block range to only the series type they concern, but not all series.
  23568. */
  23569. function detectSeriseType(legacyFunc) {
  23570. seriesType = null;
  23571. try {
  23572. // Assume there is no async when calling `eachSeriesByType`.
  23573. legacyFunc(ecModelMock, apiMock);
  23574. } catch (e) {}
  23575. return seriesType;
  23576. }
  23577. var ecModelMock = {};
  23578. var apiMock = {};
  23579. var seriesType;
  23580. mockMethods(ecModelMock, GlobalModel);
  23581. mockMethods(apiMock, ExtensionAPI);
  23582. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23583. seriesType = type;
  23584. };
  23585. ecModelMock.eachComponent = function (cond) {
  23586. if (cond.mainType === 'series' && cond.subType) {
  23587. seriesType = cond.subType;
  23588. }
  23589. };
  23590. function mockMethods(target, Clz) {
  23591. /* eslint-disable */
  23592. for (var name_1 in Clz.prototype) {
  23593. // Do not use hasOwnProperty
  23594. target[name_1] = noop;
  23595. }
  23596. /* eslint-enable */
  23597. }
  23598. /*
  23599. * Licensed to the Apache Software Foundation (ASF) under one
  23600. * or more contributor license agreements. See the NOTICE file
  23601. * distributed with this work for additional information
  23602. * regarding copyright ownership. The ASF licenses this file
  23603. * to you under the Apache License, Version 2.0 (the
  23604. * "License"); you may not use this file except in compliance
  23605. * with the License. You may obtain a copy of the License at
  23606. *
  23607. * http://www.apache.org/licenses/LICENSE-2.0
  23608. *
  23609. * Unless required by applicable law or agreed to in writing,
  23610. * software distributed under the License is distributed on an
  23611. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23612. * KIND, either express or implied. See the License for the
  23613. * specific language governing permissions and limitations
  23614. * under the License.
  23615. */
  23616. /**
  23617. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23618. */
  23619. /*
  23620. * Licensed to the Apache Software Foundation (ASF) under one
  23621. * or more contributor license agreements. See the NOTICE file
  23622. * distributed with this work for additional information
  23623. * regarding copyright ownership. The ASF licenses this file
  23624. * to you under the Apache License, Version 2.0 (the
  23625. * "License"); you may not use this file except in compliance
  23626. * with the License. You may obtain a copy of the License at
  23627. *
  23628. * http://www.apache.org/licenses/LICENSE-2.0
  23629. *
  23630. * Unless required by applicable law or agreed to in writing,
  23631. * software distributed under the License is distributed on an
  23632. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23633. * KIND, either express or implied. See the License for the
  23634. * specific language governing permissions and limitations
  23635. * under the License.
  23636. */
  23637. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  23638. var lightTheme = {
  23639. color: colorAll,
  23640. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  23641. };
  23642. /*
  23643. * Licensed to the Apache Software Foundation (ASF) under one
  23644. * or more contributor license agreements. See the NOTICE file
  23645. * distributed with this work for additional information
  23646. * regarding copyright ownership. The ASF licenses this file
  23647. * to you under the Apache License, Version 2.0 (the
  23648. * "License"); you may not use this file except in compliance
  23649. * with the License. You may obtain a copy of the License at
  23650. *
  23651. * http://www.apache.org/licenses/LICENSE-2.0
  23652. *
  23653. * Unless required by applicable law or agreed to in writing,
  23654. * software distributed under the License is distributed on an
  23655. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23656. * KIND, either express or implied. See the License for the
  23657. * specific language governing permissions and limitations
  23658. * under the License.
  23659. */
  23660. /**
  23661. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23662. */
  23663. /*
  23664. * Licensed to the Apache Software Foundation (ASF) under one
  23665. * or more contributor license agreements. See the NOTICE file
  23666. * distributed with this work for additional information
  23667. * regarding copyright ownership. The ASF licenses this file
  23668. * to you under the Apache License, Version 2.0 (the
  23669. * "License"); you may not use this file except in compliance
  23670. * with the License. You may obtain a copy of the License at
  23671. *
  23672. * http://www.apache.org/licenses/LICENSE-2.0
  23673. *
  23674. * Unless required by applicable law or agreed to in writing,
  23675. * software distributed under the License is distributed on an
  23676. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23677. * KIND, either express or implied. See the License for the
  23678. * specific language governing permissions and limitations
  23679. * under the License.
  23680. */
  23681. var contrastColor = '#B9B8CE';
  23682. var backgroundColor = '#100C2A';
  23683. var axisCommon = function () {
  23684. return {
  23685. axisLine: {
  23686. lineStyle: {
  23687. color: contrastColor
  23688. }
  23689. },
  23690. splitLine: {
  23691. lineStyle: {
  23692. color: '#484753'
  23693. }
  23694. },
  23695. splitArea: {
  23696. areaStyle: {
  23697. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  23698. }
  23699. },
  23700. minorSplitLine: {
  23701. lineStyle: {
  23702. color: '#20203B'
  23703. }
  23704. }
  23705. };
  23706. };
  23707. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  23708. var theme = {
  23709. darkMode: true,
  23710. color: colorPalette,
  23711. backgroundColor: backgroundColor,
  23712. axisPointer: {
  23713. lineStyle: {
  23714. color: '#817f91'
  23715. },
  23716. crossStyle: {
  23717. color: '#817f91'
  23718. },
  23719. label: {
  23720. // TODO Contrast of label backgorundColor
  23721. color: '#fff'
  23722. }
  23723. },
  23724. legend: {
  23725. textStyle: {
  23726. color: contrastColor
  23727. }
  23728. },
  23729. textStyle: {
  23730. color: contrastColor
  23731. },
  23732. title: {
  23733. textStyle: {
  23734. color: '#EEF1FA'
  23735. },
  23736. subtextStyle: {
  23737. color: '#B9B8CE'
  23738. }
  23739. },
  23740. toolbox: {
  23741. iconStyle: {
  23742. borderColor: contrastColor
  23743. }
  23744. },
  23745. dataZoom: {
  23746. borderColor: '#71708A',
  23747. textStyle: {
  23748. color: contrastColor
  23749. },
  23750. brushStyle: {
  23751. color: 'rgba(135,163,206,0.3)'
  23752. },
  23753. handleStyle: {
  23754. color: '#353450',
  23755. borderColor: '#C5CBE3'
  23756. },
  23757. moveHandleStyle: {
  23758. color: '#B0B6C3',
  23759. opacity: 0.3
  23760. },
  23761. fillerColor: 'rgba(135,163,206,0.2)',
  23762. emphasis: {
  23763. handleStyle: {
  23764. borderColor: '#91B7F2',
  23765. color: '#4D587D'
  23766. },
  23767. moveHandleStyle: {
  23768. color: '#636D9A',
  23769. opacity: 0.7
  23770. }
  23771. },
  23772. dataBackground: {
  23773. lineStyle: {
  23774. color: '#71708A',
  23775. width: 1
  23776. },
  23777. areaStyle: {
  23778. color: '#71708A'
  23779. }
  23780. },
  23781. selectedDataBackground: {
  23782. lineStyle: {
  23783. color: '#87A3CE'
  23784. },
  23785. areaStyle: {
  23786. color: '#87A3CE'
  23787. }
  23788. }
  23789. },
  23790. visualMap: {
  23791. textStyle: {
  23792. color: contrastColor
  23793. }
  23794. },
  23795. timeline: {
  23796. lineStyle: {
  23797. color: contrastColor
  23798. },
  23799. label: {
  23800. color: contrastColor
  23801. },
  23802. controlStyle: {
  23803. color: contrastColor,
  23804. borderColor: contrastColor
  23805. }
  23806. },
  23807. calendar: {
  23808. itemStyle: {
  23809. color: backgroundColor
  23810. },
  23811. dayLabel: {
  23812. color: contrastColor
  23813. },
  23814. monthLabel: {
  23815. color: contrastColor
  23816. },
  23817. yearLabel: {
  23818. color: contrastColor
  23819. }
  23820. },
  23821. timeAxis: axisCommon(),
  23822. logAxis: axisCommon(),
  23823. valueAxis: axisCommon(),
  23824. categoryAxis: axisCommon(),
  23825. line: {
  23826. symbol: 'circle'
  23827. },
  23828. graph: {
  23829. color: colorPalette
  23830. },
  23831. gauge: {
  23832. title: {
  23833. color: contrastColor
  23834. },
  23835. axisLine: {
  23836. lineStyle: {
  23837. color: [[1, 'rgba(207,212,219,0.2)']]
  23838. }
  23839. },
  23840. axisLabel: {
  23841. color: contrastColor
  23842. },
  23843. detail: {
  23844. color: '#EEF1FA'
  23845. }
  23846. },
  23847. candlestick: {
  23848. itemStyle: {
  23849. color: '#f64e56',
  23850. color0: '#54ea92',
  23851. borderColor: '#f64e56',
  23852. borderColor0: '#54ea92' // borderColor: '#ca2824',
  23853. // borderColor0: '#09a443'
  23854. }
  23855. }
  23856. };
  23857. theme.categoryAxis.splitLine.show = false;
  23858. /**
  23859. * Usage of query:
  23860. * `chart.on('click', query, handler);`
  23861. * The `query` can be:
  23862. * + The component type query string, only `mainType` or `mainType.subType`,
  23863. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  23864. * + The component query object, like:
  23865. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  23866. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  23867. * + The data query object, like:
  23868. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  23869. * + The other query object (cmponent customized query), like:
  23870. * `{element: 'some'}` (only available in custom series).
  23871. *
  23872. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  23873. * same as there is no such prop in the `query` object.
  23874. */
  23875. var ECEventProcessor =
  23876. /** @class */
  23877. function () {
  23878. function ECEventProcessor() {}
  23879. ECEventProcessor.prototype.normalizeQuery = function (query) {
  23880. var cptQuery = {};
  23881. var dataQuery = {};
  23882. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  23883. if (isString(query)) {
  23884. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  23885. cptQuery.mainType = condCptType.main || null;
  23886. cptQuery.subType = condCptType.sub || null;
  23887. } // `query` is an object, convert to {mainType, index, name, id}.
  23888. else {
  23889. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  23890. // can not be used in `compomentModel.filterForExposedEvent`.
  23891. var suffixes_1 = ['Index', 'Name', 'Id'];
  23892. var dataKeys_1 = {
  23893. name: 1,
  23894. dataIndex: 1,
  23895. dataType: 1
  23896. };
  23897. each(query, function (val, key) {
  23898. var reserved = false;
  23899. for (var i = 0; i < suffixes_1.length; i++) {
  23900. var propSuffix = suffixes_1[i];
  23901. var suffixPos = key.lastIndexOf(propSuffix);
  23902. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  23903. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  23904. if (mainType !== 'data') {
  23905. cptQuery.mainType = mainType;
  23906. cptQuery[propSuffix.toLowerCase()] = val;
  23907. reserved = true;
  23908. }
  23909. }
  23910. }
  23911. if (dataKeys_1.hasOwnProperty(key)) {
  23912. dataQuery[key] = val;
  23913. reserved = true;
  23914. }
  23915. if (!reserved) {
  23916. otherQuery[key] = val;
  23917. }
  23918. });
  23919. }
  23920. return {
  23921. cptQuery: cptQuery,
  23922. dataQuery: dataQuery,
  23923. otherQuery: otherQuery
  23924. };
  23925. };
  23926. ECEventProcessor.prototype.filter = function (eventType, query) {
  23927. // They should be assigned before each trigger call.
  23928. var eventInfo = this.eventInfo;
  23929. if (!eventInfo) {
  23930. return true;
  23931. }
  23932. var targetEl = eventInfo.targetEl;
  23933. var packedEvent = eventInfo.packedEvent;
  23934. var model = eventInfo.model;
  23935. var view = eventInfo.view; // For event like 'globalout'.
  23936. if (!model || !view) {
  23937. return true;
  23938. }
  23939. var cptQuery = query.cptQuery;
  23940. var dataQuery = query.dataQuery;
  23941. return check(cptQuery, model, 'mainType') && check(cptQuery, model, 'subType') && check(cptQuery, model, 'index', 'componentIndex') && check(cptQuery, model, 'name') && check(cptQuery, model, 'id') && check(dataQuery, packedEvent, 'name') && check(dataQuery, packedEvent, 'dataIndex') && check(dataQuery, packedEvent, 'dataType') && (!view.filterForExposedEvent || view.filterForExposedEvent(eventType, query.otherQuery, targetEl, packedEvent));
  23942. function check(query, host, prop, propOnHost) {
  23943. return query[prop] == null || host[propOnHost || prop] === query[prop];
  23944. }
  23945. };
  23946. ECEventProcessor.prototype.afterTrigger = function () {
  23947. // Make sure the eventInfo won't be used in next trigger.
  23948. this.eventInfo = null;
  23949. };
  23950. return ECEventProcessor;
  23951. }();
  23952. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  23953. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']); // Encoding visual for all series include which is filtered for legend drawing
  23954. var seriesSymbolTask = {
  23955. createOnAllSeries: true,
  23956. // For legend.
  23957. performRawSeries: true,
  23958. reset: function (seriesModel, ecModel) {
  23959. var data = seriesModel.getData();
  23960. if (seriesModel.legendIcon) {
  23961. data.setVisual('legendIcon', seriesModel.legendIcon);
  23962. }
  23963. if (!seriesModel.hasSymbolVisual) {
  23964. return;
  23965. }
  23966. var symbolOptions = {};
  23967. var symbolOptionsCb = {};
  23968. var hasCallback = false;
  23969. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  23970. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  23971. var val = seriesModel.get(symbolPropName);
  23972. if (isFunction(val)) {
  23973. hasCallback = true;
  23974. symbolOptionsCb[symbolPropName] = val;
  23975. } else {
  23976. symbolOptions[symbolPropName] = val;
  23977. }
  23978. }
  23979. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  23980. data.setVisual(extend({
  23981. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  23982. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  23983. }, symbolOptions)); // Only visible series has each data be visual encoded
  23984. if (ecModel.isSeriesFiltered(seriesModel)) {
  23985. return;
  23986. }
  23987. var symbolPropsCb = keys(symbolOptionsCb);
  23988. function dataEach(data, idx) {
  23989. var rawValue = seriesModel.getRawValue(idx);
  23990. var params = seriesModel.getDataParams(idx);
  23991. for (var i = 0; i < symbolPropsCb.length; i++) {
  23992. var symbolPropName = symbolPropsCb[i];
  23993. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  23994. }
  23995. }
  23996. return {
  23997. dataEach: hasCallback ? dataEach : null
  23998. };
  23999. }
  24000. };
  24001. var dataSymbolTask = {
  24002. createOnAllSeries: true,
  24003. // For legend.
  24004. performRawSeries: true,
  24005. reset: function (seriesModel, ecModel) {
  24006. if (!seriesModel.hasSymbolVisual) {
  24007. return;
  24008. } // Only visible series has each data be visual encoded
  24009. if (ecModel.isSeriesFiltered(seriesModel)) {
  24010. return;
  24011. }
  24012. var data = seriesModel.getData();
  24013. function dataEach(data, idx) {
  24014. var itemModel = data.getItemModel(idx);
  24015. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  24016. var symbolPropName = SYMBOL_PROPS[i];
  24017. var val = itemModel.getShallow(symbolPropName, true);
  24018. if (val != null) {
  24019. data.setItemVisual(idx, symbolPropName, val);
  24020. }
  24021. }
  24022. }
  24023. return {
  24024. dataEach: data.hasItemOption ? dataEach : null
  24025. };
  24026. }
  24027. };
  24028. /*
  24029. * Licensed to the Apache Software Foundation (ASF) under one
  24030. * or more contributor license agreements. See the NOTICE file
  24031. * distributed with this work for additional information
  24032. * regarding copyright ownership. The ASF licenses this file
  24033. * to you under the Apache License, Version 2.0 (the
  24034. * "License"); you may not use this file except in compliance
  24035. * with the License. You may obtain a copy of the License at
  24036. *
  24037. * http://www.apache.org/licenses/LICENSE-2.0
  24038. *
  24039. * Unless required by applicable law or agreed to in writing,
  24040. * software distributed under the License is distributed on an
  24041. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24042. * KIND, either express or implied. See the License for the
  24043. * specific language governing permissions and limitations
  24044. * under the License.
  24045. */
  24046. /**
  24047. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24048. */
  24049. /*
  24050. * Licensed to the Apache Software Foundation (ASF) under one
  24051. * or more contributor license agreements. See the NOTICE file
  24052. * distributed with this work for additional information
  24053. * regarding copyright ownership. The ASF licenses this file
  24054. * to you under the Apache License, Version 2.0 (the
  24055. * "License"); you may not use this file except in compliance
  24056. * with the License. You may obtain a copy of the License at
  24057. *
  24058. * http://www.apache.org/licenses/LICENSE-2.0
  24059. *
  24060. * Unless required by applicable law or agreed to in writing,
  24061. * software distributed under the License is distributed on an
  24062. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24063. * KIND, either express or implied. See the License for the
  24064. * specific language governing permissions and limitations
  24065. * under the License.
  24066. */
  24067. function getItemVisualFromData(data, dataIndex, key) {
  24068. switch (key) {
  24069. case 'color':
  24070. var style = data.getItemVisual(dataIndex, 'style');
  24071. return style[data.getVisual('drawType')];
  24072. case 'opacity':
  24073. return data.getItemVisual(dataIndex, 'style').opacity;
  24074. case 'symbol':
  24075. case 'symbolSize':
  24076. case 'liftZ':
  24077. return data.getItemVisual(dataIndex, key);
  24078. default:
  24079. if ("development" !== 'production') {
  24080. console.warn("Unknown visual type " + key);
  24081. }
  24082. }
  24083. }
  24084. function getVisualFromData(data, key) {
  24085. switch (key) {
  24086. case 'color':
  24087. var style = data.getVisual('style');
  24088. return style[data.getVisual('drawType')];
  24089. case 'opacity':
  24090. return data.getVisual('style').opacity;
  24091. case 'symbol':
  24092. case 'symbolSize':
  24093. case 'liftZ':
  24094. return data.getVisual(key);
  24095. default:
  24096. if ("development" !== 'production') {
  24097. console.warn("Unknown visual type " + key);
  24098. }
  24099. }
  24100. }
  24101. function setItemVisualFromData(data, dataIndex, key, value) {
  24102. switch (key) {
  24103. case 'color':
  24104. // Make sure not sharing style object.
  24105. var style = data.ensureUniqueItemVisual(dataIndex, 'style');
  24106. style[data.getVisual('drawType')] = value; // Mark the color has been changed, not from palette anymore
  24107. data.setItemVisual(dataIndex, 'colorFromPalette', false);
  24108. break;
  24109. case 'opacity':
  24110. data.ensureUniqueItemVisual(dataIndex, 'style').opacity = value;
  24111. break;
  24112. case 'symbol':
  24113. case 'symbolSize':
  24114. case 'liftZ':
  24115. data.setItemVisual(dataIndex, key, value);
  24116. break;
  24117. default:
  24118. if ("development" !== 'production') {
  24119. console.warn("Unknown visual type " + key);
  24120. }
  24121. }
  24122. }
  24123. // Includes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  24124. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  24125. function getSeriesIndices(ecModel, payload) {
  24126. var seriesIndices = [];
  24127. ecModel.eachComponent({
  24128. mainType: 'series',
  24129. subType: seriesType,
  24130. query: payload
  24131. }, function (seriesModel) {
  24132. seriesIndices.push(seriesModel.seriesIndex);
  24133. });
  24134. return seriesIndices;
  24135. }
  24136. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  24137. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  24138. payload = extend({}, payload);
  24139. if ("development" !== 'production') {
  24140. deprecateReplaceLog(payload.type, eventsMap[1]);
  24141. }
  24142. api.dispatchAction(extend(payload, {
  24143. type: eventsMap[1],
  24144. seriesIndex: getSeriesIndices(ecModel, payload)
  24145. }));
  24146. });
  24147. });
  24148. }
  24149. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  24150. var legacyEventName = type + eventPostfix;
  24151. if (!ecIns.isSilent(legacyEventName)) {
  24152. if ("development" !== 'production') {
  24153. deprecateLog("event " + legacyEventName + " is deprecated.");
  24154. }
  24155. ecModel.eachComponent({
  24156. mainType: 'series',
  24157. subType: 'pie'
  24158. }, function (seriesModel) {
  24159. var seriesIndex = seriesModel.seriesIndex;
  24160. var selectedMap = seriesModel.option.selectedMap;
  24161. var selected = payload.selected;
  24162. for (var i = 0; i < selected.length; i++) {
  24163. if (selected[i].seriesIndex === seriesIndex) {
  24164. var data = seriesModel.getData();
  24165. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  24166. ecIns.trigger(legacyEventName, {
  24167. type: legacyEventName,
  24168. seriesId: seriesModel.id,
  24169. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  24170. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  24171. });
  24172. }
  24173. }
  24174. });
  24175. }
  24176. }
  24177. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  24178. messageCenter.on('selectchanged', function (params) {
  24179. var ecModel = api.getModel();
  24180. if (params.isFromClick) {
  24181. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  24182. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  24183. } else if (params.fromAction === 'select') {
  24184. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  24185. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  24186. } else if (params.fromAction === 'unselect') {
  24187. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  24188. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  24189. }
  24190. });
  24191. }
  24192. /*
  24193. * Licensed to the Apache Software Foundation (ASF) under one
  24194. * or more contributor license agreements. See the NOTICE file
  24195. * distributed with this work for additional information
  24196. * regarding copyright ownership. The ASF licenses this file
  24197. * to you under the Apache License, Version 2.0 (the
  24198. * "License"); you may not use this file except in compliance
  24199. * with the License. You may obtain a copy of the License at
  24200. *
  24201. * http://www.apache.org/licenses/LICENSE-2.0
  24202. *
  24203. * Unless required by applicable law or agreed to in writing,
  24204. * software distributed under the License is distributed on an
  24205. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24206. * KIND, either express or implied. See the License for the
  24207. * specific language governing permissions and limitations
  24208. * under the License.
  24209. */
  24210. /**
  24211. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24212. */
  24213. /*
  24214. * Licensed to the Apache Software Foundation (ASF) under one
  24215. * or more contributor license agreements. See the NOTICE file
  24216. * distributed with this work for additional information
  24217. * regarding copyright ownership. The ASF licenses this file
  24218. * to you under the Apache License, Version 2.0 (the
  24219. * "License"); you may not use this file except in compliance
  24220. * with the License. You may obtain a copy of the License at
  24221. *
  24222. * http://www.apache.org/licenses/LICENSE-2.0
  24223. *
  24224. * Unless required by applicable law or agreed to in writing,
  24225. * software distributed under the License is distributed on an
  24226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24227. * KIND, either express or implied. See the License for the
  24228. * specific language governing permissions and limitations
  24229. * under the License.
  24230. */
  24231. function findEventDispatcher(target, det, returnFirstMatch) {
  24232. var found;
  24233. while (target) {
  24234. if (det(target)) {
  24235. found = target;
  24236. if (returnFirstMatch) {
  24237. break;
  24238. }
  24239. }
  24240. target = target.__hostTarget || target.parent;
  24241. }
  24242. return found;
  24243. }
  24244. var wmUniqueIndex = Math.round(Math.random() * 9);
  24245. var supportDefineProperty = typeof Object.defineProperty === 'function';
  24246. var WeakMap = (function () {
  24247. function WeakMap() {
  24248. this._id = '__ec_inner_' + wmUniqueIndex++;
  24249. }
  24250. WeakMap.prototype.get = function (key) {
  24251. return this._guard(key)[this._id];
  24252. };
  24253. WeakMap.prototype.set = function (key, value) {
  24254. var target = this._guard(key);
  24255. if (supportDefineProperty) {
  24256. Object.defineProperty(target, this._id, {
  24257. value: value,
  24258. enumerable: false,
  24259. configurable: true
  24260. });
  24261. }
  24262. else {
  24263. target[this._id] = value;
  24264. }
  24265. return this;
  24266. };
  24267. WeakMap.prototype["delete"] = function (key) {
  24268. if (this.has(key)) {
  24269. delete this._guard(key)[this._id];
  24270. return true;
  24271. }
  24272. return false;
  24273. };
  24274. WeakMap.prototype.has = function (key) {
  24275. return !!this._guard(key)[this._id];
  24276. };
  24277. WeakMap.prototype._guard = function (key) {
  24278. if (key !== Object(key)) {
  24279. throw TypeError('Value of WeakMap is not a non-null object.');
  24280. }
  24281. return key;
  24282. };
  24283. return WeakMap;
  24284. }());
  24285. /**
  24286. * Triangle shape
  24287. * @inner
  24288. */
  24289. var Triangle = Path.extend({
  24290. type: 'triangle',
  24291. shape: {
  24292. cx: 0,
  24293. cy: 0,
  24294. width: 0,
  24295. height: 0
  24296. },
  24297. buildPath: function (path, shape) {
  24298. var cx = shape.cx;
  24299. var cy = shape.cy;
  24300. var width = shape.width / 2;
  24301. var height = shape.height / 2;
  24302. path.moveTo(cx, cy - height);
  24303. path.lineTo(cx + width, cy + height);
  24304. path.lineTo(cx - width, cy + height);
  24305. path.closePath();
  24306. }
  24307. });
  24308. /**
  24309. * Diamond shape
  24310. * @inner
  24311. */
  24312. var Diamond = Path.extend({
  24313. type: 'diamond',
  24314. shape: {
  24315. cx: 0,
  24316. cy: 0,
  24317. width: 0,
  24318. height: 0
  24319. },
  24320. buildPath: function (path, shape) {
  24321. var cx = shape.cx;
  24322. var cy = shape.cy;
  24323. var width = shape.width / 2;
  24324. var height = shape.height / 2;
  24325. path.moveTo(cx, cy - height);
  24326. path.lineTo(cx + width, cy);
  24327. path.lineTo(cx, cy + height);
  24328. path.lineTo(cx - width, cy);
  24329. path.closePath();
  24330. }
  24331. });
  24332. /**
  24333. * Pin shape
  24334. * @inner
  24335. */
  24336. var Pin = Path.extend({
  24337. type: 'pin',
  24338. shape: {
  24339. // x, y on the cusp
  24340. x: 0,
  24341. y: 0,
  24342. width: 0,
  24343. height: 0
  24344. },
  24345. buildPath: function (path, shape) {
  24346. var x = shape.x;
  24347. var y = shape.y;
  24348. var w = shape.width / 5 * 3; // Height must be larger than width
  24349. var h = Math.max(w, shape.height);
  24350. var r = w / 2; // Dist on y with tangent point and circle center
  24351. var dy = r * r / (h - r);
  24352. var cy = y - h + r + dy;
  24353. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  24354. var dx = Math.cos(angle) * r;
  24355. var tanX = Math.sin(angle);
  24356. var tanY = Math.cos(angle);
  24357. var cpLen = r * 0.6;
  24358. var cpLen2 = r * 0.7;
  24359. path.moveTo(x - dx, cy + dy);
  24360. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  24361. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  24362. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  24363. path.closePath();
  24364. }
  24365. });
  24366. /**
  24367. * Arrow shape
  24368. * @inner
  24369. */
  24370. var Arrow = Path.extend({
  24371. type: 'arrow',
  24372. shape: {
  24373. x: 0,
  24374. y: 0,
  24375. width: 0,
  24376. height: 0
  24377. },
  24378. buildPath: function (ctx, shape) {
  24379. var height = shape.height;
  24380. var width = shape.width;
  24381. var x = shape.x;
  24382. var y = shape.y;
  24383. var dx = width / 3 * 2;
  24384. ctx.moveTo(x, y);
  24385. ctx.lineTo(x + dx, y + height);
  24386. ctx.lineTo(x, y + height / 4 * 3);
  24387. ctx.lineTo(x - dx, y + height);
  24388. ctx.lineTo(x, y);
  24389. ctx.closePath();
  24390. }
  24391. });
  24392. /**
  24393. * Map of path constructors
  24394. */
  24395. // TODO Use function to build symbol path.
  24396. var symbolCtors = {
  24397. line: Line,
  24398. rect: Rect,
  24399. roundRect: Rect,
  24400. square: Rect,
  24401. circle: Circle,
  24402. diamond: Diamond,
  24403. pin: Pin,
  24404. arrow: Arrow,
  24405. triangle: Triangle
  24406. };
  24407. var symbolShapeMakers = {
  24408. line: function (x, y, w, h, shape) {
  24409. shape.x1 = x;
  24410. shape.y1 = y + h / 2;
  24411. shape.x2 = x + w;
  24412. shape.y2 = y + h / 2;
  24413. },
  24414. rect: function (x, y, w, h, shape) {
  24415. shape.x = x;
  24416. shape.y = y;
  24417. shape.width = w;
  24418. shape.height = h;
  24419. },
  24420. roundRect: function (x, y, w, h, shape) {
  24421. shape.x = x;
  24422. shape.y = y;
  24423. shape.width = w;
  24424. shape.height = h;
  24425. shape.r = Math.min(w, h) / 4;
  24426. },
  24427. square: function (x, y, w, h, shape) {
  24428. var size = Math.min(w, h);
  24429. shape.x = x;
  24430. shape.y = y;
  24431. shape.width = size;
  24432. shape.height = size;
  24433. },
  24434. circle: function (x, y, w, h, shape) {
  24435. // Put circle in the center of square
  24436. shape.cx = x + w / 2;
  24437. shape.cy = y + h / 2;
  24438. shape.r = Math.min(w, h) / 2;
  24439. },
  24440. diamond: function (x, y, w, h, shape) {
  24441. shape.cx = x + w / 2;
  24442. shape.cy = y + h / 2;
  24443. shape.width = w;
  24444. shape.height = h;
  24445. },
  24446. pin: function (x, y, w, h, shape) {
  24447. shape.x = x + w / 2;
  24448. shape.y = y + h / 2;
  24449. shape.width = w;
  24450. shape.height = h;
  24451. },
  24452. arrow: function (x, y, w, h, shape) {
  24453. shape.x = x + w / 2;
  24454. shape.y = y + h / 2;
  24455. shape.width = w;
  24456. shape.height = h;
  24457. },
  24458. triangle: function (x, y, w, h, shape) {
  24459. shape.cx = x + w / 2;
  24460. shape.cy = y + h / 2;
  24461. shape.width = w;
  24462. shape.height = h;
  24463. }
  24464. };
  24465. var symbolBuildProxies = {};
  24466. each(symbolCtors, function (Ctor, name) {
  24467. symbolBuildProxies[name] = new Ctor();
  24468. });
  24469. var SymbolClz = Path.extend({
  24470. type: 'symbol',
  24471. shape: {
  24472. symbolType: '',
  24473. x: 0,
  24474. y: 0,
  24475. width: 0,
  24476. height: 0
  24477. },
  24478. calculateTextPosition: function (out, config, rect) {
  24479. var res = calculateTextPosition(out, config, rect);
  24480. var shape = this.shape;
  24481. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  24482. res.y = rect.y + rect.height * 0.4;
  24483. }
  24484. return res;
  24485. },
  24486. buildPath: function (ctx, shape, inBundle) {
  24487. var symbolType = shape.symbolType;
  24488. if (symbolType !== 'none') {
  24489. var proxySymbol = symbolBuildProxies[symbolType];
  24490. if (!proxySymbol) {
  24491. // Default rect
  24492. symbolType = 'rect';
  24493. proxySymbol = symbolBuildProxies[symbolType];
  24494. }
  24495. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  24496. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  24497. }
  24498. }
  24499. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  24500. function symbolPathSetColor(color, innerColor) {
  24501. if (this.type !== 'image') {
  24502. var symbolStyle = this.style;
  24503. if (this.__isEmptyBrush) {
  24504. symbolStyle.stroke = color;
  24505. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView
  24506. symbolStyle.lineWidth = 2;
  24507. } else if (this.shape.symbolType === 'line') {
  24508. symbolStyle.stroke = color;
  24509. } else {
  24510. symbolStyle.fill = color;
  24511. }
  24512. this.markRedraw();
  24513. }
  24514. }
  24515. /**
  24516. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  24517. */
  24518. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  24519. keepAspect) {
  24520. // TODO Support image object, DynamicImage.
  24521. var isEmpty = symbolType.indexOf('empty') === 0;
  24522. if (isEmpty) {
  24523. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  24524. }
  24525. var symbolPath;
  24526. if (symbolType.indexOf('image://') === 0) {
  24527. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24528. } else if (symbolType.indexOf('path://') === 0) {
  24529. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24530. } else {
  24531. symbolPath = new SymbolClz({
  24532. shape: {
  24533. symbolType: symbolType,
  24534. x: x,
  24535. y: y,
  24536. width: w,
  24537. height: h
  24538. }
  24539. });
  24540. }
  24541. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  24542. symbolPath.setColor = symbolPathSetColor;
  24543. if (color) {
  24544. symbolPath.setColor(color);
  24545. }
  24546. return symbolPath;
  24547. }
  24548. function normalizeSymbolSize(symbolSize) {
  24549. if (!isArray(symbolSize)) {
  24550. symbolSize = [+symbolSize, +symbolSize];
  24551. }
  24552. return [symbolSize[0] || 0, symbolSize[1] || 0];
  24553. }
  24554. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  24555. if (symbolOffset == null) {
  24556. return;
  24557. }
  24558. if (!isArray(symbolOffset)) {
  24559. symbolOffset = [symbolOffset, symbolOffset];
  24560. }
  24561. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  24562. }
  24563. function isSafeNum(num) {
  24564. return isFinite(num);
  24565. }
  24566. function createLinearGradient(ctx, obj, rect) {
  24567. var x = obj.x == null ? 0 : obj.x;
  24568. var x2 = obj.x2 == null ? 1 : obj.x2;
  24569. var y = obj.y == null ? 0 : obj.y;
  24570. var y2 = obj.y2 == null ? 0 : obj.y2;
  24571. if (!obj.global) {
  24572. x = x * rect.width + rect.x;
  24573. x2 = x2 * rect.width + rect.x;
  24574. y = y * rect.height + rect.y;
  24575. y2 = y2 * rect.height + rect.y;
  24576. }
  24577. x = isSafeNum(x) ? x : 0;
  24578. x2 = isSafeNum(x2) ? x2 : 1;
  24579. y = isSafeNum(y) ? y : 0;
  24580. y2 = isSafeNum(y2) ? y2 : 0;
  24581. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  24582. return canvasGradient;
  24583. }
  24584. function createRadialGradient(ctx, obj, rect) {
  24585. var width = rect.width;
  24586. var height = rect.height;
  24587. var min = Math.min(width, height);
  24588. var x = obj.x == null ? 0.5 : obj.x;
  24589. var y = obj.y == null ? 0.5 : obj.y;
  24590. var r = obj.r == null ? 0.5 : obj.r;
  24591. if (!obj.global) {
  24592. x = x * width + rect.x;
  24593. y = y * height + rect.y;
  24594. r = r * min;
  24595. }
  24596. x = isSafeNum(x) ? x : 0.5;
  24597. y = isSafeNum(y) ? y : 0.5;
  24598. r = r >= 0 && isSafeNum(r) ? r : 0.5;
  24599. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  24600. return canvasGradient;
  24601. }
  24602. function getCanvasGradient(ctx, obj, rect) {
  24603. var canvasGradient = obj.type === 'radial'
  24604. ? createRadialGradient(ctx, obj, rect)
  24605. : createLinearGradient(ctx, obj, rect);
  24606. var colorStops = obj.colorStops;
  24607. for (var i = 0; i < colorStops.length; i++) {
  24608. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  24609. }
  24610. return canvasGradient;
  24611. }
  24612. function isClipPathChanged(clipPaths, prevClipPaths) {
  24613. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  24614. return false;
  24615. }
  24616. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  24617. return true;
  24618. }
  24619. for (var i = 0; i < clipPaths.length; i++) {
  24620. if (clipPaths[i] !== prevClipPaths[i]) {
  24621. return true;
  24622. }
  24623. }
  24624. return false;
  24625. }
  24626. function parseInt10(val) {
  24627. return parseInt(val, 10);
  24628. }
  24629. function getSize(root, whIdx, opts) {
  24630. var wh = ['width', 'height'][whIdx];
  24631. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  24632. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  24633. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  24634. if (opts[wh] != null && opts[wh] !== 'auto') {
  24635. return parseFloat(opts[wh]);
  24636. }
  24637. var stl = document.defaultView.getComputedStyle(root);
  24638. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  24639. - (parseInt10(stl[plt]) || 0)
  24640. - (parseInt10(stl[prb]) || 0)) | 0;
  24641. }
  24642. function normalizeLineDash(lineType, lineWidth) {
  24643. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  24644. return null;
  24645. }
  24646. return lineType === 'dashed'
  24647. ? [4 * lineWidth, 2 * lineWidth]
  24648. : lineType === 'dotted'
  24649. ? [lineWidth]
  24650. : isNumber(lineType)
  24651. ? [lineType] : isArray(lineType) ? lineType : null;
  24652. }
  24653. function getLineDash(el) {
  24654. var style = el.style;
  24655. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24656. var lineDashOffset = style.lineDashOffset;
  24657. if (lineDash) {
  24658. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24659. if (lineScale_1 && lineScale_1 !== 1) {
  24660. lineDash = map(lineDash, function (rawVal) {
  24661. return rawVal / lineScale_1;
  24662. });
  24663. lineDashOffset /= lineScale_1;
  24664. }
  24665. }
  24666. return [lineDash, lineDashOffset];
  24667. }
  24668. var pathProxyForDraw = new PathProxy(true);
  24669. function styleHasStroke(style) {
  24670. var stroke = style.stroke;
  24671. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  24672. }
  24673. function isValidStrokeFillStyle(strokeOrFill) {
  24674. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  24675. }
  24676. function styleHasFill(style) {
  24677. var fill = style.fill;
  24678. return fill != null && fill !== 'none';
  24679. }
  24680. function doFillPath(ctx, style) {
  24681. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  24682. var originalGlobalAlpha = ctx.globalAlpha;
  24683. ctx.globalAlpha = style.fillOpacity * style.opacity;
  24684. ctx.fill();
  24685. ctx.globalAlpha = originalGlobalAlpha;
  24686. }
  24687. else {
  24688. ctx.fill();
  24689. }
  24690. }
  24691. function doStrokePath(ctx, style) {
  24692. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  24693. var originalGlobalAlpha = ctx.globalAlpha;
  24694. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  24695. ctx.stroke();
  24696. ctx.globalAlpha = originalGlobalAlpha;
  24697. }
  24698. else {
  24699. ctx.stroke();
  24700. }
  24701. }
  24702. function createCanvasPattern(ctx, pattern, el) {
  24703. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  24704. if (isImageReady(image)) {
  24705. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  24706. if (typeof DOMMatrix === 'function'
  24707. && canvasPattern
  24708. && canvasPattern.setTransform) {
  24709. var matrix = new DOMMatrix();
  24710. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  24711. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  24712. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  24713. canvasPattern.setTransform(matrix);
  24714. }
  24715. return canvasPattern;
  24716. }
  24717. }
  24718. function brushPath(ctx, el, style, inBatch) {
  24719. var _a;
  24720. var hasStroke = styleHasStroke(style);
  24721. var hasFill = styleHasFill(style);
  24722. var strokePercent = style.strokePercent;
  24723. var strokePart = strokePercent < 1;
  24724. var firstDraw = !el.path;
  24725. if ((!el.silent || strokePart) && firstDraw) {
  24726. el.createPathProxy();
  24727. }
  24728. var path = el.path || pathProxyForDraw;
  24729. var dirtyFlag = el.__dirty;
  24730. if (!inBatch) {
  24731. var fill = style.fill;
  24732. var stroke = style.stroke;
  24733. var hasFillGradient = hasFill && !!fill.colorStops;
  24734. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  24735. var hasFillPattern = hasFill && !!fill.image;
  24736. var hasStrokePattern = hasStroke && !!stroke.image;
  24737. var fillGradient = void 0;
  24738. var strokeGradient = void 0;
  24739. var fillPattern = void 0;
  24740. var strokePattern = void 0;
  24741. var rect = void 0;
  24742. if (hasFillGradient || hasStrokeGradient) {
  24743. rect = el.getBoundingRect();
  24744. }
  24745. if (hasFillGradient) {
  24746. fillGradient = dirtyFlag
  24747. ? getCanvasGradient(ctx, fill, rect)
  24748. : el.__canvasFillGradient;
  24749. el.__canvasFillGradient = fillGradient;
  24750. }
  24751. if (hasStrokeGradient) {
  24752. strokeGradient = dirtyFlag
  24753. ? getCanvasGradient(ctx, stroke, rect)
  24754. : el.__canvasStrokeGradient;
  24755. el.__canvasStrokeGradient = strokeGradient;
  24756. }
  24757. if (hasFillPattern) {
  24758. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  24759. ? createCanvasPattern(ctx, fill, el)
  24760. : el.__canvasFillPattern;
  24761. el.__canvasFillPattern = fillPattern;
  24762. }
  24763. if (hasStrokePattern) {
  24764. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  24765. ? createCanvasPattern(ctx, stroke, el)
  24766. : el.__canvasStrokePattern;
  24767. el.__canvasStrokePattern = fillPattern;
  24768. }
  24769. if (hasFillGradient) {
  24770. ctx.fillStyle = fillGradient;
  24771. }
  24772. else if (hasFillPattern) {
  24773. if (fillPattern) {
  24774. ctx.fillStyle = fillPattern;
  24775. }
  24776. else {
  24777. hasFill = false;
  24778. }
  24779. }
  24780. if (hasStrokeGradient) {
  24781. ctx.strokeStyle = strokeGradient;
  24782. }
  24783. else if (hasStrokePattern) {
  24784. if (strokePattern) {
  24785. ctx.strokeStyle = strokePattern;
  24786. }
  24787. else {
  24788. hasStroke = false;
  24789. }
  24790. }
  24791. }
  24792. var scale = el.getGlobalScale();
  24793. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  24794. var lineDash;
  24795. var lineDashOffset;
  24796. if (ctx.setLineDash && style.lineDash) {
  24797. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24798. }
  24799. var needsRebuild = true;
  24800. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  24801. path.setDPR(ctx.dpr);
  24802. if (strokePart) {
  24803. path.setContext(null);
  24804. }
  24805. else {
  24806. path.setContext(ctx);
  24807. needsRebuild = false;
  24808. }
  24809. path.reset();
  24810. el.buildPath(path, el.shape, inBatch);
  24811. path.toStatic();
  24812. el.pathUpdated();
  24813. }
  24814. if (needsRebuild) {
  24815. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  24816. }
  24817. if (lineDash) {
  24818. ctx.setLineDash(lineDash);
  24819. ctx.lineDashOffset = lineDashOffset;
  24820. }
  24821. if (!inBatch) {
  24822. if (style.strokeFirst) {
  24823. if (hasStroke) {
  24824. doStrokePath(ctx, style);
  24825. }
  24826. if (hasFill) {
  24827. doFillPath(ctx, style);
  24828. }
  24829. }
  24830. else {
  24831. if (hasFill) {
  24832. doFillPath(ctx, style);
  24833. }
  24834. if (hasStroke) {
  24835. doStrokePath(ctx, style);
  24836. }
  24837. }
  24838. }
  24839. if (lineDash) {
  24840. ctx.setLineDash([]);
  24841. }
  24842. }
  24843. function brushImage(ctx, el, style) {
  24844. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24845. if (!image || !isImageReady(image)) {
  24846. return;
  24847. }
  24848. var x = style.x || 0;
  24849. var y = style.y || 0;
  24850. var width = el.getWidth();
  24851. var height = el.getHeight();
  24852. var aspect = image.width / image.height;
  24853. if (width == null && height != null) {
  24854. width = height * aspect;
  24855. }
  24856. else if (height == null && width != null) {
  24857. height = width / aspect;
  24858. }
  24859. else if (width == null && height == null) {
  24860. width = image.width;
  24861. height = image.height;
  24862. }
  24863. if (style.sWidth && style.sHeight) {
  24864. var sx = style.sx || 0;
  24865. var sy = style.sy || 0;
  24866. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  24867. }
  24868. else if (style.sx && style.sy) {
  24869. var sx = style.sx;
  24870. var sy = style.sy;
  24871. var sWidth = width - sx;
  24872. var sHeight = height - sy;
  24873. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  24874. }
  24875. else {
  24876. ctx.drawImage(image, x, y, width, height);
  24877. }
  24878. }
  24879. function brushText(ctx, el, style) {
  24880. var _a;
  24881. var text = style.text;
  24882. text != null && (text += '');
  24883. if (text) {
  24884. ctx.font = style.font || DEFAULT_FONT;
  24885. ctx.textAlign = style.textAlign;
  24886. ctx.textBaseline = style.textBaseline;
  24887. var lineDash = void 0;
  24888. var lineDashOffset = void 0;
  24889. if (ctx.setLineDash && style.lineDash) {
  24890. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24891. }
  24892. if (lineDash) {
  24893. ctx.setLineDash(lineDash);
  24894. ctx.lineDashOffset = lineDashOffset;
  24895. }
  24896. if (style.strokeFirst) {
  24897. if (styleHasStroke(style)) {
  24898. ctx.strokeText(text, style.x, style.y);
  24899. }
  24900. if (styleHasFill(style)) {
  24901. ctx.fillText(text, style.x, style.y);
  24902. }
  24903. }
  24904. else {
  24905. if (styleHasFill(style)) {
  24906. ctx.fillText(text, style.x, style.y);
  24907. }
  24908. if (styleHasStroke(style)) {
  24909. ctx.strokeText(text, style.x, style.y);
  24910. }
  24911. }
  24912. if (lineDash) {
  24913. ctx.setLineDash([]);
  24914. }
  24915. }
  24916. }
  24917. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  24918. var STROKE_PROPS = [
  24919. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  24920. ];
  24921. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  24922. var styleChanged = false;
  24923. if (!forceSetAll) {
  24924. prevStyle = prevStyle || {};
  24925. if (style === prevStyle) {
  24926. return false;
  24927. }
  24928. }
  24929. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24930. flushPathDrawn(ctx, scope);
  24931. styleChanged = true;
  24932. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  24933. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  24934. }
  24935. if (forceSetAll || style.blend !== prevStyle.blend) {
  24936. if (!styleChanged) {
  24937. flushPathDrawn(ctx, scope);
  24938. styleChanged = true;
  24939. }
  24940. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  24941. }
  24942. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  24943. var propName = SHADOW_NUMBER_PROPS[i];
  24944. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24945. if (!styleChanged) {
  24946. flushPathDrawn(ctx, scope);
  24947. styleChanged = true;
  24948. }
  24949. ctx[propName] = ctx.dpr * (style[propName] || 0);
  24950. }
  24951. }
  24952. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  24953. if (!styleChanged) {
  24954. flushPathDrawn(ctx, scope);
  24955. styleChanged = true;
  24956. }
  24957. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  24958. }
  24959. return styleChanged;
  24960. }
  24961. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  24962. var style = getStyle(el, scope.inHover);
  24963. var prevStyle = forceSetAll
  24964. ? null
  24965. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  24966. if (style === prevStyle) {
  24967. return false;
  24968. }
  24969. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  24970. if (forceSetAll || style.fill !== prevStyle.fill) {
  24971. if (!styleChanged) {
  24972. flushPathDrawn(ctx, scope);
  24973. styleChanged = true;
  24974. }
  24975. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  24976. }
  24977. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  24978. if (!styleChanged) {
  24979. flushPathDrawn(ctx, scope);
  24980. styleChanged = true;
  24981. }
  24982. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  24983. }
  24984. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24985. if (!styleChanged) {
  24986. flushPathDrawn(ctx, scope);
  24987. styleChanged = true;
  24988. }
  24989. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  24990. }
  24991. if (el.hasStroke()) {
  24992. var lineWidth = style.lineWidth;
  24993. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  24994. if (ctx.lineWidth !== newLineWidth) {
  24995. if (!styleChanged) {
  24996. flushPathDrawn(ctx, scope);
  24997. styleChanged = true;
  24998. }
  24999. ctx.lineWidth = newLineWidth;
  25000. }
  25001. }
  25002. for (var i = 0; i < STROKE_PROPS.length; i++) {
  25003. var prop = STROKE_PROPS[i];
  25004. var propName = prop[0];
  25005. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  25006. if (!styleChanged) {
  25007. flushPathDrawn(ctx, scope);
  25008. styleChanged = true;
  25009. }
  25010. ctx[propName] = style[propName] || prop[1];
  25011. }
  25012. }
  25013. return styleChanged;
  25014. }
  25015. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  25016. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  25017. }
  25018. function setContextTransform(ctx, el) {
  25019. var m = el.transform;
  25020. var dpr = ctx.dpr || 1;
  25021. if (m) {
  25022. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  25023. }
  25024. else {
  25025. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  25026. }
  25027. }
  25028. function updateClipStatus(clipPaths, ctx, scope) {
  25029. var allClipped = false;
  25030. for (var i = 0; i < clipPaths.length; i++) {
  25031. var clipPath = clipPaths[i];
  25032. allClipped = allClipped || clipPath.isZeroArea();
  25033. setContextTransform(ctx, clipPath);
  25034. ctx.beginPath();
  25035. clipPath.buildPath(ctx, clipPath.shape);
  25036. ctx.clip();
  25037. }
  25038. scope.allClipped = allClipped;
  25039. }
  25040. function isTransformChanged(m0, m1) {
  25041. if (m0 && m1) {
  25042. return m0[0] !== m1[0]
  25043. || m0[1] !== m1[1]
  25044. || m0[2] !== m1[2]
  25045. || m0[3] !== m1[3]
  25046. || m0[4] !== m1[4]
  25047. || m0[5] !== m1[5];
  25048. }
  25049. else if (!m0 && !m1) {
  25050. return false;
  25051. }
  25052. return true;
  25053. }
  25054. var DRAW_TYPE_PATH = 1;
  25055. var DRAW_TYPE_IMAGE = 2;
  25056. var DRAW_TYPE_TEXT = 3;
  25057. var DRAW_TYPE_INCREMENTAL = 4;
  25058. function canPathBatch(style) {
  25059. var hasFill = styleHasFill(style);
  25060. var hasStroke = styleHasStroke(style);
  25061. return !(style.lineDash
  25062. || !(+hasFill ^ +hasStroke)
  25063. || (hasFill && typeof style.fill !== 'string')
  25064. || (hasStroke && typeof style.stroke !== 'string')
  25065. || style.strokePercent < 1
  25066. || style.strokeOpacity < 1
  25067. || style.fillOpacity < 1);
  25068. }
  25069. function flushPathDrawn(ctx, scope) {
  25070. scope.batchFill && ctx.fill();
  25071. scope.batchStroke && ctx.stroke();
  25072. scope.batchFill = '';
  25073. scope.batchStroke = '';
  25074. }
  25075. function getStyle(el, inHover) {
  25076. return inHover ? (el.__hoverStyle || el.style) : el.style;
  25077. }
  25078. function brushSingle(ctx, el) {
  25079. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  25080. }
  25081. function brush(ctx, el, scope, isLast) {
  25082. var m = el.transform;
  25083. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  25084. el.__dirty &= ~REDRAW_BIT;
  25085. el.__isRendered = false;
  25086. return;
  25087. }
  25088. var clipPaths = el.__clipPaths;
  25089. var prevElClipPaths = scope.prevElClipPaths;
  25090. var forceSetTransform = false;
  25091. var forceSetStyle = false;
  25092. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  25093. if (prevElClipPaths && prevElClipPaths.length) {
  25094. flushPathDrawn(ctx, scope);
  25095. ctx.restore();
  25096. forceSetStyle = forceSetTransform = true;
  25097. scope.prevElClipPaths = null;
  25098. scope.allClipped = false;
  25099. scope.prevEl = null;
  25100. }
  25101. if (clipPaths && clipPaths.length) {
  25102. flushPathDrawn(ctx, scope);
  25103. ctx.save();
  25104. updateClipStatus(clipPaths, ctx, scope);
  25105. forceSetTransform = true;
  25106. }
  25107. scope.prevElClipPaths = clipPaths;
  25108. }
  25109. if (scope.allClipped) {
  25110. el.__isRendered = false;
  25111. return;
  25112. }
  25113. el.beforeBrush && el.beforeBrush();
  25114. el.innerBeforeBrush();
  25115. var prevEl = scope.prevEl;
  25116. if (!prevEl) {
  25117. forceSetStyle = forceSetTransform = true;
  25118. }
  25119. var canBatchPath = el instanceof Path
  25120. && el.autoBatch
  25121. && canPathBatch(el.style);
  25122. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  25123. flushPathDrawn(ctx, scope);
  25124. setContextTransform(ctx, el);
  25125. }
  25126. else if (!canBatchPath) {
  25127. flushPathDrawn(ctx, scope);
  25128. }
  25129. var style = getStyle(el, scope.inHover);
  25130. if (el instanceof Path) {
  25131. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  25132. forceSetStyle = true;
  25133. scope.lastDrawType = DRAW_TYPE_PATH;
  25134. }
  25135. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25136. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  25137. ctx.beginPath();
  25138. }
  25139. brushPath(ctx, el, style, canBatchPath);
  25140. if (canBatchPath) {
  25141. scope.batchFill = style.fill || '';
  25142. scope.batchStroke = style.stroke || '';
  25143. }
  25144. }
  25145. else {
  25146. if (el instanceof TSpan) {
  25147. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  25148. forceSetStyle = true;
  25149. scope.lastDrawType = DRAW_TYPE_TEXT;
  25150. }
  25151. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25152. brushText(ctx, el, style);
  25153. }
  25154. else if (el instanceof ZRImage) {
  25155. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  25156. forceSetStyle = true;
  25157. scope.lastDrawType = DRAW_TYPE_IMAGE;
  25158. }
  25159. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  25160. brushImage(ctx, el, style);
  25161. }
  25162. else if (el.getTemporalDisplayables) {
  25163. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  25164. forceSetStyle = true;
  25165. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  25166. }
  25167. brushIncremental(ctx, el, scope);
  25168. }
  25169. }
  25170. if (canBatchPath && isLast) {
  25171. flushPathDrawn(ctx, scope);
  25172. }
  25173. el.innerAfterBrush();
  25174. el.afterBrush && el.afterBrush();
  25175. scope.prevEl = el;
  25176. el.__dirty = 0;
  25177. el.__isRendered = true;
  25178. }
  25179. function brushIncremental(ctx, el, scope) {
  25180. var displayables = el.getDisplayables();
  25181. var temporalDisplayables = el.getTemporalDisplayables();
  25182. ctx.save();
  25183. var innerScope = {
  25184. prevElClipPaths: null,
  25185. prevEl: null,
  25186. allClipped: false,
  25187. viewWidth: scope.viewWidth,
  25188. viewHeight: scope.viewHeight,
  25189. inHover: scope.inHover
  25190. };
  25191. var i;
  25192. var len;
  25193. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  25194. var displayable = displayables[i];
  25195. displayable.beforeBrush && displayable.beforeBrush();
  25196. displayable.innerBeforeBrush();
  25197. brush(ctx, displayable, innerScope, i === len - 1);
  25198. displayable.innerAfterBrush();
  25199. displayable.afterBrush && displayable.afterBrush();
  25200. innerScope.prevEl = displayable;
  25201. }
  25202. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  25203. var displayable = temporalDisplayables[i_1];
  25204. displayable.beforeBrush && displayable.beforeBrush();
  25205. displayable.innerBeforeBrush();
  25206. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  25207. displayable.innerAfterBrush();
  25208. displayable.afterBrush && displayable.afterBrush();
  25209. innerScope.prevEl = displayable;
  25210. }
  25211. el.clearTemporalDisplayables();
  25212. el.notClear = true;
  25213. ctx.restore();
  25214. }
  25215. var decalMap = new WeakMap();
  25216. var decalCache = new LRU(100);
  25217. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  25218. /**
  25219. * Create or update pattern image from decal options
  25220. *
  25221. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  25222. * @return {Pattern} pattern with generated image, null if no decal
  25223. */
  25224. function createOrUpdatePatternFromDecal(decalObject, api) {
  25225. if (decalObject === 'none') {
  25226. return null;
  25227. }
  25228. var dpr = api.getDevicePixelRatio();
  25229. var zr = api.getZr();
  25230. var isSVG = zr.painter.type === 'svg';
  25231. if (decalObject.dirty) {
  25232. decalMap["delete"](decalObject);
  25233. }
  25234. var oldPattern = decalMap.get(decalObject);
  25235. if (oldPattern) {
  25236. return oldPattern;
  25237. }
  25238. var decalOpt = defaults(decalObject, {
  25239. symbol: 'rect',
  25240. symbolSize: 1,
  25241. symbolKeepAspect: true,
  25242. color: 'rgba(0, 0, 0, 0.2)',
  25243. backgroundColor: null,
  25244. dashArrayX: 5,
  25245. dashArrayY: 5,
  25246. rotation: 0,
  25247. maxTileWidth: 512,
  25248. maxTileHeight: 512
  25249. });
  25250. if (decalOpt.backgroundColor === 'none') {
  25251. decalOpt.backgroundColor = null;
  25252. }
  25253. var pattern = {
  25254. repeat: 'repeat'
  25255. };
  25256. setPatternnSource(pattern);
  25257. pattern.rotation = decalOpt.rotation;
  25258. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  25259. decalMap.set(decalObject, pattern);
  25260. decalObject.dirty = false;
  25261. return pattern;
  25262. function setPatternnSource(pattern) {
  25263. var keys = [dpr];
  25264. var isValidKey = true;
  25265. for (var i = 0; i < decalKeys.length; ++i) {
  25266. var value = decalOpt[decalKeys[i]];
  25267. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  25268. isValidKey = false;
  25269. break;
  25270. }
  25271. keys.push(value);
  25272. }
  25273. var cacheKey;
  25274. if (isValidKey) {
  25275. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  25276. var cache = decalCache.get(cacheKey);
  25277. if (cache) {
  25278. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  25279. }
  25280. }
  25281. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  25282. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  25283. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  25284. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  25285. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  25286. var canvas = !isSVG && platformApi.createCanvas();
  25287. var svgRoot = isSVG && {
  25288. tag: 'g',
  25289. attrs: {},
  25290. key: 'dcl',
  25291. children: []
  25292. };
  25293. var pSize = getPatternSize();
  25294. var ctx;
  25295. if (canvas) {
  25296. canvas.width = pSize.width * dpr;
  25297. canvas.height = pSize.height * dpr;
  25298. ctx = canvas.getContext('2d');
  25299. }
  25300. brushDecal();
  25301. if (isValidKey) {
  25302. decalCache.put(cacheKey, canvas || svgRoot);
  25303. }
  25304. pattern.image = canvas;
  25305. pattern.svgElement = svgRoot;
  25306. pattern.svgWidth = pSize.width;
  25307. pattern.svgHeight = pSize.height;
  25308. /**
  25309. * Get minimum length that can make a repeatable pattern.
  25310. *
  25311. * @return {Object} pattern width and height
  25312. */
  25313. function getPatternSize() {
  25314. /**
  25315. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  25316. * |--- --- --- --- --- ...
  25317. * |-- -- -- -- -- -- -- -- ...
  25318. * |--- --- --- --- --- ...
  25319. * |-- -- -- -- -- -- -- -- ...
  25320. * So the minimum length of X is 15,
  25321. * which is the least common multiple of `3 + 2` and `2 + 1`
  25322. * |--- --- --- |--- --- ...
  25323. * |-- -- -- -- -- |-- -- -- ...
  25324. */
  25325. var width = 1;
  25326. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  25327. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  25328. }
  25329. var symbolRepeats = 1;
  25330. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  25331. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  25332. }
  25333. width *= symbolRepeats;
  25334. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  25335. if ("development" !== 'production') {
  25336. var warn = function (attrName) {
  25337. /* eslint-disable-next-line */
  25338. console.warn("Calculated decal size is greater than " + attrName + " due to decal option settings so " + attrName + " is used for the decal size. Please consider changing the decal option to make a smaller decal or set " + attrName + " to be larger to avoid incontinuity.");
  25339. };
  25340. if (width > decalOpt.maxTileWidth) {
  25341. warn('maxTileWidth');
  25342. }
  25343. if (height > decalOpt.maxTileHeight) {
  25344. warn('maxTileHeight');
  25345. }
  25346. }
  25347. return {
  25348. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  25349. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  25350. };
  25351. }
  25352. function brushDecal() {
  25353. if (ctx) {
  25354. ctx.clearRect(0, 0, canvas.width, canvas.height);
  25355. if (decalOpt.backgroundColor) {
  25356. ctx.fillStyle = decalOpt.backgroundColor;
  25357. ctx.fillRect(0, 0, canvas.width, canvas.height);
  25358. }
  25359. }
  25360. var ySum = 0;
  25361. for (var i = 0; i < dashArrayY.length; ++i) {
  25362. ySum += dashArrayY[i];
  25363. }
  25364. if (ySum <= 0) {
  25365. // dashArrayY is 0, draw nothing
  25366. return;
  25367. }
  25368. var y = -lineBlockLengthY;
  25369. var yId = 0;
  25370. var yIdTotal = 0;
  25371. var xId0 = 0;
  25372. while (y < pSize.height) {
  25373. if (yId % 2 === 0) {
  25374. var symbolYId = yIdTotal / 2 % symbolArray.length;
  25375. var x = 0;
  25376. var xId1 = 0;
  25377. var xId1Total = 0;
  25378. while (x < pSize.width * 2) {
  25379. var xSum = 0;
  25380. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  25381. xSum += dashArrayX[xId0][i];
  25382. }
  25383. if (xSum <= 0) {
  25384. // Skip empty line
  25385. break;
  25386. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  25387. if (xId1 % 2 === 0) {
  25388. var size = (1 - decalOpt.symbolSize) * 0.5;
  25389. var left = x + dashArrayX[xId0][xId1] * size;
  25390. var top_1 = y + dashArrayY[yId] * size;
  25391. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  25392. var height = dashArrayY[yId] * decalOpt.symbolSize;
  25393. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  25394. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  25395. }
  25396. x += dashArrayX[xId0][xId1];
  25397. ++xId1Total;
  25398. ++xId1;
  25399. if (xId1 === dashArrayX[xId0].length) {
  25400. xId1 = 0;
  25401. }
  25402. }
  25403. ++xId0;
  25404. if (xId0 === dashArrayX.length) {
  25405. xId0 = 0;
  25406. }
  25407. }
  25408. y += dashArrayY[yId];
  25409. ++yIdTotal;
  25410. ++yId;
  25411. if (yId === dashArrayY.length) {
  25412. yId = 0;
  25413. }
  25414. }
  25415. function brushSymbol(x, y, width, height, symbolType) {
  25416. var scale = isSVG ? 1 : dpr;
  25417. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  25418. if (isSVG) {
  25419. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  25420. if (symbolVNode) {
  25421. svgRoot.children.push(symbolVNode);
  25422. }
  25423. } else {
  25424. // Paint to canvas for all other renderers.
  25425. brushSingle(ctx, symbol);
  25426. }
  25427. }
  25428. }
  25429. }
  25430. }
  25431. /**
  25432. * Convert symbol array into normalized array
  25433. *
  25434. * @param {string | (string | string[])[]} symbol symbol input
  25435. * @return {string[][]} normolized symbol array
  25436. */
  25437. function normalizeSymbolArray(symbol) {
  25438. if (!symbol || symbol.length === 0) {
  25439. return [['rect']];
  25440. }
  25441. if (isString(symbol)) {
  25442. return [[symbol]];
  25443. }
  25444. var isAllString = true;
  25445. for (var i = 0; i < symbol.length; ++i) {
  25446. if (!isString(symbol[i])) {
  25447. isAllString = false;
  25448. break;
  25449. }
  25450. }
  25451. if (isAllString) {
  25452. return normalizeSymbolArray([symbol]);
  25453. }
  25454. var result = [];
  25455. for (var i = 0; i < symbol.length; ++i) {
  25456. if (isString(symbol[i])) {
  25457. result.push([symbol[i]]);
  25458. } else {
  25459. result.push(symbol[i]);
  25460. }
  25461. }
  25462. return result;
  25463. }
  25464. /**
  25465. * Convert dash input into dashArray
  25466. *
  25467. * @param {DecalDashArrayX} dash dash input
  25468. * @return {number[][]} normolized dash array
  25469. */
  25470. function normalizeDashArrayX(dash) {
  25471. if (!dash || dash.length === 0) {
  25472. return [[0, 0]];
  25473. }
  25474. if (isNumber(dash)) {
  25475. var dashValue = Math.ceil(dash);
  25476. return [[dashValue, dashValue]];
  25477. }
  25478. /**
  25479. * [20, 5] should be normalized into [[20, 5]],
  25480. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  25481. */
  25482. var isAllNumber = true;
  25483. for (var i = 0; i < dash.length; ++i) {
  25484. if (!isNumber(dash[i])) {
  25485. isAllNumber = false;
  25486. break;
  25487. }
  25488. }
  25489. if (isAllNumber) {
  25490. return normalizeDashArrayX([dash]);
  25491. }
  25492. var result = [];
  25493. for (var i = 0; i < dash.length; ++i) {
  25494. if (isNumber(dash[i])) {
  25495. var dashValue = Math.ceil(dash[i]);
  25496. result.push([dashValue, dashValue]);
  25497. } else {
  25498. var dashValue = map(dash[i], function (n) {
  25499. return Math.ceil(n);
  25500. });
  25501. if (dashValue.length % 2 === 1) {
  25502. // [4, 2, 1] means |---- - -- |---- - -- |
  25503. // so normalize it to be [4, 2, 1, 4, 2, 1]
  25504. result.push(dashValue.concat(dashValue));
  25505. } else {
  25506. result.push(dashValue);
  25507. }
  25508. }
  25509. }
  25510. return result;
  25511. }
  25512. /**
  25513. * Convert dash input into dashArray
  25514. *
  25515. * @param {DecalDashArrayY} dash dash input
  25516. * @return {number[]} normolized dash array
  25517. */
  25518. function normalizeDashArrayY(dash) {
  25519. if (!dash || typeof dash === 'object' && dash.length === 0) {
  25520. return [0, 0];
  25521. }
  25522. if (isNumber(dash)) {
  25523. var dashValue_1 = Math.ceil(dash);
  25524. return [dashValue_1, dashValue_1];
  25525. }
  25526. var dashValue = map(dash, function (n) {
  25527. return Math.ceil(n);
  25528. });
  25529. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  25530. }
  25531. /**
  25532. * Get block length of each line. A block is the length of dash line and space.
  25533. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  25534. * that, so the block length of this line is 5.
  25535. *
  25536. * @param {number[][]} dash dash array of X or Y
  25537. * @return {number[]} block length of each line
  25538. */
  25539. function getLineBlockLengthX(dash) {
  25540. return map(dash, function (line) {
  25541. return getLineBlockLengthY(line);
  25542. });
  25543. }
  25544. function getLineBlockLengthY(dash) {
  25545. var blockLength = 0;
  25546. for (var i = 0; i < dash.length; ++i) {
  25547. blockLength += dash[i];
  25548. }
  25549. if (dash.length % 2 === 1) {
  25550. // [4, 2, 1] means |---- - -- |---- - -- |
  25551. // So total length is (4 + 2 + 1) * 2
  25552. return blockLength * 2;
  25553. }
  25554. return blockLength;
  25555. }
  25556. function decalVisual(ecModel, api) {
  25557. ecModel.eachRawSeries(function (seriesModel) {
  25558. if (ecModel.isSeriesFiltered(seriesModel)) {
  25559. return;
  25560. }
  25561. var data = seriesModel.getData();
  25562. if (data.hasItemVisual()) {
  25563. data.each(function (idx) {
  25564. var decal = data.getItemVisual(idx, 'decal');
  25565. if (decal) {
  25566. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  25567. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  25568. }
  25569. });
  25570. }
  25571. var decal = data.getVisual('decal');
  25572. if (decal) {
  25573. var style = data.getVisual('style');
  25574. style.decal = createOrUpdatePatternFromDecal(decal, api);
  25575. }
  25576. });
  25577. }
  25578. var lifecycle = new Eventful();
  25579. // The implementations will be registered when installing the component.
  25580. // Avoid these code being bundled to the core module.
  25581. var implsStore = {}; // TODO Type
  25582. function registerImpl(name, impl) {
  25583. if ("development" !== 'production') {
  25584. if (implsStore[name]) {
  25585. error("Already has an implementation of " + name + ".");
  25586. }
  25587. }
  25588. implsStore[name] = impl;
  25589. }
  25590. function getImpl(name) {
  25591. if ("development" !== 'production') {
  25592. if (!implsStore[name]) {
  25593. error("Implementation of " + name + " doesn't exists.");
  25594. }
  25595. }
  25596. return implsStore[name];
  25597. }
  25598. var version$1 = '5.4.2';
  25599. var dependencies = {
  25600. zrender: '5.4.3'
  25601. };
  25602. var TEST_FRAME_REMAIN_TIME = 1;
  25603. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  25604. // So data stack stage should be in front of data processing stage.
  25605. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  25606. // put at the beginning of data processing.
  25607. var PRIORITY_PROCESSOR_FILTER = 1000;
  25608. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  25609. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  25610. var PRIORITY_VISUAL_LAYOUT = 1000;
  25611. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  25612. var PRIORITY_VISUAL_GLOBAL = 2000;
  25613. var PRIORITY_VISUAL_CHART = 3000;
  25614. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  25615. // overwrite the viusal result of component (like `visualMap`)
  25616. // using data item specific setting (like itemStyle.xxx on data item)
  25617. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  25618. // visual result like `symbolSize`.
  25619. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  25620. var PRIORITY_VISUAL_BRUSH = 5000;
  25621. var PRIORITY_VISUAL_ARIA = 6000;
  25622. var PRIORITY_VISUAL_DECAL = 7000;
  25623. var PRIORITY = {
  25624. PROCESSOR: {
  25625. FILTER: PRIORITY_PROCESSOR_FILTER,
  25626. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  25627. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  25628. },
  25629. VISUAL: {
  25630. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  25631. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  25632. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  25633. CHART: PRIORITY_VISUAL_CHART,
  25634. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  25635. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  25636. BRUSH: PRIORITY_VISUAL_BRUSH,
  25637. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  25638. ARIA: PRIORITY_VISUAL_ARIA,
  25639. DECAL: PRIORITY_VISUAL_DECAL
  25640. }
  25641. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  25642. // where they must not be invoked nestedly, except the only case: invoke
  25643. // dispatchAction with updateMethod "none" in main process.
  25644. // This flag is used to carry out this rule.
  25645. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  25646. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  25647. var PENDING_UPDATE = '__pendingUpdate';
  25648. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  25649. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  25650. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  25651. var CONNECT_STATUS_PENDING = 0;
  25652. var CONNECT_STATUS_UPDATING = 1;
  25653. var CONNECT_STATUS_UPDATED = 2;
  25654. function createRegisterEventWithLowercaseECharts(method) {
  25655. return function () {
  25656. var args = [];
  25657. for (var _i = 0; _i < arguments.length; _i++) {
  25658. args[_i] = arguments[_i];
  25659. }
  25660. if (this.isDisposed()) {
  25661. disposedWarning(this.id);
  25662. return;
  25663. }
  25664. return toLowercaseNameAndCallEventful(this, method, args);
  25665. };
  25666. }
  25667. function createRegisterEventWithLowercaseMessageCenter(method) {
  25668. return function () {
  25669. var args = [];
  25670. for (var _i = 0; _i < arguments.length; _i++) {
  25671. args[_i] = arguments[_i];
  25672. }
  25673. return toLowercaseNameAndCallEventful(this, method, args);
  25674. };
  25675. }
  25676. function toLowercaseNameAndCallEventful(host, method, args) {
  25677. // `args[0]` is event name. Event name is all lowercase.
  25678. args[0] = args[0] && args[0].toLowerCase();
  25679. return Eventful.prototype[method].apply(host, args);
  25680. }
  25681. var MessageCenter =
  25682. /** @class */
  25683. function (_super) {
  25684. __extends(MessageCenter, _super);
  25685. function MessageCenter() {
  25686. return _super !== null && _super.apply(this, arguments) || this;
  25687. }
  25688. return MessageCenter;
  25689. }(Eventful);
  25690. var messageCenterProto = MessageCenter.prototype;
  25691. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  25692. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  25693. // Internal method names for class ECharts
  25694. // ---------------------------------------
  25695. var prepare;
  25696. var prepareView;
  25697. var updateDirectly;
  25698. var updateMethods;
  25699. var doConvertPixel;
  25700. var updateStreamModes;
  25701. var doDispatchAction;
  25702. var flushPendingActions;
  25703. var triggerUpdatedEvent;
  25704. var bindRenderedEvent;
  25705. var bindMouseEvent;
  25706. var render;
  25707. var renderComponents;
  25708. var renderSeries;
  25709. var createExtensionAPI;
  25710. var enableConnect;
  25711. var markStatusToUpdate;
  25712. var applyChangedStates;
  25713. var ECharts =
  25714. /** @class */
  25715. function (_super) {
  25716. __extends(ECharts, _super);
  25717. function ECharts(dom, // Theme name or themeOption.
  25718. theme, opts) {
  25719. var _this = _super.call(this, new ECEventProcessor()) || this;
  25720. _this._chartsViews = [];
  25721. _this._chartsMap = {};
  25722. _this._componentsViews = [];
  25723. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  25724. _this._pendingActions = [];
  25725. opts = opts || {}; // Get theme by name
  25726. if (isString(theme)) {
  25727. theme = themeStorage[theme];
  25728. }
  25729. _this._dom = dom;
  25730. var defaultRenderer = 'canvas';
  25731. var defaultCoarsePointer = 'auto';
  25732. var defaultUseDirtyRect = false;
  25733. if ("development" !== 'production') {
  25734. var root =
  25735. /* eslint-disable-next-line */
  25736. env.hasGlobalWindow ? window : global;
  25737. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  25738. defaultCoarsePointer = retrieve2(root.__ECHARTS__DEFAULT__COARSE_POINTER, defaultCoarsePointer);
  25739. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  25740. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  25741. }
  25742. var zr = _this._zr = init(dom, {
  25743. renderer: opts.renderer || defaultRenderer,
  25744. devicePixelRatio: opts.devicePixelRatio,
  25745. width: opts.width,
  25746. height: opts.height,
  25747. ssr: opts.ssr,
  25748. useDirtyRect: retrieve2(opts.useDirtyRect, defaultUseDirtyRect),
  25749. useCoarsePointer: retrieve2(opts.useCoarsePointer, defaultCoarsePointer),
  25750. pointerSize: opts.pointerSize
  25751. });
  25752. _this._ssr = opts.ssr; // Expect 60 fps.
  25753. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  25754. theme = clone(theme);
  25755. theme && globalBackwardCompat(theme, true);
  25756. _this._theme = theme;
  25757. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  25758. _this._coordSysMgr = new CoordinateSystemManager();
  25759. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  25760. function prioritySortFunc(a, b) {
  25761. return a.__prio - b.__prio;
  25762. }
  25763. sort(visualFuncs, prioritySortFunc);
  25764. sort(dataProcessorFuncs, prioritySortFunc);
  25765. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  25766. _this._messageCenter = new MessageCenter(); // Init mouse events
  25767. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  25768. _this.resize = bind(_this.resize, _this);
  25769. zr.animation.on('frame', _this._onframe, _this);
  25770. bindRenderedEvent(zr, _this);
  25771. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  25772. setAsPrimitive(_this);
  25773. return _this;
  25774. }
  25775. ECharts.prototype._onframe = function () {
  25776. if (this._disposed) {
  25777. return;
  25778. }
  25779. applyChangedStates(this);
  25780. var scheduler = this._scheduler; // Lazy update
  25781. if (this[PENDING_UPDATE]) {
  25782. var silent = this[PENDING_UPDATE].silent;
  25783. this[IN_MAIN_PROCESS_KEY] = true;
  25784. try {
  25785. prepare(this);
  25786. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  25787. } catch (e) {
  25788. this[IN_MAIN_PROCESS_KEY] = false;
  25789. this[PENDING_UPDATE] = null;
  25790. throw e;
  25791. } // At present, in each frame, zrender performs:
  25792. // (1) animation step forward.
  25793. // (2) trigger('frame') (where this `_onframe` is called)
  25794. // (3) zrender flush (render).
  25795. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  25796. // will render the final state of the elements before the real animation started.
  25797. this._zr.flush();
  25798. this[IN_MAIN_PROCESS_KEY] = false;
  25799. this[PENDING_UPDATE] = null;
  25800. flushPendingActions.call(this, silent);
  25801. triggerUpdatedEvent.call(this, silent);
  25802. } // Avoid do both lazy update and progress in one frame.
  25803. else if (scheduler.unfinished) {
  25804. // Stream progress.
  25805. var remainTime = TEST_FRAME_REMAIN_TIME;
  25806. var ecModel = this._model;
  25807. var api = this._api;
  25808. scheduler.unfinished = false;
  25809. do {
  25810. var startTime = +new Date();
  25811. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  25812. scheduler.performDataProcessorTasks(ecModel);
  25813. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  25814. // each frame is not a good user experience. So we follow the rule that
  25815. // the extent of the coordinate system is determined in the first frame (the
  25816. // frame is executed immediately after task reset.
  25817. // this._coordSysMgr.update(ecModel, api);
  25818. // console.log('--- ec frame visual ---', remainTime);
  25819. scheduler.performVisualTasks(ecModel);
  25820. renderSeries(this, this._model, api, 'remain', {});
  25821. remainTime -= +new Date() - startTime;
  25822. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  25823. if (!scheduler.unfinished) {
  25824. this._zr.flush();
  25825. } // Else, zr flushing be ensue within the same frame,
  25826. // because zr flushing is after onframe event.
  25827. }
  25828. };
  25829. ECharts.prototype.getDom = function () {
  25830. return this._dom;
  25831. };
  25832. ECharts.prototype.getId = function () {
  25833. return this.id;
  25834. };
  25835. ECharts.prototype.getZr = function () {
  25836. return this._zr;
  25837. };
  25838. ECharts.prototype.isSSR = function () {
  25839. return this._ssr;
  25840. };
  25841. /* eslint-disable-next-line */
  25842. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  25843. if (this[IN_MAIN_PROCESS_KEY]) {
  25844. if ("development" !== 'production') {
  25845. error('`setOption` should not be called during main process.');
  25846. }
  25847. return;
  25848. }
  25849. if (this._disposed) {
  25850. disposedWarning(this.id);
  25851. return;
  25852. }
  25853. var silent;
  25854. var replaceMerge;
  25855. var transitionOpt;
  25856. if (isObject(notMerge)) {
  25857. lazyUpdate = notMerge.lazyUpdate;
  25858. silent = notMerge.silent;
  25859. replaceMerge = notMerge.replaceMerge;
  25860. transitionOpt = notMerge.transition;
  25861. notMerge = notMerge.notMerge;
  25862. }
  25863. this[IN_MAIN_PROCESS_KEY] = true;
  25864. if (!this._model || notMerge) {
  25865. var optionManager = new OptionManager(this._api);
  25866. var theme = this._theme;
  25867. var ecModel = this._model = new GlobalModel();
  25868. ecModel.scheduler = this._scheduler;
  25869. ecModel.ssr = this._ssr;
  25870. ecModel.init(null, null, null, theme, this._locale, optionManager);
  25871. }
  25872. this._model.setOption(option, {
  25873. replaceMerge: replaceMerge
  25874. }, optionPreprocessorFuncs);
  25875. var updateParams = {
  25876. seriesTransition: transitionOpt,
  25877. optionChanged: true
  25878. };
  25879. if (lazyUpdate) {
  25880. this[PENDING_UPDATE] = {
  25881. silent: silent,
  25882. updateParams: updateParams
  25883. };
  25884. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  25885. // It should wake it up to make sure zrender start to render at the next frame.
  25886. this.getZr().wakeUp();
  25887. } else {
  25888. try {
  25889. prepare(this);
  25890. updateMethods.update.call(this, null, updateParams);
  25891. } catch (e) {
  25892. this[PENDING_UPDATE] = null;
  25893. this[IN_MAIN_PROCESS_KEY] = false;
  25894. throw e;
  25895. } // Ensure zr refresh sychronously, and then pixel in canvas can be
  25896. // fetched after `setOption`.
  25897. if (!this._ssr) {
  25898. // not use flush when using ssr mode.
  25899. this._zr.flush();
  25900. }
  25901. this[PENDING_UPDATE] = null;
  25902. this[IN_MAIN_PROCESS_KEY] = false;
  25903. flushPendingActions.call(this, silent);
  25904. triggerUpdatedEvent.call(this, silent);
  25905. }
  25906. };
  25907. /**
  25908. * @deprecated
  25909. */
  25910. ECharts.prototype.setTheme = function () {
  25911. deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  25912. }; // We don't want developers to use getModel directly.
  25913. ECharts.prototype.getModel = function () {
  25914. return this._model;
  25915. };
  25916. ECharts.prototype.getOption = function () {
  25917. return this._model && this._model.getOption();
  25918. };
  25919. ECharts.prototype.getWidth = function () {
  25920. return this._zr.getWidth();
  25921. };
  25922. ECharts.prototype.getHeight = function () {
  25923. return this._zr.getHeight();
  25924. };
  25925. ECharts.prototype.getDevicePixelRatio = function () {
  25926. return this._zr.painter.dpr
  25927. /* eslint-disable-next-line */
  25928. || env.hasGlobalWindow && window.devicePixelRatio || 1;
  25929. };
  25930. /**
  25931. * Get canvas which has all thing rendered
  25932. * @deprecated Use renderToCanvas instead.
  25933. */
  25934. ECharts.prototype.getRenderedCanvas = function (opts) {
  25935. if ("development" !== 'production') {
  25936. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  25937. }
  25938. return this.renderToCanvas(opts);
  25939. };
  25940. ECharts.prototype.renderToCanvas = function (opts) {
  25941. opts = opts || {};
  25942. var painter = this._zr.painter;
  25943. if ("development" !== 'production') {
  25944. if (painter.type !== 'canvas') {
  25945. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  25946. }
  25947. }
  25948. return painter.getRenderedCanvas({
  25949. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  25950. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  25951. });
  25952. };
  25953. ECharts.prototype.renderToSVGString = function (opts) {
  25954. opts = opts || {};
  25955. var painter = this._zr.painter;
  25956. if ("development" !== 'production') {
  25957. if (painter.type !== 'svg') {
  25958. throw new Error('renderToSVGString can only be used in the svg renderer.');
  25959. }
  25960. }
  25961. return painter.renderToString({
  25962. useViewBox: opts.useViewBox
  25963. });
  25964. };
  25965. /**
  25966. * Get svg data url
  25967. */
  25968. ECharts.prototype.getSvgDataURL = function () {
  25969. if (!env.svgSupported) {
  25970. return;
  25971. }
  25972. var zr = this._zr;
  25973. var list = zr.storage.getDisplayList(); // Stop animations
  25974. each(list, function (el) {
  25975. el.stopAnimation(null, true);
  25976. });
  25977. return zr.painter.toDataURL();
  25978. };
  25979. ECharts.prototype.getDataURL = function (opts) {
  25980. if (this._disposed) {
  25981. disposedWarning(this.id);
  25982. return;
  25983. }
  25984. opts = opts || {};
  25985. var excludeComponents = opts.excludeComponents;
  25986. var ecModel = this._model;
  25987. var excludesComponentViews = [];
  25988. var self = this;
  25989. each(excludeComponents, function (componentType) {
  25990. ecModel.eachComponent({
  25991. mainType: componentType
  25992. }, function (component) {
  25993. var view = self._componentsMap[component.__viewId];
  25994. if (!view.group.ignore) {
  25995. excludesComponentViews.push(view);
  25996. view.group.ignore = true;
  25997. }
  25998. });
  25999. });
  26000. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  26001. each(excludesComponentViews, function (view) {
  26002. view.group.ignore = false;
  26003. });
  26004. return url;
  26005. };
  26006. ECharts.prototype.getConnectedDataURL = function (opts) {
  26007. if (this._disposed) {
  26008. disposedWarning(this.id);
  26009. return;
  26010. }
  26011. var isSvg = opts.type === 'svg';
  26012. var groupId = this.group;
  26013. var mathMin = Math.min;
  26014. var mathMax = Math.max;
  26015. var MAX_NUMBER = Infinity;
  26016. if (connectedGroups[groupId]) {
  26017. var left_1 = MAX_NUMBER;
  26018. var top_1 = MAX_NUMBER;
  26019. var right_1 = -MAX_NUMBER;
  26020. var bottom_1 = -MAX_NUMBER;
  26021. var canvasList_1 = [];
  26022. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  26023. each(instances$1, function (chart, id) {
  26024. if (chart.group === groupId) {
  26025. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  26026. var boundingRect = chart.getDom().getBoundingClientRect();
  26027. left_1 = mathMin(boundingRect.left, left_1);
  26028. top_1 = mathMin(boundingRect.top, top_1);
  26029. right_1 = mathMax(boundingRect.right, right_1);
  26030. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  26031. canvasList_1.push({
  26032. dom: canvas,
  26033. left: boundingRect.left,
  26034. top: boundingRect.top
  26035. });
  26036. }
  26037. });
  26038. left_1 *= dpr_1;
  26039. top_1 *= dpr_1;
  26040. right_1 *= dpr_1;
  26041. bottom_1 *= dpr_1;
  26042. var width = right_1 - left_1;
  26043. var height = bottom_1 - top_1;
  26044. var targetCanvas = platformApi.createCanvas();
  26045. var zr_1 = init(targetCanvas, {
  26046. renderer: isSvg ? 'svg' : 'canvas'
  26047. });
  26048. zr_1.resize({
  26049. width: width,
  26050. height: height
  26051. });
  26052. if (isSvg) {
  26053. var content_1 = '';
  26054. each(canvasList_1, function (item) {
  26055. var x = item.left - left_1;
  26056. var y = item.top - top_1;
  26057. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  26058. });
  26059. zr_1.painter.getSvgRoot().innerHTML = content_1;
  26060. if (opts.connectedBackgroundColor) {
  26061. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  26062. }
  26063. zr_1.refreshImmediately();
  26064. return zr_1.painter.toDataURL();
  26065. } else {
  26066. // Background between the charts
  26067. if (opts.connectedBackgroundColor) {
  26068. zr_1.add(new Rect({
  26069. shape: {
  26070. x: 0,
  26071. y: 0,
  26072. width: width,
  26073. height: height
  26074. },
  26075. style: {
  26076. fill: opts.connectedBackgroundColor
  26077. }
  26078. }));
  26079. }
  26080. each(canvasList_1, function (item) {
  26081. var img = new ZRImage({
  26082. style: {
  26083. x: item.left * dpr_1 - left_1,
  26084. y: item.top * dpr_1 - top_1,
  26085. image: item.dom
  26086. }
  26087. });
  26088. zr_1.add(img);
  26089. });
  26090. zr_1.refreshImmediately();
  26091. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  26092. }
  26093. } else {
  26094. return this.getDataURL(opts);
  26095. }
  26096. };
  26097. ECharts.prototype.convertToPixel = function (finder, value) {
  26098. return doConvertPixel(this, 'convertToPixel', finder, value);
  26099. };
  26100. ECharts.prototype.convertFromPixel = function (finder, value) {
  26101. return doConvertPixel(this, 'convertFromPixel', finder, value);
  26102. };
  26103. /**
  26104. * Is the specified coordinate systems or components contain the given pixel point.
  26105. * @param {Array|number} value
  26106. * @return {boolean} result
  26107. */
  26108. ECharts.prototype.containPixel = function (finder, value) {
  26109. if (this._disposed) {
  26110. disposedWarning(this.id);
  26111. return;
  26112. }
  26113. var ecModel = this._model;
  26114. var result;
  26115. var findResult = parseFinder(ecModel, finder);
  26116. each(findResult, function (models, key) {
  26117. key.indexOf('Models') >= 0 && each(models, function (model) {
  26118. var coordSys = model.coordinateSystem;
  26119. if (coordSys && coordSys.containPoint) {
  26120. result = result || !!coordSys.containPoint(value);
  26121. } else if (key === 'seriesModels') {
  26122. var view = this._chartsMap[model.__viewId];
  26123. if (view && view.containPoint) {
  26124. result = result || view.containPoint(value, model);
  26125. } else {
  26126. if ("development" !== 'production') {
  26127. warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  26128. }
  26129. }
  26130. } else {
  26131. if ("development" !== 'production') {
  26132. warn(key + ': containPoint is not supported');
  26133. }
  26134. }
  26135. }, this);
  26136. }, this);
  26137. return !!result;
  26138. };
  26139. /**
  26140. * Get visual from series or data.
  26141. * @param finder
  26142. * If string, e.g., 'series', means {seriesIndex: 0}.
  26143. * If Object, could contain some of these properties below:
  26144. * {
  26145. * seriesIndex / seriesId / seriesName,
  26146. * dataIndex / dataIndexInside
  26147. * }
  26148. * If dataIndex is not specified, series visual will be fetched,
  26149. * but not data item visual.
  26150. * If all of seriesIndex, seriesId, seriesName are not specified,
  26151. * visual will be fetched from first series.
  26152. * @param visualType 'color', 'symbol', 'symbolSize'
  26153. */
  26154. ECharts.prototype.getVisual = function (finder, visualType) {
  26155. var ecModel = this._model;
  26156. var parsedFinder = parseFinder(ecModel, finder, {
  26157. defaultMainType: 'series'
  26158. });
  26159. var seriesModel = parsedFinder.seriesModel;
  26160. if ("development" !== 'production') {
  26161. if (!seriesModel) {
  26162. warn('There is no specified series model');
  26163. }
  26164. }
  26165. var data = seriesModel.getData();
  26166. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  26167. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  26168. };
  26169. /**
  26170. * Get view of corresponding component model
  26171. */
  26172. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  26173. return this._componentsMap[componentModel.__viewId];
  26174. };
  26175. /**
  26176. * Get view of corresponding series model
  26177. */
  26178. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  26179. return this._chartsMap[seriesModel.__viewId];
  26180. };
  26181. ECharts.prototype._initEvents = function () {
  26182. var _this = this;
  26183. each(MOUSE_EVENT_NAMES, function (eveName) {
  26184. var handler = function (e) {
  26185. var ecModel = _this.getModel();
  26186. var el = e.target;
  26187. var params;
  26188. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  26189. if (isGlobalOut) {
  26190. params = {};
  26191. } else {
  26192. el && findEventDispatcher(el, function (parent) {
  26193. var ecData = getECData(parent);
  26194. if (ecData && ecData.dataIndex != null) {
  26195. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  26196. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {};
  26197. return true;
  26198. } // If element has custom eventData of components
  26199. else if (ecData.eventData) {
  26200. params = extend({}, ecData.eventData);
  26201. return true;
  26202. }
  26203. }, true);
  26204. } // Contract: if params prepared in mouse event,
  26205. // these properties must be specified:
  26206. // {
  26207. // componentType: string (component main type)
  26208. // componentIndex: number
  26209. // }
  26210. // Otherwise event query can not work.
  26211. if (params) {
  26212. var componentType = params.componentType;
  26213. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  26214. // markLine/markPoint/markArea, the componentType is
  26215. // 'markLine'/'markPoint'/'markArea', but we should better
  26216. // enable them to be queried by seriesIndex, since their
  26217. // option is set in each series.
  26218. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  26219. componentType = 'series';
  26220. componentIndex = params.seriesIndex;
  26221. }
  26222. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  26223. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  26224. if ("development" !== 'production') {
  26225. // `event.componentType` and `event[componentTpype + 'Index']` must not
  26226. // be missed, otherwise there is no way to distinguish source component.
  26227. // See `dataFormat.getDataParams`.
  26228. if (!isGlobalOut && !(model && view)) {
  26229. warn('model or view can not be found by params');
  26230. }
  26231. }
  26232. params.event = e;
  26233. params.type = eveName;
  26234. _this._$eventProcessor.eventInfo = {
  26235. targetEl: el,
  26236. packedEvent: params,
  26237. model: model,
  26238. view: view
  26239. };
  26240. _this.trigger(eveName, params);
  26241. }
  26242. }; // Consider that some component (like tooltip, brush, ...)
  26243. // register zr event handler, but user event handler might
  26244. // do anything, such as call `setOption` or `dispatchAction`,
  26245. // which probably update any of the content and probably
  26246. // cause problem if it is called previous other inner handlers.
  26247. handler.zrEventfulCallAtLast = true;
  26248. _this._zr.on(eveName, handler, _this);
  26249. });
  26250. each(eventActionMap, function (actionType, eventType) {
  26251. _this._messageCenter.on(eventType, function (event) {
  26252. this.trigger(eventType, event);
  26253. }, _this);
  26254. }); // Extra events
  26255. // TODO register?
  26256. each(['selectchanged'], function (eventType) {
  26257. _this._messageCenter.on(eventType, function (event) {
  26258. this.trigger(eventType, event);
  26259. }, _this);
  26260. });
  26261. handleLegacySelectEvents(this._messageCenter, this, this._api);
  26262. };
  26263. ECharts.prototype.isDisposed = function () {
  26264. return this._disposed;
  26265. };
  26266. ECharts.prototype.clear = function () {
  26267. if (this._disposed) {
  26268. disposedWarning(this.id);
  26269. return;
  26270. }
  26271. this.setOption({
  26272. series: []
  26273. }, true);
  26274. };
  26275. ECharts.prototype.dispose = function () {
  26276. if (this._disposed) {
  26277. disposedWarning(this.id);
  26278. return;
  26279. }
  26280. this._disposed = true;
  26281. var dom = this.getDom();
  26282. if (dom) {
  26283. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  26284. }
  26285. var chart = this;
  26286. var api = chart._api;
  26287. var ecModel = chart._model;
  26288. each(chart._componentsViews, function (component) {
  26289. component.dispose(ecModel, api);
  26290. });
  26291. each(chart._chartsViews, function (chart) {
  26292. chart.dispose(ecModel, api);
  26293. }); // Dispose after all views disposed
  26294. chart._zr.dispose(); // Set properties to null.
  26295. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  26296. chart._dom = chart._model = chart._chartsMap = chart._componentsMap = chart._chartsViews = chart._componentsViews = chart._scheduler = chart._api = chart._zr = chart._throttledZrFlush = chart._theme = chart._coordSysMgr = chart._messageCenter = null;
  26297. delete instances$1[chart.id];
  26298. };
  26299. /**
  26300. * Resize the chart
  26301. */
  26302. ECharts.prototype.resize = function (opts) {
  26303. if (this[IN_MAIN_PROCESS_KEY]) {
  26304. if ("development" !== 'production') {
  26305. error('`resize` should not be called during main process.');
  26306. }
  26307. return;
  26308. }
  26309. if (this._disposed) {
  26310. disposedWarning(this.id);
  26311. return;
  26312. }
  26313. this._zr.resize(opts);
  26314. var ecModel = this._model; // Resize loading effect
  26315. this._loadingFX && this._loadingFX.resize();
  26316. if (!ecModel) {
  26317. return;
  26318. }
  26319. var needPrepare = ecModel.resetOption('media');
  26320. var silent = opts && opts.silent; // There is some real cases that:
  26321. // chart.setOption(option, { lazyUpdate: true });
  26322. // chart.resize();
  26323. if (this[PENDING_UPDATE]) {
  26324. if (silent == null) {
  26325. silent = this[PENDING_UPDATE].silent;
  26326. }
  26327. needPrepare = true;
  26328. this[PENDING_UPDATE] = null;
  26329. }
  26330. this[IN_MAIN_PROCESS_KEY] = true;
  26331. try {
  26332. needPrepare && prepare(this);
  26333. updateMethods.update.call(this, {
  26334. type: 'resize',
  26335. animation: extend({
  26336. // Disable animation
  26337. duration: 0
  26338. }, opts && opts.animation)
  26339. });
  26340. } catch (e) {
  26341. this[IN_MAIN_PROCESS_KEY] = false;
  26342. throw e;
  26343. }
  26344. this[IN_MAIN_PROCESS_KEY] = false;
  26345. flushPendingActions.call(this, silent);
  26346. triggerUpdatedEvent.call(this, silent);
  26347. };
  26348. ECharts.prototype.showLoading = function (name, cfg) {
  26349. if (this._disposed) {
  26350. disposedWarning(this.id);
  26351. return;
  26352. }
  26353. if (isObject(name)) {
  26354. cfg = name;
  26355. name = '';
  26356. }
  26357. name = name || 'default';
  26358. this.hideLoading();
  26359. if (!loadingEffects[name]) {
  26360. if ("development" !== 'production') {
  26361. warn('Loading effects ' + name + ' not exists.');
  26362. }
  26363. return;
  26364. }
  26365. var el = loadingEffects[name](this._api, cfg);
  26366. var zr = this._zr;
  26367. this._loadingFX = el;
  26368. zr.add(el);
  26369. };
  26370. /**
  26371. * Hide loading effect
  26372. */
  26373. ECharts.prototype.hideLoading = function () {
  26374. if (this._disposed) {
  26375. disposedWarning(this.id);
  26376. return;
  26377. }
  26378. this._loadingFX && this._zr.remove(this._loadingFX);
  26379. this._loadingFX = null;
  26380. };
  26381. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  26382. var payload = extend({}, eventObj);
  26383. payload.type = eventActionMap[eventObj.type];
  26384. return payload;
  26385. };
  26386. /**
  26387. * @param opt If pass boolean, means opt.silent
  26388. * @param opt.silent Default `false`. Whether trigger events.
  26389. * @param opt.flush Default `undefined`.
  26390. * true: Flush immediately, and then pixel in canvas can be fetched
  26391. * immediately. Caution: it might affect performance.
  26392. * false: Not flush.
  26393. * undefined: Auto decide whether perform flush.
  26394. */
  26395. ECharts.prototype.dispatchAction = function (payload, opt) {
  26396. if (this._disposed) {
  26397. disposedWarning(this.id);
  26398. return;
  26399. }
  26400. if (!isObject(opt)) {
  26401. opt = {
  26402. silent: !!opt
  26403. };
  26404. }
  26405. if (!actions[payload.type]) {
  26406. return;
  26407. } // Avoid dispatch action before setOption. Especially in `connect`.
  26408. if (!this._model) {
  26409. return;
  26410. } // May dispatchAction in rendering procedure
  26411. if (this[IN_MAIN_PROCESS_KEY]) {
  26412. this._pendingActions.push(payload);
  26413. return;
  26414. }
  26415. var silent = opt.silent;
  26416. doDispatchAction.call(this, payload, silent);
  26417. var flush = opt.flush;
  26418. if (flush) {
  26419. this._zr.flush();
  26420. } else if (flush !== false && env.browser.weChat) {
  26421. // In WeChat embedded browser, `requestAnimationFrame` and `setInterval`
  26422. // hang when sliding page (on touch event), which cause that zr does not
  26423. // refresh until user interaction finished, which is not expected.
  26424. // But `dispatchAction` may be called too frequently when pan on touch
  26425. // screen, which impacts performance if do not throttle them.
  26426. this._throttledZrFlush();
  26427. }
  26428. flushPendingActions.call(this, silent);
  26429. triggerUpdatedEvent.call(this, silent);
  26430. };
  26431. ECharts.prototype.updateLabelLayout = function () {
  26432. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  26433. // Not adding series labels.
  26434. // TODO
  26435. updatedSeries: []
  26436. });
  26437. };
  26438. ECharts.prototype.appendData = function (params) {
  26439. if (this._disposed) {
  26440. disposedWarning(this.id);
  26441. return;
  26442. }
  26443. var seriesIndex = params.seriesIndex;
  26444. var ecModel = this.getModel();
  26445. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  26446. if ("development" !== 'production') {
  26447. assert(params.data && seriesModel);
  26448. }
  26449. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  26450. // system, util some scenario require that. In the expected usage of
  26451. // `appendData`, the initial extent of coordinate system should better
  26452. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  26453. // the extent changed while `appendData`, the location of the painted
  26454. // graphic elements have to be changed, which make the usage of
  26455. // `appendData` meaningless.
  26456. this._scheduler.unfinished = true;
  26457. this.getZr().wakeUp();
  26458. }; // A work around for no `internal` modifier in ts yet but
  26459. // need to strictly hide private methods to JS users.
  26460. ECharts.internalField = function () {
  26461. prepare = function (ecIns) {
  26462. var scheduler = ecIns._scheduler;
  26463. scheduler.restorePipelines(ecIns._model);
  26464. scheduler.prepareStageTasks();
  26465. prepareView(ecIns, true);
  26466. prepareView(ecIns, false);
  26467. scheduler.plan();
  26468. };
  26469. /**
  26470. * Prepare view instances of charts and components
  26471. */
  26472. prepareView = function (ecIns, isComponent) {
  26473. var ecModel = ecIns._model;
  26474. var scheduler = ecIns._scheduler;
  26475. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  26476. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  26477. var zr = ecIns._zr;
  26478. var api = ecIns._api;
  26479. for (var i = 0; i < viewList.length; i++) {
  26480. viewList[i].__alive = false;
  26481. }
  26482. isComponent ? ecModel.eachComponent(function (componentType, model) {
  26483. componentType !== 'series' && doPrepare(model);
  26484. }) : ecModel.eachSeries(doPrepare);
  26485. function doPrepare(model) {
  26486. // By default view will be reused if possible for the case that `setOption` with "notMerge"
  26487. // mode and need to enable transition animation. (Usually, when they have the same id, or
  26488. // especially no id but have the same type & name & index. See the `model.id` generation
  26489. // rule in `makeIdAndName` and `viewId` generation rule here).
  26490. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  26491. // the new model has nothing to do with the old model.
  26492. var requireNewView = model.__requireNewView; // This command should not work twice.
  26493. model.__requireNewView = false; // Consider: id same and type changed.
  26494. var viewId = '_ec_' + model.id + '_' + model.type;
  26495. var view = !requireNewView && viewMap[viewId];
  26496. if (!view) {
  26497. var classType = parseClassType(model.type);
  26498. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  26499. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  26500. // For backward compat, still support a chart type declared as only subType
  26501. // like "liquidfill", but recommend "series.liquidfill"
  26502. // But need a base class to make a type series.
  26503. ChartView.getClass(classType.sub);
  26504. if ("development" !== 'production') {
  26505. assert(Clazz, classType.sub + ' does not exist.');
  26506. }
  26507. view = new Clazz();
  26508. view.init(ecModel, api);
  26509. viewMap[viewId] = view;
  26510. viewList.push(view);
  26511. zr.add(view.group);
  26512. }
  26513. model.__viewId = view.__id = viewId;
  26514. view.__alive = true;
  26515. view.__model = model;
  26516. view.group.__ecComponentInfo = {
  26517. mainType: model.mainType,
  26518. index: model.componentIndex
  26519. };
  26520. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  26521. }
  26522. for (var i = 0; i < viewList.length;) {
  26523. var view = viewList[i];
  26524. if (!view.__alive) {
  26525. !isComponent && view.renderTask.dispose();
  26526. zr.remove(view.group);
  26527. view.dispose(ecModel, api);
  26528. viewList.splice(i, 1);
  26529. if (viewMap[view.__id] === view) {
  26530. delete viewMap[view.__id];
  26531. }
  26532. view.__id = view.group.__ecComponentInfo = null;
  26533. } else {
  26534. i++;
  26535. }
  26536. }
  26537. };
  26538. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  26539. var ecModel = ecIns._model;
  26540. ecModel.setUpdatePayload(payload); // broadcast
  26541. if (!mainType) {
  26542. // FIXME
  26543. // Chart will not be update directly here, except set dirty.
  26544. // But there is no such scenario now.
  26545. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  26546. return;
  26547. }
  26548. var query = {};
  26549. query[mainType + 'Id'] = payload[mainType + 'Id'];
  26550. query[mainType + 'Index'] = payload[mainType + 'Index'];
  26551. query[mainType + 'Name'] = payload[mainType + 'Name'];
  26552. var condition = {
  26553. mainType: mainType,
  26554. query: query
  26555. };
  26556. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  26557. var excludeSeriesId = payload.excludeSeriesId;
  26558. var excludeSeriesIdMap;
  26559. if (excludeSeriesId != null) {
  26560. excludeSeriesIdMap = createHashMap();
  26561. each(normalizeToArray(excludeSeriesId), function (id) {
  26562. var modelId = convertOptionIdName(id, null);
  26563. if (modelId != null) {
  26564. excludeSeriesIdMap.set(modelId, true);
  26565. }
  26566. });
  26567. } // If dispatchAction before setOption, do nothing.
  26568. ecModel && ecModel.eachComponent(condition, function (model) {
  26569. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26570. if (isExcluded) {
  26571. return;
  26572. }
  26573. if (isHighDownPayload(payload)) {
  26574. if (model instanceof SeriesModel) {
  26575. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  26576. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  26577. }
  26578. } else {
  26579. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  26580. focusSelf = _a.focusSelf,
  26581. dispatchers = _a.dispatchers;
  26582. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  26583. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  26584. } // PENDING:
  26585. // Whether to put this "enter emphasis" code in `ComponentView`,
  26586. // which will be the same as `ChartView` but might be not necessary
  26587. // and will be far from this logic.
  26588. if (dispatchers) {
  26589. each(dispatchers, function (dispatcher) {
  26590. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  26591. });
  26592. }
  26593. }
  26594. } else if (isSelectChangePayload(payload)) {
  26595. // TODO geo
  26596. if (model instanceof SeriesModel) {
  26597. toggleSelectionFromPayload(model, payload, ecIns._api);
  26598. updateSeriesElementSelection(model);
  26599. markStatusToUpdate(ecIns);
  26600. }
  26601. }
  26602. }, ecIns);
  26603. ecModel && ecModel.eachComponent(condition, function (model) {
  26604. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26605. if (isExcluded) {
  26606. return;
  26607. }
  26608. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  26609. }, ecIns);
  26610. function callView(view) {
  26611. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  26612. }
  26613. };
  26614. updateMethods = {
  26615. prepareAndUpdate: function (payload) {
  26616. prepare(this);
  26617. updateMethods.update.call(this, payload, {
  26618. // Needs to mark option changed if newOption is given.
  26619. // It's from MagicType.
  26620. // TODO If use a separate flag optionChanged in payload?
  26621. optionChanged: payload.newOption != null
  26622. });
  26623. },
  26624. update: function (payload, updateParams) {
  26625. var ecModel = this._model;
  26626. var api = this._api;
  26627. var zr = this._zr;
  26628. var coordSysMgr = this._coordSysMgr;
  26629. var scheduler = this._scheduler; // update before setOption
  26630. if (!ecModel) {
  26631. return;
  26632. }
  26633. ecModel.setUpdatePayload(payload);
  26634. scheduler.restoreData(ecModel, payload);
  26635. scheduler.performSeriesTasks(ecModel); // TODO
  26636. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  26637. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  26638. // Create new coordinate system each update
  26639. // In LineView may save the old coordinate system and use it to get the original point.
  26640. coordSysMgr.create(ecModel, api);
  26641. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  26642. // stream modes after data processing, where the filtered data is used to
  26643. // determine whether to use progressive rendering.
  26644. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  26645. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  26646. // the drawback is the full coord info can not be fetched. Fortunately this full
  26647. // coord is not required in stream mode updater currently.
  26648. coordSysMgr.update(ecModel, api);
  26649. clearColorPalette(ecModel);
  26650. scheduler.performVisualTasks(ecModel, payload);
  26651. render(this, ecModel, api, payload, updateParams); // Set background
  26652. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  26653. var darkMode = ecModel.get('darkMode');
  26654. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  26655. if (darkMode != null && darkMode !== 'auto') {
  26656. zr.setDarkMode(darkMode);
  26657. }
  26658. lifecycle.trigger('afterupdate', ecModel, api);
  26659. },
  26660. updateTransform: function (payload) {
  26661. var _this = this;
  26662. var ecModel = this._model;
  26663. var api = this._api; // update before setOption
  26664. if (!ecModel) {
  26665. return;
  26666. }
  26667. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  26668. var componentDirtyList = [];
  26669. ecModel.eachComponent(function (componentType, componentModel) {
  26670. if (componentType === 'series') {
  26671. return;
  26672. }
  26673. var componentView = _this.getViewOfComponentModel(componentModel);
  26674. if (componentView && componentView.__alive) {
  26675. if (componentView.updateTransform) {
  26676. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  26677. result && result.update && componentDirtyList.push(componentView);
  26678. } else {
  26679. componentDirtyList.push(componentView);
  26680. }
  26681. }
  26682. });
  26683. var seriesDirtyMap = createHashMap();
  26684. ecModel.eachSeries(function (seriesModel) {
  26685. var chartView = _this._chartsMap[seriesModel.__viewId];
  26686. if (chartView.updateTransform) {
  26687. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  26688. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  26689. } else {
  26690. seriesDirtyMap.set(seriesModel.uid, 1);
  26691. }
  26692. });
  26693. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26694. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  26695. this._scheduler.performVisualTasks(ecModel, payload, {
  26696. setDirty: true,
  26697. dirtyMap: seriesDirtyMap
  26698. }); // Currently, not call render of components. Geo render cost a lot.
  26699. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  26700. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  26701. lifecycle.trigger('afterupdate', ecModel, api);
  26702. },
  26703. updateView: function (payload) {
  26704. var ecModel = this._model; // update before setOption
  26705. if (!ecModel) {
  26706. return;
  26707. }
  26708. ecModel.setUpdatePayload(payload);
  26709. ChartView.markUpdateMethod(payload, 'updateView');
  26710. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26711. this._scheduler.performVisualTasks(ecModel, payload, {
  26712. setDirty: true
  26713. });
  26714. render(this, ecModel, this._api, payload, {});
  26715. lifecycle.trigger('afterupdate', ecModel, this._api);
  26716. },
  26717. updateVisual: function (payload) {
  26718. // updateMethods.update.call(this, payload);
  26719. var _this = this;
  26720. var ecModel = this._model; // update before setOption
  26721. if (!ecModel) {
  26722. return;
  26723. }
  26724. ecModel.setUpdatePayload(payload); // clear all visual
  26725. ecModel.eachSeries(function (seriesModel) {
  26726. seriesModel.getData().clearAllVisual();
  26727. }); // Perform visual
  26728. ChartView.markUpdateMethod(payload, 'updateVisual');
  26729. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26730. this._scheduler.performVisualTasks(ecModel, payload, {
  26731. visualType: 'visual',
  26732. setDirty: true
  26733. });
  26734. ecModel.eachComponent(function (componentType, componentModel) {
  26735. if (componentType !== 'series') {
  26736. var componentView = _this.getViewOfComponentModel(componentModel);
  26737. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  26738. }
  26739. });
  26740. ecModel.eachSeries(function (seriesModel) {
  26741. var chartView = _this._chartsMap[seriesModel.__viewId];
  26742. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  26743. });
  26744. lifecycle.trigger('afterupdate', ecModel, this._api);
  26745. },
  26746. updateLayout: function (payload) {
  26747. updateMethods.update.call(this, payload);
  26748. }
  26749. };
  26750. doConvertPixel = function (ecIns, methodName, finder, value) {
  26751. if (ecIns._disposed) {
  26752. disposedWarning(ecIns.id);
  26753. return;
  26754. }
  26755. var ecModel = ecIns._model;
  26756. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  26757. var result;
  26758. var parsedFinder = parseFinder(ecModel, finder);
  26759. for (var i = 0; i < coordSysList.length; i++) {
  26760. var coordSys = coordSysList[i];
  26761. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  26762. return result;
  26763. }
  26764. }
  26765. if ("development" !== 'production') {
  26766. warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  26767. }
  26768. };
  26769. updateStreamModes = function (ecIns, ecModel) {
  26770. var chartsMap = ecIns._chartsMap;
  26771. var scheduler = ecIns._scheduler;
  26772. ecModel.eachSeries(function (seriesModel) {
  26773. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  26774. });
  26775. };
  26776. doDispatchAction = function (payload, silent) {
  26777. var _this = this;
  26778. var ecModel = this.getModel();
  26779. var payloadType = payload.type;
  26780. var escapeConnect = payload.escapeConnect;
  26781. var actionWrap = actions[payloadType];
  26782. var actionInfo = actionWrap.actionInfo;
  26783. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  26784. var updateMethod = cptTypeTmp.pop();
  26785. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  26786. this[IN_MAIN_PROCESS_KEY] = true;
  26787. var payloads = [payload];
  26788. var batched = false; // Batch action
  26789. if (payload.batch) {
  26790. batched = true;
  26791. payloads = map(payload.batch, function (item) {
  26792. item = defaults(extend({}, item), payload);
  26793. item.batch = null;
  26794. return item;
  26795. });
  26796. }
  26797. var eventObjBatch = [];
  26798. var eventObj;
  26799. var isSelectChange = isSelectChangePayload(payload);
  26800. var isHighDown = isHighDownPayload(payload); // Only leave blur once if there are multiple batches.
  26801. if (isHighDown) {
  26802. allLeaveBlur(this._api);
  26803. }
  26804. each(payloads, function (batchItem) {
  26805. // Action can specify the event by return it.
  26806. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  26807. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  26808. eventObj.type = actionInfo.event || eventObj.type;
  26809. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  26810. if (isHighDown) {
  26811. var _a = preParseFinder(payload),
  26812. queryOptionMap = _a.queryOptionMap,
  26813. mainTypeSpecified = _a.mainTypeSpecified;
  26814. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  26815. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  26816. markStatusToUpdate(_this);
  26817. } else if (isSelectChange) {
  26818. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  26819. // geo still use 'geoselect'.
  26820. updateDirectly(_this, updateMethod, batchItem, 'series');
  26821. markStatusToUpdate(_this);
  26822. } else if (cptType) {
  26823. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  26824. }
  26825. });
  26826. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  26827. try {
  26828. // Still dirty
  26829. if (this[PENDING_UPDATE]) {
  26830. prepare(this);
  26831. updateMethods.update.call(this, payload);
  26832. this[PENDING_UPDATE] = null;
  26833. } else {
  26834. updateMethods[updateMethod].call(this, payload);
  26835. }
  26836. } catch (e) {
  26837. this[IN_MAIN_PROCESS_KEY] = false;
  26838. throw e;
  26839. }
  26840. } // Follow the rule of action batch
  26841. if (batched) {
  26842. eventObj = {
  26843. type: actionInfo.event || payloadType,
  26844. escapeConnect: escapeConnect,
  26845. batch: eventObjBatch
  26846. };
  26847. } else {
  26848. eventObj = eventObjBatch[0];
  26849. }
  26850. this[IN_MAIN_PROCESS_KEY] = false;
  26851. if (!silent) {
  26852. var messageCenter = this._messageCenter;
  26853. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  26854. if (isSelectChange) {
  26855. var newObj = {
  26856. type: 'selectchanged',
  26857. escapeConnect: escapeConnect,
  26858. selected: getAllSelectedIndices(ecModel),
  26859. isFromClick: payload.isFromClick || false,
  26860. fromAction: payload.type,
  26861. fromActionPayload: payload
  26862. };
  26863. messageCenter.trigger(newObj.type, newObj);
  26864. }
  26865. }
  26866. };
  26867. flushPendingActions = function (silent) {
  26868. var pendingActions = this._pendingActions;
  26869. while (pendingActions.length) {
  26870. var payload = pendingActions.shift();
  26871. doDispatchAction.call(this, payload, silent);
  26872. }
  26873. };
  26874. triggerUpdatedEvent = function (silent) {
  26875. !silent && this.trigger('updated');
  26876. };
  26877. /**
  26878. * Event `rendered` is triggered when zr
  26879. * rendered. It is useful for realtime
  26880. * snapshot (reflect animation).
  26881. *
  26882. * Event `finished` is triggered when:
  26883. * (1) zrender rendering finished.
  26884. * (2) initial animation finished.
  26885. * (3) progressive rendering finished.
  26886. * (4) no pending action.
  26887. * (5) no delayed setOption needs to be processed.
  26888. */
  26889. bindRenderedEvent = function (zr, ecIns) {
  26890. zr.on('rendered', function (params) {
  26891. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatedly,
  26892. // so it should only be triggered when rendering indeed happens
  26893. // in zrender. (Consider the case that dipatchAction is keep
  26894. // triggering when mouse move).
  26895. if ( // Although zr is dirty if initial animation is not finished
  26896. // and this checking is called on frame, we also check
  26897. // animation finished for robustness.
  26898. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  26899. ecIns.trigger('finished');
  26900. }
  26901. });
  26902. };
  26903. bindMouseEvent = function (zr, ecIns) {
  26904. zr.on('mouseover', function (e) {
  26905. var el = e.target;
  26906. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26907. if (dispatcher) {
  26908. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  26909. markStatusToUpdate(ecIns);
  26910. }
  26911. }).on('mouseout', function (e) {
  26912. var el = e.target;
  26913. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26914. if (dispatcher) {
  26915. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  26916. markStatusToUpdate(ecIns);
  26917. }
  26918. }).on('click', function (e) {
  26919. var el = e.target;
  26920. var dispatcher = findEventDispatcher(el, function (target) {
  26921. return getECData(target).dataIndex != null;
  26922. }, true);
  26923. if (dispatcher) {
  26924. var actionType = dispatcher.selected ? 'unselect' : 'select';
  26925. var ecData = getECData(dispatcher);
  26926. ecIns._api.dispatchAction({
  26927. type: actionType,
  26928. dataType: ecData.dataType,
  26929. dataIndexInside: ecData.dataIndex,
  26930. seriesIndex: ecData.seriesIndex,
  26931. isFromClick: true
  26932. });
  26933. }
  26934. });
  26935. };
  26936. function clearColorPalette(ecModel) {
  26937. ecModel.clearColorPalette();
  26938. ecModel.eachSeries(function (seriesModel) {
  26939. seriesModel.clearColorPalette();
  26940. });
  26941. }
  26942. function allocateZlevels(ecModel) {
  26943. var componentZLevels = [];
  26944. var seriesZLevels = [];
  26945. var hasSeperateZLevel = false;
  26946. ecModel.eachComponent(function (componentType, componentModel) {
  26947. var zlevel = componentModel.get('zlevel') || 0;
  26948. var z = componentModel.get('z') || 0;
  26949. var zlevelKey = componentModel.getZLevelKey();
  26950. hasSeperateZLevel = hasSeperateZLevel || !!zlevelKey;
  26951. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  26952. zlevel: zlevel,
  26953. z: z,
  26954. idx: componentModel.componentIndex,
  26955. type: componentType,
  26956. key: zlevelKey
  26957. });
  26958. });
  26959. if (hasSeperateZLevel) {
  26960. // Series after component
  26961. var zLevels = componentZLevels.concat(seriesZLevels);
  26962. var lastSeriesZLevel_1;
  26963. var lastSeriesKey_1;
  26964. sort(zLevels, function (a, b) {
  26965. if (a.zlevel === b.zlevel) {
  26966. return a.z - b.z;
  26967. }
  26968. return a.zlevel - b.zlevel;
  26969. });
  26970. each(zLevels, function (item) {
  26971. var componentModel = ecModel.getComponent(item.type, item.idx);
  26972. var zlevel = item.zlevel;
  26973. var key = item.key;
  26974. if (lastSeriesZLevel_1 != null) {
  26975. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  26976. }
  26977. if (key) {
  26978. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  26979. zlevel++;
  26980. }
  26981. lastSeriesKey_1 = key;
  26982. } else if (lastSeriesKey_1) {
  26983. if (zlevel === lastSeriesZLevel_1) {
  26984. zlevel++;
  26985. }
  26986. lastSeriesKey_1 = '';
  26987. }
  26988. lastSeriesZLevel_1 = zlevel;
  26989. componentModel.setZLevel(zlevel);
  26990. });
  26991. }
  26992. }
  26993. render = function (ecIns, ecModel, api, payload, updateParams) {
  26994. allocateZlevels(ecModel);
  26995. renderComponents(ecIns, ecModel, api, payload, updateParams);
  26996. each(ecIns._chartsViews, function (chart) {
  26997. chart.__alive = false;
  26998. });
  26999. renderSeries(ecIns, ecModel, api, payload, updateParams); // Remove groups of unrendered charts
  27000. each(ecIns._chartsViews, function (chart) {
  27001. if (!chart.__alive) {
  27002. chart.remove(ecModel, api);
  27003. }
  27004. });
  27005. };
  27006. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  27007. each(dirtyList || ecIns._componentsViews, function (componentView) {
  27008. var componentModel = componentView.__model;
  27009. clearStates(componentModel, componentView);
  27010. componentView.render(componentModel, ecModel, api, payload);
  27011. updateZ(componentModel, componentView);
  27012. updateStates(componentModel, componentView);
  27013. });
  27014. };
  27015. /**
  27016. * Render each chart and component
  27017. */
  27018. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  27019. // Render all charts
  27020. var scheduler = ecIns._scheduler;
  27021. updateParams = extend(updateParams || {}, {
  27022. updatedSeries: ecModel.getSeries()
  27023. }); // TODO progressive?
  27024. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  27025. var unfinished = false;
  27026. ecModel.eachSeries(function (seriesModel) {
  27027. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27028. chartView.__alive = true;
  27029. var renderTask = chartView.renderTask;
  27030. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  27031. clearStates(seriesModel, chartView);
  27032. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  27033. renderTask.dirty();
  27034. }
  27035. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  27036. unfinished = true;
  27037. }
  27038. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  27039. // incremental render (always render from the __startIndex each frame)
  27040. // chartView.group.markRedraw();
  27041. updateBlend(seriesModel, chartView);
  27042. updateSeriesElementSelection(seriesModel);
  27043. });
  27044. scheduler.unfinished = unfinished || scheduler.unfinished;
  27045. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams); // transition after label is layouted.
  27046. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  27047. ecModel.eachSeries(function (seriesModel) {
  27048. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  27049. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  27050. // label should be in normal status when layouting.
  27051. updateStates(seriesModel, chartView);
  27052. }); // If use hover layer
  27053. updateHoverLayerStatus(ecIns, ecModel);
  27054. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  27055. };
  27056. markStatusToUpdate = function (ecIns) {
  27057. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  27058. ecIns.getZr().wakeUp();
  27059. };
  27060. applyChangedStates = function (ecIns) {
  27061. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  27062. return;
  27063. }
  27064. ecIns.getZr().storage.traverse(function (el) {
  27065. // Not applied on removed elements, it may still in fading.
  27066. if (isElementRemoved(el)) {
  27067. return;
  27068. }
  27069. applyElementStates(el);
  27070. });
  27071. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  27072. };
  27073. function applyElementStates(el) {
  27074. var newStates = [];
  27075. var oldStates = el.currentStates; // Keep other states.
  27076. for (var i = 0; i < oldStates.length; i++) {
  27077. var stateName = oldStates[i];
  27078. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  27079. newStates.push(stateName);
  27080. }
  27081. } // Only use states when it's exists.
  27082. if (el.selected && el.states.select) {
  27083. newStates.push('select');
  27084. }
  27085. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  27086. newStates.push('emphasis');
  27087. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  27088. newStates.push('blur');
  27089. }
  27090. el.useStates(newStates);
  27091. }
  27092. function updateHoverLayerStatus(ecIns, ecModel) {
  27093. var zr = ecIns._zr;
  27094. var storage = zr.storage;
  27095. var elCount = 0;
  27096. storage.traverse(function (el) {
  27097. if (!el.isGroup) {
  27098. elCount++;
  27099. }
  27100. });
  27101. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  27102. ecModel.eachSeries(function (seriesModel) {
  27103. if (seriesModel.preventUsingHoverLayer) {
  27104. return;
  27105. }
  27106. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27107. if (chartView.__alive) {
  27108. chartView.eachRendered(function (el) {
  27109. if (el.states.emphasis) {
  27110. el.states.emphasis.hoverLayer = true;
  27111. }
  27112. });
  27113. }
  27114. });
  27115. }
  27116. }
  27117. /**
  27118. * Update chart and blend.
  27119. */
  27120. function updateBlend(seriesModel, chartView) {
  27121. var blendMode = seriesModel.get('blendMode') || null;
  27122. chartView.eachRendered(function (el) {
  27123. // FIXME marker and other components
  27124. if (!el.isGroup) {
  27125. // DON'T mark the element dirty. In case element is incremental and don't want to rerender.
  27126. el.style.blend = blendMode;
  27127. }
  27128. });
  27129. }
  27130. function updateZ(model, view) {
  27131. if (model.preventAutoZ) {
  27132. return;
  27133. }
  27134. var z = model.get('z') || 0;
  27135. var zlevel = model.get('zlevel') || 0; // Set z and zlevel
  27136. view.eachRendered(function (el) {
  27137. doUpdateZ(el, z, zlevel, -Infinity); // Don't traverse the children because it has been traversed in _updateZ.
  27138. return true;
  27139. });
  27140. }
  27141. function doUpdateZ(el, z, zlevel, maxZ2) {
  27142. // Group may also have textContent
  27143. var label = el.getTextContent();
  27144. var labelLine = el.getTextGuideLine();
  27145. var isGroup = el.isGroup;
  27146. if (isGroup) {
  27147. // set z & zlevel of children elements of Group
  27148. var children = el.childrenRef();
  27149. for (var i = 0; i < children.length; i++) {
  27150. maxZ2 = Math.max(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  27151. }
  27152. } else {
  27153. // not Group
  27154. el.z = z;
  27155. el.zlevel = zlevel;
  27156. maxZ2 = Math.max(el.z2, maxZ2);
  27157. } // always set z and zlevel if label/labelLine exists
  27158. if (label) {
  27159. label.z = z;
  27160. label.zlevel = zlevel; // lift z2 of text content
  27161. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  27162. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  27163. }
  27164. if (labelLine) {
  27165. var textGuideLineConfig = el.textGuideLineConfig;
  27166. labelLine.z = z;
  27167. labelLine.zlevel = zlevel;
  27168. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  27169. }
  27170. return maxZ2;
  27171. } // Clear states without animation.
  27172. // TODO States on component.
  27173. function clearStates(model, view) {
  27174. view.eachRendered(function (el) {
  27175. // Not applied on removed elements, it may still in fading.
  27176. if (isElementRemoved(el)) {
  27177. return;
  27178. }
  27179. var textContent = el.getTextContent();
  27180. var textGuide = el.getTextGuideLine();
  27181. if (el.stateTransition) {
  27182. el.stateTransition = null;
  27183. }
  27184. if (textContent && textContent.stateTransition) {
  27185. textContent.stateTransition = null;
  27186. }
  27187. if (textGuide && textGuide.stateTransition) {
  27188. textGuide.stateTransition = null;
  27189. } // TODO If el is incremental.
  27190. if (el.hasState()) {
  27191. el.prevStates = el.currentStates;
  27192. el.clearStates();
  27193. } else if (el.prevStates) {
  27194. el.prevStates = null;
  27195. }
  27196. });
  27197. }
  27198. function updateStates(model, view) {
  27199. var stateAnimationModel = model.getModel('stateAnimation');
  27200. var enableAnimation = model.isAnimationEnabled();
  27201. var duration = stateAnimationModel.get('duration');
  27202. var stateTransition = duration > 0 ? {
  27203. duration: duration,
  27204. delay: stateAnimationModel.get('delay'),
  27205. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  27206. } : null;
  27207. view.eachRendered(function (el) {
  27208. if (el.states && el.states.emphasis) {
  27209. // Not applied on removed elements, it may still in fading.
  27210. if (isElementRemoved(el)) {
  27211. return;
  27212. }
  27213. if (el instanceof Path) {
  27214. savePathStates(el);
  27215. } // Only updated on changed element. In case element is incremental and don't want to rerender.
  27216. // TODO, a more proper way?
  27217. if (el.__dirty) {
  27218. var prevStates = el.prevStates; // Restore states without animation
  27219. if (prevStates) {
  27220. el.useStates(prevStates);
  27221. }
  27222. } // Update state transition and enable animation again.
  27223. if (enableAnimation) {
  27224. el.stateTransition = stateTransition;
  27225. var textContent = el.getTextContent();
  27226. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  27227. if (textContent) {
  27228. textContent.stateTransition = stateTransition;
  27229. }
  27230. if (textGuide) {
  27231. textGuide.stateTransition = stateTransition;
  27232. }
  27233. } // Use highlighted and selected flag to toggle states.
  27234. if (el.__dirty) {
  27235. applyElementStates(el);
  27236. }
  27237. }
  27238. });
  27239. }
  27240. createExtensionAPI = function (ecIns) {
  27241. return new (
  27242. /** @class */
  27243. function (_super) {
  27244. __extends(class_1, _super);
  27245. function class_1() {
  27246. return _super !== null && _super.apply(this, arguments) || this;
  27247. }
  27248. class_1.prototype.getCoordinateSystems = function () {
  27249. return ecIns._coordSysMgr.getCoordinateSystems();
  27250. };
  27251. class_1.prototype.getComponentByElement = function (el) {
  27252. while (el) {
  27253. var modelInfo = el.__ecComponentInfo;
  27254. if (modelInfo != null) {
  27255. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  27256. }
  27257. el = el.parent;
  27258. }
  27259. };
  27260. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  27261. enterEmphasis(el, highlightDigit);
  27262. markStatusToUpdate(ecIns);
  27263. };
  27264. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  27265. leaveEmphasis(el, highlightDigit);
  27266. markStatusToUpdate(ecIns);
  27267. };
  27268. class_1.prototype.enterBlur = function (el) {
  27269. enterBlur(el);
  27270. markStatusToUpdate(ecIns);
  27271. };
  27272. class_1.prototype.leaveBlur = function (el) {
  27273. leaveBlur(el);
  27274. markStatusToUpdate(ecIns);
  27275. };
  27276. class_1.prototype.enterSelect = function (el) {
  27277. enterSelect(el);
  27278. markStatusToUpdate(ecIns);
  27279. };
  27280. class_1.prototype.leaveSelect = function (el) {
  27281. leaveSelect(el);
  27282. markStatusToUpdate(ecIns);
  27283. };
  27284. class_1.prototype.getModel = function () {
  27285. return ecIns.getModel();
  27286. };
  27287. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  27288. return ecIns.getViewOfComponentModel(componentModel);
  27289. };
  27290. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  27291. return ecIns.getViewOfSeriesModel(seriesModel);
  27292. };
  27293. return class_1;
  27294. }(ExtensionAPI))(ecIns);
  27295. };
  27296. enableConnect = function (chart) {
  27297. function updateConnectedChartsStatus(charts, status) {
  27298. for (var i = 0; i < charts.length; i++) {
  27299. var otherChart = charts[i];
  27300. otherChart[CONNECT_STATUS_KEY] = status;
  27301. }
  27302. }
  27303. each(eventActionMap, function (actionType, eventType) {
  27304. chart._messageCenter.on(eventType, function (event) {
  27305. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  27306. if (event && event.escapeConnect) {
  27307. return;
  27308. }
  27309. var action_1 = chart.makeActionFromEvent(event);
  27310. var otherCharts_1 = [];
  27311. each(instances$1, function (otherChart) {
  27312. if (otherChart !== chart && otherChart.group === chart.group) {
  27313. otherCharts_1.push(otherChart);
  27314. }
  27315. });
  27316. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  27317. each(otherCharts_1, function (otherChart) {
  27318. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  27319. otherChart.dispatchAction(action_1);
  27320. }
  27321. });
  27322. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  27323. }
  27324. });
  27325. });
  27326. };
  27327. }();
  27328. return ECharts;
  27329. }(Eventful);
  27330. var echartsProto = ECharts.prototype;
  27331. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  27332. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  27333. /**
  27334. * @deprecated
  27335. */
  27336. // @ts-ignore
  27337. echartsProto.one = function (eventName, cb, ctx) {
  27338. var self = this;
  27339. deprecateLog('ECharts#one is deprecated.');
  27340. function wrapped() {
  27341. var args2 = [];
  27342. for (var _i = 0; _i < arguments.length; _i++) {
  27343. args2[_i] = arguments[_i];
  27344. }
  27345. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  27346. self.off(eventName, wrapped);
  27347. }
  27348. this.on.call(this, eventName, wrapped, ctx);
  27349. };
  27350. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  27351. function disposedWarning(id) {
  27352. if ("development" !== 'production') {
  27353. warn('Instance ' + id + ' has been disposed');
  27354. }
  27355. }
  27356. var actions = {};
  27357. /**
  27358. * Map eventType to actionType
  27359. */
  27360. var eventActionMap = {};
  27361. var dataProcessorFuncs = [];
  27362. var optionPreprocessorFuncs = [];
  27363. var visualFuncs = [];
  27364. var themeStorage = {};
  27365. var loadingEffects = {};
  27366. var instances$1 = {};
  27367. var connectedGroups = {};
  27368. var idBase = +new Date() - 0;
  27369. var groupIdBase = +new Date() - 0;
  27370. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  27371. /**
  27372. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  27373. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  27374. * @param opts.width Use clientWidth of the input `dom` by default.
  27375. * Can be 'auto' (the same as null/undefined)
  27376. * @param opts.height Use clientHeight of the input `dom` by default.
  27377. * Can be 'auto' (the same as null/undefined)
  27378. * @param opts.locale Specify the locale.
  27379. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  27380. */
  27381. function init$1(dom, theme, opts) {
  27382. var isClient = !(opts && opts.ssr);
  27383. if (isClient) {
  27384. if ("development" !== 'production') {
  27385. if (!dom) {
  27386. throw new Error('Initialize failed: invalid dom.');
  27387. }
  27388. }
  27389. var existInstance = getInstanceByDom(dom);
  27390. if (existInstance) {
  27391. if ("development" !== 'production') {
  27392. warn('There is a chart instance already initialized on the dom.');
  27393. }
  27394. return existInstance;
  27395. }
  27396. if ("development" !== 'production') {
  27397. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  27398. warn('Can\'t get DOM width or height. Please check ' + 'dom.clientWidth and dom.clientHeight. They should not be 0.' + 'For example, you may need to call this in the callback ' + 'of window.onload.');
  27399. }
  27400. }
  27401. }
  27402. var chart = new ECharts(dom, theme, opts);
  27403. chart.id = 'ec_' + idBase++;
  27404. instances$1[chart.id] = chart;
  27405. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  27406. enableConnect(chart);
  27407. lifecycle.trigger('afterinit', chart);
  27408. return chart;
  27409. }
  27410. /**
  27411. * @usage
  27412. * (A)
  27413. * ```js
  27414. * let chart1 = echarts.init(dom1);
  27415. * let chart2 = echarts.init(dom2);
  27416. * chart1.group = 'xxx';
  27417. * chart2.group = 'xxx';
  27418. * echarts.connect('xxx');
  27419. * ```
  27420. * (B)
  27421. * ```js
  27422. * let chart1 = echarts.init(dom1);
  27423. * let chart2 = echarts.init(dom2);
  27424. * echarts.connect('xxx', [chart1, chart2]);
  27425. * ```
  27426. */
  27427. function connect(groupId) {
  27428. // Is array of charts
  27429. if (isArray(groupId)) {
  27430. var charts = groupId;
  27431. groupId = null; // If any chart has group
  27432. each(charts, function (chart) {
  27433. if (chart.group != null) {
  27434. groupId = chart.group;
  27435. }
  27436. });
  27437. groupId = groupId || 'g_' + groupIdBase++;
  27438. each(charts, function (chart) {
  27439. chart.group = groupId;
  27440. });
  27441. }
  27442. connectedGroups[groupId] = true;
  27443. return groupId;
  27444. }
  27445. /**
  27446. * @deprecated
  27447. */
  27448. function disConnect(groupId) {
  27449. connectedGroups[groupId] = false;
  27450. }
  27451. /**
  27452. * Alias and backward compatibility
  27453. */
  27454. var disconnect = disConnect;
  27455. /**
  27456. * Dispose a chart instance
  27457. */
  27458. function dispose$1(chart) {
  27459. if (isString(chart)) {
  27460. chart = instances$1[chart];
  27461. } else if (!(chart instanceof ECharts)) {
  27462. // Try to treat as dom
  27463. chart = getInstanceByDom(chart);
  27464. }
  27465. if (chart instanceof ECharts && !chart.isDisposed()) {
  27466. chart.dispose();
  27467. }
  27468. }
  27469. function getInstanceByDom(dom) {
  27470. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  27471. }
  27472. function getInstanceById(key) {
  27473. return instances$1[key];
  27474. }
  27475. /**
  27476. * Register theme
  27477. */
  27478. function registerTheme(name, theme) {
  27479. themeStorage[name] = theme;
  27480. }
  27481. /**
  27482. * Register option preprocessor
  27483. */
  27484. function registerPreprocessor(preprocessorFunc) {
  27485. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  27486. optionPreprocessorFuncs.push(preprocessorFunc);
  27487. }
  27488. }
  27489. function registerProcessor(priority, processor) {
  27490. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  27491. }
  27492. /**
  27493. * Register postIniter
  27494. * @param {Function} postInitFunc
  27495. */
  27496. function registerPostInit(postInitFunc) {
  27497. registerUpdateLifecycle('afterinit', postInitFunc);
  27498. }
  27499. /**
  27500. * Register postUpdater
  27501. * @param {Function} postUpdateFunc
  27502. */
  27503. function registerPostUpdate(postUpdateFunc) {
  27504. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  27505. }
  27506. function registerUpdateLifecycle(name, cb) {
  27507. lifecycle.on(name, cb);
  27508. }
  27509. function registerAction(actionInfo, eventName, action) {
  27510. if (isFunction(eventName)) {
  27511. action = eventName;
  27512. eventName = '';
  27513. }
  27514. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  27515. event: eventName
  27516. }][0]; // Event name is all lowercase
  27517. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  27518. eventName = actionInfo.event;
  27519. if (eventActionMap[eventName]) {
  27520. // Already registered.
  27521. return;
  27522. } // Validate action type and event name.
  27523. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  27524. if (!actions[actionType]) {
  27525. actions[actionType] = {
  27526. action: action,
  27527. actionInfo: actionInfo
  27528. };
  27529. }
  27530. eventActionMap[eventName] = actionType;
  27531. }
  27532. function registerCoordinateSystem(type, coordSysCreator) {
  27533. CoordinateSystemManager.register(type, coordSysCreator);
  27534. }
  27535. /**
  27536. * Get dimensions of specified coordinate system.
  27537. * @param {string} type
  27538. * @return {Array.<string|Object>}
  27539. */
  27540. function getCoordinateSystemDimensions(type) {
  27541. var coordSysCreator = CoordinateSystemManager.get(type);
  27542. if (coordSysCreator) {
  27543. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  27544. }
  27545. }
  27546. function registerLayout(priority, layoutTask) {
  27547. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  27548. }
  27549. function registerVisual(priority, visualTask) {
  27550. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  27551. }
  27552. var registeredTasks = [];
  27553. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  27554. if (isFunction(priority) || isObject(priority)) {
  27555. fn = priority;
  27556. priority = defaultPriority;
  27557. }
  27558. if ("development" !== 'production') {
  27559. if (isNaN(priority) || priority == null) {
  27560. throw new Error('Illegal priority');
  27561. } // Check duplicate
  27562. each(targetList, function (wrap) {
  27563. assert(wrap.__raw !== fn);
  27564. });
  27565. } // Already registered
  27566. if (indexOf(registeredTasks, fn) >= 0) {
  27567. return;
  27568. }
  27569. registeredTasks.push(fn);
  27570. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  27571. stageHandler.__prio = priority;
  27572. stageHandler.__raw = fn;
  27573. targetList.push(stageHandler);
  27574. }
  27575. function registerLoading(name, loadingFx) {
  27576. loadingEffects[name] = loadingFx;
  27577. }
  27578. /**
  27579. * ZRender need a canvas context to do measureText.
  27580. * But in node environment canvas may be created by node-canvas.
  27581. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  27582. *
  27583. *
  27584. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  27585. *
  27586. * @example
  27587. * let Canvas = require('canvas');
  27588. * let echarts = require('echarts');
  27589. * echarts.setCanvasCreator(function () {
  27590. * // Small size is enough.
  27591. * return new Canvas(32, 32);
  27592. * });
  27593. */
  27594. function setCanvasCreator(creator) {
  27595. if ("development" !== 'production') {
  27596. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  27597. }
  27598. setPlatformAPI({
  27599. createCanvas: creator
  27600. });
  27601. }
  27602. /**
  27603. * The parameters and usage: see `geoSourceManager.registerMap`.
  27604. * Compatible with previous `echarts.registerMap`.
  27605. */
  27606. function registerMap(mapName, geoJson, specialAreas) {
  27607. var registerMap = getImpl('registerMap');
  27608. registerMap && registerMap(mapName, geoJson, specialAreas);
  27609. }
  27610. function getMap(mapName) {
  27611. var getMap = getImpl('getMap');
  27612. return getMap && getMap(mapName);
  27613. }
  27614. var registerTransform = registerExternalTransform;
  27615. /**
  27616. * Globa dispatchAction to a specified chart instance.
  27617. */
  27618. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  27619. // if (!payload || !payload.chartId) {
  27620. // // Must have chartId to find chart
  27621. // return;
  27622. // }
  27623. // const chart = instances[payload.chartId];
  27624. // if (chart) {
  27625. // chart.dispatchAction(payload, opt);
  27626. // }
  27627. // }
  27628. // Builtin global visual
  27629. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  27630. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  27631. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  27632. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  27633. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  27634. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  27635. registerPreprocessor(globalBackwardCompat);
  27636. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  27637. registerLoading('default', defaultLoading); // Default actions
  27638. registerAction({
  27639. type: HIGHLIGHT_ACTION_TYPE,
  27640. event: HIGHLIGHT_ACTION_TYPE,
  27641. update: HIGHLIGHT_ACTION_TYPE
  27642. }, noop);
  27643. registerAction({
  27644. type: DOWNPLAY_ACTION_TYPE,
  27645. event: DOWNPLAY_ACTION_TYPE,
  27646. update: DOWNPLAY_ACTION_TYPE
  27647. }, noop);
  27648. registerAction({
  27649. type: SELECT_ACTION_TYPE,
  27650. event: SELECT_ACTION_TYPE,
  27651. update: SELECT_ACTION_TYPE
  27652. }, noop);
  27653. registerAction({
  27654. type: UNSELECT_ACTION_TYPE,
  27655. event: UNSELECT_ACTION_TYPE,
  27656. update: UNSELECT_ACTION_TYPE
  27657. }, noop);
  27658. registerAction({
  27659. type: TOGGLE_SELECT_ACTION_TYPE,
  27660. event: TOGGLE_SELECT_ACTION_TYPE,
  27661. update: TOGGLE_SELECT_ACTION_TYPE
  27662. }, noop); // Default theme
  27663. registerTheme('light', lightTheme);
  27664. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  27665. // be mounted on `echarts` is the extension `dataTool` is imported.
  27666. var dataTool = {};
  27667. var extensions = [];
  27668. var extensionRegisters = {
  27669. registerPreprocessor: registerPreprocessor,
  27670. registerProcessor: registerProcessor,
  27671. registerPostInit: registerPostInit,
  27672. registerPostUpdate: registerPostUpdate,
  27673. registerUpdateLifecycle: registerUpdateLifecycle,
  27674. registerAction: registerAction,
  27675. registerCoordinateSystem: registerCoordinateSystem,
  27676. registerLayout: registerLayout,
  27677. registerVisual: registerVisual,
  27678. registerTransform: registerTransform,
  27679. registerLoading: registerLoading,
  27680. registerMap: registerMap,
  27681. registerImpl: registerImpl,
  27682. PRIORITY: PRIORITY,
  27683. ComponentModel: ComponentModel,
  27684. ComponentView: ComponentView,
  27685. SeriesModel: SeriesModel,
  27686. ChartView: ChartView,
  27687. // TODO Use ComponentModel and SeriesModel instead of Constructor
  27688. registerComponentModel: function (ComponentModelClass) {
  27689. ComponentModel.registerClass(ComponentModelClass);
  27690. },
  27691. registerComponentView: function (ComponentViewClass) {
  27692. ComponentView.registerClass(ComponentViewClass);
  27693. },
  27694. registerSeriesModel: function (SeriesModelClass) {
  27695. SeriesModel.registerClass(SeriesModelClass);
  27696. },
  27697. registerChartView: function (ChartViewClass) {
  27698. ChartView.registerClass(ChartViewClass);
  27699. },
  27700. registerSubTypeDefaulter: function (componentType, defaulter) {
  27701. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  27702. },
  27703. registerPainter: function (painterType, PainterCtor) {
  27704. registerPainter(painterType, PainterCtor);
  27705. }
  27706. };
  27707. function use(ext) {
  27708. if (isArray(ext)) {
  27709. // use([ChartLine, ChartBar]);
  27710. each(ext, function (singleExt) {
  27711. use(singleExt);
  27712. });
  27713. return;
  27714. }
  27715. if (indexOf(extensions, ext) >= 0) {
  27716. return;
  27717. }
  27718. extensions.push(ext);
  27719. if (isFunction(ext)) {
  27720. ext = {
  27721. install: ext
  27722. };
  27723. }
  27724. ext.install(extensionRegisters);
  27725. }
  27726. /*
  27727. * Licensed to the Apache Software Foundation (ASF) under one
  27728. * or more contributor license agreements. See the NOTICE file
  27729. * distributed with this work for additional information
  27730. * regarding copyright ownership. The ASF licenses this file
  27731. * to you under the Apache License, Version 2.0 (the
  27732. * "License"); you may not use this file except in compliance
  27733. * with the License. You may obtain a copy of the License at
  27734. *
  27735. * http://www.apache.org/licenses/LICENSE-2.0
  27736. *
  27737. * Unless required by applicable law or agreed to in writing,
  27738. * software distributed under the License is distributed on an
  27739. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27740. * KIND, either express or implied. See the License for the
  27741. * specific language governing permissions and limitations
  27742. * under the License.
  27743. */
  27744. /**
  27745. * AUTO-GENERATED FILE. DO NOT MODIFY.
  27746. */
  27747. /*
  27748. * Licensed to the Apache Software Foundation (ASF) under one
  27749. * or more contributor license agreements. See the NOTICE file
  27750. * distributed with this work for additional information
  27751. * regarding copyright ownership. The ASF licenses this file
  27752. * to you under the Apache License, Version 2.0 (the
  27753. * "License"); you may not use this file except in compliance
  27754. * with the License. You may obtain a copy of the License at
  27755. *
  27756. * http://www.apache.org/licenses/LICENSE-2.0
  27757. *
  27758. * Unless required by applicable law or agreed to in writing,
  27759. * software distributed under the License is distributed on an
  27760. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27761. * KIND, either express or implied. See the License for the
  27762. * specific language governing permissions and limitations
  27763. * under the License.
  27764. */
  27765. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  27766. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  27767. }
  27768. function defaultKeyGetter(item) {
  27769. return item;
  27770. }
  27771. var DataDiffer =
  27772. /** @class */
  27773. function () {
  27774. /**
  27775. * @param context Can be visited by this.context in callback.
  27776. */
  27777. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  27778. diffMode) {
  27779. this._old = oldArr;
  27780. this._new = newArr;
  27781. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  27782. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  27783. this.context = context;
  27784. this._diffModeMultiple = diffMode === 'multiple';
  27785. }
  27786. /**
  27787. * Callback function when add a data
  27788. */
  27789. DataDiffer.prototype.add = function (func) {
  27790. this._add = func;
  27791. return this;
  27792. };
  27793. /**
  27794. * Callback function when update a data
  27795. */
  27796. DataDiffer.prototype.update = function (func) {
  27797. this._update = func;
  27798. return this;
  27799. };
  27800. /**
  27801. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27802. */
  27803. DataDiffer.prototype.updateManyToOne = function (func) {
  27804. this._updateManyToOne = func;
  27805. return this;
  27806. };
  27807. /**
  27808. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27809. */
  27810. DataDiffer.prototype.updateOneToMany = function (func) {
  27811. this._updateOneToMany = func;
  27812. return this;
  27813. };
  27814. /**
  27815. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27816. */
  27817. DataDiffer.prototype.updateManyToMany = function (func) {
  27818. this._updateManyToMany = func;
  27819. return this;
  27820. };
  27821. /**
  27822. * Callback function when remove a data
  27823. */
  27824. DataDiffer.prototype.remove = function (func) {
  27825. this._remove = func;
  27826. return this;
  27827. };
  27828. DataDiffer.prototype.execute = function () {
  27829. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  27830. };
  27831. DataDiffer.prototype._executeOneToOne = function () {
  27832. var oldArr = this._old;
  27833. var newArr = this._new;
  27834. var newDataIndexMap = {};
  27835. var oldDataKeyArr = new Array(oldArr.length);
  27836. var newDataKeyArr = new Array(newArr.length);
  27837. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  27838. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27839. for (var i = 0; i < oldArr.length; i++) {
  27840. var oldKey = oldDataKeyArr[i];
  27841. var newIdxMapVal = newDataIndexMap[oldKey];
  27842. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  27843. if (newIdxMapValLen > 1) {
  27844. // Consider there is duplicate key (for example, use dataItem.name as key).
  27845. // We should make sure every item in newArr and oldArr can be visited.
  27846. var newIdx = newIdxMapVal.shift();
  27847. if (newIdxMapVal.length === 1) {
  27848. newDataIndexMap[oldKey] = newIdxMapVal[0];
  27849. }
  27850. this._update && this._update(newIdx, i);
  27851. } else if (newIdxMapValLen === 1) {
  27852. newDataIndexMap[oldKey] = null;
  27853. this._update && this._update(newIdxMapVal, i);
  27854. } else {
  27855. this._remove && this._remove(i);
  27856. }
  27857. }
  27858. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27859. };
  27860. /**
  27861. * For example, consider the case:
  27862. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  27863. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  27864. * Where:
  27865. * o0, o1, n0 has key 'a' (many to one)
  27866. * o5, n4, n5, n6 has key 'b' (one to many)
  27867. * o2, n1 has key 'c' (one to one)
  27868. * n2, n3 has key 'd' (add)
  27869. * o3, o4 has key 'e' (remove)
  27870. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  27871. * Then:
  27872. * (The order of the following directives are not ensured.)
  27873. * this._updateManyToOne(n0, [o0, o1]);
  27874. * this._updateOneToMany([n4, n5, n6], o5);
  27875. * this._update(n1, o2);
  27876. * this._remove(o3);
  27877. * this._remove(o4);
  27878. * this._remove(o6);
  27879. * this._remove(o7);
  27880. * this._add(n2);
  27881. * this._add(n3);
  27882. * this._add(n7);
  27883. * this._add(n8);
  27884. */
  27885. DataDiffer.prototype._executeMultiple = function () {
  27886. var oldArr = this._old;
  27887. var newArr = this._new;
  27888. var oldDataIndexMap = {};
  27889. var newDataIndexMap = {};
  27890. var oldDataKeyArr = [];
  27891. var newDataKeyArr = [];
  27892. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  27893. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27894. for (var i = 0; i < oldDataKeyArr.length; i++) {
  27895. var oldKey = oldDataKeyArr[i];
  27896. var oldIdxMapVal = oldDataIndexMap[oldKey];
  27897. var newIdxMapVal = newDataIndexMap[oldKey];
  27898. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  27899. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27900. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  27901. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  27902. newDataIndexMap[oldKey] = null;
  27903. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  27904. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  27905. newDataIndexMap[oldKey] = null;
  27906. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  27907. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  27908. newDataIndexMap[oldKey] = null;
  27909. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  27910. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  27911. newDataIndexMap[oldKey] = null;
  27912. } else if (oldIdxMapValLen > 1) {
  27913. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  27914. this._remove && this._remove(oldIdxMapVal[i_1]);
  27915. }
  27916. } else {
  27917. this._remove && this._remove(oldIdxMapVal);
  27918. }
  27919. }
  27920. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27921. };
  27922. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  27923. for (var i = 0; i < newDataKeyArr.length; i++) {
  27924. var newKey = newDataKeyArr[i];
  27925. var newIdxMapVal = newDataIndexMap[newKey];
  27926. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27927. if (idxMapValLen > 1) {
  27928. for (var j = 0; j < idxMapValLen; j++) {
  27929. this._add && this._add(newIdxMapVal[j]);
  27930. }
  27931. } else if (idxMapValLen === 1) {
  27932. this._add && this._add(newIdxMapVal);
  27933. } // Support both `newDataKeyArr` are duplication removed or not removed.
  27934. newDataIndexMap[newKey] = null;
  27935. }
  27936. };
  27937. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  27938. map, // In 'byKey', the output `keyArr` is duplication removed.
  27939. // In 'byIndex', the output `keyArr` is not duplication removed and
  27940. // its indices are accurately corresponding to `arr`.
  27941. keyArr, keyGetterName) {
  27942. var cbModeMultiple = this._diffModeMultiple;
  27943. for (var i = 0; i < arr.length; i++) {
  27944. // Add prefix to avoid conflict with Object.prototype.
  27945. var key = '_ec_' + this[keyGetterName](arr[i], i);
  27946. if (!cbModeMultiple) {
  27947. keyArr[i] = key;
  27948. }
  27949. if (!map) {
  27950. continue;
  27951. }
  27952. var idxMapVal = map[key];
  27953. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  27954. if (idxMapValLen === 0) {
  27955. // Simple optimize: in most cases, one index has one key,
  27956. // do not need array.
  27957. map[key] = i;
  27958. if (cbModeMultiple) {
  27959. keyArr.push(key);
  27960. }
  27961. } else if (idxMapValLen === 1) {
  27962. map[key] = [idxMapVal, i];
  27963. } else {
  27964. idxMapVal.push(i);
  27965. }
  27966. }
  27967. };
  27968. return DataDiffer;
  27969. }();
  27970. var DimensionUserOuput =
  27971. /** @class */
  27972. function () {
  27973. function DimensionUserOuput(encode, dimRequest) {
  27974. this._encode = encode;
  27975. this._schema = dimRequest;
  27976. }
  27977. DimensionUserOuput.prototype.get = function () {
  27978. return {
  27979. // Do not generate full dimension name until fist used.
  27980. fullDimensions: this._getFullDimensionNames(),
  27981. encode: this._encode
  27982. };
  27983. };
  27984. /**
  27985. * Get all data store dimension names.
  27986. * Theoretically a series data store is defined both by series and used dataset (if any).
  27987. * If some dimensions are omitted for performance reason in `this.dimensions`,
  27988. * the dimension name may not be auto-generated if user does not specify a dimension name.
  27989. * In this case, the dimension name is `null`/`undefined`.
  27990. */
  27991. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  27992. if (!this._cachedDimNames) {
  27993. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  27994. }
  27995. return this._cachedDimNames;
  27996. };
  27997. return DimensionUserOuput;
  27998. }();
  27999. function summarizeDimensions(data, schema) {
  28000. var summary = {};
  28001. var encode = summary.encode = {};
  28002. var notExtraCoordDimMap = createHashMap();
  28003. var defaultedLabel = [];
  28004. var defaultedTooltip = [];
  28005. var userOutputEncode = {};
  28006. each(data.dimensions, function (dimName) {
  28007. var dimItem = data.getDimensionInfo(dimName);
  28008. var coordDim = dimItem.coordDim;
  28009. if (coordDim) {
  28010. if ("development" !== 'production') {
  28011. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  28012. }
  28013. var coordDimIndex = dimItem.coordDimIndex;
  28014. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  28015. if (!dimItem.isExtraCoord) {
  28016. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  28017. // because when dataset is used, it is hard to guess which dimension
  28018. // can be value dimension. If both show x, y on label is not look good,
  28019. // and conventionally y axis is focused more.
  28020. if (mayLabelDimType(dimItem.type)) {
  28021. defaultedLabel[0] = dimName;
  28022. } // User output encode do not contain generated coords.
  28023. // And it only has index. User can use index to retrieve value from the raw item array.
  28024. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  28025. }
  28026. if (dimItem.defaultTooltip) {
  28027. defaultedTooltip.push(dimName);
  28028. }
  28029. }
  28030. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  28031. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  28032. var dimIndex = dimItem.otherDims[otherDim];
  28033. if (dimIndex != null && dimIndex !== false) {
  28034. encodeArr[dimIndex] = dimItem.name;
  28035. }
  28036. });
  28037. });
  28038. var dataDimsOnCoord = [];
  28039. var encodeFirstDimNotExtra = {};
  28040. notExtraCoordDimMap.each(function (v, coordDim) {
  28041. var dimArr = encode[coordDim];
  28042. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  28043. // dim canot on more than one coordDim.
  28044. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  28045. });
  28046. summary.dataDimsOnCoord = dataDimsOnCoord;
  28047. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  28048. return data.getDimensionInfo(dimName).storeDimIndex;
  28049. });
  28050. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  28051. var encodeLabel = encode.label; // FIXME `encode.label` is not recommended, because formatter cannot be set
  28052. // in this way. Use label.formatter instead. Maybe remove this approach someday.
  28053. if (encodeLabel && encodeLabel.length) {
  28054. defaultedLabel = encodeLabel.slice();
  28055. }
  28056. var encodeTooltip = encode.tooltip;
  28057. if (encodeTooltip && encodeTooltip.length) {
  28058. defaultedTooltip = encodeTooltip.slice();
  28059. } else if (!defaultedTooltip.length) {
  28060. defaultedTooltip = defaultedLabel.slice();
  28061. }
  28062. encode.defaultedLabel = defaultedLabel;
  28063. encode.defaultedTooltip = defaultedTooltip;
  28064. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  28065. return summary;
  28066. }
  28067. function getOrCreateEncodeArr(encode, dim) {
  28068. if (!encode.hasOwnProperty(dim)) {
  28069. encode[dim] = [];
  28070. }
  28071. return encode[dim];
  28072. } // FIXME:TS should be type `AxisType`
  28073. function getDimensionTypeByAxis(axisType) {
  28074. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  28075. }
  28076. function mayLabelDimType(dimType) {
  28077. // In most cases, ordinal and time do not suitable for label.
  28078. // Ordinal info can be displayed on axis. Time is too long.
  28079. return !(dimType === 'ordinal' || dimType === 'time');
  28080. } // function findTheLastDimMayLabel(data) {
  28081. // // Get last value dim
  28082. // let dimensions = data.dimensions.slice();
  28083. // let valueType;
  28084. // let valueDim;
  28085. // while (dimensions.length && (
  28086. // valueDim = dimensions.pop(),
  28087. // valueType = data.getDimensionInfo(valueDim).type,
  28088. // valueType === 'ordinal' || valueType === 'time'
  28089. // )) {} // jshint ignore:line
  28090. // return valueDim;
  28091. // }
  28092. var SeriesDimensionDefine =
  28093. /** @class */
  28094. function () {
  28095. /**
  28096. * @param opt All of the fields will be shallow copied.
  28097. */
  28098. function SeriesDimensionDefine(opt) {
  28099. /**
  28100. * The format of `otherDims` is:
  28101. * ```js
  28102. * {
  28103. * tooltip?: number
  28104. * label?: number
  28105. * itemName?: number
  28106. * seriesName?: number
  28107. * }
  28108. * ```
  28109. *
  28110. * A `series.encode` can specified these fields:
  28111. * ```js
  28112. * encode: {
  28113. * // "3, 1, 5" is the index of data dimension.
  28114. * tooltip: [3, 1, 5],
  28115. * label: [0, 3],
  28116. * ...
  28117. * }
  28118. * ```
  28119. * `otherDims` is the parse result of the `series.encode` above, like:
  28120. * ```js
  28121. * // Suppose the index of this data dimension is `3`.
  28122. * this.otherDims = {
  28123. * // `3` is at the index `0` of the `encode.tooltip`
  28124. * tooltip: 0,
  28125. * // `3` is at the index `1` of the `encode.label`
  28126. * label: 1
  28127. * };
  28128. * ```
  28129. *
  28130. * This prop should never be `null`/`undefined` after initialized.
  28131. */
  28132. this.otherDims = {};
  28133. if (opt != null) {
  28134. extend(this, opt);
  28135. }
  28136. }
  28137. return SeriesDimensionDefine;
  28138. }();
  28139. var inner$4 = makeInner();
  28140. var dimTypeShort = {
  28141. float: 'f',
  28142. int: 'i',
  28143. ordinal: 'o',
  28144. number: 'n',
  28145. time: 't'
  28146. };
  28147. /**
  28148. * Represents the dimension requirement of a series.
  28149. *
  28150. * NOTICE:
  28151. * When there are too many dimensions in dataset and many series, only the used dimensions
  28152. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  28153. * But users may query data by other unused dimension names.
  28154. * In this case, users can only query data if and only if they have defined dimension names
  28155. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  28156. * `source` dimensions.
  28157. */
  28158. var SeriesDataSchema =
  28159. /** @class */
  28160. function () {
  28161. function SeriesDataSchema(opt) {
  28162. this.dimensions = opt.dimensions;
  28163. this._dimOmitted = opt.dimensionOmitted;
  28164. this.source = opt.source;
  28165. this._fullDimCount = opt.fullDimensionCount;
  28166. this._updateDimOmitted(opt.dimensionOmitted);
  28167. }
  28168. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  28169. return this._dimOmitted;
  28170. };
  28171. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  28172. this._dimOmitted = dimensionOmitted;
  28173. if (!dimensionOmitted) {
  28174. return;
  28175. }
  28176. if (!this._dimNameMap) {
  28177. this._dimNameMap = ensureSourceDimNameMap(this.source);
  28178. }
  28179. };
  28180. /**
  28181. * @caution Can only be used when `dimensionOmitted: true`.
  28182. *
  28183. * Get index by user defined dimension name (i.e., not internal generate name).
  28184. * That is, get index from `dimensionsDefine`.
  28185. * If no `dimensionsDefine`, or no name get, return -1.
  28186. */
  28187. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  28188. return retrieve2(this._dimNameMap.get(dimName), -1);
  28189. };
  28190. /**
  28191. * @caution Can only be used when `dimensionOmitted: true`.
  28192. *
  28193. * Notice: may return `null`/`undefined` if user not specify dimension names.
  28194. */
  28195. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  28196. var dimensionsDefine = this.source.dimensionsDefine;
  28197. if (dimensionsDefine) {
  28198. return dimensionsDefine[dimIndex];
  28199. }
  28200. };
  28201. SeriesDataSchema.prototype.makeStoreSchema = function () {
  28202. var dimCount = this._fullDimCount;
  28203. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  28204. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount); // If source don't have dimensions or series don't omit unsed dimensions.
  28205. // Generate from seriesDimList directly
  28206. var dimHash = '';
  28207. var dims = [];
  28208. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  28209. var property = void 0;
  28210. var type = void 0;
  28211. var ordinalMeta = void 0;
  28212. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  28213. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28214. property = willRetrieveDataByName ? seriesDimDef.name : null;
  28215. type = seriesDimDef.type;
  28216. ordinalMeta = seriesDimDef.ordinalMeta;
  28217. seriesDimIdx++;
  28218. } else {
  28219. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28220. if (sourceDimDef) {
  28221. property = willRetrieveDataByName ? sourceDimDef.name : null;
  28222. type = sourceDimDef.type;
  28223. }
  28224. }
  28225. dims.push({
  28226. property: property,
  28227. type: type,
  28228. ordinalMeta: ordinalMeta
  28229. }); // If retrieving data by index,
  28230. // use <index, type, ordinalMeta> to determine whether data can be shared.
  28231. // (Because in this case there might be no dimension name defined in dataset, but indices always exists).
  28232. // (Indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  28233. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  28234. // use <property, type, ordinalMeta> in hash.
  28235. if (willRetrieveDataByName && property != null // For data stack, we have make sure each series has its own dim on this store.
  28236. // So we do not add property to hash to make sure they can share this store.
  28237. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  28238. dimHash += makeHashStrict // Use escape character '`' in case that property name contains '$'.
  28239. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2') // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  28240. : property;
  28241. }
  28242. dimHash += '$';
  28243. dimHash += dimTypeShort[type] || 'f';
  28244. if (ordinalMeta) {
  28245. dimHash += ordinalMeta.uid;
  28246. }
  28247. dimHash += '$';
  28248. } // Source from endpoint(usually series) will be read differently
  28249. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  28250. // So we use this three props as key.
  28251. var source = this.source;
  28252. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  28253. return {
  28254. dimensions: dims,
  28255. hash: hash
  28256. };
  28257. };
  28258. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  28259. var result = [];
  28260. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  28261. var name_1 = void 0;
  28262. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  28263. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28264. if (!seriesDimDef.isCalculationCoord) {
  28265. name_1 = seriesDimDef.name;
  28266. }
  28267. seriesDimIdx++;
  28268. } else {
  28269. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28270. if (sourceDimDef) {
  28271. name_1 = sourceDimDef.name;
  28272. }
  28273. }
  28274. result.push(name_1);
  28275. }
  28276. return result;
  28277. };
  28278. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  28279. this.dimensions.push(dimDef);
  28280. dimDef.isCalculationCoord = true;
  28281. this._fullDimCount++; // If append dimension on a data store, consider the store
  28282. // might be shared by different series, series dimensions not
  28283. // really map to store dimensions.
  28284. this._updateDimOmitted(true);
  28285. };
  28286. return SeriesDataSchema;
  28287. }();
  28288. function isSeriesDataSchema(schema) {
  28289. return schema instanceof SeriesDataSchema;
  28290. }
  28291. function createDimNameMap(dimsDef) {
  28292. var dataDimNameMap = createHashMap();
  28293. for (var i = 0; i < (dimsDef || []).length; i++) {
  28294. var dimDefItemRaw = dimsDef[i];
  28295. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  28296. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28297. dataDimNameMap.set(userDimName, i);
  28298. }
  28299. }
  28300. return dataDimNameMap;
  28301. }
  28302. function ensureSourceDimNameMap(source) {
  28303. var innerSource = inner$4(source);
  28304. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  28305. }
  28306. function shouldOmitUnusedDimensions(dimCount) {
  28307. return dimCount > 30;
  28308. }
  28309. var isObject$2 = isObject;
  28310. var map$1 = map;
  28311. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array; // Use prefix to avoid index to be the same as otherIdList[idx],
  28312. // which will cause weird update animation.
  28313. var ID_PREFIX = 'e\0\0';
  28314. var INDEX_NOT_FOUND = -1; // type SeriesDimensionIndex = DimensionIndex;
  28315. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  28316. var CLONE_PROPERTIES = ['_approximateExtent']; // -----------------------------
  28317. // Internal method declarations:
  28318. // -----------------------------
  28319. var prepareInvertedIndex;
  28320. var getId;
  28321. var getIdNameFromStore;
  28322. var normalizeDimensions;
  28323. var transferProperties;
  28324. var cloneListForMapAndSample;
  28325. var makeIdFromName;
  28326. var SeriesData =
  28327. /** @class */
  28328. function () {
  28329. /**
  28330. * @param dimensionsInput.dimensions
  28331. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  28332. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  28333. */
  28334. function SeriesData(dimensionsInput, hostModel) {
  28335. this.type = 'list';
  28336. this._dimOmitted = false;
  28337. this._nameList = [];
  28338. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  28339. // Never used yet (not used yet).
  28340. // private _optionModels: Model[] = [];
  28341. // Global visual properties after visual coding
  28342. this._visual = {}; // Global layout properties.
  28343. this._layout = {}; // Item visual properties after visual coding
  28344. this._itemVisuals = []; // Item layout properties after layout
  28345. this._itemLayouts = []; // Graphic elements
  28346. this._graphicEls = []; // key: dim, value: extent
  28347. this._approximateExtent = {};
  28348. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  28349. // (in type `OptionDataItemObject`).
  28350. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  28351. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  28352. this.hasItemOption = false; // Methods that create a new list based on this list should be listed here.
  28353. // Notice that those method should `RETURN` the new list.
  28354. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  28355. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28356. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  28357. var dimensions;
  28358. var assignStoreDimIdx = false;
  28359. if (isSeriesDataSchema(dimensionsInput)) {
  28360. dimensions = dimensionsInput.dimensions;
  28361. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  28362. this._schema = dimensionsInput;
  28363. } else {
  28364. assignStoreDimIdx = true;
  28365. dimensions = dimensionsInput;
  28366. }
  28367. dimensions = dimensions || ['x', 'y'];
  28368. var dimensionInfos = {};
  28369. var dimensionNames = [];
  28370. var invertedIndicesMap = {};
  28371. var needsHasOwn = false;
  28372. var emptyObj = {};
  28373. for (var i = 0; i < dimensions.length; i++) {
  28374. // Use the original dimensions[i], where other flag props may exists.
  28375. var dimInfoInput = dimensions[i];
  28376. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  28377. name: dimInfoInput
  28378. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  28379. var dimensionName = dimensionInfo.name;
  28380. dimensionInfo.type = dimensionInfo.type || 'float';
  28381. if (!dimensionInfo.coordDim) {
  28382. dimensionInfo.coordDim = dimensionName;
  28383. dimensionInfo.coordDimIndex = 0;
  28384. }
  28385. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  28386. dimensionNames.push(dimensionName);
  28387. dimensionInfos[dimensionName] = dimensionInfo;
  28388. if (emptyObj[dimensionName] != null) {
  28389. needsHasOwn = true;
  28390. }
  28391. if (dimensionInfo.createInvertedIndices) {
  28392. invertedIndicesMap[dimensionName] = [];
  28393. }
  28394. if (otherDims.itemName === 0) {
  28395. this._nameDimIdx = i;
  28396. }
  28397. if (otherDims.itemId === 0) {
  28398. this._idDimIdx = i;
  28399. }
  28400. if ("development" !== 'production') {
  28401. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  28402. }
  28403. if (assignStoreDimIdx) {
  28404. dimensionInfo.storeDimIndex = i;
  28405. }
  28406. }
  28407. this.dimensions = dimensionNames;
  28408. this._dimInfos = dimensionInfos;
  28409. this._initGetDimensionInfo(needsHasOwn);
  28410. this.hostModel = hostModel;
  28411. this._invertedIndicesMap = invertedIndicesMap;
  28412. if (this._dimOmitted) {
  28413. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  28414. each(dimensionNames, function (dimName) {
  28415. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  28416. });
  28417. }
  28418. }
  28419. /**
  28420. *
  28421. * Get concrete dimension name by dimension name or dimension index.
  28422. * If input a dimension name, do not validate whether the dimension name exits.
  28423. *
  28424. * @caution
  28425. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  28426. * Because only those dimensions will have auto-generated dimension names if not
  28427. * have a user-specified name, and other dimensions will get a return of null/undefined.
  28428. *
  28429. * @notice Because of this reason, should better use `getDimensionIndex` instead, for examples:
  28430. * ```js
  28431. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  28432. * ```
  28433. *
  28434. * @return Concrete dim name.
  28435. */
  28436. SeriesData.prototype.getDimension = function (dim) {
  28437. var dimIdx = this._recognizeDimIndex(dim);
  28438. if (dimIdx == null) {
  28439. return dim;
  28440. }
  28441. dimIdx = dim;
  28442. if (!this._dimOmitted) {
  28443. return this.dimensions[dimIdx];
  28444. } // Retrieve from series dimension definition because it probably contains
  28445. // generated dimension name (like 'x', 'y').
  28446. var dimName = this._dimIdxToName.get(dimIdx);
  28447. if (dimName != null) {
  28448. return dimName;
  28449. }
  28450. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  28451. if (sourceDimDef) {
  28452. return sourceDimDef.name;
  28453. }
  28454. };
  28455. /**
  28456. * Get dimension index in data store. Return -1 if not found.
  28457. * Can be used to index value from getRawValue.
  28458. */
  28459. SeriesData.prototype.getDimensionIndex = function (dim) {
  28460. var dimIdx = this._recognizeDimIndex(dim);
  28461. if (dimIdx != null) {
  28462. return dimIdx;
  28463. }
  28464. if (dim == null) {
  28465. return -1;
  28466. }
  28467. var dimInfo = this._getDimInfo(dim);
  28468. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  28469. };
  28470. /**
  28471. * The meanings of the input parameter `dim`:
  28472. *
  28473. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  28474. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  28475. * + If dim is a number-like string (e.g., `"1"`):
  28476. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  28477. * it means that concrete name.
  28478. * + If not, it will be converted to a number, which means the index of the dimension.
  28479. * (why? because of the backward compatibility. We have been tolerating number-like string in
  28480. * dimension setting, although now it seems that it is not a good idea.)
  28481. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  28482. * if no dimension name is defined as `"1"`.
  28483. * + If dim is a not-number-like string, it means the concrete dim name.
  28484. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  28485. * or customized in `dimensions` property of option like `"age"`.
  28486. *
  28487. * @return recognized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  28488. */
  28489. SeriesData.prototype._recognizeDimIndex = function (dim) {
  28490. if (isNumber(dim) // If being a number-like string but not being defined as a dimension name.
  28491. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  28492. return +dim;
  28493. }
  28494. };
  28495. SeriesData.prototype._getStoreDimIndex = function (dim) {
  28496. var dimIdx = this.getDimensionIndex(dim);
  28497. if ("development" !== 'production') {
  28498. if (dimIdx == null) {
  28499. throw new Error('Unknown dimension ' + dim);
  28500. }
  28501. }
  28502. return dimIdx;
  28503. };
  28504. /**
  28505. * Get type and calculation info of particular dimension
  28506. * @param dim
  28507. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  28508. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  28509. */
  28510. SeriesData.prototype.getDimensionInfo = function (dim) {
  28511. // Do not clone, because there may be categories in dimInfo.
  28512. return this._getDimInfo(this.getDimension(dim));
  28513. };
  28514. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  28515. var dimensionInfos = this._dimInfos;
  28516. this._getDimInfo = needsHasOwn ? function (dimName) {
  28517. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  28518. } : function (dimName) {
  28519. return dimensionInfos[dimName];
  28520. };
  28521. };
  28522. /**
  28523. * concrete dimension name list on coord.
  28524. */
  28525. SeriesData.prototype.getDimensionsOnCoord = function () {
  28526. return this._dimSummary.dataDimsOnCoord.slice();
  28527. };
  28528. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  28529. var dimensionsSummary = this._dimSummary;
  28530. if (idx == null) {
  28531. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  28532. }
  28533. var dims = dimensionsSummary.encode[coordDim];
  28534. return dims ? dims[idx] : null;
  28535. };
  28536. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  28537. var dimensionsSummary = this._dimSummary;
  28538. var dims = dimensionsSummary.encode[coordDim];
  28539. return (dims || []).slice();
  28540. };
  28541. SeriesData.prototype.getStore = function () {
  28542. return this._store;
  28543. };
  28544. /**
  28545. * Initialize from data
  28546. * @param data source or data or data store.
  28547. * @param nameList The name of a datum is used on data diff and
  28548. * default label/tooltip.
  28549. * A name can be specified in encode.itemName,
  28550. * or dataItem.name (only for series option data),
  28551. * or provided in nameList from outside.
  28552. */
  28553. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  28554. var _this = this;
  28555. var store;
  28556. if (data instanceof DataStore) {
  28557. store = data;
  28558. }
  28559. if (!store) {
  28560. var dimensions = this.dimensions;
  28561. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  28562. store = new DataStore();
  28563. var dimensionInfos = map$1(dimensions, function (dimName) {
  28564. return {
  28565. type: _this._dimInfos[dimName].type,
  28566. property: dimName
  28567. };
  28568. });
  28569. store.initData(provider, dimensionInfos, dimValueGetter);
  28570. }
  28571. this._store = store; // Reset
  28572. this._nameList = (nameList || []).slice();
  28573. this._idList = [];
  28574. this._nameRepeatCount = {};
  28575. this._doInit(0, store.count()); // Cache summary info for fast visit. See "dimensionHelper".
  28576. // Needs to be initialized after store is prepared.
  28577. this._dimSummary = summarizeDimensions(this, this._schema);
  28578. this.userOutput = this._dimSummary.userOutput;
  28579. };
  28580. /**
  28581. * Caution: Can be only called on raw data (before `this._indices` created).
  28582. */
  28583. SeriesData.prototype.appendData = function (data) {
  28584. var range = this._store.appendData(data);
  28585. this._doInit(range[0], range[1]);
  28586. };
  28587. /**
  28588. * Caution: Can be only called on raw data (before `this._indices` created).
  28589. * This method does not modify `rawData` (`dataProvider`), but only
  28590. * add values to store.
  28591. *
  28592. * The final count will be increased by `Math.max(values.length, names.length)`.
  28593. *
  28594. * @param values That is the SourceType: 'arrayRows', like
  28595. * [
  28596. * [12, 33, 44],
  28597. * [NaN, 43, 1],
  28598. * ['-', 'asdf', 0]
  28599. * ]
  28600. * Each item is exactly corresponding to a dimension.
  28601. */
  28602. SeriesData.prototype.appendValues = function (values, names) {
  28603. var _a = this._store.appendValues(values, names.length),
  28604. start = _a.start,
  28605. end = _a.end;
  28606. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  28607. this._updateOrdinalMeta();
  28608. if (names) {
  28609. for (var idx = start; idx < end; idx++) {
  28610. var sourceIdx = idx - start;
  28611. this._nameList[idx] = names[sourceIdx];
  28612. if (shouldMakeIdFromName) {
  28613. makeIdFromName(this, idx);
  28614. }
  28615. }
  28616. }
  28617. };
  28618. SeriesData.prototype._updateOrdinalMeta = function () {
  28619. var store = this._store;
  28620. var dimensions = this.dimensions;
  28621. for (var i = 0; i < dimensions.length; i++) {
  28622. var dimInfo = this._dimInfos[dimensions[i]];
  28623. if (dimInfo.ordinalMeta) {
  28624. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  28625. }
  28626. }
  28627. };
  28628. SeriesData.prototype._shouldMakeIdFromName = function () {
  28629. var provider = this._store.getProvider();
  28630. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  28631. };
  28632. SeriesData.prototype._doInit = function (start, end) {
  28633. if (start >= end) {
  28634. return;
  28635. }
  28636. var store = this._store;
  28637. var provider = store.getProvider();
  28638. this._updateOrdinalMeta();
  28639. var nameList = this._nameList;
  28640. var idList = this._idList;
  28641. var sourceFormat = provider.getSource().sourceFormat;
  28642. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL; // Each data item is value
  28643. // [1, 2]
  28644. // 2
  28645. // Bar chart, line chart which uses category axis
  28646. // only gives the 'y' value. 'x' value is the indices of category
  28647. // Use a tempValue to normalize the value to be a (x, y) value
  28648. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  28649. // This kind of ids and names are always stored `_nameList` and `_idList`.
  28650. if (isFormatOriginal && !provider.pure) {
  28651. var sharedDataItem = [];
  28652. for (var idx = start; idx < end; idx++) {
  28653. // NOTICE: Try not to write things into dataItem
  28654. var dataItem = provider.getItem(idx, sharedDataItem);
  28655. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  28656. this.hasItemOption = true;
  28657. }
  28658. if (dataItem) {
  28659. var itemName = dataItem.name;
  28660. if (nameList[idx] == null && itemName != null) {
  28661. nameList[idx] = convertOptionIdName(itemName, null);
  28662. }
  28663. var itemId = dataItem.id;
  28664. if (idList[idx] == null && itemId != null) {
  28665. idList[idx] = convertOptionIdName(itemId, null);
  28666. }
  28667. }
  28668. }
  28669. }
  28670. if (this._shouldMakeIdFromName()) {
  28671. for (var idx = start; idx < end; idx++) {
  28672. makeIdFromName(this, idx);
  28673. }
  28674. }
  28675. prepareInvertedIndex(this);
  28676. };
  28677. /**
  28678. * PENDING: In fact currently this function is only used to short-circuit
  28679. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  28680. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  28681. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  28682. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  28683. * But if we add "custom data filter" in future, which is not "axis related", this method may
  28684. * be still needed.
  28685. *
  28686. * Optimize for the scenario that data is filtered by a given extent.
  28687. * Consider that if data amount is more than hundreds of thousand,
  28688. * extent calculation will cost more than 10ms and the cache will
  28689. * be erased because of the filtering.
  28690. */
  28691. SeriesData.prototype.getApproximateExtent = function (dim) {
  28692. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  28693. };
  28694. /**
  28695. * Calculate extent on a filtered data might be time consuming.
  28696. * Approximate extent is only used for: calculate extent of filtered data outside.
  28697. */
  28698. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  28699. dim = this.getDimension(dim);
  28700. this._approximateExtent[dim] = extent.slice();
  28701. };
  28702. SeriesData.prototype.getCalculationInfo = function (key) {
  28703. return this._calculationInfo[key];
  28704. };
  28705. SeriesData.prototype.setCalculationInfo = function (key, value) {
  28706. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  28707. };
  28708. /**
  28709. * @return Never be null/undefined. `number` will be converted to string. Because:
  28710. * In most cases, name is used in display, where returning a string is more convenient.
  28711. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  28712. * rule that name `2` equals to name `'2'`.
  28713. */
  28714. SeriesData.prototype.getName = function (idx) {
  28715. var rawIndex = this.getRawIndex(idx);
  28716. var name = this._nameList[rawIndex];
  28717. if (name == null && this._nameDimIdx != null) {
  28718. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  28719. }
  28720. if (name == null) {
  28721. name = '';
  28722. }
  28723. return name;
  28724. };
  28725. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  28726. var ordinal = this._store.get(dimIdx, idx);
  28727. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  28728. if (ordinalMeta) {
  28729. return ordinalMeta.categories[ordinal];
  28730. }
  28731. return ordinal;
  28732. };
  28733. /**
  28734. * @return Never null/undefined. `number` will be converted to string. Because:
  28735. * In all cases having encountered at present, id is used in making diff comparison, which
  28736. * are usually based on hash map. We can keep the rule that the internal id are always string
  28737. * (treat `2` is the same as `'2'`) to make the related logic simple.
  28738. */
  28739. SeriesData.prototype.getId = function (idx) {
  28740. return getId(this, this.getRawIndex(idx));
  28741. };
  28742. SeriesData.prototype.count = function () {
  28743. return this._store.count();
  28744. };
  28745. /**
  28746. * Get value. Return NaN if idx is out of range.
  28747. *
  28748. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  28749. */
  28750. SeriesData.prototype.get = function (dim, idx) {
  28751. var store = this._store;
  28752. var dimInfo = this._dimInfos[dim];
  28753. if (dimInfo) {
  28754. return store.get(dimInfo.storeDimIndex, idx);
  28755. }
  28756. };
  28757. /**
  28758. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  28759. */
  28760. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  28761. var store = this._store;
  28762. var dimInfo = this._dimInfos[dim];
  28763. if (dimInfo) {
  28764. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  28765. }
  28766. };
  28767. SeriesData.prototype.getIndices = function () {
  28768. return this._store.getIndices();
  28769. };
  28770. SeriesData.prototype.getDataExtent = function (dim) {
  28771. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  28772. };
  28773. SeriesData.prototype.getSum = function (dim) {
  28774. return this._store.getSum(this._getStoreDimIndex(dim));
  28775. };
  28776. SeriesData.prototype.getMedian = function (dim) {
  28777. return this._store.getMedian(this._getStoreDimIndex(dim));
  28778. };
  28779. SeriesData.prototype.getValues = function (dimensions, idx) {
  28780. var _this = this;
  28781. var store = this._store;
  28782. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  28783. return _this._getStoreDimIndex(dim);
  28784. }), idx) : store.getValues(dimensions);
  28785. };
  28786. /**
  28787. * If value is NaN. Including '-'
  28788. * Only check the coord dimensions.
  28789. */
  28790. SeriesData.prototype.hasValue = function (idx) {
  28791. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  28792. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  28793. // Ordinal type originally can be string or number.
  28794. // But when an ordinal type is used on coord, it can
  28795. // not be string but only number. So we can also use isNaN.
  28796. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  28797. return false;
  28798. }
  28799. }
  28800. return true;
  28801. };
  28802. /**
  28803. * Retrieve the index with given name
  28804. */
  28805. SeriesData.prototype.indexOfName = function (name) {
  28806. for (var i = 0, len = this._store.count(); i < len; i++) {
  28807. if (this.getName(i) === name) {
  28808. return i;
  28809. }
  28810. }
  28811. return -1;
  28812. };
  28813. SeriesData.prototype.getRawIndex = function (idx) {
  28814. return this._store.getRawIndex(idx);
  28815. };
  28816. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  28817. return this._store.indexOfRawIndex(rawIndex);
  28818. };
  28819. /**
  28820. * Only support the dimension which inverted index created.
  28821. * Do not support other cases until required.
  28822. * @param dim concrete dim
  28823. * @param value ordinal index
  28824. * @return rawIndex
  28825. */
  28826. SeriesData.prototype.rawIndexOf = function (dim, value) {
  28827. var invertedIndices = dim && this._invertedIndicesMap[dim];
  28828. if ("development" !== 'production') {
  28829. if (!invertedIndices) {
  28830. throw new Error('Do not supported yet');
  28831. }
  28832. }
  28833. var rawIndex = invertedIndices[value];
  28834. if (rawIndex == null || isNaN(rawIndex)) {
  28835. return INDEX_NOT_FOUND;
  28836. }
  28837. return rawIndex;
  28838. };
  28839. /**
  28840. * Retrieve the index of nearest value
  28841. * @param dim
  28842. * @param value
  28843. * @param [maxDistance=Infinity]
  28844. * @return If and only if multiple indices has
  28845. * the same value, they are put to the result.
  28846. */
  28847. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  28848. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  28849. };
  28850. SeriesData.prototype.each = function (dims, cb, ctx) {
  28851. if (isFunction(dims)) {
  28852. ctx = cb;
  28853. cb = dims;
  28854. dims = [];
  28855. } // ctxCompat just for compat echarts3
  28856. var fCtx = ctx || this;
  28857. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28858. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28859. };
  28860. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  28861. if (isFunction(dims)) {
  28862. ctx = cb;
  28863. cb = dims;
  28864. dims = [];
  28865. } // ctxCompat just for compat echarts3
  28866. var fCtx = ctx || this;
  28867. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28868. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28869. return this;
  28870. };
  28871. /**
  28872. * Select data in range. (For optimization of filter)
  28873. * (Manually inline code, support 5 million data filtering in data zoom.)
  28874. */
  28875. SeriesData.prototype.selectRange = function (range) {
  28876. var _this = this;
  28877. var innerRange = {};
  28878. var dims = keys(range);
  28879. each(dims, function (dim) {
  28880. var dimIdx = _this._getStoreDimIndex(dim);
  28881. innerRange[dimIdx] = range[dim];
  28882. });
  28883. this._store = this._store.selectRange(innerRange);
  28884. return this;
  28885. };
  28886. /* eslint-enable max-len */
  28887. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  28888. if (isFunction(dims)) {
  28889. ctx = cb;
  28890. cb = dims;
  28891. dims = [];
  28892. } // ctxCompat just for compat echarts3
  28893. ctx = ctx || this;
  28894. var result = [];
  28895. this.each(dims, function () {
  28896. result.push(cb && cb.apply(this, arguments));
  28897. }, ctx);
  28898. return result;
  28899. };
  28900. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  28901. var fCtx = ctx || ctxCompat || this;
  28902. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28903. var list = cloneListForMapAndSample(this);
  28904. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28905. return list;
  28906. };
  28907. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  28908. var _this = this; // ctxCompat just for compat echarts3
  28909. var fCtx = ctx || ctxCompat || this;
  28910. if ("development" !== 'production') {
  28911. each(normalizeDimensions(dims), function (dim) {
  28912. var dimInfo = _this.getDimensionInfo(dim);
  28913. if (!dimInfo.isCalculationCoord) {
  28914. console.error('Danger: only stack dimension can be modified');
  28915. }
  28916. });
  28917. }
  28918. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this); // If do shallow clone here, if there are too many stacked series,
  28919. // it still cost lots of memory, because `_store.dimensions` are not shared.
  28920. // We should consider there probably be shallow clone happen in each series
  28921. // in consequent filter/map.
  28922. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28923. };
  28924. /**
  28925. * Large data down sampling on given dimension
  28926. * @param sampleIndex Sample index for name and id
  28927. */
  28928. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28929. var list = cloneListForMapAndSample(this);
  28930. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  28931. return list;
  28932. };
  28933. /**
  28934. * Large data down sampling using largest-triangle-three-buckets
  28935. * @param {string} valueDimension
  28936. * @param {number} targetCount
  28937. */
  28938. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  28939. var list = cloneListForMapAndSample(this);
  28940. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  28941. return list;
  28942. };
  28943. SeriesData.prototype.getRawDataItem = function (idx) {
  28944. return this._store.getRawDataItem(idx);
  28945. };
  28946. /**
  28947. * Get model of one data item.
  28948. */
  28949. // TODO: Type of data item
  28950. SeriesData.prototype.getItemModel = function (idx) {
  28951. var hostModel = this.hostModel;
  28952. var dataItem = this.getRawDataItem(idx);
  28953. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  28954. };
  28955. /**
  28956. * Create a data differ
  28957. */
  28958. SeriesData.prototype.diff = function (otherList) {
  28959. var thisList = this;
  28960. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  28961. return getId(otherList, idx);
  28962. }, function (idx) {
  28963. return getId(thisList, idx);
  28964. });
  28965. };
  28966. /**
  28967. * Get visual property.
  28968. */
  28969. SeriesData.prototype.getVisual = function (key) {
  28970. var visual = this._visual;
  28971. return visual && visual[key];
  28972. };
  28973. SeriesData.prototype.setVisual = function (kvObj, val) {
  28974. this._visual = this._visual || {};
  28975. if (isObject$2(kvObj)) {
  28976. extend(this._visual, kvObj);
  28977. } else {
  28978. this._visual[kvObj] = val;
  28979. }
  28980. };
  28981. /**
  28982. * Get visual property of single data item
  28983. */
  28984. // eslint-disable-next-line
  28985. SeriesData.prototype.getItemVisual = function (idx, key) {
  28986. var itemVisual = this._itemVisuals[idx];
  28987. var val = itemVisual && itemVisual[key];
  28988. if (val == null) {
  28989. // Use global visual property
  28990. return this.getVisual(key);
  28991. }
  28992. return val;
  28993. };
  28994. /**
  28995. * If exists visual property of single data item
  28996. */
  28997. SeriesData.prototype.hasItemVisual = function () {
  28998. return this._itemVisuals.length > 0;
  28999. };
  29000. /**
  29001. * Make sure itemVisual property is unique
  29002. */
  29003. // TODO: use key to save visual to reduce memory.
  29004. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  29005. var itemVisuals = this._itemVisuals;
  29006. var itemVisual = itemVisuals[idx];
  29007. if (!itemVisual) {
  29008. itemVisual = itemVisuals[idx] = {};
  29009. }
  29010. var val = itemVisual[key];
  29011. if (val == null) {
  29012. val = this.getVisual(key); // TODO Performance?
  29013. if (isArray(val)) {
  29014. val = val.slice();
  29015. } else if (isObject$2(val)) {
  29016. val = extend({}, val);
  29017. }
  29018. itemVisual[key] = val;
  29019. }
  29020. return val;
  29021. }; // eslint-disable-next-line
  29022. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  29023. var itemVisual = this._itemVisuals[idx] || {};
  29024. this._itemVisuals[idx] = itemVisual;
  29025. if (isObject$2(key)) {
  29026. extend(itemVisual, key);
  29027. } else {
  29028. itemVisual[key] = value;
  29029. }
  29030. };
  29031. /**
  29032. * Clear itemVisuals and list visual.
  29033. */
  29034. SeriesData.prototype.clearAllVisual = function () {
  29035. this._visual = {};
  29036. this._itemVisuals = [];
  29037. };
  29038. SeriesData.prototype.setLayout = function (key, val) {
  29039. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  29040. };
  29041. /**
  29042. * Get layout property.
  29043. */
  29044. SeriesData.prototype.getLayout = function (key) {
  29045. return this._layout[key];
  29046. };
  29047. /**
  29048. * Get layout of single data item
  29049. */
  29050. SeriesData.prototype.getItemLayout = function (idx) {
  29051. return this._itemLayouts[idx];
  29052. };
  29053. /**
  29054. * Set layout of single data item
  29055. */
  29056. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  29057. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  29058. };
  29059. /**
  29060. * Clear all layout of single data item
  29061. */
  29062. SeriesData.prototype.clearItemLayouts = function () {
  29063. this._itemLayouts.length = 0;
  29064. };
  29065. /**
  29066. * Set graphic element relative to data. It can be set as null
  29067. */
  29068. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  29069. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  29070. setCommonECData(seriesIndex, this.dataType, idx, el);
  29071. this._graphicEls[idx] = el;
  29072. };
  29073. SeriesData.prototype.getItemGraphicEl = function (idx) {
  29074. return this._graphicEls[idx];
  29075. };
  29076. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  29077. each(this._graphicEls, function (el, idx) {
  29078. if (el) {
  29079. cb && cb.call(context, el, idx);
  29080. }
  29081. });
  29082. };
  29083. /**
  29084. * Shallow clone a new list except visual and layout properties, and graph elements.
  29085. * New list only change the indices.
  29086. */
  29087. SeriesData.prototype.cloneShallow = function (list) {
  29088. if (!list) {
  29089. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  29090. }
  29091. transferProperties(list, this);
  29092. list._store = this._store;
  29093. return list;
  29094. };
  29095. /**
  29096. * Wrap some method to add more feature
  29097. */
  29098. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  29099. var originalMethod = this[methodName];
  29100. if (!isFunction(originalMethod)) {
  29101. return;
  29102. }
  29103. this.__wrappedMethods = this.__wrappedMethods || [];
  29104. this.__wrappedMethods.push(methodName);
  29105. this[methodName] = function () {
  29106. var res = originalMethod.apply(this, arguments);
  29107. return injectFunction.apply(this, [res].concat(slice(arguments)));
  29108. };
  29109. }; // ----------------------------------------------------------
  29110. // A work around for internal method visiting private member.
  29111. // ----------------------------------------------------------
  29112. SeriesData.internalField = function () {
  29113. prepareInvertedIndex = function (data) {
  29114. var invertedIndicesMap = data._invertedIndicesMap;
  29115. each(invertedIndicesMap, function (invertedIndices, dim) {
  29116. var dimInfo = data._dimInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  29117. var ordinalMeta = dimInfo.ordinalMeta;
  29118. var store = data._store;
  29119. if (ordinalMeta) {
  29120. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  29121. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  29122. for (var i = 0; i < invertedIndices.length; i++) {
  29123. invertedIndices[i] = INDEX_NOT_FOUND;
  29124. }
  29125. for (var i = 0; i < store.count(); i++) {
  29126. // Only support the case that all values are distinct.
  29127. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  29128. }
  29129. }
  29130. });
  29131. };
  29132. getIdNameFromStore = function (data, dimIdx, idx) {
  29133. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  29134. };
  29135. /**
  29136. * @see the comment of `List['getId']`.
  29137. */
  29138. getId = function (data, rawIndex) {
  29139. var id = data._idList[rawIndex];
  29140. if (id == null && data._idDimIdx != null) {
  29141. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  29142. }
  29143. if (id == null) {
  29144. id = ID_PREFIX + rawIndex;
  29145. }
  29146. return id;
  29147. };
  29148. normalizeDimensions = function (dimensions) {
  29149. if (!isArray(dimensions)) {
  29150. dimensions = dimensions != null ? [dimensions] : [];
  29151. }
  29152. return dimensions;
  29153. };
  29154. /**
  29155. * Data in excludeDimensions is copied, otherwise transferred.
  29156. */
  29157. cloneListForMapAndSample = function (original) {
  29158. var list = new SeriesData(original._schema ? original._schema : map$1(original.dimensions, original._getDimInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked
  29159. transferProperties(list, original);
  29160. return list;
  29161. };
  29162. transferProperties = function (target, source) {
  29163. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  29164. if (source.hasOwnProperty(propName)) {
  29165. target[propName] = source[propName];
  29166. }
  29167. });
  29168. target.__wrappedMethods = source.__wrappedMethods;
  29169. each(CLONE_PROPERTIES, function (propName) {
  29170. target[propName] = clone(source[propName]);
  29171. });
  29172. target._calculationInfo = extend({}, source._calculationInfo);
  29173. };
  29174. makeIdFromName = function (data, idx) {
  29175. var nameList = data._nameList;
  29176. var idList = data._idList;
  29177. var nameDimIdx = data._nameDimIdx;
  29178. var idDimIdx = data._idDimIdx;
  29179. var name = nameList[idx];
  29180. var id = idList[idx];
  29181. if (name == null && nameDimIdx != null) {
  29182. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  29183. }
  29184. if (id == null && idDimIdx != null) {
  29185. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  29186. }
  29187. if (id == null && name != null) {
  29188. var nameRepeatCount = data._nameRepeatCount;
  29189. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  29190. id = name;
  29191. if (nmCnt > 1) {
  29192. id += '__ec__' + nmCnt;
  29193. }
  29194. idList[idx] = id;
  29195. }
  29196. };
  29197. }();
  29198. return SeriesData;
  29199. }();
  29200. /**
  29201. * For outside usage compat (like echarts-gl are using it).
  29202. */
  29203. function createDimensions(source, opt) {
  29204. return prepareSeriesDataSchema(source, opt).dimensions;
  29205. }
  29206. /**
  29207. * This method builds the relationship between:
  29208. * + "what the coord sys or series requires (see `coordDimensions`)",
  29209. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  29210. * + "what the data source provids (see `source`)".
  29211. *
  29212. * Some guess strategy will be adapted if user does not define something.
  29213. * If no 'value' dimension specified, the first no-named dimension will be
  29214. * named as 'value'.
  29215. *
  29216. * @return The results are always sorted by `storeDimIndex` asc.
  29217. */
  29218. function prepareSeriesDataSchema( // TODO: TYPE completeDimensions type
  29219. source, opt) {
  29220. if (!isSourceInstance(source)) {
  29221. source = createSourceFromSeriesDataOption(source);
  29222. }
  29223. opt = opt || {};
  29224. var sysDims = opt.coordDimensions || [];
  29225. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  29226. var coordDimNameMap = createHashMap();
  29227. var resultList = [];
  29228. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount); // Try to ignore unused dimensions if sharing a high dimension datastore
  29229. // 30 is an experience value.
  29230. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  29231. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  29232. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  29233. var encodeDef = opt.encodeDefine;
  29234. if (!encodeDef && opt.encodeDefaulter) {
  29235. encodeDef = opt.encodeDefaulter(source, dimCount);
  29236. }
  29237. var encodeDefMap = createHashMap(encodeDef);
  29238. var indicesMap = new CtorInt32Array(dimCount);
  29239. for (var i = 0; i < indicesMap.length; i++) {
  29240. indicesMap[i] = -1;
  29241. }
  29242. function getResultItem(dimIdx) {
  29243. var idx = indicesMap[dimIdx];
  29244. if (idx < 0) {
  29245. var dimDefItemRaw = dimsDef[dimIdx];
  29246. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  29247. name: dimDefItemRaw
  29248. };
  29249. var resultItem = new SeriesDimensionDefine();
  29250. var userDimName = dimDefItem.name;
  29251. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  29252. // Only if `series.dimensions` is defined in option
  29253. // displayName, will be set, and dimension will be displayed vertically in
  29254. // tooltip by default.
  29255. resultItem.name = resultItem.displayName = userDimName;
  29256. }
  29257. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  29258. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  29259. var newIdx = resultList.length;
  29260. indicesMap[dimIdx] = newIdx;
  29261. resultItem.storeDimIndex = dimIdx;
  29262. resultList.push(resultItem);
  29263. return resultItem;
  29264. }
  29265. return resultList[idx];
  29266. }
  29267. if (!omitUnusedDimensions) {
  29268. for (var i = 0; i < dimCount; i++) {
  29269. getResultItem(i);
  29270. }
  29271. } // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  29272. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  29273. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  29274. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  29275. // this case.
  29276. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  29277. encodeDefMap.set(coordDim, false);
  29278. return;
  29279. }
  29280. var validDataDims = encodeDefMap.set(coordDim, []);
  29281. each(dataDims, function (resultDimIdxOrName, idx) {
  29282. // The input resultDimIdx can be dim name or index.
  29283. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  29284. if (resultDimIdx != null && resultDimIdx < dimCount) {
  29285. validDataDims[idx] = resultDimIdx;
  29286. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  29287. }
  29288. });
  29289. }); // Apply templates and default order from `sysDims`.
  29290. var availDimIdx = 0;
  29291. each(sysDims, function (sysDimItemRaw) {
  29292. var coordDim;
  29293. var sysDimItemDimsDef;
  29294. var sysDimItemOtherDims;
  29295. var sysDimItem;
  29296. if (isString(sysDimItemRaw)) {
  29297. coordDim = sysDimItemRaw;
  29298. sysDimItem = {};
  29299. } else {
  29300. sysDimItem = sysDimItemRaw;
  29301. coordDim = sysDimItem.name;
  29302. var ordinalMeta = sysDimItem.ordinalMeta;
  29303. sysDimItem.ordinalMeta = null;
  29304. sysDimItem = extend({}, sysDimItem);
  29305. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  29306. sysDimItemDimsDef = sysDimItem.dimsDef;
  29307. sysDimItemOtherDims = sysDimItem.otherDims;
  29308. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  29309. }
  29310. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  29311. if (dataDims === false) {
  29312. return;
  29313. }
  29314. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  29315. if (!dataDims.length) {
  29316. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  29317. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  29318. availDimIdx++;
  29319. }
  29320. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  29321. }
  29322. } // Apply templates.
  29323. each(dataDims, function (resultDimIdx, coordDimIndex) {
  29324. var resultItem = getResultItem(resultDimIdx); // Coordinate system has a higher priority on dim type than source.
  29325. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  29326. resultItem.type = sysDimItem.type;
  29327. }
  29328. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  29329. if (resultItem.name == null && sysDimItemDimsDef) {
  29330. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  29331. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  29332. name: sysDimItemDimsDefItem
  29333. });
  29334. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  29335. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  29336. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  29337. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  29338. });
  29339. });
  29340. function applyDim(resultItem, coordDim, coordDimIndex) {
  29341. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  29342. resultItem.otherDims[coordDim] = coordDimIndex;
  29343. } else {
  29344. resultItem.coordDim = coordDim;
  29345. resultItem.coordDimIndex = coordDimIndex;
  29346. coordDimNameMap.set(coordDim, true);
  29347. }
  29348. } // Make sure the first extra dim is 'value'.
  29349. var generateCoord = opt.generateCoord;
  29350. var generateCoordCount = opt.generateCoordCount;
  29351. var fromZero = generateCoordCount != null;
  29352. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  29353. var extra = generateCoord || 'value';
  29354. function ifNoNameFillWithCoordName(resultItem) {
  29355. if (resultItem.name == null) {
  29356. // Duplication will be removed in the next step.
  29357. resultItem.name = resultItem.coordDim;
  29358. }
  29359. } // Set dim `name` and other `coordDim` and other props.
  29360. if (!omitUnusedDimensions) {
  29361. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  29362. var resultItem = getResultItem(resultDimIdx);
  29363. var coordDim = resultItem.coordDim;
  29364. if (coordDim == null) {
  29365. // TODO no need to generate coordDim for isExtraCoord?
  29366. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  29367. resultItem.coordDimIndex = 0; // Series specified generateCoord is using out.
  29368. if (!generateCoord || generateCoordCount <= 0) {
  29369. resultItem.isExtraCoord = true;
  29370. }
  29371. generateCoordCount--;
  29372. }
  29373. ifNoNameFillWithCoordName(resultItem);
  29374. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  29375. // {
  29376. // dataset: {source: [
  29377. // ['2001', 123],
  29378. // ['2002', 456],
  29379. // ...
  29380. // ['The others', 987],
  29381. // ]},
  29382. // series: {type: 'pie'}
  29383. // }
  29384. // The first column should better be treated as a "ordinal" although it
  29385. // might not be detected as an "ordinal" by `guessOrdinal`.
  29386. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  29387. resultItem.type = 'ordinal';
  29388. }
  29389. }
  29390. } else {
  29391. each(resultList, function (resultItem) {
  29392. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  29393. ifNoNameFillWithCoordName(resultItem);
  29394. }); // Sort dimensions: there are some rule that use the last dim as label,
  29395. // and for some latter travel process easier.
  29396. resultList.sort(function (item0, item1) {
  29397. return item0.storeDimIndex - item1.storeDimIndex;
  29398. });
  29399. }
  29400. removeDuplication(resultList);
  29401. return new SeriesDataSchema({
  29402. source: source,
  29403. dimensions: resultList,
  29404. fullDimensionCount: dimCount,
  29405. dimensionOmitted: omitUnusedDimensions
  29406. });
  29407. }
  29408. function removeDuplication(result) {
  29409. var duplicationMap = createHashMap();
  29410. for (var i = 0; i < result.length; i++) {
  29411. var dim = result[i];
  29412. var dimOriginalName = dim.name;
  29413. var count = duplicationMap.get(dimOriginalName) || 0;
  29414. if (count > 0) {
  29415. // Starts from 0.
  29416. dim.name = dimOriginalName + (count - 1);
  29417. }
  29418. count++;
  29419. duplicationMap.set(dimOriginalName, count);
  29420. }
  29421. } // ??? TODO
  29422. // Originally detect dimCount by data[0]. Should we
  29423. // optimize it to only by sysDims and dimensions and encode.
  29424. // So only necessary dims will be initialized.
  29425. // But
  29426. // (1) custom series should be considered. where other dims
  29427. // may be visited.
  29428. // (2) sometimes user need to calculate bubble size or use visualMap
  29429. // on other dimensions besides coordSys needed.
  29430. // So, dims that is not used by system, should be shared in data store?
  29431. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  29432. // Note that the result dimCount should not small than columns count
  29433. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  29434. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  29435. each(sysDims, function (sysDimItem) {
  29436. var sysDimItemDimsDef;
  29437. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  29438. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  29439. }
  29440. });
  29441. return dimCount;
  29442. }
  29443. function genCoordDimName(name, map, fromZero) {
  29444. if (fromZero || map.hasKey(name)) {
  29445. var i = 0;
  29446. while (map.hasKey(name + i)) {
  29447. i++;
  29448. }
  29449. name += i;
  29450. }
  29451. map.set(name, true);
  29452. return name;
  29453. }
  29454. /**
  29455. * @class
  29456. * For example:
  29457. * {
  29458. * coordSysName: 'cartesian2d',
  29459. * coordSysDims: ['x', 'y', ...],
  29460. * axisMap: HashMap({
  29461. * x: xAxisModel,
  29462. * y: yAxisModel
  29463. * }),
  29464. * categoryAxisMap: HashMap({
  29465. * x: xAxisModel,
  29466. * y: undefined
  29467. * }),
  29468. * // The index of the first category axis in `coordSysDims`.
  29469. * // `null/undefined` means no category axis exists.
  29470. * firstCategoryDimIndex: 1,
  29471. * // To replace user specified encode.
  29472. * }
  29473. */
  29474. var CoordSysInfo =
  29475. /** @class */
  29476. function () {
  29477. function CoordSysInfo(coordSysName) {
  29478. this.coordSysDims = [];
  29479. this.axisMap = createHashMap();
  29480. this.categoryAxisMap = createHashMap();
  29481. this.coordSysName = coordSysName;
  29482. }
  29483. return CoordSysInfo;
  29484. }();
  29485. function getCoordSysInfoBySeries(seriesModel) {
  29486. var coordSysName = seriesModel.get('coordinateSystem');
  29487. var result = new CoordSysInfo(coordSysName);
  29488. var fetch = fetchers[coordSysName];
  29489. if (fetch) {
  29490. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  29491. return result;
  29492. }
  29493. }
  29494. var fetchers = {
  29495. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  29496. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  29497. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  29498. if ("development" !== 'production') {
  29499. if (!xAxisModel) {
  29500. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  29501. }
  29502. if (!yAxisModel) {
  29503. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  29504. }
  29505. }
  29506. result.coordSysDims = ['x', 'y'];
  29507. axisMap.set('x', xAxisModel);
  29508. axisMap.set('y', yAxisModel);
  29509. if (isCategory(xAxisModel)) {
  29510. categoryAxisMap.set('x', xAxisModel);
  29511. result.firstCategoryDimIndex = 0;
  29512. }
  29513. if (isCategory(yAxisModel)) {
  29514. categoryAxisMap.set('y', yAxisModel);
  29515. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29516. }
  29517. },
  29518. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  29519. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  29520. if ("development" !== 'production') {
  29521. if (!singleAxisModel) {
  29522. throw new Error('singleAxis should be specified.');
  29523. }
  29524. }
  29525. result.coordSysDims = ['single'];
  29526. axisMap.set('single', singleAxisModel);
  29527. if (isCategory(singleAxisModel)) {
  29528. categoryAxisMap.set('single', singleAxisModel);
  29529. result.firstCategoryDimIndex = 0;
  29530. }
  29531. },
  29532. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  29533. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  29534. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  29535. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  29536. if ("development" !== 'production') {
  29537. if (!angleAxisModel) {
  29538. throw new Error('angleAxis option not found');
  29539. }
  29540. if (!radiusAxisModel) {
  29541. throw new Error('radiusAxis option not found');
  29542. }
  29543. }
  29544. result.coordSysDims = ['radius', 'angle'];
  29545. axisMap.set('radius', radiusAxisModel);
  29546. axisMap.set('angle', angleAxisModel);
  29547. if (isCategory(radiusAxisModel)) {
  29548. categoryAxisMap.set('radius', radiusAxisModel);
  29549. result.firstCategoryDimIndex = 0;
  29550. }
  29551. if (isCategory(angleAxisModel)) {
  29552. categoryAxisMap.set('angle', angleAxisModel);
  29553. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29554. }
  29555. },
  29556. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  29557. result.coordSysDims = ['lng', 'lat'];
  29558. },
  29559. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  29560. var ecModel = seriesModel.ecModel;
  29561. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  29562. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  29563. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  29564. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  29565. var axisDim = coordSysDims[index];
  29566. axisMap.set(axisDim, axisModel);
  29567. if (isCategory(axisModel)) {
  29568. categoryAxisMap.set(axisDim, axisModel);
  29569. if (result.firstCategoryDimIndex == null) {
  29570. result.firstCategoryDimIndex = index;
  29571. }
  29572. }
  29573. });
  29574. }
  29575. };
  29576. function isCategory(axisModel) {
  29577. return axisModel.get('type') === 'category';
  29578. }
  29579. /**
  29580. * Note that it is too complicated to support 3d stack by value
  29581. * (have to create two-dimension inverted index), so in 3d case
  29582. * we just support that stacked by index.
  29583. *
  29584. * @param seriesModel
  29585. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  29586. * The input will be modified.
  29587. * @param opt
  29588. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  29589. * @param opt.byIndex=false
  29590. * @return calculationInfo
  29591. * {
  29592. * stackedDimension: string
  29593. * stackedByDimension: string
  29594. * isStackedByIndex: boolean
  29595. * stackedOverDimension: string
  29596. * stackResultDimension: string
  29597. * }
  29598. */
  29599. function enableDataStack(seriesModel, dimensionsInput, opt) {
  29600. opt = opt || {};
  29601. var byIndex = opt.byIndex;
  29602. var stackedCoordDimension = opt.stackedCoordDimension;
  29603. var dimensionDefineList;
  29604. var schema;
  29605. var store;
  29606. if (isLegacyDimensionsInput(dimensionsInput)) {
  29607. dimensionDefineList = dimensionsInput;
  29608. } else {
  29609. schema = dimensionsInput.schema;
  29610. dimensionDefineList = schema.dimensions;
  29611. store = dimensionsInput.store;
  29612. } // Compatibal: when `stack` is set as '', do not stack.
  29613. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29614. var stackedByDimInfo;
  29615. var stackedDimInfo;
  29616. var stackResultDimension;
  29617. var stackedOverDimension;
  29618. each(dimensionDefineList, function (dimensionInfo, index) {
  29619. if (isString(dimensionInfo)) {
  29620. dimensionDefineList[index] = dimensionInfo = {
  29621. name: dimensionInfo
  29622. };
  29623. }
  29624. if (mayStack && !dimensionInfo.isExtraCoord) {
  29625. // Find the first ordinal dimension as the stackedByDimInfo.
  29626. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29627. stackedByDimInfo = dimensionInfo;
  29628. } // Find the first stackable dimension as the stackedDimInfo.
  29629. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  29630. stackedDimInfo = dimensionInfo;
  29631. }
  29632. }
  29633. });
  29634. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29635. // Compatible with previous design, value axis (time axis) only stack by index.
  29636. // It may make sense if the user provides elaborately constructed data.
  29637. byIndex = true;
  29638. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29639. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29640. // might not be a good way.
  29641. if (stackedDimInfo) {
  29642. // Use a weird name that not duplicated with other names.
  29643. // Also need to use seriesModel.id as postfix because different
  29644. // series may share same data store. The stack dimension needs to be distinguished.
  29645. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  29646. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id; // Create inverted index to fast query index by value.
  29647. if (stackedByDimInfo) {
  29648. stackedByDimInfo.createInvertedIndices = true;
  29649. }
  29650. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  29651. var stackedDimType = stackedDimInfo.type;
  29652. var stackedDimCoordIndex_1 = 0;
  29653. each(dimensionDefineList, function (dimensionInfo) {
  29654. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  29655. stackedDimCoordIndex_1++;
  29656. }
  29657. });
  29658. var stackedOverDimensionDefine = {
  29659. name: stackResultDimension,
  29660. coordDim: stackedDimCoordDim_1,
  29661. coordDimIndex: stackedDimCoordIndex_1,
  29662. type: stackedDimType,
  29663. isExtraCoord: true,
  29664. isCalculationCoord: true,
  29665. storeDimIndex: dimensionDefineList.length
  29666. };
  29667. var stackResultDimensionDefine = {
  29668. name: stackedOverDimension,
  29669. // This dimension contains stack base (generally, 0), so do not set it as
  29670. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29671. coordDim: stackedOverDimension,
  29672. coordDimIndex: stackedDimCoordIndex_1 + 1,
  29673. type: stackedDimType,
  29674. isExtraCoord: true,
  29675. isCalculationCoord: true,
  29676. storeDimIndex: dimensionDefineList.length + 1
  29677. };
  29678. if (schema) {
  29679. if (store) {
  29680. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  29681. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  29682. }
  29683. schema.appendCalculationDimension(stackedOverDimensionDefine);
  29684. schema.appendCalculationDimension(stackResultDimensionDefine);
  29685. } else {
  29686. dimensionDefineList.push(stackedOverDimensionDefine);
  29687. dimensionDefineList.push(stackResultDimensionDefine);
  29688. }
  29689. }
  29690. return {
  29691. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29692. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29693. isStackedByIndex: byIndex,
  29694. stackedOverDimension: stackedOverDimension,
  29695. stackResultDimension: stackResultDimension
  29696. };
  29697. }
  29698. function isLegacyDimensionsInput(dimensionsInput) {
  29699. return !isSeriesDataSchema(dimensionsInput.schema);
  29700. }
  29701. function isDimensionStacked(data, stackedDim) {
  29702. // Each single series only maps to one pair of axis. So we do not need to
  29703. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29704. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  29705. }
  29706. function getStackedDimension(data, targetDim) {
  29707. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  29708. }
  29709. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  29710. var coordSysName = seriesModel.get('coordinateSystem');
  29711. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29712. var coordSysDimDefs;
  29713. if (coordSysInfo && coordSysInfo.coordSysDims) {
  29714. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29715. var dimInfo = {
  29716. name: dim
  29717. };
  29718. var axisModel = coordSysInfo.axisMap.get(dim);
  29719. if (axisModel) {
  29720. var axisType = axisModel.get('type');
  29721. dimInfo.type = getDimensionTypeByAxis(axisType);
  29722. }
  29723. return dimInfo;
  29724. });
  29725. }
  29726. if (!coordSysDimDefs) {
  29727. // Get dimensions from registered coordinate system
  29728. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  29729. }
  29730. return coordSysDimDefs;
  29731. }
  29732. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  29733. var firstCategoryDimIndex;
  29734. var hasNameEncode;
  29735. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  29736. var coordDim = dimInfo.coordDim;
  29737. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29738. if (categoryAxisModel) {
  29739. if (firstCategoryDimIndex == null) {
  29740. firstCategoryDimIndex = dimIndex;
  29741. }
  29742. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29743. if (createInvertedIndices) {
  29744. dimInfo.createInvertedIndices = true;
  29745. }
  29746. }
  29747. if (dimInfo.otherDims.itemName != null) {
  29748. hasNameEncode = true;
  29749. }
  29750. });
  29751. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29752. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29753. }
  29754. return firstCategoryDimIndex;
  29755. }
  29756. /**
  29757. * Caution: there are side effects to `sourceManager` in this method.
  29758. * Should better only be called in `Series['getInitialData']`.
  29759. */
  29760. function createSeriesData(sourceRaw, seriesModel, opt) {
  29761. opt = opt || {};
  29762. var sourceManager = seriesModel.getSourceManager();
  29763. var source;
  29764. var isOriginalSource = false;
  29765. if (sourceRaw) {
  29766. isOriginalSource = true;
  29767. source = createSourceFromSeriesDataOption(sourceRaw);
  29768. } else {
  29769. source = sourceManager.getSource(); // Is series.data. not dataset.
  29770. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  29771. }
  29772. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29773. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  29774. var useEncodeDefaulter = opt.useEncodeDefaulter;
  29775. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  29776. var createDimensionOptions = {
  29777. coordDimensions: coordSysDimDefs,
  29778. generateCoord: opt.generateCoord,
  29779. encodeDefine: seriesModel.getEncode(),
  29780. encodeDefaulter: encodeDefaulter,
  29781. canOmitUnusedDimensions: !isOriginalSource
  29782. };
  29783. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  29784. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  29785. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  29786. var stackCalculationInfo = enableDataStack(seriesModel, {
  29787. schema: schema,
  29788. store: store
  29789. });
  29790. var data = new SeriesData(schema, seriesModel);
  29791. data.setCalculationInfo(stackCalculationInfo);
  29792. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29793. // Use dataIndex as ordinal value in categoryAxis
  29794. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29795. } : null;
  29796. data.hasItemOption = false;
  29797. data.initData( // Try to reuse the data store in sourceManager if using dataset.
  29798. isOriginalSource ? source : store, null, dimValueGetter);
  29799. return data;
  29800. }
  29801. function isNeedCompleteOrdinalData(source) {
  29802. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29803. var sampleItem = firstDataNotNull(source.data || []);
  29804. return !isArray(getDataItemValue(sampleItem));
  29805. }
  29806. }
  29807. function firstDataNotNull(arr) {
  29808. var i = 0;
  29809. while (i < arr.length && arr[i] == null) {
  29810. i++;
  29811. }
  29812. return arr[i];
  29813. }
  29814. var Scale =
  29815. /** @class */
  29816. function () {
  29817. function Scale(setting) {
  29818. this._setting = setting || {};
  29819. this._extent = [Infinity, -Infinity];
  29820. }
  29821. Scale.prototype.getSetting = function (name) {
  29822. return this._setting[name];
  29823. };
  29824. /**
  29825. * Set extent from data
  29826. */
  29827. Scale.prototype.unionExtent = function (other) {
  29828. var extent = this._extent;
  29829. other[0] < extent[0] && (extent[0] = other[0]);
  29830. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  29831. // this.setExtent(extent[0], extent[1]);
  29832. };
  29833. /**
  29834. * Set extent from data
  29835. */
  29836. Scale.prototype.unionExtentFromData = function (data, dim) {
  29837. this.unionExtent(data.getApproximateExtent(dim));
  29838. };
  29839. /**
  29840. * Get extent
  29841. *
  29842. * Extent is always in increase order.
  29843. */
  29844. Scale.prototype.getExtent = function () {
  29845. return this._extent.slice();
  29846. };
  29847. /**
  29848. * Set extent
  29849. */
  29850. Scale.prototype.setExtent = function (start, end) {
  29851. var thisExtent = this._extent;
  29852. if (!isNaN(start)) {
  29853. thisExtent[0] = start;
  29854. }
  29855. if (!isNaN(end)) {
  29856. thisExtent[1] = end;
  29857. }
  29858. };
  29859. /**
  29860. * If value is in extent range
  29861. */
  29862. Scale.prototype.isInExtentRange = function (value) {
  29863. return this._extent[0] <= value && this._extent[1] >= value;
  29864. };
  29865. /**
  29866. * When axis extent depends on data and no data exists,
  29867. * axis ticks should not be drawn, which is named 'blank'.
  29868. */
  29869. Scale.prototype.isBlank = function () {
  29870. return this._isBlank;
  29871. };
  29872. /**
  29873. * When axis extent depends on data and no data exists,
  29874. * axis ticks should not be drawn, which is named 'blank'.
  29875. */
  29876. Scale.prototype.setBlank = function (isBlank) {
  29877. this._isBlank = isBlank;
  29878. };
  29879. return Scale;
  29880. }();
  29881. enableClassManagement(Scale);
  29882. var uidBase = 0;
  29883. var OrdinalMeta =
  29884. /** @class */
  29885. function () {
  29886. function OrdinalMeta(opt) {
  29887. this.categories = opt.categories || [];
  29888. this._needCollect = opt.needCollect;
  29889. this._deduplication = opt.deduplication;
  29890. this.uid = ++uidBase;
  29891. }
  29892. OrdinalMeta.createByAxisModel = function (axisModel) {
  29893. var option = axisModel.option;
  29894. var data = option.data;
  29895. var categories = data && map(data, getName);
  29896. return new OrdinalMeta({
  29897. categories: categories,
  29898. needCollect: !categories,
  29899. // deduplication is default in axis.
  29900. deduplication: option.dedplication !== false
  29901. });
  29902. };
  29903. OrdinalMeta.prototype.getOrdinal = function (category) {
  29904. // @ts-ignore
  29905. return this._getOrCreateMap().get(category);
  29906. };
  29907. /**
  29908. * @return The ordinal. If not found, return NaN.
  29909. */
  29910. OrdinalMeta.prototype.parseAndCollect = function (category) {
  29911. var index;
  29912. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  29913. // This feature is only supported when !needCollect, because we should
  29914. // consider a common case: a value is 2017, which is a number but is
  29915. // expected to be tread as a category. This case usually happen in dataset,
  29916. // where it happent to be no need of the index feature.
  29917. if (!isString(category) && !needCollect) {
  29918. return category;
  29919. } // Optimize for the scenario:
  29920. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29921. // data has been ensured not duplicate and is large data.
  29922. // Notice, if a dataset dimension provide categroies, usually echarts
  29923. // should remove duplication except user tell echarts dont do that
  29924. // (set axis.deduplication = false), because echarts do not know whether
  29925. // the values in the category dimension has duplication (consider the
  29926. // parallel-aqi example)
  29927. if (needCollect && !this._deduplication) {
  29928. index = this.categories.length;
  29929. this.categories[index] = category;
  29930. return index;
  29931. }
  29932. var map = this._getOrCreateMap(); // @ts-ignore
  29933. index = map.get(category);
  29934. if (index == null) {
  29935. if (needCollect) {
  29936. index = this.categories.length;
  29937. this.categories[index] = category; // @ts-ignore
  29938. map.set(category, index);
  29939. } else {
  29940. index = NaN;
  29941. }
  29942. }
  29943. return index;
  29944. }; // Consider big data, do not create map until needed.
  29945. OrdinalMeta.prototype._getOrCreateMap = function () {
  29946. return this._map || (this._map = createHashMap(this.categories));
  29947. };
  29948. return OrdinalMeta;
  29949. }();
  29950. function getName(obj) {
  29951. if (isObject(obj) && obj.value != null) {
  29952. return obj.value;
  29953. } else {
  29954. return obj + '';
  29955. }
  29956. }
  29957. function isValueNice(val) {
  29958. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  29959. var f = Math.abs(val / exp10);
  29960. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  29961. }
  29962. function isIntervalOrLogScale(scale) {
  29963. return scale.type === 'interval' || scale.type === 'log';
  29964. }
  29965. /**
  29966. * @param extent Both extent[0] and extent[1] should be valid number.
  29967. * Should be extent[0] < extent[1].
  29968. * @param splitNumber splitNumber should be >= 1.
  29969. */
  29970. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29971. var result = {};
  29972. var span = extent[1] - extent[0];
  29973. var interval = result.interval = nice(span / splitNumber, true);
  29974. if (minInterval != null && interval < minInterval) {
  29975. interval = result.interval = minInterval;
  29976. }
  29977. if (maxInterval != null && interval > maxInterval) {
  29978. interval = result.interval = maxInterval;
  29979. } // Tow more digital for tick.
  29980. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  29981. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  29982. fixExtent(niceTickExtent, extent);
  29983. return result;
  29984. }
  29985. function increaseInterval(interval) {
  29986. var exp10 = Math.pow(10, quantityExponent(interval)); // Increase interval
  29987. var f = interval / exp10;
  29988. if (!f) {
  29989. f = 1;
  29990. } else if (f === 2) {
  29991. f = 3;
  29992. } else if (f === 3) {
  29993. f = 5;
  29994. } else {
  29995. // f is 1 or 5
  29996. f *= 2;
  29997. }
  29998. return round(f * exp10);
  29999. }
  30000. /**
  30001. * @return interval precision
  30002. */
  30003. function getIntervalPrecision(interval) {
  30004. // Tow more digital for tick.
  30005. return getPrecision(interval) + 2;
  30006. }
  30007. function clamp(niceTickExtent, idx, extent) {
  30008. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  30009. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  30010. function fixExtent(niceTickExtent, extent) {
  30011. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  30012. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  30013. clamp(niceTickExtent, 0, extent);
  30014. clamp(niceTickExtent, 1, extent);
  30015. if (niceTickExtent[0] > niceTickExtent[1]) {
  30016. niceTickExtent[0] = niceTickExtent[1];
  30017. }
  30018. }
  30019. function contain$1(val, extent) {
  30020. return val >= extent[0] && val <= extent[1];
  30021. }
  30022. function normalize$1(val, extent) {
  30023. if (extent[1] === extent[0]) {
  30024. return 0.5;
  30025. }
  30026. return (val - extent[0]) / (extent[1] - extent[0]);
  30027. }
  30028. function scale$2(val, extent) {
  30029. return val * (extent[1] - extent[0]) + extent[0];
  30030. }
  30031. var OrdinalScale =
  30032. /** @class */
  30033. function (_super) {
  30034. __extends(OrdinalScale, _super);
  30035. function OrdinalScale(setting) {
  30036. var _this = _super.call(this, setting) || this;
  30037. _this.type = 'ordinal';
  30038. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  30039. // import approach to get OrdinalMeta class.
  30040. if (!ordinalMeta) {
  30041. ordinalMeta = new OrdinalMeta({});
  30042. }
  30043. if (isArray(ordinalMeta)) {
  30044. ordinalMeta = new OrdinalMeta({
  30045. categories: map(ordinalMeta, function (item) {
  30046. return isObject(item) ? item.value : item;
  30047. })
  30048. });
  30049. }
  30050. _this._ordinalMeta = ordinalMeta;
  30051. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  30052. return _this;
  30053. }
  30054. OrdinalScale.prototype.parse = function (val) {
  30055. // Caution: Math.round(null) will return `0` rather than `NaN`
  30056. if (val == null) {
  30057. return NaN;
  30058. }
  30059. return isString(val) ? this._ordinalMeta.getOrdinal(val) // val might be float.
  30060. : Math.round(val);
  30061. };
  30062. OrdinalScale.prototype.contain = function (rank) {
  30063. rank = this.parse(rank);
  30064. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  30065. };
  30066. /**
  30067. * Normalize given rank or name to linear [0, 1]
  30068. * @param val raw ordinal number.
  30069. * @return normalized value in [0, 1].
  30070. */
  30071. OrdinalScale.prototype.normalize = function (val) {
  30072. val = this._getTickNumber(this.parse(val));
  30073. return normalize$1(val, this._extent);
  30074. };
  30075. /**
  30076. * @param val normalized value in [0, 1].
  30077. * @return raw ordinal number.
  30078. */
  30079. OrdinalScale.prototype.scale = function (val) {
  30080. val = Math.round(scale$2(val, this._extent));
  30081. return this.getRawOrdinalNumber(val);
  30082. };
  30083. OrdinalScale.prototype.getTicks = function () {
  30084. var ticks = [];
  30085. var extent = this._extent;
  30086. var rank = extent[0];
  30087. while (rank <= extent[1]) {
  30088. ticks.push({
  30089. value: rank
  30090. });
  30091. rank++;
  30092. }
  30093. return ticks;
  30094. };
  30095. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  30096. // Not support.
  30097. return;
  30098. };
  30099. /**
  30100. * @see `Ordinal['_ordinalNumbersByTick']`
  30101. */
  30102. OrdinalScale.prototype.setSortInfo = function (info) {
  30103. if (info == null) {
  30104. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  30105. return;
  30106. }
  30107. var infoOrdinalNumbers = info.ordinalNumbers;
  30108. var ordinalsByTick = this._ordinalNumbersByTick = [];
  30109. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  30110. var tickNum = 0;
  30111. var allCategoryLen = this._ordinalMeta.categories.length;
  30112. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  30113. var ordinalNumber = infoOrdinalNumbers[tickNum];
  30114. ordinalsByTick[tickNum] = ordinalNumber;
  30115. ticksByOrdinal[ordinalNumber] = tickNum;
  30116. } // Handle that `series.data` only covers part of the `axis.category.data`.
  30117. var unusedOrdinal = 0;
  30118. for (; tickNum < allCategoryLen; ++tickNum) {
  30119. while (ticksByOrdinal[unusedOrdinal] != null) {
  30120. unusedOrdinal++;
  30121. }
  30122. ordinalsByTick.push(unusedOrdinal);
  30123. ticksByOrdinal[unusedOrdinal] = tickNum;
  30124. }
  30125. };
  30126. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  30127. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  30128. // where ordinal numbers are used as tick value directly.
  30129. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  30130. };
  30131. /**
  30132. * @usage
  30133. * ```js
  30134. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  30135. *
  30136. * // case0
  30137. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  30138. * // case1
  30139. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  30140. * // case2
  30141. * const coord = axis.dataToCoord(ordinalNumber);
  30142. * ```
  30143. *
  30144. * @param {OrdinalNumber} tickNumber index of display
  30145. */
  30146. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  30147. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  30148. // where ordinal numbers are used as tick value directly.
  30149. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  30150. };
  30151. /**
  30152. * Get item on tick
  30153. */
  30154. OrdinalScale.prototype.getLabel = function (tick) {
  30155. if (!this.isBlank()) {
  30156. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  30157. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  30158. // Return empty if it's not exist.
  30159. return cateogry == null ? '' : cateogry + '';
  30160. }
  30161. };
  30162. OrdinalScale.prototype.count = function () {
  30163. return this._extent[1] - this._extent[0] + 1;
  30164. };
  30165. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  30166. this.unionExtent(data.getApproximateExtent(dim));
  30167. };
  30168. /**
  30169. * @override
  30170. * If value is in extent range
  30171. */
  30172. OrdinalScale.prototype.isInExtentRange = function (value) {
  30173. value = this._getTickNumber(value);
  30174. return this._extent[0] <= value && this._extent[1] >= value;
  30175. };
  30176. OrdinalScale.prototype.getOrdinalMeta = function () {
  30177. return this._ordinalMeta;
  30178. };
  30179. OrdinalScale.prototype.calcNiceTicks = function () {};
  30180. OrdinalScale.prototype.calcNiceExtent = function () {};
  30181. OrdinalScale.type = 'ordinal';
  30182. return OrdinalScale;
  30183. }(Scale);
  30184. Scale.registerClass(OrdinalScale);
  30185. var roundNumber = round;
  30186. var IntervalScale =
  30187. /** @class */
  30188. function (_super) {
  30189. __extends(IntervalScale, _super);
  30190. function IntervalScale() {
  30191. var _this = _super !== null && _super.apply(this, arguments) || this;
  30192. _this.type = 'interval'; // Step is calculated in adjustExtent.
  30193. _this._interval = 0;
  30194. _this._intervalPrecision = 2;
  30195. return _this;
  30196. }
  30197. IntervalScale.prototype.parse = function (val) {
  30198. return val;
  30199. };
  30200. IntervalScale.prototype.contain = function (val) {
  30201. return contain$1(val, this._extent);
  30202. };
  30203. IntervalScale.prototype.normalize = function (val) {
  30204. return normalize$1(val, this._extent);
  30205. };
  30206. IntervalScale.prototype.scale = function (val) {
  30207. return scale$2(val, this._extent);
  30208. };
  30209. IntervalScale.prototype.setExtent = function (start, end) {
  30210. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  30211. if (!isNaN(start)) {
  30212. thisExtent[0] = parseFloat(start);
  30213. }
  30214. if (!isNaN(end)) {
  30215. thisExtent[1] = parseFloat(end);
  30216. }
  30217. };
  30218. IntervalScale.prototype.unionExtent = function (other) {
  30219. var extent = this._extent;
  30220. other[0] < extent[0] && (extent[0] = other[0]);
  30221. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  30222. this.setExtent(extent[0], extent[1]);
  30223. };
  30224. IntervalScale.prototype.getInterval = function () {
  30225. return this._interval;
  30226. };
  30227. IntervalScale.prototype.setInterval = function (interval) {
  30228. this._interval = interval; // Dropped auto calculated niceExtent and use user-set extent.
  30229. // We assume user wants to set both interval, min, max to get a better result.
  30230. this._niceExtent = this._extent.slice();
  30231. this._intervalPrecision = getIntervalPrecision(interval);
  30232. };
  30233. /**
  30234. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  30235. */
  30236. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  30237. var interval = this._interval;
  30238. var extent = this._extent;
  30239. var niceTickExtent = this._niceExtent;
  30240. var intervalPrecision = this._intervalPrecision;
  30241. var ticks = []; // If interval is 0, return [];
  30242. if (!interval) {
  30243. return ticks;
  30244. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  30245. var safeLimit = 10000;
  30246. if (extent[0] < niceTickExtent[0]) {
  30247. if (expandToNicedExtent) {
  30248. ticks.push({
  30249. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  30250. });
  30251. } else {
  30252. ticks.push({
  30253. value: extent[0]
  30254. });
  30255. }
  30256. }
  30257. var tick = niceTickExtent[0];
  30258. while (tick <= niceTickExtent[1]) {
  30259. ticks.push({
  30260. value: tick
  30261. }); // Avoid rounding error
  30262. tick = roundNumber(tick + interval, intervalPrecision);
  30263. if (tick === ticks[ticks.length - 1].value) {
  30264. // Consider out of safe float point, e.g.,
  30265. // -3711126.9907707 + 2e-10 === -3711126.9907707
  30266. break;
  30267. }
  30268. if (ticks.length > safeLimit) {
  30269. return [];
  30270. }
  30271. } // Consider this case: the last item of ticks is smaller
  30272. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  30273. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  30274. if (extent[1] > lastNiceTick) {
  30275. if (expandToNicedExtent) {
  30276. ticks.push({
  30277. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  30278. });
  30279. } else {
  30280. ticks.push({
  30281. value: extent[1]
  30282. });
  30283. }
  30284. }
  30285. return ticks;
  30286. };
  30287. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  30288. var ticks = this.getTicks(true);
  30289. var minorTicks = [];
  30290. var extent = this.getExtent();
  30291. for (var i = 1; i < ticks.length; i++) {
  30292. var nextTick = ticks[i];
  30293. var prevTick = ticks[i - 1];
  30294. var count = 0;
  30295. var minorTicksGroup = [];
  30296. var interval = nextTick.value - prevTick.value;
  30297. var minorInterval = interval / splitNumber;
  30298. while (count < splitNumber - 1) {
  30299. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  30300. if (minorTick > extent[0] && minorTick < extent[1]) {
  30301. minorTicksGroup.push(minorTick);
  30302. }
  30303. count++;
  30304. }
  30305. minorTicks.push(minorTicksGroup);
  30306. }
  30307. return minorTicks;
  30308. };
  30309. /**
  30310. * @param opt.precision If 'auto', use nice presision.
  30311. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  30312. */
  30313. IntervalScale.prototype.getLabel = function (data, opt) {
  30314. if (data == null) {
  30315. return '';
  30316. }
  30317. var precision = opt && opt.precision;
  30318. if (precision == null) {
  30319. precision = getPrecision(data.value) || 0;
  30320. } else if (precision === 'auto') {
  30321. // Should be more precise then tick.
  30322. precision = this._intervalPrecision;
  30323. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  30324. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  30325. var dataNum = roundNumber(data.value, precision, true);
  30326. return addCommas(dataNum);
  30327. };
  30328. /**
  30329. * @param splitNumber By default `5`.
  30330. */
  30331. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  30332. splitNumber = splitNumber || 5;
  30333. var extent = this._extent;
  30334. var span = extent[1] - extent[0];
  30335. if (!isFinite(span)) {
  30336. return;
  30337. } // User may set axis min 0 and data are all negative
  30338. // FIXME If it needs to reverse ?
  30339. if (span < 0) {
  30340. span = -span;
  30341. extent.reverse();
  30342. }
  30343. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  30344. this._intervalPrecision = result.intervalPrecision;
  30345. this._interval = result.interval;
  30346. this._niceExtent = result.niceTickExtent;
  30347. };
  30348. IntervalScale.prototype.calcNiceExtent = function (opt) {
  30349. var extent = this._extent; // If extent start and end are same, expand them
  30350. if (extent[0] === extent[1]) {
  30351. if (extent[0] !== 0) {
  30352. // Expand extent
  30353. // Note that extents can be both negative. See #13154
  30354. var expandSize = Math.abs(extent[0]); // In the fowllowing case
  30355. // Axis has been fixed max 100
  30356. // Plus data are all 100 and axis extent are [100, 100].
  30357. // Extend to the both side will cause expanded max is larger than fixed max.
  30358. // So only expand to the smaller side.
  30359. if (!opt.fixMax) {
  30360. extent[1] += expandSize / 2;
  30361. extent[0] -= expandSize / 2;
  30362. } else {
  30363. extent[0] -= expandSize / 2;
  30364. }
  30365. } else {
  30366. extent[1] = 1;
  30367. }
  30368. }
  30369. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  30370. if (!isFinite(span)) {
  30371. extent[0] = 0;
  30372. extent[1] = 1;
  30373. }
  30374. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  30375. var interval = this._interval;
  30376. if (!opt.fixMin) {
  30377. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  30378. }
  30379. if (!opt.fixMax) {
  30380. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  30381. }
  30382. };
  30383. IntervalScale.prototype.setNiceExtent = function (min, max) {
  30384. this._niceExtent = [min, max];
  30385. };
  30386. IntervalScale.type = 'interval';
  30387. return IntervalScale;
  30388. }(Scale);
  30389. Scale.registerClass(IntervalScale);
  30390. /* global Float32Array */
  30391. var supportFloat32Array = typeof Float32Array !== 'undefined';
  30392. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  30393. function createFloat32Array(arg) {
  30394. if (isArray(arg)) {
  30395. // Return self directly if don't support TypedArray.
  30396. return supportFloat32Array ? new Float32Array(arg) : arg;
  30397. } // Else is number
  30398. return new Float32ArrayCtor(arg);
  30399. }
  30400. var STACK_PREFIX = '__ec_stack_';
  30401. function getSeriesStackId(seriesModel) {
  30402. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  30403. }
  30404. function getAxisKey(axis) {
  30405. return axis.dim + axis.index;
  30406. }
  30407. /**
  30408. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  30409. */
  30410. function getLayoutOnAxis(opt) {
  30411. var params = [];
  30412. var baseAxis = opt.axis;
  30413. var axisKey = 'axis0';
  30414. if (baseAxis.type !== 'category') {
  30415. return;
  30416. }
  30417. var bandWidth = baseAxis.getBandWidth();
  30418. for (var i = 0; i < opt.count || 0; i++) {
  30419. params.push(defaults({
  30420. bandWidth: bandWidth,
  30421. axisKey: axisKey,
  30422. stackId: STACK_PREFIX + i
  30423. }, opt));
  30424. }
  30425. var widthAndOffsets = doCalBarWidthAndOffset(params);
  30426. var result = [];
  30427. for (var i = 0; i < opt.count; i++) {
  30428. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  30429. item.offsetCenter = item.offset + item.width / 2;
  30430. result.push(item);
  30431. }
  30432. return result;
  30433. }
  30434. function prepareLayoutBarSeries(seriesType, ecModel) {
  30435. var seriesModels = [];
  30436. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30437. // Check series coordinate, do layout for cartesian2d only
  30438. if (isOnCartesian(seriesModel)) {
  30439. seriesModels.push(seriesModel);
  30440. }
  30441. });
  30442. return seriesModels;
  30443. }
  30444. /**
  30445. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  30446. * values.
  30447. * This works for time axes, value axes, and log axes.
  30448. * For a single time axis, return value is in the form like
  30449. * {'x_0': [1000000]}.
  30450. * The value of 1000000 is in milliseconds.
  30451. */
  30452. function getValueAxesMinGaps(barSeries) {
  30453. /**
  30454. * Map from axis.index to values.
  30455. * For a single time axis, axisValues is in the form like
  30456. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  30457. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  30458. * series.
  30459. */
  30460. var axisValues = {};
  30461. each(barSeries, function (seriesModel) {
  30462. var cartesian = seriesModel.coordinateSystem;
  30463. var baseAxis = cartesian.getBaseAxis();
  30464. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  30465. return;
  30466. }
  30467. var data = seriesModel.getData();
  30468. var key = baseAxis.dim + '_' + baseAxis.index;
  30469. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30470. var store = data.getStore();
  30471. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  30472. var value = store.get(dimIdx, i);
  30473. if (!axisValues[key]) {
  30474. // No previous data for the axis
  30475. axisValues[key] = [value];
  30476. } else {
  30477. // No value in previous series
  30478. axisValues[key].push(value);
  30479. } // Ignore duplicated time values in the same axis
  30480. }
  30481. });
  30482. var axisMinGaps = {};
  30483. for (var key in axisValues) {
  30484. if (axisValues.hasOwnProperty(key)) {
  30485. var valuesInAxis = axisValues[key];
  30486. if (valuesInAxis) {
  30487. // Sort axis values into ascending order to calculate gaps
  30488. valuesInAxis.sort(function (a, b) {
  30489. return a - b;
  30490. });
  30491. var min = null;
  30492. for (var j = 1; j < valuesInAxis.length; ++j) {
  30493. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  30494. if (delta > 0) {
  30495. // Ignore 0 delta because they are of the same axis value
  30496. min = min === null ? delta : Math.min(min, delta);
  30497. }
  30498. } // Set to null if only have one data
  30499. axisMinGaps[key] = min;
  30500. }
  30501. }
  30502. }
  30503. return axisMinGaps;
  30504. }
  30505. function makeColumnLayout(barSeries) {
  30506. var axisMinGaps = getValueAxesMinGaps(barSeries);
  30507. var seriesInfoList = [];
  30508. each(barSeries, function (seriesModel) {
  30509. var cartesian = seriesModel.coordinateSystem;
  30510. var baseAxis = cartesian.getBaseAxis();
  30511. var axisExtent = baseAxis.getExtent();
  30512. var bandWidth;
  30513. if (baseAxis.type === 'category') {
  30514. bandWidth = baseAxis.getBandWidth();
  30515. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  30516. var key = baseAxis.dim + '_' + baseAxis.index;
  30517. var minGap = axisMinGaps[key];
  30518. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  30519. var scale = baseAxis.scale.getExtent();
  30520. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30521. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  30522. } else {
  30523. var data = seriesModel.getData();
  30524. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30525. }
  30526. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  30527. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  30528. var barMinWidth = parsePercent$1( // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  30529. // the auto-calculated bar width might be less than 0.5 / 1.
  30530. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  30531. var barGap = seriesModel.get('barGap');
  30532. var barCategoryGap = seriesModel.get('barCategoryGap');
  30533. seriesInfoList.push({
  30534. bandWidth: bandWidth,
  30535. barWidth: barWidth,
  30536. barMaxWidth: barMaxWidth,
  30537. barMinWidth: barMinWidth,
  30538. barGap: barGap,
  30539. barCategoryGap: barCategoryGap,
  30540. axisKey: getAxisKey(baseAxis),
  30541. stackId: getSeriesStackId(seriesModel)
  30542. });
  30543. });
  30544. return doCalBarWidthAndOffset(seriesInfoList);
  30545. }
  30546. function doCalBarWidthAndOffset(seriesInfoList) {
  30547. // Columns info on each category axis. Key is cartesian name
  30548. var columnsMap = {};
  30549. each(seriesInfoList, function (seriesInfo, idx) {
  30550. var axisKey = seriesInfo.axisKey;
  30551. var bandWidth = seriesInfo.bandWidth;
  30552. var columnsOnAxis = columnsMap[axisKey] || {
  30553. bandWidth: bandWidth,
  30554. remainedWidth: bandWidth,
  30555. autoWidthCount: 0,
  30556. categoryGap: null,
  30557. gap: '20%',
  30558. stacks: {}
  30559. };
  30560. var stacks = columnsOnAxis.stacks;
  30561. columnsMap[axisKey] = columnsOnAxis;
  30562. var stackId = seriesInfo.stackId;
  30563. if (!stacks[stackId]) {
  30564. columnsOnAxis.autoWidthCount++;
  30565. }
  30566. stacks[stackId] = stacks[stackId] || {
  30567. width: 0,
  30568. maxWidth: 0
  30569. }; // Caution: In a single coordinate system, these barGrid attributes
  30570. // will be shared by series. Consider that they have default values,
  30571. // only the attributes set on the last series will work.
  30572. // Do not change this fact unless there will be a break change.
  30573. var barWidth = seriesInfo.barWidth;
  30574. if (barWidth && !stacks[stackId].width) {
  30575. // See #6312, do not restrict width.
  30576. stacks[stackId].width = barWidth;
  30577. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30578. columnsOnAxis.remainedWidth -= barWidth;
  30579. }
  30580. var barMaxWidth = seriesInfo.barMaxWidth;
  30581. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30582. var barMinWidth = seriesInfo.barMinWidth;
  30583. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30584. var barGap = seriesInfo.barGap;
  30585. barGap != null && (columnsOnAxis.gap = barGap);
  30586. var barCategoryGap = seriesInfo.barCategoryGap;
  30587. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  30588. });
  30589. var result = {};
  30590. each(columnsMap, function (columnsOnAxis, coordSysName) {
  30591. result[coordSysName] = {};
  30592. var stacks = columnsOnAxis.stacks;
  30593. var bandWidth = columnsOnAxis.bandWidth;
  30594. var categoryGapPercent = columnsOnAxis.categoryGap;
  30595. if (categoryGapPercent == null) {
  30596. var columnCount = keys(stacks).length; // More columns in one group
  30597. // the spaces between group is smaller. Or the column will be too thin.
  30598. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  30599. }
  30600. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  30601. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30602. var remainedWidth = columnsOnAxis.remainedWidth;
  30603. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30604. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30605. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  30606. each(stacks, function (column) {
  30607. var maxWidth = column.maxWidth;
  30608. var minWidth = column.minWidth;
  30609. if (!column.width) {
  30610. var finalWidth = autoWidth;
  30611. if (maxWidth && maxWidth < finalWidth) {
  30612. finalWidth = Math.min(maxWidth, remainedWidth);
  30613. } // `minWidth` has higher priority. `minWidth` decide that whether the
  30614. // bar is able to be visible. So `minWidth` should not be restricted
  30615. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30616. // the extreme cases for `value` axis, bars are allowed to overlap
  30617. // with each other if `minWidth` specified.
  30618. if (minWidth && minWidth > finalWidth) {
  30619. finalWidth = minWidth;
  30620. }
  30621. if (finalWidth !== autoWidth) {
  30622. column.width = finalWidth;
  30623. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30624. autoWidthCount--;
  30625. }
  30626. } else {
  30627. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30628. // CSS does. Because barWidth can be a percent value, where
  30629. // `barMaxWidth` can be used to restrict the final width.
  30630. var finalWidth = column.width;
  30631. if (maxWidth) {
  30632. finalWidth = Math.min(finalWidth, maxWidth);
  30633. } // `minWidth` has higher priority, as described above
  30634. if (minWidth) {
  30635. finalWidth = Math.max(finalWidth, minWidth);
  30636. }
  30637. column.width = finalWidth;
  30638. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30639. autoWidthCount--;
  30640. }
  30641. }); // Recalculate width again
  30642. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30643. autoWidth = Math.max(autoWidth, 0);
  30644. var widthSum = 0;
  30645. var lastColumn;
  30646. each(stacks, function (column, idx) {
  30647. if (!column.width) {
  30648. column.width = autoWidth;
  30649. }
  30650. lastColumn = column;
  30651. widthSum += column.width * (1 + barGapPercent);
  30652. });
  30653. if (lastColumn) {
  30654. widthSum -= lastColumn.width * barGapPercent;
  30655. }
  30656. var offset = -widthSum / 2;
  30657. each(stacks, function (column, stackId) {
  30658. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30659. bandWidth: bandWidth,
  30660. offset: offset,
  30661. width: column.width
  30662. };
  30663. offset += column.width * (1 + barGapPercent);
  30664. });
  30665. });
  30666. return result;
  30667. }
  30668. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30669. if (barWidthAndOffset && axis) {
  30670. var result = barWidthAndOffset[getAxisKey(axis)];
  30671. if (result != null && seriesModel != null) {
  30672. return result[getSeriesStackId(seriesModel)];
  30673. }
  30674. return result;
  30675. }
  30676. }
  30677. function layout(seriesType, ecModel) {
  30678. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30679. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30680. each(seriesModels, function (seriesModel) {
  30681. var data = seriesModel.getData();
  30682. var cartesian = seriesModel.coordinateSystem;
  30683. var baseAxis = cartesian.getBaseAxis();
  30684. var stackId = getSeriesStackId(seriesModel);
  30685. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30686. var columnOffset = columnLayoutInfo.offset;
  30687. var columnWidth = columnLayoutInfo.width;
  30688. data.setLayout({
  30689. bandWidth: columnLayoutInfo.bandWidth,
  30690. offset: columnOffset,
  30691. size: columnWidth
  30692. });
  30693. });
  30694. } // TODO: Do not support stack in large mode yet.
  30695. function createProgressiveLayout(seriesType) {
  30696. return {
  30697. seriesType: seriesType,
  30698. plan: createRenderPlanner(),
  30699. reset: function (seriesModel) {
  30700. if (!isOnCartesian(seriesModel)) {
  30701. return;
  30702. }
  30703. var data = seriesModel.getData();
  30704. var cartesian = seriesModel.coordinateSystem;
  30705. var baseAxis = cartesian.getBaseAxis();
  30706. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30707. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  30708. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30709. var drawBackground = seriesModel.get('showBackground', true);
  30710. var valueDim = data.mapDimension(valueAxis.dim);
  30711. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  30712. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  30713. var isValueAxisH = valueAxis.isHorizontal();
  30714. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  30715. var isLarge = isInLargeMode(seriesModel);
  30716. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30717. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim); // Layout info.
  30718. var columnWidth = data.getLayout('size');
  30719. var columnOffset = data.getLayout('offset');
  30720. return {
  30721. progress: function (params, data) {
  30722. var count = params.count;
  30723. var largePoints = isLarge && createFloat32Array(count * 3);
  30724. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  30725. var largeDataIndices = isLarge && createFloat32Array(count);
  30726. var coordLayout = cartesian.master.getRect();
  30727. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  30728. var dataIndex;
  30729. var store = data.getStore();
  30730. var idxOffset = 0;
  30731. while ((dataIndex = params.next()) != null) {
  30732. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  30733. var baseValue = store.get(baseDimIdx, dataIndex);
  30734. var baseCoord = valueAxisStart;
  30735. var startValue = void 0; // Because of the barMinHeight, we can not use the value in
  30736. // stackResultDimension directly.
  30737. if (stacked) {
  30738. startValue = +value - store.get(valueDimIdx, dataIndex);
  30739. }
  30740. var x = void 0;
  30741. var y = void 0;
  30742. var width = void 0;
  30743. var height = void 0;
  30744. if (isValueAxisH) {
  30745. var coord = cartesian.dataToPoint([value, baseValue]);
  30746. if (stacked) {
  30747. var startCoord = cartesian.dataToPoint([startValue, baseValue]);
  30748. baseCoord = startCoord[0];
  30749. }
  30750. x = baseCoord;
  30751. y = coord[1] + columnOffset;
  30752. width = coord[0] - baseCoord;
  30753. height = columnWidth;
  30754. if (Math.abs(width) < barMinHeight) {
  30755. width = (width < 0 ? -1 : 1) * barMinHeight;
  30756. }
  30757. } else {
  30758. var coord = cartesian.dataToPoint([baseValue, value]);
  30759. if (stacked) {
  30760. var startCoord = cartesian.dataToPoint([baseValue, startValue]);
  30761. baseCoord = startCoord[1];
  30762. }
  30763. x = coord[0] + columnOffset;
  30764. y = baseCoord;
  30765. width = columnWidth;
  30766. height = coord[1] - baseCoord;
  30767. if (Math.abs(height) < barMinHeight) {
  30768. // Include zero to has a positive bar
  30769. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30770. }
  30771. }
  30772. if (!isLarge) {
  30773. data.setItemLayout(dataIndex, {
  30774. x: x,
  30775. y: y,
  30776. width: width,
  30777. height: height
  30778. });
  30779. } else {
  30780. largePoints[idxOffset] = x;
  30781. largePoints[idxOffset + 1] = y;
  30782. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  30783. if (largeBackgroundPoints) {
  30784. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  30785. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  30786. largeBackgroundPoints[idxOffset + 2] = bgSize;
  30787. }
  30788. largeDataIndices[dataIndex] = dataIndex;
  30789. }
  30790. idxOffset += 3;
  30791. }
  30792. if (isLarge) {
  30793. data.setLayout({
  30794. largePoints: largePoints,
  30795. largeDataIndices: largeDataIndices,
  30796. largeBackgroundPoints: largeBackgroundPoints,
  30797. valueAxisHorizontal: isValueAxisH
  30798. });
  30799. }
  30800. }
  30801. };
  30802. }
  30803. };
  30804. }
  30805. function isOnCartesian(seriesModel) {
  30806. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30807. }
  30808. function isInLargeMode(seriesModel) {
  30809. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30810. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30811. function getValueAxisStart(baseAxis, valueAxis) {
  30812. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30813. }
  30814. var bisect = function (a, x, lo, hi) {
  30815. while (lo < hi) {
  30816. var mid = lo + hi >>> 1;
  30817. if (a[mid][1] < x) {
  30818. lo = mid + 1;
  30819. } else {
  30820. hi = mid;
  30821. }
  30822. }
  30823. return lo;
  30824. };
  30825. var TimeScale =
  30826. /** @class */
  30827. function (_super) {
  30828. __extends(TimeScale, _super);
  30829. function TimeScale(settings) {
  30830. var _this = _super.call(this, settings) || this;
  30831. _this.type = 'time';
  30832. return _this;
  30833. }
  30834. /**
  30835. * Get label is mainly for other components like dataZoom, tooltip.
  30836. */
  30837. TimeScale.prototype.getLabel = function (tick) {
  30838. var useUTC = this.getSetting('useUTC');
  30839. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  30840. };
  30841. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  30842. var isUTC = this.getSetting('useUTC');
  30843. var lang = this.getSetting('locale');
  30844. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  30845. };
  30846. /**
  30847. * @override
  30848. */
  30849. TimeScale.prototype.getTicks = function () {
  30850. var interval = this._interval;
  30851. var extent = this._extent;
  30852. var ticks = []; // If interval is 0, return [];
  30853. if (!interval) {
  30854. return ticks;
  30855. }
  30856. ticks.push({
  30857. value: extent[0],
  30858. level: 0
  30859. });
  30860. var useUTC = this.getSetting('useUTC');
  30861. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  30862. ticks = ticks.concat(innerTicks);
  30863. ticks.push({
  30864. value: extent[1],
  30865. level: 0
  30866. });
  30867. return ticks;
  30868. };
  30869. TimeScale.prototype.calcNiceExtent = function (opt) {
  30870. var extent = this._extent; // If extent start and end are same, expand them
  30871. if (extent[0] === extent[1]) {
  30872. // Expand extent
  30873. extent[0] -= ONE_DAY;
  30874. extent[1] += ONE_DAY;
  30875. } // If there are no data and extent are [Infinity, -Infinity]
  30876. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30877. var d = new Date();
  30878. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30879. extent[0] = extent[1] - ONE_DAY;
  30880. }
  30881. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30882. };
  30883. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  30884. approxTickNum = approxTickNum || 10;
  30885. var extent = this._extent;
  30886. var span = extent[1] - extent[0];
  30887. this._approxInterval = span / approxTickNum;
  30888. if (minInterval != null && this._approxInterval < minInterval) {
  30889. this._approxInterval = minInterval;
  30890. }
  30891. if (maxInterval != null && this._approxInterval > maxInterval) {
  30892. this._approxInterval = maxInterval;
  30893. }
  30894. var scaleIntervalsLen = scaleIntervals.length;
  30895. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  30896. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  30897. // We check one more level to avoid the ticks are to sparse in some case.
  30898. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  30899. };
  30900. TimeScale.prototype.parse = function (val) {
  30901. // val might be float.
  30902. return isNumber(val) ? val : +parseDate(val);
  30903. };
  30904. TimeScale.prototype.contain = function (val) {
  30905. return contain$1(this.parse(val), this._extent);
  30906. };
  30907. TimeScale.prototype.normalize = function (val) {
  30908. return normalize$1(this.parse(val), this._extent);
  30909. };
  30910. TimeScale.prototype.scale = function (val) {
  30911. return scale$2(val, this._extent);
  30912. };
  30913. TimeScale.type = 'time';
  30914. return TimeScale;
  30915. }(IntervalScale);
  30916. /**
  30917. * This implementation was originally copied from "d3.js"
  30918. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30919. * with some modifications made for this program.
  30920. * See the license statement at the head of this file.
  30921. */
  30922. var scaleIntervals = [// Format interval
  30923. ['second', ONE_SECOND], ['minute', ONE_MINUTE], ['hour', ONE_HOUR], ['quarter-day', ONE_HOUR * 6], ['half-day', ONE_HOUR * 12], ['day', ONE_DAY * 1.2], ['half-week', ONE_DAY * 3.5], ['week', ONE_DAY * 7], ['month', ONE_DAY * 31], ['quarter', ONE_DAY * 95], ['half-year', ONE_YEAR / 2], ['year', ONE_YEAR] // 1Y
  30924. ];
  30925. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  30926. var dateA = parseDate(valueA);
  30927. var dateB = parseDate(valueB);
  30928. var isSame = function (unit) {
  30929. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  30930. };
  30931. var isSameYear = function () {
  30932. return isSame('year');
  30933. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  30934. // const isSameQuater = () => isSameYear() && isSame('quarter');
  30935. var isSameMonth = function () {
  30936. return isSameYear() && isSame('month');
  30937. };
  30938. var isSameDay = function () {
  30939. return isSameMonth() && isSame('day');
  30940. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  30941. var isSameHour = function () {
  30942. return isSameDay() && isSame('hour');
  30943. };
  30944. var isSameMinute = function () {
  30945. return isSameHour() && isSame('minute');
  30946. };
  30947. var isSameSecond = function () {
  30948. return isSameMinute() && isSame('second');
  30949. };
  30950. var isSameMilliSecond = function () {
  30951. return isSameSecond() && isSame('millisecond');
  30952. };
  30953. switch (unit) {
  30954. case 'year':
  30955. return isSameYear();
  30956. case 'month':
  30957. return isSameMonth();
  30958. case 'day':
  30959. return isSameDay();
  30960. case 'hour':
  30961. return isSameHour();
  30962. case 'minute':
  30963. return isSameMinute();
  30964. case 'second':
  30965. return isSameSecond();
  30966. case 'millisecond':
  30967. return isSameMilliSecond();
  30968. }
  30969. } // const primaryUnitGetters = {
  30970. // year: fullYearGetterName(),
  30971. // month: monthGetterName(),
  30972. // day: dateGetterName(),
  30973. // hour: hoursGetterName(),
  30974. // minute: minutesGetterName(),
  30975. // second: secondsGetterName(),
  30976. // millisecond: millisecondsGetterName()
  30977. // };
  30978. // const primaryUnitUTCGetters = {
  30979. // year: fullYearGetterName(true),
  30980. // month: monthGetterName(true),
  30981. // day: dateGetterName(true),
  30982. // hour: hoursGetterName(true),
  30983. // minute: minutesGetterName(true),
  30984. // second: secondsGetterName(true),
  30985. // millisecond: millisecondsGetterName(true)
  30986. // };
  30987. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  30988. // step = step || 1;
  30989. // switch (getPrimaryTimeUnit(unitName)) {
  30990. // case 'year':
  30991. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  30992. // break;
  30993. // case 'month':
  30994. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  30995. // break;
  30996. // case 'day':
  30997. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  30998. // break;
  30999. // case 'hour':
  31000. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  31001. // break;
  31002. // case 'minute':
  31003. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  31004. // break;
  31005. // case 'second':
  31006. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  31007. // break;
  31008. // case 'millisecond':
  31009. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  31010. // break;
  31011. // }
  31012. // return date.getTime();
  31013. // }
  31014. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  31015. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  31016. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  31017. function getDateInterval(approxInterval, daysInMonth) {
  31018. approxInterval /= ONE_DAY;
  31019. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick between two months.
  31020. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  31021. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  31022. }
  31023. function getMonthInterval(approxInterval) {
  31024. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  31025. approxInterval /= APPROX_ONE_MONTH;
  31026. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  31027. }
  31028. function getHourInterval(approxInterval) {
  31029. approxInterval /= ONE_HOUR;
  31030. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  31031. }
  31032. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  31033. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  31034. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  31035. }
  31036. function getMillisecondsInterval(approxInterval) {
  31037. return nice(approxInterval, true);
  31038. }
  31039. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  31040. var outDate = new Date(date);
  31041. switch (getPrimaryTimeUnit(unitName)) {
  31042. case 'year':
  31043. case 'month':
  31044. outDate[monthSetterName(isUTC)](0);
  31045. case 'day':
  31046. outDate[dateSetterName(isUTC)](1);
  31047. case 'hour':
  31048. outDate[hoursSetterName(isUTC)](0);
  31049. case 'minute':
  31050. outDate[minutesSetterName(isUTC)](0);
  31051. case 'second':
  31052. outDate[secondsSetterName(isUTC)](0);
  31053. outDate[millisecondsSetterName(isUTC)](0);
  31054. }
  31055. return outDate.getTime();
  31056. }
  31057. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  31058. var safeLimit = 10000;
  31059. var unitNames = timeUnits;
  31060. var iter = 0;
  31061. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  31062. var date = new Date(minTimestamp);
  31063. var dateTime = minTimestamp;
  31064. var d = date[getMethodName](); // if (isDate) {
  31065. // d -= 1; // Starts with 0; PENDING
  31066. // }
  31067. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  31068. out.push({
  31069. value: dateTime
  31070. });
  31071. d += interval;
  31072. date[setMethodName](d);
  31073. dateTime = date.getTime();
  31074. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  31075. out.push({
  31076. value: dateTime,
  31077. notAdd: true
  31078. });
  31079. }
  31080. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  31081. var newAddedTicks = [];
  31082. var isFirstLevel = !lastLevelTicks.length;
  31083. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  31084. return;
  31085. }
  31086. if (isFirstLevel) {
  31087. lastLevelTicks = [{
  31088. // TODO Optimize. Not include so may ticks.
  31089. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  31090. }, {
  31091. value: extent[1]
  31092. }];
  31093. }
  31094. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  31095. var startTick = lastLevelTicks[i].value;
  31096. var endTick = lastLevelTicks[i + 1].value;
  31097. if (startTick === endTick) {
  31098. continue;
  31099. }
  31100. var interval = void 0;
  31101. var getterName = void 0;
  31102. var setterName = void 0;
  31103. var isDate = false;
  31104. switch (unitName) {
  31105. case 'year':
  31106. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  31107. getterName = fullYearGetterName(isUTC);
  31108. setterName = fullYearSetterName(isUTC);
  31109. break;
  31110. case 'half-year':
  31111. case 'quarter':
  31112. case 'month':
  31113. interval = getMonthInterval(approxInterval);
  31114. getterName = monthGetterName(isUTC);
  31115. setterName = monthSetterName(isUTC);
  31116. break;
  31117. case 'week': // PENDING If week is added. Ignore day.
  31118. case 'half-week':
  31119. case 'day':
  31120. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  31121. getterName = dateGetterName(isUTC);
  31122. setterName = dateSetterName(isUTC);
  31123. isDate = true;
  31124. break;
  31125. case 'half-day':
  31126. case 'quarter-day':
  31127. case 'hour':
  31128. interval = getHourInterval(approxInterval);
  31129. getterName = hoursGetterName(isUTC);
  31130. setterName = hoursSetterName(isUTC);
  31131. break;
  31132. case 'minute':
  31133. interval = getMinutesAndSecondsInterval(approxInterval, true);
  31134. getterName = minutesGetterName(isUTC);
  31135. setterName = minutesSetterName(isUTC);
  31136. break;
  31137. case 'second':
  31138. interval = getMinutesAndSecondsInterval(approxInterval, false);
  31139. getterName = secondsGetterName(isUTC);
  31140. setterName = secondsSetterName(isUTC);
  31141. break;
  31142. case 'millisecond':
  31143. interval = getMillisecondsInterval(approxInterval);
  31144. getterName = millisecondsGetterName(isUTC);
  31145. setterName = millisecondsSetterName(isUTC);
  31146. break;
  31147. }
  31148. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  31149. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  31150. // Add nearest years to the left extent.
  31151. levelTicks.unshift({
  31152. value: levelTicks[0].value - interval
  31153. });
  31154. }
  31155. }
  31156. for (var i = 0; i < newAddedTicks.length; i++) {
  31157. levelTicks.push(newAddedTicks[i]);
  31158. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  31159. return newAddedTicks;
  31160. }
  31161. var levelsTicks = [];
  31162. var currentLevelTicks = [];
  31163. var tickCount = 0;
  31164. var lastLevelTickCount = 0;
  31165. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  31166. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  31167. if (!isPrimaryTimeUnit(unitNames[i])) {
  31168. // TODO
  31169. continue;
  31170. }
  31171. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  31172. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  31173. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  31174. if (currentLevelTicks.length) {
  31175. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  31176. currentLevelTicks.sort(function (a, b) {
  31177. return a.value - b.value;
  31178. });
  31179. var levelTicksRemoveDuplicated = [];
  31180. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  31181. var tickValue = currentLevelTicks[i_1].value;
  31182. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  31183. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  31184. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  31185. tickCount++;
  31186. }
  31187. }
  31188. }
  31189. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  31190. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  31191. break;
  31192. } // Only treat primary time unit as one level.
  31193. levelsTicks.push(levelTicksRemoveDuplicated);
  31194. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  31195. break;
  31196. }
  31197. } // Reset if next unitName is primary
  31198. currentLevelTicks = [];
  31199. }
  31200. }
  31201. if ("development" !== 'production') {
  31202. if (iter >= safeLimit) {
  31203. warn('Exceed safe limit.');
  31204. }
  31205. }
  31206. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  31207. return filter(levelTicks, function (tick) {
  31208. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  31209. });
  31210. }), function (levelTicks) {
  31211. return levelTicks.length > 0;
  31212. });
  31213. var ticks = [];
  31214. var maxLevel = levelsTicksInExtent.length - 1;
  31215. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  31216. var levelTicks = levelsTicksInExtent[i];
  31217. for (var k = 0; k < levelTicks.length; ++k) {
  31218. ticks.push({
  31219. value: levelTicks[k].value,
  31220. level: maxLevel - i
  31221. });
  31222. }
  31223. }
  31224. ticks.sort(function (a, b) {
  31225. return a.value - b.value;
  31226. }); // Remove duplicates
  31227. var result = [];
  31228. for (var i = 0; i < ticks.length; ++i) {
  31229. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  31230. result.push(ticks[i]);
  31231. }
  31232. }
  31233. return result;
  31234. }
  31235. Scale.registerClass(TimeScale);
  31236. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  31237. var intervalScaleProto = IntervalScale.prototype;
  31238. var roundingErrorFix = round;
  31239. var mathFloor = Math.floor;
  31240. var mathCeil = Math.ceil;
  31241. var mathPow$1 = Math.pow;
  31242. var mathLog = Math.log;
  31243. var LogScale =
  31244. /** @class */
  31245. function (_super) {
  31246. __extends(LogScale, _super);
  31247. function LogScale() {
  31248. var _this = _super !== null && _super.apply(this, arguments) || this;
  31249. _this.type = 'log';
  31250. _this.base = 10;
  31251. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  31252. _this._interval = 0;
  31253. return _this;
  31254. }
  31255. /**
  31256. * @param Whether expand the ticks to niced extent.
  31257. */
  31258. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  31259. var originalScale = this._originalScale;
  31260. var extent = this._extent;
  31261. var originalExtent = originalScale.getExtent();
  31262. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  31263. return map(ticks, function (tick) {
  31264. var val = tick.value;
  31265. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  31266. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  31267. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  31268. return {
  31269. value: powVal
  31270. };
  31271. }, this);
  31272. };
  31273. LogScale.prototype.setExtent = function (start, end) {
  31274. var base = mathLog(this.base); // log(-Infinity) is NaN, so safe guard here
  31275. start = mathLog(Math.max(0, start)) / base;
  31276. end = mathLog(Math.max(0, end)) / base;
  31277. intervalScaleProto.setExtent.call(this, start, end);
  31278. };
  31279. /**
  31280. * @return {number} end
  31281. */
  31282. LogScale.prototype.getExtent = function () {
  31283. var base = this.base;
  31284. var extent = scaleProto.getExtent.call(this);
  31285. extent[0] = mathPow$1(base, extent[0]);
  31286. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  31287. var originalScale = this._originalScale;
  31288. var originalExtent = originalScale.getExtent();
  31289. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  31290. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  31291. return extent;
  31292. };
  31293. LogScale.prototype.unionExtent = function (extent) {
  31294. this._originalScale.unionExtent(extent);
  31295. var base = this.base;
  31296. extent[0] = mathLog(extent[0]) / mathLog(base);
  31297. extent[1] = mathLog(extent[1]) / mathLog(base);
  31298. scaleProto.unionExtent.call(this, extent);
  31299. };
  31300. LogScale.prototype.unionExtentFromData = function (data, dim) {
  31301. // TODO
  31302. // filter value that <= 0
  31303. this.unionExtent(data.getApproximateExtent(dim));
  31304. };
  31305. /**
  31306. * Update interval and extent of intervals for nice ticks
  31307. * @param approxTickNum default 10 Given approx tick number
  31308. */
  31309. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  31310. approxTickNum = approxTickNum || 10;
  31311. var extent = this._extent;
  31312. var span = extent[1] - extent[0];
  31313. if (span === Infinity || span <= 0) {
  31314. return;
  31315. }
  31316. var interval = quantity(span);
  31317. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  31318. if (err <= 0.5) {
  31319. interval *= 10;
  31320. } // Interval should be integer
  31321. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  31322. interval *= 10;
  31323. }
  31324. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  31325. this._interval = interval;
  31326. this._niceExtent = niceExtent;
  31327. };
  31328. LogScale.prototype.calcNiceExtent = function (opt) {
  31329. intervalScaleProto.calcNiceExtent.call(this, opt);
  31330. this._fixMin = opt.fixMin;
  31331. this._fixMax = opt.fixMax;
  31332. };
  31333. LogScale.prototype.parse = function (val) {
  31334. return val;
  31335. };
  31336. LogScale.prototype.contain = function (val) {
  31337. val = mathLog(val) / mathLog(this.base);
  31338. return contain$1(val, this._extent);
  31339. };
  31340. LogScale.prototype.normalize = function (val) {
  31341. val = mathLog(val) / mathLog(this.base);
  31342. return normalize$1(val, this._extent);
  31343. };
  31344. LogScale.prototype.scale = function (val) {
  31345. val = scale$2(val, this._extent);
  31346. return mathPow$1(this.base, val);
  31347. };
  31348. LogScale.type = 'log';
  31349. return LogScale;
  31350. }(Scale);
  31351. var proto = LogScale.prototype;
  31352. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  31353. proto.getLabel = intervalScaleProto.getLabel;
  31354. function fixRoundingError(val, originalVal) {
  31355. return roundingErrorFix(val, getPrecision(originalVal));
  31356. }
  31357. Scale.registerClass(LogScale);
  31358. var ScaleRawExtentInfo =
  31359. /** @class */
  31360. function () {
  31361. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31362. originalExtent) {
  31363. this._prepareParams(scale, model, originalExtent);
  31364. }
  31365. /**
  31366. * Parameters depending on outside (like model, user callback)
  31367. * are prepared and fixed here.
  31368. */
  31369. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  31370. dataExtent) {
  31371. if (dataExtent[1] < dataExtent[0]) {
  31372. dataExtent = [NaN, NaN];
  31373. }
  31374. this._dataMin = dataExtent[0];
  31375. this._dataMax = dataExtent[1];
  31376. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  31377. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  31378. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  31379. if (isFunction(modelMinRaw)) {
  31380. // This callback always provides users the full data extent (before data is filtered).
  31381. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  31382. min: dataExtent[0],
  31383. max: dataExtent[1]
  31384. }));
  31385. } else if (modelMinRaw !== 'dataMin') {
  31386. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  31387. }
  31388. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  31389. if (isFunction(modelMaxRaw)) {
  31390. // This callback always provides users the full data extent (before data is filtered).
  31391. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  31392. min: dataExtent[0],
  31393. max: dataExtent[1]
  31394. }));
  31395. } else if (modelMaxRaw !== 'dataMax') {
  31396. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  31397. }
  31398. if (isOrdinal) {
  31399. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  31400. // and progressive rendering is using, here the category result might just only contain
  31401. // the processed chunk rather than the entire result.
  31402. this._axisDataLen = model.getCategories().length;
  31403. } else {
  31404. var boundaryGap = model.get('boundaryGap');
  31405. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  31406. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  31407. if ("development" !== 'production') {
  31408. console.warn('Boolean type for boundaryGap is only ' + 'allowed for ordinal axis. Please use string in ' + 'percentage instead, e.g., "20%". Currently, ' + 'boundaryGap is set to be 0.');
  31409. }
  31410. this._boundaryGapInner = [0, 0];
  31411. } else {
  31412. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  31413. }
  31414. }
  31415. };
  31416. /**
  31417. * Calculate extent by prepared parameters.
  31418. * This method has no external dependency and can be called duplicatedly,
  31419. * getting the same result.
  31420. * If parameters changed, should call this method to recalcuate.
  31421. */
  31422. ScaleRawExtentInfo.prototype.calculate = function () {
  31423. // Notice: When min/max is not set (that is, when there are null/undefined,
  31424. // which is the most common case), these cases should be ensured:
  31425. // (1) For 'ordinal', show all axis.data.
  31426. // (2) For others:
  31427. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  31428. // disabled).
  31429. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  31430. // be the result that originalExtent enlarged by boundaryGap.
  31431. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  31432. var isOrdinal = this._isOrdinal;
  31433. var dataMin = this._dataMin;
  31434. var dataMax = this._dataMax;
  31435. var axisDataLen = this._axisDataLen;
  31436. var boundaryGapInner = this._boundaryGapInner;
  31437. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  31438. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  31439. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  31440. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  31441. var minFixed = min != null;
  31442. var maxFixed = max != null;
  31443. if (min == null) {
  31444. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  31445. }
  31446. if (max == null) {
  31447. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  31448. }
  31449. (min == null || !isFinite(min)) && (min = NaN);
  31450. (max == null || !isFinite(max)) && (max = NaN);
  31451. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  31452. if (this._needCrossZero) {
  31453. // Axis is over zero and min is not set
  31454. if (min > 0 && max > 0 && !minFixed) {
  31455. min = 0; // minFixed = true;
  31456. } // Axis is under zero and max is not set
  31457. if (min < 0 && max < 0 && !maxFixed) {
  31458. max = 0; // maxFixed = true;
  31459. } // PENDING:
  31460. // When `needCrossZero` and all data is positive/negative, should it be ensured
  31461. // that the results processed by boundaryGap are positive/negative?
  31462. // If so, here `minFixed`/`maxFixed` need to be set.
  31463. }
  31464. var determinedMin = this._determinedMin;
  31465. var determinedMax = this._determinedMax;
  31466. if (determinedMin != null) {
  31467. min = determinedMin;
  31468. minFixed = true;
  31469. }
  31470. if (determinedMax != null) {
  31471. max = determinedMax;
  31472. maxFixed = true;
  31473. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  31474. // `NaN` means min/max axis is blank.
  31475. return {
  31476. min: min,
  31477. max: max,
  31478. minFixed: minFixed,
  31479. maxFixed: maxFixed,
  31480. isBlank: isBlank
  31481. };
  31482. };
  31483. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  31484. if ("development" !== 'production') {
  31485. assert(!this.frozen);
  31486. }
  31487. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  31488. };
  31489. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  31490. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  31491. if ("development" !== 'production') {
  31492. assert(!this.frozen // Earse them usually means logic flaw.
  31493. && this[attr] == null);
  31494. }
  31495. this[attr] = val;
  31496. };
  31497. ScaleRawExtentInfo.prototype.freeze = function () {
  31498. // @ts-ignore
  31499. this.frozen = true;
  31500. };
  31501. return ScaleRawExtentInfo;
  31502. }();
  31503. var DETERMINED_MIN_MAX_ATTR = {
  31504. min: '_determinedMin',
  31505. max: '_determinedMax'
  31506. };
  31507. var DATA_MIN_MAX_ATTR = {
  31508. min: '_dataMin',
  31509. max: '_dataMax'
  31510. };
  31511. /**
  31512. * Get scale min max and related info only depends on model settings.
  31513. * This method can be called after coordinate system created.
  31514. * For example, in data processing stage.
  31515. *
  31516. * Scale extent info probably be required multiple times during a workflow.
  31517. * For example:
  31518. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  31519. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  31520. * (3) `coordSys.update` use it to finally decide the scale extent.
  31521. * But the callback of `min`/`max` should not be called multiple times.
  31522. * The code below should not be implemented repeatedly either.
  31523. * So we cache the result in the scale instance, which will be recreated at the beginning
  31524. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  31525. */
  31526. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31527. originalExtent) {
  31528. // Do not permit to recreate.
  31529. var rawExtentInfo = scale.rawExtentInfo;
  31530. if (rawExtentInfo) {
  31531. return rawExtentInfo;
  31532. }
  31533. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  31534. scale.rawExtentInfo = rawExtentInfo;
  31535. return rawExtentInfo;
  31536. }
  31537. function parseAxisModelMinMax(scale, minMax) {
  31538. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  31539. }
  31540. /**
  31541. * Get axis scale extent before niced.
  31542. * Item of returned array can only be number (including Infinity and NaN).
  31543. *
  31544. * Caution:
  31545. * Precondition of calling this method:
  31546. * The scale extent has been initialized using series data extent via
  31547. * `scale.setExtent` or `scale.unionExtentFromData`;
  31548. */
  31549. function getScaleExtent(scale, model) {
  31550. var scaleType = scale.type;
  31551. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  31552. scale.setBlank(rawExtentResult.isBlank);
  31553. var min = rawExtentResult.min;
  31554. var max = rawExtentResult.max; // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  31555. // is base axis
  31556. // FIXME
  31557. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31558. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31559. // Should not depend on series type `bar`?
  31560. // (3) Fix that might overlap when using dataZoom.
  31561. // (4) Consider other chart types using `barGrid`?
  31562. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31563. var ecModel = model.ecModel;
  31564. if (ecModel && scaleType === 'time'
  31565. /* || scaleType === 'interval' */
  31566. ) {
  31567. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31568. var isBaseAxisAndHasBarSeries_1 = false;
  31569. each(barSeriesModels, function (seriesModel) {
  31570. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  31571. });
  31572. if (isBaseAxisAndHasBarSeries_1) {
  31573. // Calculate placement of bars on axis. TODO should be decoupled
  31574. // with barLayout
  31575. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  31576. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31577. min = adjustedScale.min;
  31578. max = adjustedScale.max;
  31579. }
  31580. }
  31581. return {
  31582. extent: [min, max],
  31583. // "fix" means "fixed", the value should not be
  31584. // changed in the subsequent steps.
  31585. fixMin: rawExtentResult.minFixed,
  31586. fixMax: rawExtentResult.maxFixed
  31587. };
  31588. }
  31589. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  31590. barWidthAndOffset) {
  31591. // Get Axis Length
  31592. var axisExtent = model.axis.getExtent();
  31593. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  31594. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31595. if (barsOnCurrentAxis === undefined) {
  31596. return {
  31597. min: min,
  31598. max: max
  31599. };
  31600. }
  31601. var minOverflow = Infinity;
  31602. each(barsOnCurrentAxis, function (item) {
  31603. minOverflow = Math.min(item.offset, minOverflow);
  31604. });
  31605. var maxOverflow = -Infinity;
  31606. each(barsOnCurrentAxis, function (item) {
  31607. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31608. });
  31609. minOverflow = Math.abs(minOverflow);
  31610. maxOverflow = Math.abs(maxOverflow);
  31611. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  31612. var oldRange = max - min;
  31613. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  31614. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  31615. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31616. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31617. return {
  31618. min: min,
  31619. max: max
  31620. };
  31621. } // Precondition of calling this method:
  31622. // The scale extent has been initialized using series data extent via
  31623. // `scale.setExtent` or `scale.unionExtentFromData`;
  31624. function niceScaleExtent(scale, inModel) {
  31625. var model = inModel;
  31626. var extentInfo = getScaleExtent(scale, model);
  31627. var extent = extentInfo.extent;
  31628. var splitNumber = model.get('splitNumber');
  31629. if (scale instanceof LogScale) {
  31630. scale.base = model.get('logBase');
  31631. }
  31632. var scaleType = scale.type;
  31633. var interval = model.get('interval');
  31634. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  31635. scale.setExtent(extent[0], extent[1]);
  31636. scale.calcNiceExtent({
  31637. splitNumber: splitNumber,
  31638. fixMin: extentInfo.fixMin,
  31639. fixMax: extentInfo.fixMax,
  31640. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  31641. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  31642. }); // If some one specified the min, max. And the default calculated interval
  31643. // is not good enough. He can specify the interval. It is often appeared
  31644. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  31645. // to be 60.
  31646. // FIXME
  31647. if (interval != null) {
  31648. scale.setInterval && scale.setInterval(interval);
  31649. }
  31650. }
  31651. /**
  31652. * @param axisType Default retrieve from model.type
  31653. */
  31654. function createScaleByModel(model, axisType) {
  31655. axisType = axisType || model.get('type');
  31656. if (axisType) {
  31657. switch (axisType) {
  31658. // Buildin scale
  31659. case 'category':
  31660. return new OrdinalScale({
  31661. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  31662. extent: [Infinity, -Infinity]
  31663. });
  31664. case 'time':
  31665. return new TimeScale({
  31666. locale: model.ecModel.getLocaleModel(),
  31667. useUTC: model.ecModel.get('useUTC')
  31668. });
  31669. default:
  31670. // case 'value'/'interval', 'log', or others.
  31671. return new (Scale.getClass(axisType) || IntervalScale)();
  31672. }
  31673. }
  31674. }
  31675. /**
  31676. * Check if the axis cross 0
  31677. */
  31678. function ifAxisCrossZero(axis) {
  31679. var dataExtent = axis.scale.getExtent();
  31680. var min = dataExtent[0];
  31681. var max = dataExtent[1];
  31682. return !(min > 0 && max > 0 || min < 0 && max < 0);
  31683. }
  31684. /**
  31685. * @param axis
  31686. * @return Label formatter function.
  31687. * param: {number} tickValue,
  31688. * param: {number} idx, the index in all ticks.
  31689. * If category axis, this param is not required.
  31690. * return: {string} label string.
  31691. */
  31692. function makeLabelFormatter(axis) {
  31693. var labelFormatter = axis.getLabelModel().get('formatter');
  31694. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31695. if (axis.scale.type === 'time') {
  31696. return function (tpl) {
  31697. return function (tick, idx) {
  31698. return axis.scale.getFormattedLabel(tick, idx, tpl);
  31699. };
  31700. }(labelFormatter);
  31701. } else if (isString(labelFormatter)) {
  31702. return function (tpl) {
  31703. return function (tick) {
  31704. // For category axis, get raw value; for numeric axis,
  31705. // get formatted label like '1,333,444'.
  31706. var label = axis.scale.getLabel(tick);
  31707. var text = tpl.replace('{value}', label != null ? label : '');
  31708. return text;
  31709. };
  31710. }(labelFormatter);
  31711. } else if (isFunction(labelFormatter)) {
  31712. return function (cb) {
  31713. return function (tick, idx) {
  31714. // The original intention of `idx` is "the index of the tick in all ticks".
  31715. // But the previous implementation of category axis do not consider the
  31716. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31717. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31718. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31719. // the definition here for back compatibility.
  31720. if (categoryTickStart != null) {
  31721. idx = tick.value - categoryTickStart;
  31722. }
  31723. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  31724. level: tick.level
  31725. } : null);
  31726. };
  31727. }(labelFormatter);
  31728. } else {
  31729. return function (tick) {
  31730. return axis.scale.getLabel(tick);
  31731. };
  31732. }
  31733. }
  31734. function getAxisRawValue(axis, tick) {
  31735. // In category axis with data zoom, tick is not the original
  31736. // index of axis.data. So tick should not be exposed to user
  31737. // in category axis.
  31738. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  31739. }
  31740. /**
  31741. * @param axis
  31742. * @return Be null/undefined if no labels.
  31743. */
  31744. function estimateLabelUnionRect(axis) {
  31745. var axisModel = axis.model;
  31746. var scale = axis.scale;
  31747. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  31748. return;
  31749. }
  31750. var realNumberScaleTicks;
  31751. var tickCount;
  31752. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  31753. if (scale instanceof OrdinalScale) {
  31754. tickCount = scale.count();
  31755. } else {
  31756. realNumberScaleTicks = scale.getTicks();
  31757. tickCount = realNumberScaleTicks.length;
  31758. }
  31759. var axisLabelModel = axis.getLabelModel();
  31760. var labelFormatter = makeLabelFormatter(axis);
  31761. var rect;
  31762. var step = 1; // Simple optimization for large amount of labels
  31763. if (tickCount > 40) {
  31764. step = Math.ceil(tickCount / 40);
  31765. }
  31766. for (var i = 0; i < tickCount; i += step) {
  31767. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  31768. value: categoryScaleExtent[0] + i
  31769. };
  31770. var label = labelFormatter(tick, i);
  31771. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31772. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31773. rect ? rect.union(singleRect) : rect = singleRect;
  31774. }
  31775. return rect;
  31776. }
  31777. function rotateTextRect(textRect, rotate) {
  31778. var rotateRadians = rotate * Math.PI / 180;
  31779. var beforeWidth = textRect.width;
  31780. var beforeHeight = textRect.height;
  31781. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  31782. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  31783. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  31784. return rotatedRect;
  31785. }
  31786. /**
  31787. * @param model axisLabelModel or axisTickModel
  31788. * @return {number|String} Can be null|'auto'|number|function
  31789. */
  31790. function getOptionCategoryInterval(model) {
  31791. var interval = model.get('interval');
  31792. return interval == null ? 'auto' : interval;
  31793. }
  31794. /**
  31795. * Set `categoryInterval` as 0 implicitly indicates that
  31796. * show all labels regardless of overlap.
  31797. * @param {Object} axis axisModel.axis
  31798. */
  31799. function shouldShowAllLabels(axis) {
  31800. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31801. }
  31802. function getDataDimensionsOnAxis(data, axisDim) {
  31803. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  31804. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  31805. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  31806. // there has been stacked result dim?
  31807. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  31808. // For example, the extent of the original dimension
  31809. // is [0.1, 0.5], the extent of the `stackResultDimension`
  31810. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  31811. // because there is no graphic corresponding to [0.1, 0.5].
  31812. // See the case in `test/area-stack.html` `main1`, where area line
  31813. // stack needs `yAxis` not start from 0.
  31814. dataDimMap[getStackedDimension(data, dataDim)] = true;
  31815. });
  31816. return keys(dataDimMap);
  31817. }
  31818. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  31819. if (data) {
  31820. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  31821. var seriesExtent = data.getApproximateExtent(dim);
  31822. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  31823. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  31824. });
  31825. }
  31826. }
  31827. /*
  31828. * Licensed to the Apache Software Foundation (ASF) under one
  31829. * or more contributor license agreements. See the NOTICE file
  31830. * distributed with this work for additional information
  31831. * regarding copyright ownership. The ASF licenses this file
  31832. * to you under the Apache License, Version 2.0 (the
  31833. * "License"); you may not use this file except in compliance
  31834. * with the License. You may obtain a copy of the License at
  31835. *
  31836. * http://www.apache.org/licenses/LICENSE-2.0
  31837. *
  31838. * Unless required by applicable law or agreed to in writing,
  31839. * software distributed under the License is distributed on an
  31840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31841. * KIND, either express or implied. See the License for the
  31842. * specific language governing permissions and limitations
  31843. * under the License.
  31844. */
  31845. /**
  31846. * AUTO-GENERATED FILE. DO NOT MODIFY.
  31847. */
  31848. /*
  31849. * Licensed to the Apache Software Foundation (ASF) under one
  31850. * or more contributor license agreements. See the NOTICE file
  31851. * distributed with this work for additional information
  31852. * regarding copyright ownership. The ASF licenses this file
  31853. * to you under the Apache License, Version 2.0 (the
  31854. * "License"); you may not use this file except in compliance
  31855. * with the License. You may obtain a copy of the License at
  31856. *
  31857. * http://www.apache.org/licenses/LICENSE-2.0
  31858. *
  31859. * Unless required by applicable law or agreed to in writing,
  31860. * software distributed under the License is distributed on an
  31861. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31862. * KIND, either express or implied. See the License for the
  31863. * specific language governing permissions and limitations
  31864. * under the License.
  31865. */
  31866. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  31867. var AxisModelCommonMixin =
  31868. /** @class */
  31869. function () {
  31870. function AxisModelCommonMixin() {}
  31871. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  31872. var option = this.option;
  31873. return !option.scale;
  31874. };
  31875. /**
  31876. * Should be implemented by each axis model if necessary.
  31877. * @return coordinate system model
  31878. */
  31879. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  31880. return;
  31881. };
  31882. return AxisModelCommonMixin;
  31883. }();
  31884. /**
  31885. * Create a multi dimension List structure from seriesModel.
  31886. */
  31887. function createList(seriesModel) {
  31888. return createSeriesData(null, seriesModel);
  31889. } // export function createGraph(seriesModel) {
  31890. var dataStack$1 = {
  31891. isDimensionStacked: isDimensionStacked,
  31892. enableDataStack: enableDataStack,
  31893. getStackedDimension: getStackedDimension
  31894. };
  31895. /**
  31896. * Create scale
  31897. * @param {Array.<number>} dataExtent
  31898. * @param {Object|module:echarts/Model} option If `optoin.type`
  31899. * is secified, it can only be `'value'` currently.
  31900. */
  31901. function createScale(dataExtent, option) {
  31902. var axisModel = option;
  31903. if (!(option instanceof Model)) {
  31904. axisModel = new Model(option); // FIXME
  31905. // Currently AxisModelCommonMixin has nothing to do with the
  31906. // the requirements of `axisHelper.createScaleByModel`. For
  31907. // example the methods `getCategories` and `getOrdinalMeta`
  31908. // are required for `'category'` axis, and ecModel is required
  31909. // for `'time'` axis. But occasionally echarts-gl happened
  31910. // to only use `'value'` axis.
  31911. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  31912. }
  31913. var scale = createScaleByModel(axisModel);
  31914. scale.setExtent(dataExtent[0], dataExtent[1]);
  31915. niceScaleExtent(scale, axisModel);
  31916. return scale;
  31917. }
  31918. /**
  31919. * Mixin common methods to axis model,
  31920. *
  31921. * Include methods
  31922. * `getFormattedLabels() => Array.<string>`
  31923. * `getCategories() => Array.<string>`
  31924. * `getMin(origin: boolean) => number`
  31925. * `getMax(origin: boolean) => number`
  31926. * `getNeedCrossZero() => boolean`
  31927. */
  31928. function mixinAxisModelCommonMethods(Model) {
  31929. mixin(Model, AxisModelCommonMixin);
  31930. }
  31931. function createTextStyle$1(textStyleModel, opts) {
  31932. opts = opts || {};
  31933. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  31934. }
  31935. var helper = /*#__PURE__*/Object.freeze({
  31936. __proto__: null,
  31937. createList: createList,
  31938. getLayoutRect: getLayoutRect,
  31939. dataStack: dataStack$1,
  31940. createScale: createScale,
  31941. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31942. getECData: getECData,
  31943. createTextStyle: createTextStyle$1,
  31944. createDimensions: createDimensions,
  31945. createSymbol: createSymbol,
  31946. enableHoverEmphasis: enableHoverEmphasis
  31947. });
  31948. var EPSILON$4 = 1e-8;
  31949. function isAroundEqual$1(a, b) {
  31950. return Math.abs(a - b) < EPSILON$4;
  31951. }
  31952. function contain$2(points, x, y) {
  31953. var w = 0;
  31954. var p = points[0];
  31955. if (!p) {
  31956. return false;
  31957. }
  31958. for (var i = 1; i < points.length; i++) {
  31959. var p2 = points[i];
  31960. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31961. p = p2;
  31962. }
  31963. var p0 = points[0];
  31964. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31965. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31966. }
  31967. return w !== 0;
  31968. }
  31969. var TMP_TRANSFORM = [];
  31970. function transformPoints(points, transform) {
  31971. for (var p = 0; p < points.length; p++) {
  31972. applyTransform(points[p], points[p], transform);
  31973. }
  31974. }
  31975. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  31976. for (var i = 0; i < points.length; i++) {
  31977. var p = points[i];
  31978. if (projection) {
  31979. // projection may return null point.
  31980. p = projection.project(p);
  31981. }
  31982. if (p && isFinite(p[0]) && isFinite(p[1])) {
  31983. min(min$1, min$1, p);
  31984. max(max$1, max$1, p);
  31985. }
  31986. }
  31987. }
  31988. function centroid(points) {
  31989. var signedArea = 0;
  31990. var cx = 0;
  31991. var cy = 0;
  31992. var len = points.length;
  31993. var x0 = points[len - 1][0];
  31994. var y0 = points[len - 1][1]; // Polygon should been closed.
  31995. for (var i = 0; i < len; i++) {
  31996. var x1 = points[i][0];
  31997. var y1 = points[i][1];
  31998. var a = x0 * y1 - x1 * y0;
  31999. signedArea += a;
  32000. cx += (x0 + x1) * a;
  32001. cy += (y0 + y1) * a;
  32002. x0 = x1;
  32003. y0 = y1;
  32004. }
  32005. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  32006. }
  32007. var Region =
  32008. /** @class */
  32009. function () {
  32010. function Region(name) {
  32011. this.name = name;
  32012. }
  32013. Region.prototype.setCenter = function (center) {
  32014. this._center = center;
  32015. };
  32016. /**
  32017. * Get center point in data unit. That is,
  32018. * for GeoJSONRegion, the unit is lat/lng,
  32019. * for GeoSVGRegion, the unit is SVG local coord.
  32020. */
  32021. Region.prototype.getCenter = function () {
  32022. var center = this._center;
  32023. if (!center) {
  32024. // In most cases there are no need to calculate this center.
  32025. // So calculate only when called.
  32026. center = this._center = this.calcCenter();
  32027. }
  32028. return center;
  32029. };
  32030. return Region;
  32031. }();
  32032. var GeoJSONPolygonGeometry =
  32033. /** @class */
  32034. function () {
  32035. function GeoJSONPolygonGeometry(exterior, interiors) {
  32036. this.type = 'polygon';
  32037. this.exterior = exterior;
  32038. this.interiors = interiors;
  32039. }
  32040. return GeoJSONPolygonGeometry;
  32041. }();
  32042. var GeoJSONLineStringGeometry =
  32043. /** @class */
  32044. function () {
  32045. function GeoJSONLineStringGeometry(points) {
  32046. this.type = 'linestring';
  32047. this.points = points;
  32048. }
  32049. return GeoJSONLineStringGeometry;
  32050. }();
  32051. var GeoJSONRegion =
  32052. /** @class */
  32053. function (_super) {
  32054. __extends(GeoJSONRegion, _super);
  32055. function GeoJSONRegion(name, geometries, cp) {
  32056. var _this = _super.call(this, name) || this;
  32057. _this.type = 'geoJSON';
  32058. _this.geometries = geometries;
  32059. _this._center = cp && [cp[0], cp[1]];
  32060. return _this;
  32061. }
  32062. GeoJSONRegion.prototype.calcCenter = function () {
  32063. var geometries = this.geometries;
  32064. var largestGeo;
  32065. var largestGeoSize = 0;
  32066. for (var i = 0; i < geometries.length; i++) {
  32067. var geo = geometries[i];
  32068. var exterior = geo.exterior; // Simple trick to use points count instead of polygon area as region size.
  32069. // Ignore linestring
  32070. var size = exterior && exterior.length;
  32071. if (size > largestGeoSize) {
  32072. largestGeo = geo;
  32073. largestGeoSize = size;
  32074. }
  32075. }
  32076. if (largestGeo) {
  32077. return centroid(largestGeo.exterior);
  32078. } // from bounding rect by default.
  32079. var rect = this.getBoundingRect();
  32080. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32081. };
  32082. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  32083. var rect = this._rect; // Always recalculate if using projection.
  32084. if (rect && !projection) {
  32085. return rect;
  32086. }
  32087. var min = [Infinity, Infinity];
  32088. var max = [-Infinity, -Infinity];
  32089. var geometries = this.geometries;
  32090. each(geometries, function (geo) {
  32091. if (geo.type === 'polygon') {
  32092. // Doesn't consider hole
  32093. updateBBoxFromPoints(geo.exterior, min, max, projection);
  32094. } else {
  32095. each(geo.points, function (points) {
  32096. updateBBoxFromPoints(points, min, max, projection);
  32097. });
  32098. }
  32099. }); // Normalie invalid bounding.
  32100. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  32101. min[0] = min[1] = max[0] = max[1] = 0;
  32102. }
  32103. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  32104. if (!projection) {
  32105. this._rect = rect;
  32106. }
  32107. return rect;
  32108. };
  32109. GeoJSONRegion.prototype.contain = function (coord) {
  32110. var rect = this.getBoundingRect();
  32111. var geometries = this.geometries;
  32112. if (!rect.contain(coord[0], coord[1])) {
  32113. return false;
  32114. }
  32115. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  32116. var geo = geometries[i]; // Only support polygon.
  32117. if (geo.type !== 'polygon') {
  32118. continue;
  32119. }
  32120. var exterior = geo.exterior;
  32121. var interiors = geo.interiors;
  32122. if (contain$2(exterior, coord[0], coord[1])) {
  32123. // Not in the region if point is in the hole.
  32124. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  32125. if (contain$2(interiors[k], coord[0], coord[1])) {
  32126. continue loopGeo;
  32127. }
  32128. }
  32129. return true;
  32130. }
  32131. }
  32132. return false;
  32133. };
  32134. /**
  32135. * Transform the raw coords to target bounding.
  32136. * @param x
  32137. * @param y
  32138. * @param width
  32139. * @param height
  32140. */
  32141. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  32142. var rect = this.getBoundingRect();
  32143. var aspect = rect.width / rect.height;
  32144. if (!width) {
  32145. width = aspect * height;
  32146. } else if (!height) {
  32147. height = width / aspect;
  32148. }
  32149. var target = new BoundingRect(x, y, width, height);
  32150. var transform = rect.calculateTransform(target);
  32151. var geometries = this.geometries;
  32152. for (var i = 0; i < geometries.length; i++) {
  32153. var geo = geometries[i];
  32154. if (geo.type === 'polygon') {
  32155. transformPoints(geo.exterior, transform);
  32156. each(geo.interiors, function (interior) {
  32157. transformPoints(interior, transform);
  32158. });
  32159. } else {
  32160. each(geo.points, function (points) {
  32161. transformPoints(points, transform);
  32162. });
  32163. }
  32164. }
  32165. rect = this._rect;
  32166. rect.copy(target); // Update center
  32167. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32168. };
  32169. GeoJSONRegion.prototype.cloneShallow = function (name) {
  32170. name == null && (name = this.name);
  32171. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  32172. newRegion._rect = this._rect;
  32173. newRegion.transformTo = null; // Simply avoid to be called.
  32174. return newRegion;
  32175. };
  32176. return GeoJSONRegion;
  32177. }(Region);
  32178. var GeoSVGRegion =
  32179. /** @class */
  32180. function (_super) {
  32181. __extends(GeoSVGRegion, _super);
  32182. function GeoSVGRegion(name, elOnlyForCalculate) {
  32183. var _this = _super.call(this, name) || this;
  32184. _this.type = 'geoSVG';
  32185. _this._elOnlyForCalculate = elOnlyForCalculate;
  32186. return _this;
  32187. }
  32188. GeoSVGRegion.prototype.calcCenter = function () {
  32189. var el = this._elOnlyForCalculate;
  32190. var rect = el.getBoundingRect();
  32191. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32192. var mat = identity(TMP_TRANSFORM);
  32193. var target = el;
  32194. while (target && !target.isGeoSVGGraphicRoot) {
  32195. mul$1(mat, target.getLocalTransform(), mat);
  32196. target = target.parent;
  32197. }
  32198. invert(mat, mat);
  32199. applyTransform(center, center, mat);
  32200. return center;
  32201. };
  32202. return GeoSVGRegion;
  32203. }(Region);
  32204. function decode(json) {
  32205. if (!json.UTF8Encoding) {
  32206. return json;
  32207. }
  32208. var jsonCompressed = json;
  32209. var encodeScale = jsonCompressed.UTF8Scale;
  32210. if (encodeScale == null) {
  32211. encodeScale = 1024;
  32212. }
  32213. var features = jsonCompressed.features;
  32214. each(features, function (feature) {
  32215. var geometry = feature.geometry;
  32216. var encodeOffsets = geometry.encodeOffsets;
  32217. var coordinates = geometry.coordinates; // Geometry may be appeded manually in the script after json loaded.
  32218. // In this case this geometry is usually not encoded.
  32219. if (!encodeOffsets) {
  32220. return;
  32221. }
  32222. switch (geometry.type) {
  32223. case 'LineString':
  32224. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  32225. break;
  32226. case 'Polygon':
  32227. decodeRings(coordinates, encodeOffsets, encodeScale);
  32228. break;
  32229. case 'MultiLineString':
  32230. decodeRings(coordinates, encodeOffsets, encodeScale);
  32231. break;
  32232. case 'MultiPolygon':
  32233. each(coordinates, function (rings, idx) {
  32234. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  32235. });
  32236. }
  32237. }); // Has been decoded
  32238. jsonCompressed.UTF8Encoding = false;
  32239. return jsonCompressed;
  32240. }
  32241. function decodeRings(rings, encodeOffsets, encodeScale) {
  32242. for (var c = 0; c < rings.length; c++) {
  32243. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  32244. }
  32245. }
  32246. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  32247. var result = [];
  32248. var prevX = encodeOffsets[0];
  32249. var prevY = encodeOffsets[1];
  32250. for (var i = 0; i < coordinate.length; i += 2) {
  32251. var x = coordinate.charCodeAt(i) - 64;
  32252. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  32253. x = x >> 1 ^ -(x & 1);
  32254. y = y >> 1 ^ -(y & 1); // Delta deocding
  32255. x += prevX;
  32256. y += prevY;
  32257. prevX = x;
  32258. prevY = y; // Dequantize
  32259. result.push([x / encodeScale, y / encodeScale]);
  32260. }
  32261. return result;
  32262. }
  32263. function parseGeoJSON(geoJson, nameProperty) {
  32264. geoJson = decode(geoJson);
  32265. return map(filter(geoJson.features, function (featureObj) {
  32266. // Output of mapshaper may have geometry null
  32267. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  32268. }), function (featureObj) {
  32269. var properties = featureObj.properties;
  32270. var geo = featureObj.geometry;
  32271. var geometries = [];
  32272. switch (geo.type) {
  32273. case 'Polygon':
  32274. var coordinates = geo.coordinates; // According to the GeoJSON specification.
  32275. // First must be exterior, and the rest are all interior(holes).
  32276. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  32277. break;
  32278. case 'MultiPolygon':
  32279. each(geo.coordinates, function (item) {
  32280. if (item[0]) {
  32281. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  32282. }
  32283. });
  32284. break;
  32285. case 'LineString':
  32286. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  32287. break;
  32288. case 'MultiLineString':
  32289. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  32290. }
  32291. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  32292. region.properties = properties;
  32293. return region;
  32294. });
  32295. }
  32296. var number = /*#__PURE__*/Object.freeze({
  32297. __proto__: null,
  32298. linearMap: linearMap,
  32299. round: round,
  32300. asc: asc,
  32301. getPrecision: getPrecision,
  32302. getPrecisionSafe: getPrecisionSafe,
  32303. getPixelPrecision: getPixelPrecision,
  32304. getPercentWithPrecision: getPercentWithPrecision,
  32305. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  32306. remRadian: remRadian,
  32307. isRadianAroundZero: isRadianAroundZero,
  32308. parseDate: parseDate,
  32309. quantity: quantity,
  32310. quantityExponent: quantityExponent,
  32311. nice: nice,
  32312. quantile: quantile,
  32313. reformIntervals: reformIntervals,
  32314. isNumeric: isNumeric,
  32315. numericToNumber: numericToNumber
  32316. });
  32317. var time = /*#__PURE__*/Object.freeze({
  32318. __proto__: null,
  32319. parse: parseDate,
  32320. format: format
  32321. });
  32322. var graphic$1 = /*#__PURE__*/Object.freeze({
  32323. __proto__: null,
  32324. extendShape: extendShape,
  32325. extendPath: extendPath,
  32326. makePath: makePath,
  32327. makeImage: makeImage,
  32328. mergePath: mergePath$1,
  32329. resizePath: resizePath,
  32330. createIcon: createIcon,
  32331. updateProps: updateProps,
  32332. initProps: initProps,
  32333. getTransform: getTransform,
  32334. clipPointsByRect: clipPointsByRect,
  32335. clipRectByRect: clipRectByRect,
  32336. registerShape: registerShape,
  32337. getShapeClass: getShapeClass,
  32338. Group: Group,
  32339. Image: ZRImage,
  32340. Text: ZRText,
  32341. Circle: Circle,
  32342. Ellipse: Ellipse,
  32343. Sector: Sector,
  32344. Ring: Ring,
  32345. Polygon: Polygon,
  32346. Polyline: Polyline,
  32347. Rect: Rect,
  32348. Line: Line,
  32349. BezierCurve: BezierCurve,
  32350. Arc: Arc,
  32351. IncrementalDisplayable: IncrementalDisplayable,
  32352. CompoundPath: CompoundPath,
  32353. LinearGradient: LinearGradient,
  32354. RadialGradient: RadialGradient,
  32355. BoundingRect: BoundingRect
  32356. });
  32357. var format$1 = /*#__PURE__*/Object.freeze({
  32358. __proto__: null,
  32359. addCommas: addCommas,
  32360. toCamelCase: toCamelCase,
  32361. normalizeCssArray: normalizeCssArray$1,
  32362. encodeHTML: encodeHTML,
  32363. formatTpl: formatTpl,
  32364. getTooltipMarker: getTooltipMarker,
  32365. formatTime: formatTime,
  32366. capitalFirst: capitalFirst,
  32367. truncateText: truncateText,
  32368. getTextRect: getTextRect
  32369. });
  32370. var util$1 = /*#__PURE__*/Object.freeze({
  32371. __proto__: null,
  32372. map: map,
  32373. each: each,
  32374. indexOf: indexOf,
  32375. inherits: inherits,
  32376. reduce: reduce,
  32377. filter: filter,
  32378. bind: bind,
  32379. curry: curry,
  32380. isArray: isArray,
  32381. isString: isString,
  32382. isObject: isObject,
  32383. isFunction: isFunction,
  32384. extend: extend,
  32385. defaults: defaults,
  32386. clone: clone,
  32387. merge: merge
  32388. });
  32389. var inner$5 = makeInner();
  32390. function createAxisLabels(axis) {
  32391. // Only ordinal scale support tick interval
  32392. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  32393. }
  32394. /**
  32395. * @param {module:echats/coord/Axis} axis
  32396. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  32397. * @return {Object} {
  32398. * ticks: Array.<number>
  32399. * tickCategoryInterval: number
  32400. * }
  32401. */
  32402. function createAxisTicks(axis, tickModel) {
  32403. // Only ordinal scale support tick interval
  32404. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  32405. ticks: map(axis.scale.getTicks(), function (tick) {
  32406. return tick.value;
  32407. })
  32408. };
  32409. }
  32410. function makeCategoryLabels(axis) {
  32411. var labelModel = axis.getLabelModel();
  32412. var result = makeCategoryLabelsActually(axis, labelModel);
  32413. return !labelModel.get('show') || axis.scale.isBlank() ? {
  32414. labels: [],
  32415. labelCategoryInterval: result.labelCategoryInterval
  32416. } : result;
  32417. }
  32418. function makeCategoryLabelsActually(axis, labelModel) {
  32419. var labelsCache = getListCache(axis, 'labels');
  32420. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  32421. var result = listCacheGet(labelsCache, optionLabelInterval);
  32422. if (result) {
  32423. return result;
  32424. }
  32425. var labels;
  32426. var numericLabelInterval;
  32427. if (isFunction(optionLabelInterval)) {
  32428. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  32429. } else {
  32430. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  32431. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  32432. } // Cache to avoid calling interval function repeatedly.
  32433. return listCacheSet(labelsCache, optionLabelInterval, {
  32434. labels: labels,
  32435. labelCategoryInterval: numericLabelInterval
  32436. });
  32437. }
  32438. function makeCategoryTicks(axis, tickModel) {
  32439. var ticksCache = getListCache(axis, 'ticks');
  32440. var optionTickInterval = getOptionCategoryInterval(tickModel);
  32441. var result = listCacheGet(ticksCache, optionTickInterval);
  32442. if (result) {
  32443. return result;
  32444. }
  32445. var ticks;
  32446. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  32447. // we should not return all ticks.
  32448. if (!tickModel.get('show') || axis.scale.isBlank()) {
  32449. ticks = [];
  32450. }
  32451. if (isFunction(optionTickInterval)) {
  32452. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  32453. } // Always use label interval by default despite label show. Consider this
  32454. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  32455. // labels. `splitLine` and `axisTick` should be consistent in this case.
  32456. else if (optionTickInterval === 'auto') {
  32457. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  32458. tickCategoryInterval = labelsResult.labelCategoryInterval;
  32459. ticks = map(labelsResult.labels, function (labelItem) {
  32460. return labelItem.tickValue;
  32461. });
  32462. } else {
  32463. tickCategoryInterval = optionTickInterval;
  32464. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  32465. } // Cache to avoid calling interval function repeatedly.
  32466. return listCacheSet(ticksCache, optionTickInterval, {
  32467. ticks: ticks,
  32468. tickCategoryInterval: tickCategoryInterval
  32469. });
  32470. }
  32471. function makeRealNumberLabels(axis) {
  32472. var ticks = axis.scale.getTicks();
  32473. var labelFormatter = makeLabelFormatter(axis);
  32474. return {
  32475. labels: map(ticks, function (tick, idx) {
  32476. return {
  32477. level: tick.level,
  32478. formattedLabel: labelFormatter(tick, idx),
  32479. rawLabel: axis.scale.getLabel(tick),
  32480. tickValue: tick.value
  32481. };
  32482. })
  32483. };
  32484. }
  32485. function getListCache(axis, prop) {
  32486. // Because key can be a function, and cache size always is small, we use array cache.
  32487. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  32488. }
  32489. function listCacheGet(cache, key) {
  32490. for (var i = 0; i < cache.length; i++) {
  32491. if (cache[i].key === key) {
  32492. return cache[i].value;
  32493. }
  32494. }
  32495. }
  32496. function listCacheSet(cache, key, value) {
  32497. cache.push({
  32498. key: key,
  32499. value: value
  32500. });
  32501. return value;
  32502. }
  32503. function makeAutoCategoryInterval(axis) {
  32504. var result = inner$5(axis).autoInterval;
  32505. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  32506. }
  32507. /**
  32508. * Calculate interval for category axis ticks and labels.
  32509. * To get precise result, at least one of `getRotate` and `isHorizontal`
  32510. * should be implemented in axis.
  32511. */
  32512. function calculateCategoryInterval(axis) {
  32513. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  32514. var labelFormatter = makeLabelFormatter(axis);
  32515. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32516. var ordinalScale = axis.scale;
  32517. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  32518. // avoid generating a long array by `getTicks`
  32519. // in large category data case.
  32520. var tickCount = ordinalScale.count();
  32521. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32522. return 0;
  32523. }
  32524. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  32525. if (tickCount > 40) {
  32526. step = Math.max(1, Math.floor(tickCount / 40));
  32527. }
  32528. var tickValue = ordinalExtent[0];
  32529. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32530. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32531. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32532. var maxW = 0;
  32533. var maxH = 0; // Caution: Performance sensitive for large category data.
  32534. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32535. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32536. var width = 0;
  32537. var height = 0; // Not precise, do not consider align and vertical align
  32538. // and each distance from axis line yet.
  32539. var rect = getBoundingRect(labelFormatter({
  32540. value: tickValue
  32541. }), params.font, 'center', 'top'); // Magic number
  32542. width = rect.width * 1.3;
  32543. height = rect.height * 1.3; // Min size, void long loop.
  32544. maxW = Math.max(maxW, width, 7);
  32545. maxH = Math.max(maxH, height, 7);
  32546. }
  32547. var dw = maxW / unitW;
  32548. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  32549. isNaN(dw) && (dw = Infinity);
  32550. isNaN(dh) && (dh = Infinity);
  32551. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32552. var cache = inner$5(axis.model);
  32553. var axisExtent = axis.getExtent();
  32554. var lastAutoInterval = cache.lastAutoInterval;
  32555. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  32556. // otherwise the calculated interval might jitter when the zoom
  32557. // window size is close to the interval-changing size.
  32558. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32559. // The jitter will cause that sometimes the displayed labels are
  32560. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32561. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  32562. // point is not the same when zooming in or zooming out.
  32563. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  32564. // be used. Otherwise some hidden labels might not be shown again.
  32565. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  32566. interval = lastAutoInterval;
  32567. } // Only update cache if cache not used, otherwise the
  32568. // changing of interval is too insensitive.
  32569. else {
  32570. cache.lastTickCount = tickCount;
  32571. cache.lastAutoInterval = interval;
  32572. cache.axisExtent0 = axisExtent[0];
  32573. cache.axisExtent1 = axisExtent[1];
  32574. }
  32575. return interval;
  32576. }
  32577. function fetchAutoCategoryIntervalCalculationParams(axis) {
  32578. var labelModel = axis.getLabelModel();
  32579. return {
  32580. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  32581. labelRotate: labelModel.get('rotate') || 0,
  32582. font: labelModel.getFont()
  32583. };
  32584. }
  32585. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32586. var labelFormatter = makeLabelFormatter(axis);
  32587. var ordinalScale = axis.scale;
  32588. var ordinalExtent = ordinalScale.getExtent();
  32589. var labelModel = axis.getLabelModel();
  32590. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32591. var step = Math.max((categoryInterval || 0) + 1, 1);
  32592. var startTick = ordinalExtent[0];
  32593. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  32594. // while zooming and moving while interval > 0. Otherwise the selection
  32595. // of displayable ticks and symbols probably keep changing.
  32596. // 3 is empirical value.
  32597. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32598. startTick = Math.round(Math.ceil(startTick / step) * step);
  32599. } // (1) Only add min max label here but leave overlap checking
  32600. // to render stage, which also ensure the returned list
  32601. // suitable for splitLine and splitArea rendering.
  32602. // (2) Scales except category always contain min max label so
  32603. // do not need to perform this process.
  32604. var showAllLabel = shouldShowAllLabels(axis);
  32605. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32606. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32607. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32608. addItem(ordinalExtent[0]);
  32609. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32610. var tickValue = startTick;
  32611. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32612. addItem(tickValue);
  32613. }
  32614. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32615. addItem(ordinalExtent[1]);
  32616. }
  32617. function addItem(tickValue) {
  32618. var tickObj = {
  32619. value: tickValue
  32620. };
  32621. result.push(onlyTick ? tickValue : {
  32622. formattedLabel: labelFormatter(tickObj),
  32623. rawLabel: ordinalScale.getLabel(tickObj),
  32624. tickValue: tickValue
  32625. });
  32626. }
  32627. return result;
  32628. }
  32629. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32630. var ordinalScale = axis.scale;
  32631. var labelFormatter = makeLabelFormatter(axis);
  32632. var result = [];
  32633. each(ordinalScale.getTicks(), function (tick) {
  32634. var rawLabel = ordinalScale.getLabel(tick);
  32635. var tickValue = tick.value;
  32636. if (categoryInterval(tick.value, rawLabel)) {
  32637. result.push(onlyTick ? tickValue : {
  32638. formattedLabel: labelFormatter(tick),
  32639. rawLabel: rawLabel,
  32640. tickValue: tickValue
  32641. });
  32642. }
  32643. });
  32644. return result;
  32645. }
  32646. var NORMALIZED_EXTENT = [0, 1];
  32647. /**
  32648. * Base class of Axis.
  32649. */
  32650. var Axis =
  32651. /** @class */
  32652. function () {
  32653. function Axis(dim, scale, extent) {
  32654. this.onBand = false;
  32655. this.inverse = false;
  32656. this.dim = dim;
  32657. this.scale = scale;
  32658. this._extent = extent || [0, 0];
  32659. }
  32660. /**
  32661. * If axis extent contain given coord
  32662. */
  32663. Axis.prototype.contain = function (coord) {
  32664. var extent = this._extent;
  32665. var min = Math.min(extent[0], extent[1]);
  32666. var max = Math.max(extent[0], extent[1]);
  32667. return coord >= min && coord <= max;
  32668. };
  32669. /**
  32670. * If axis extent contain given data
  32671. */
  32672. Axis.prototype.containData = function (data) {
  32673. return this.scale.contain(data);
  32674. };
  32675. /**
  32676. * Get coord extent.
  32677. */
  32678. Axis.prototype.getExtent = function () {
  32679. return this._extent.slice();
  32680. };
  32681. /**
  32682. * Get precision used for formatting
  32683. */
  32684. Axis.prototype.getPixelPrecision = function (dataExtent) {
  32685. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  32686. };
  32687. /**
  32688. * Set coord extent
  32689. */
  32690. Axis.prototype.setExtent = function (start, end) {
  32691. var extent = this._extent;
  32692. extent[0] = start;
  32693. extent[1] = end;
  32694. };
  32695. /**
  32696. * Convert data to coord. Data is the rank if it has an ordinal scale
  32697. */
  32698. Axis.prototype.dataToCoord = function (data, clamp) {
  32699. var extent = this._extent;
  32700. var scale = this.scale;
  32701. data = scale.normalize(data);
  32702. if (this.onBand && scale.type === 'ordinal') {
  32703. extent = extent.slice();
  32704. fixExtentWithBands(extent, scale.count());
  32705. }
  32706. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32707. };
  32708. /**
  32709. * Convert coord to data. Data is the rank if it has an ordinal scale
  32710. */
  32711. Axis.prototype.coordToData = function (coord, clamp) {
  32712. var extent = this._extent;
  32713. var scale = this.scale;
  32714. if (this.onBand && scale.type === 'ordinal') {
  32715. extent = extent.slice();
  32716. fixExtentWithBands(extent, scale.count());
  32717. }
  32718. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32719. return this.scale.scale(t);
  32720. };
  32721. /**
  32722. * Convert pixel point to data in axis
  32723. */
  32724. Axis.prototype.pointToData = function (point, clamp) {
  32725. // Should be implemented in derived class if necessary.
  32726. return;
  32727. };
  32728. /**
  32729. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32730. * `axis.getTicksCoords` considers `onBand`, which is used by
  32731. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32732. * @param opt.tickModel default: axis.model.getModel('axisTick')
  32733. * @param opt.clamp If `true`, the first and the last
  32734. * tick must be at the axis end points. Otherwise, clip ticks
  32735. * that outside the axis extent.
  32736. */
  32737. Axis.prototype.getTicksCoords = function (opt) {
  32738. opt = opt || {};
  32739. var tickModel = opt.tickModel || this.getTickModel();
  32740. var result = createAxisTicks(this, tickModel);
  32741. var ticks = result.ticks;
  32742. var ticksCoords = map(ticks, function (tickVal) {
  32743. return {
  32744. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  32745. tickValue: tickVal
  32746. };
  32747. }, this);
  32748. var alignWithLabel = tickModel.get('alignWithLabel');
  32749. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  32750. return ticksCoords;
  32751. };
  32752. Axis.prototype.getMinorTicksCoords = function () {
  32753. if (this.scale.type === 'ordinal') {
  32754. // Category axis doesn't support minor ticks
  32755. return [];
  32756. }
  32757. var minorTickModel = this.model.getModel('minorTick');
  32758. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  32759. if (!(splitNumber > 0 && splitNumber < 100)) {
  32760. splitNumber = 5;
  32761. }
  32762. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32763. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32764. return map(minorTicksGroup, function (minorTick) {
  32765. return {
  32766. coord: this.dataToCoord(minorTick),
  32767. tickValue: minorTick
  32768. };
  32769. }, this);
  32770. }, this);
  32771. return minorTicksCoords;
  32772. };
  32773. Axis.prototype.getViewLabels = function () {
  32774. return createAxisLabels(this).labels;
  32775. };
  32776. Axis.prototype.getLabelModel = function () {
  32777. return this.model.getModel('axisLabel');
  32778. };
  32779. /**
  32780. * Notice here we only get the default tick model. For splitLine
  32781. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32782. * manually when calling `getTicksCoords`.
  32783. * In GL, this method may be overridden to:
  32784. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32785. */
  32786. Axis.prototype.getTickModel = function () {
  32787. return this.model.getModel('axisTick');
  32788. };
  32789. /**
  32790. * Get width of band
  32791. */
  32792. Axis.prototype.getBandWidth = function () {
  32793. var axisExtent = this._extent;
  32794. var dataExtent = this.scale.getExtent();
  32795. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  32796. len === 0 && (len = 1);
  32797. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32798. return Math.abs(size) / len;
  32799. };
  32800. /**
  32801. * Only be called in category axis.
  32802. * Can be overridden, consider other axes like in 3D.
  32803. * @return Auto interval for cateogry axis tick and label
  32804. */
  32805. Axis.prototype.calculateCategoryInterval = function () {
  32806. return calculateCategoryInterval(this);
  32807. };
  32808. return Axis;
  32809. }();
  32810. function fixExtentWithBands(extent, nTick) {
  32811. var size = extent[1] - extent[0];
  32812. var len = nTick;
  32813. var margin = size / len / 2;
  32814. extent[0] += margin;
  32815. extent[1] -= margin;
  32816. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32817. // |---1---|---2---|---3---|---4---|.
  32818. // So the displayed ticks and splitLine/splitArea should between
  32819. // each data item, otherwise cause misleading (e.g., split tow bars
  32820. // of a single data item when there are two bar series).
  32821. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32822. // splitLine/spliteArea should layout appropriately corresponding
  32823. // to displayed labels. (So we should not use `getBandWidth` in this
  32824. // case).
  32825. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32826. var ticksLen = ticksCoords.length;
  32827. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32828. return;
  32829. }
  32830. var axisExtent = axis.getExtent();
  32831. var last;
  32832. var diffSize;
  32833. if (ticksLen === 1) {
  32834. ticksCoords[0].coord = axisExtent[0];
  32835. last = ticksCoords[1] = {
  32836. coord: axisExtent[0]
  32837. };
  32838. } else {
  32839. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32840. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32841. each(ticksCoords, function (ticksItem) {
  32842. ticksItem.coord -= shift_1 / 2;
  32843. });
  32844. var dataExtent = axis.scale.getExtent();
  32845. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32846. last = {
  32847. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  32848. };
  32849. ticksCoords.push(last);
  32850. }
  32851. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  32852. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32853. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  32854. }
  32855. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32856. ticksCoords.unshift({
  32857. coord: axisExtent[0]
  32858. });
  32859. }
  32860. if (littleThan(axisExtent[1], last.coord)) {
  32861. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  32862. }
  32863. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32864. ticksCoords.push({
  32865. coord: axisExtent[1]
  32866. });
  32867. }
  32868. function littleThan(a, b) {
  32869. // Avoid rounding error cause calculated tick coord different with extent.
  32870. // It may cause an extra unnecessary tick added.
  32871. a = round(a);
  32872. b = round(b);
  32873. return inverse ? a > b : a < b;
  32874. }
  32875. }
  32876. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  32877. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  32878. // class Bar3DModel extends ComponentModel {}
  32879. // export function install(registers) { registers.registerComponentModel(Bar3DModel); }
  32880. // echarts.use(install);
  32881. function extendComponentModel(proto) {
  32882. var Model = ComponentModel.extend(proto);
  32883. ComponentModel.registerClass(Model);
  32884. return Model;
  32885. }
  32886. function extendComponentView(proto) {
  32887. var View = ComponentView.extend(proto);
  32888. ComponentView.registerClass(View);
  32889. return View;
  32890. }
  32891. function extendSeriesModel(proto) {
  32892. var Model = SeriesModel.extend(proto);
  32893. SeriesModel.registerClass(Model);
  32894. return Model;
  32895. }
  32896. function extendChartView(proto) {
  32897. var View = ChartView.extend(proto);
  32898. ChartView.registerClass(View);
  32899. return View;
  32900. }
  32901. var PI2$6 = Math.PI * 2;
  32902. var CMD$3 = PathProxy.CMD;
  32903. var DEFAULT_SEARCH_SPACE = ['top', 'right', 'bottom', 'left'];
  32904. function getCandidateAnchor(pos, distance, rect, outPt, outDir) {
  32905. var width = rect.width;
  32906. var height = rect.height;
  32907. switch (pos) {
  32908. case 'top':
  32909. outPt.set(rect.x + width / 2, rect.y - distance);
  32910. outDir.set(0, -1);
  32911. break;
  32912. case 'bottom':
  32913. outPt.set(rect.x + width / 2, rect.y + height + distance);
  32914. outDir.set(0, 1);
  32915. break;
  32916. case 'left':
  32917. outPt.set(rect.x - distance, rect.y + height / 2);
  32918. outDir.set(-1, 0);
  32919. break;
  32920. case 'right':
  32921. outPt.set(rect.x + width + distance, rect.y + height / 2);
  32922. outDir.set(1, 0);
  32923. break;
  32924. }
  32925. }
  32926. function projectPointToArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y, out) {
  32927. x -= cx;
  32928. y -= cy;
  32929. var d = Math.sqrt(x * x + y * y);
  32930. x /= d;
  32931. y /= d; // Intersect point.
  32932. var ox = x * r + cx;
  32933. var oy = y * r + cy;
  32934. if (Math.abs(startAngle - endAngle) % PI2$6 < 1e-4) {
  32935. // Is a circle
  32936. out[0] = ox;
  32937. out[1] = oy;
  32938. return d - r;
  32939. }
  32940. if (anticlockwise) {
  32941. var tmp = startAngle;
  32942. startAngle = normalizeRadian(endAngle);
  32943. endAngle = normalizeRadian(tmp);
  32944. } else {
  32945. startAngle = normalizeRadian(startAngle);
  32946. endAngle = normalizeRadian(endAngle);
  32947. }
  32948. if (startAngle > endAngle) {
  32949. endAngle += PI2$6;
  32950. }
  32951. var angle = Math.atan2(y, x);
  32952. if (angle < 0) {
  32953. angle += PI2$6;
  32954. }
  32955. if (angle >= startAngle && angle <= endAngle || angle + PI2$6 >= startAngle && angle + PI2$6 <= endAngle) {
  32956. // Project point is on the arc.
  32957. out[0] = ox;
  32958. out[1] = oy;
  32959. return d - r;
  32960. }
  32961. var x1 = r * Math.cos(startAngle) + cx;
  32962. var y1 = r * Math.sin(startAngle) + cy;
  32963. var x2 = r * Math.cos(endAngle) + cx;
  32964. var y2 = r * Math.sin(endAngle) + cy;
  32965. var d1 = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
  32966. var d2 = (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y);
  32967. if (d1 < d2) {
  32968. out[0] = x1;
  32969. out[1] = y1;
  32970. return Math.sqrt(d1);
  32971. } else {
  32972. out[0] = x2;
  32973. out[1] = y2;
  32974. return Math.sqrt(d2);
  32975. }
  32976. }
  32977. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  32978. var dx = x - x1;
  32979. var dy = y - y1;
  32980. var dx1 = x2 - x1;
  32981. var dy1 = y2 - y1;
  32982. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  32983. dx1 /= lineLen;
  32984. dy1 /= lineLen; // dot product
  32985. var projectedLen = dx * dx1 + dy * dy1;
  32986. var t = projectedLen / lineLen;
  32987. if (limitToEnds) {
  32988. t = Math.min(Math.max(t, 0), 1);
  32989. }
  32990. t *= lineLen;
  32991. var ox = out[0] = x1 + t * dx1;
  32992. var oy = out[1] = y1 + t * dy1;
  32993. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  32994. }
  32995. function projectPointToRect(x1, y1, width, height, x, y, out) {
  32996. if (width < 0) {
  32997. x1 = x1 + width;
  32998. width = -width;
  32999. }
  33000. if (height < 0) {
  33001. y1 = y1 + height;
  33002. height = -height;
  33003. }
  33004. var x2 = x1 + width;
  33005. var y2 = y1 + height;
  33006. var ox = out[0] = Math.min(Math.max(x, x1), x2);
  33007. var oy = out[1] = Math.min(Math.max(y, y1), y2);
  33008. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  33009. }
  33010. var tmpPt = [];
  33011. function nearestPointOnRect(pt, rect, out) {
  33012. var dist = projectPointToRect(rect.x, rect.y, rect.width, rect.height, pt.x, pt.y, tmpPt);
  33013. out.set(tmpPt[0], tmpPt[1]);
  33014. return dist;
  33015. }
  33016. /**
  33017. * Calculate min distance corresponding point.
  33018. * This method won't evaluate if point is in the path.
  33019. */
  33020. function nearestPointOnPath(pt, path, out) {
  33021. var xi = 0;
  33022. var yi = 0;
  33023. var x0 = 0;
  33024. var y0 = 0;
  33025. var x1;
  33026. var y1;
  33027. var minDist = Infinity;
  33028. var data = path.data;
  33029. var x = pt.x;
  33030. var y = pt.y;
  33031. for (var i = 0; i < data.length;) {
  33032. var cmd = data[i++];
  33033. if (i === 1) {
  33034. xi = data[i];
  33035. yi = data[i + 1];
  33036. x0 = xi;
  33037. y0 = yi;
  33038. }
  33039. var d = minDist;
  33040. switch (cmd) {
  33041. case CMD$3.M:
  33042. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  33043. // 在 closePath 的时候使用
  33044. x0 = data[i++];
  33045. y0 = data[i++];
  33046. xi = x0;
  33047. yi = y0;
  33048. break;
  33049. case CMD$3.L:
  33050. d = projectPointToLine(xi, yi, data[i], data[i + 1], x, y, tmpPt, true);
  33051. xi = data[i++];
  33052. yi = data[i++];
  33053. break;
  33054. case CMD$3.C:
  33055. d = cubicProjectPoint(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  33056. xi = data[i++];
  33057. yi = data[i++];
  33058. break;
  33059. case CMD$3.Q:
  33060. d = quadraticProjectPoint(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  33061. xi = data[i++];
  33062. yi = data[i++];
  33063. break;
  33064. case CMD$3.A:
  33065. // TODO Arc 判断的开销比较大
  33066. var cx = data[i++];
  33067. var cy = data[i++];
  33068. var rx = data[i++];
  33069. var ry = data[i++];
  33070. var theta = data[i++];
  33071. var dTheta = data[i++]; // TODO Arc 旋转
  33072. i += 1;
  33073. var anticlockwise = !!(1 - data[i++]);
  33074. x1 = Math.cos(theta) * rx + cx;
  33075. y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令
  33076. if (i <= 1) {
  33077. // 第一个命令起点还未定义
  33078. x0 = x1;
  33079. y0 = y1;
  33080. } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  33081. var _x = (x - cx) * ry / rx + cx;
  33082. d = projectPointToArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y, tmpPt);
  33083. xi = Math.cos(theta + dTheta) * rx + cx;
  33084. yi = Math.sin(theta + dTheta) * ry + cy;
  33085. break;
  33086. case CMD$3.R:
  33087. x0 = xi = data[i++];
  33088. y0 = yi = data[i++];
  33089. var width = data[i++];
  33090. var height = data[i++];
  33091. d = projectPointToRect(x0, y0, width, height, x, y, tmpPt);
  33092. break;
  33093. case CMD$3.Z:
  33094. d = projectPointToLine(xi, yi, x0, y0, x, y, tmpPt, true);
  33095. xi = x0;
  33096. yi = y0;
  33097. break;
  33098. }
  33099. if (d < minDist) {
  33100. minDist = d;
  33101. out.set(tmpPt[0], tmpPt[1]);
  33102. }
  33103. }
  33104. return minDist;
  33105. } // Temporal variable for intermediate usage.
  33106. var pt0 = new Point();
  33107. var pt1 = new Point();
  33108. var pt2 = new Point();
  33109. var dir = new Point();
  33110. var dir2 = new Point();
  33111. /**
  33112. * Calculate a proper guide line based on the label position and graphic element definition
  33113. * @param label
  33114. * @param labelRect
  33115. * @param target
  33116. * @param targetRect
  33117. */
  33118. function updateLabelLinePoints(target, labelLineModel) {
  33119. if (!target) {
  33120. return;
  33121. }
  33122. var labelLine = target.getTextGuideLine();
  33123. var label = target.getTextContent(); // Needs to create text guide in each charts.
  33124. if (!(label && labelLine)) {
  33125. return;
  33126. }
  33127. var labelGuideConfig = target.textGuideLineConfig || {};
  33128. var points = [[0, 0], [0, 0], [0, 0]];
  33129. var searchSpace = labelGuideConfig.candidates || DEFAULT_SEARCH_SPACE;
  33130. var labelRect = label.getBoundingRect().clone();
  33131. labelRect.applyTransform(label.getComputedTransform());
  33132. var minDist = Infinity;
  33133. var anchorPoint = labelGuideConfig.anchor;
  33134. var targetTransform = target.getComputedTransform();
  33135. var targetInversedTransform = targetTransform && invert([], targetTransform);
  33136. var len = labelLineModel.get('length2') || 0;
  33137. if (anchorPoint) {
  33138. pt2.copy(anchorPoint);
  33139. }
  33140. for (var i = 0; i < searchSpace.length; i++) {
  33141. var candidate = searchSpace[i];
  33142. getCandidateAnchor(candidate, 0, labelRect, pt0, dir);
  33143. Point.scaleAndAdd(pt1, pt0, dir, len); // Transform to target coord space.
  33144. pt1.transform(targetInversedTransform); // Note: getBoundingRect will ensure the `path` being created.
  33145. var boundingRect = target.getBoundingRect();
  33146. var dist = anchorPoint ? anchorPoint.distance(pt1) : target instanceof Path ? nearestPointOnPath(pt1, target.path, pt2) : nearestPointOnRect(pt1, boundingRect, pt2); // TODO pt2 is in the path
  33147. if (dist < minDist) {
  33148. minDist = dist; // Transform back to global space.
  33149. pt1.transform(targetTransform);
  33150. pt2.transform(targetTransform);
  33151. pt2.toArray(points[0]);
  33152. pt1.toArray(points[1]);
  33153. pt0.toArray(points[2]);
  33154. }
  33155. }
  33156. limitTurnAngle(points, labelLineModel.get('minTurnAngle'));
  33157. labelLine.setShape({
  33158. points: points
  33159. });
  33160. } // Temporal variable for the limitTurnAngle function
  33161. var tmpArr = [];
  33162. var tmpProjPoint = new Point();
  33163. /**
  33164. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  33165. * @param linePoints
  33166. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  33167. */
  33168. function limitTurnAngle(linePoints, minTurnAngle) {
  33169. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  33170. return;
  33171. }
  33172. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  33173. // /pt1----pt2 (label)
  33174. // /
  33175. // pt0/
  33176. pt0.fromArray(linePoints[0]);
  33177. pt1.fromArray(linePoints[1]);
  33178. pt2.fromArray(linePoints[2]);
  33179. Point.sub(dir, pt0, pt1);
  33180. Point.sub(dir2, pt2, pt1);
  33181. var len1 = dir.len();
  33182. var len2 = dir2.len();
  33183. if (len1 < 1e-3 || len2 < 1e-3) {
  33184. return;
  33185. }
  33186. dir.scale(1 / len1);
  33187. dir2.scale(1 / len2);
  33188. var angleCos = dir.dot(dir2);
  33189. var minTurnAngleCos = Math.cos(minTurnAngle);
  33190. if (minTurnAngleCos < angleCos) {
  33191. // Smaller than minTurnAngle
  33192. // Calculate project point of pt0 on pt1-pt2
  33193. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33194. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  33195. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  33196. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33197. if (isNaN(t)) {
  33198. return;
  33199. }
  33200. if (t < 0) {
  33201. Point.copy(tmpProjPoint, pt1);
  33202. } else if (t > 1) {
  33203. Point.copy(tmpProjPoint, pt2);
  33204. }
  33205. tmpProjPoint.toArray(linePoints[1]);
  33206. }
  33207. }
  33208. /**
  33209. * Limit the angle of line and the surface
  33210. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  33211. */
  33212. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  33213. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  33214. return;
  33215. }
  33216. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  33217. pt0.fromArray(linePoints[0]);
  33218. pt1.fromArray(linePoints[1]);
  33219. pt2.fromArray(linePoints[2]);
  33220. Point.sub(dir, pt1, pt0);
  33221. Point.sub(dir2, pt2, pt1);
  33222. var len1 = dir.len();
  33223. var len2 = dir2.len();
  33224. if (len1 < 1e-3 || len2 < 1e-3) {
  33225. return;
  33226. }
  33227. dir.scale(1 / len1);
  33228. dir2.scale(1 / len2);
  33229. var angleCos = dir.dot(surfaceNormal);
  33230. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  33231. if (angleCos < maxSurfaceAngleCos) {
  33232. // Calculate project point of pt0 on pt1-pt2
  33233. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33234. tmpProjPoint.fromArray(tmpArr);
  33235. var HALF_PI = Math.PI / 2;
  33236. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  33237. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  33238. if (newAngle >= HALF_PI) {
  33239. // parallel
  33240. Point.copy(tmpProjPoint, pt2);
  33241. } else {
  33242. // Calculate new projected length with limited minTurnAngle and get the new connect point
  33243. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  33244. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33245. if (isNaN(t)) {
  33246. return;
  33247. }
  33248. if (t < 0) {
  33249. Point.copy(tmpProjPoint, pt1);
  33250. } else if (t > 1) {
  33251. Point.copy(tmpProjPoint, pt2);
  33252. }
  33253. }
  33254. tmpProjPoint.toArray(linePoints[1]);
  33255. }
  33256. }
  33257. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  33258. var isNormal = stateName === 'normal';
  33259. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  33260. stateObj.ignore = ignore; // Set smooth
  33261. var smooth = stateModel.get('smooth');
  33262. if (smooth && smooth === true) {
  33263. smooth = 0.3;
  33264. }
  33265. stateObj.shape = stateObj.shape || {};
  33266. if (smooth > 0) {
  33267. stateObj.shape.smooth = smooth;
  33268. }
  33269. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  33270. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  33271. }
  33272. function buildLabelLinePath(path, shape) {
  33273. var smooth = shape.smooth;
  33274. var points = shape.points;
  33275. if (!points) {
  33276. return;
  33277. }
  33278. path.moveTo(points[0][0], points[0][1]);
  33279. if (smooth > 0 && points.length >= 3) {
  33280. var len1 = dist(points[0], points[1]);
  33281. var len2 = dist(points[1], points[2]);
  33282. if (!len1 || !len2) {
  33283. path.lineTo(points[1][0], points[1][1]);
  33284. path.lineTo(points[2][0], points[2][1]);
  33285. return;
  33286. }
  33287. var moveLen = Math.min(len1, len2) * smooth;
  33288. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  33289. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  33290. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  33291. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  33292. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  33293. } else {
  33294. for (var i = 1; i < points.length; i++) {
  33295. path.lineTo(points[i][0], points[i][1]);
  33296. }
  33297. }
  33298. }
  33299. /**
  33300. * Create a label line if necessary and set it's style.
  33301. */
  33302. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  33303. var labelLine = targetEl.getTextGuideLine();
  33304. var label = targetEl.getTextContent();
  33305. if (!label) {
  33306. // Not show label line if there is no label.
  33307. if (labelLine) {
  33308. targetEl.removeTextGuideLine();
  33309. }
  33310. return;
  33311. }
  33312. var normalModel = statesModels.normal;
  33313. var showNormal = normalModel.get('show');
  33314. var labelIgnoreNormal = label.ignore;
  33315. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  33316. var stateName = DISPLAY_STATES[i];
  33317. var stateModel = statesModels[stateName];
  33318. var isNormal = stateName === 'normal';
  33319. if (stateModel) {
  33320. var stateShow = stateModel.get('show');
  33321. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  33322. if (isLabelIgnored // Not show when label is not shown in this state.
  33323. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  33324. ) {
  33325. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  33326. if (stateObj) {
  33327. stateObj.ignore = true;
  33328. }
  33329. continue;
  33330. } // Create labelLine if not exists
  33331. if (!labelLine) {
  33332. labelLine = new Polyline();
  33333. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  33334. // NOTE: NORMAL should always been the first!
  33335. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  33336. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  33337. } // Use same state proxy.
  33338. if (targetEl.stateProxy) {
  33339. labelLine.stateProxy = targetEl.stateProxy;
  33340. }
  33341. }
  33342. setLabelLineState(labelLine, false, stateName, stateModel);
  33343. }
  33344. }
  33345. if (labelLine) {
  33346. defaults(labelLine.style, defaultStyle); // Not fill.
  33347. labelLine.style.fill = null;
  33348. var showAbove = normalModel.get('showAbove');
  33349. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  33350. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  33351. labelLine.buildPath = buildLabelLinePath;
  33352. }
  33353. }
  33354. function getLabelLineStatesModels(itemModel, labelLineName) {
  33355. labelLineName = labelLineName || 'labelLine';
  33356. var statesModels = {
  33357. normal: itemModel.getModel(labelLineName)
  33358. };
  33359. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  33360. var stateName = SPECIAL_STATES[i];
  33361. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  33362. }
  33363. return statesModels;
  33364. }
  33365. function prepareLayoutList(input) {
  33366. var list = [];
  33367. for (var i = 0; i < input.length; i++) {
  33368. var rawItem = input[i];
  33369. if (rawItem.defaultAttr.ignore) {
  33370. continue;
  33371. }
  33372. var label = rawItem.label;
  33373. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  33374. var localRect = label.getBoundingRect();
  33375. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  33376. var minMargin = label.style.margin || 0;
  33377. var globalRect = localRect.clone();
  33378. globalRect.applyTransform(transform);
  33379. globalRect.x -= minMargin / 2;
  33380. globalRect.y -= minMargin / 2;
  33381. globalRect.width += minMargin;
  33382. globalRect.height += minMargin;
  33383. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  33384. list.push({
  33385. label: label,
  33386. labelLine: rawItem.labelLine,
  33387. rect: globalRect,
  33388. localRect: localRect,
  33389. obb: obb,
  33390. priority: rawItem.priority,
  33391. defaultAttr: rawItem.defaultAttr,
  33392. layoutOption: rawItem.computedLayoutOption,
  33393. axisAligned: isAxisAligned,
  33394. transform: transform
  33395. });
  33396. }
  33397. return list;
  33398. }
  33399. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  33400. var len = list.length;
  33401. if (len < 2) {
  33402. return;
  33403. }
  33404. list.sort(function (a, b) {
  33405. return a.rect[xyDim] - b.rect[xyDim];
  33406. });
  33407. var lastPos = 0;
  33408. var delta;
  33409. var adjusted = false;
  33410. var totalShifts = 0;
  33411. for (var i = 0; i < len; i++) {
  33412. var item = list[i];
  33413. var rect = item.rect;
  33414. delta = rect[xyDim] - lastPos;
  33415. if (delta < 0) {
  33416. // shiftForward(i, len, -delta);
  33417. rect[xyDim] -= delta;
  33418. item.label[xyDim] -= delta;
  33419. adjusted = true;
  33420. }
  33421. var shift = Math.max(-delta, 0);
  33422. totalShifts += shift;
  33423. lastPos = rect[xyDim] + rect[sizeDim];
  33424. }
  33425. if (totalShifts > 0 && balanceShift) {
  33426. // Shift back to make the distribution more equally.
  33427. shiftList(-totalShifts / len, 0, len);
  33428. } // TODO bleedMargin?
  33429. var first = list[0];
  33430. var last = list[len - 1];
  33431. var minGap;
  33432. var maxGap;
  33433. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  33434. minGap < 0 && squeezeGaps(-minGap, 0.8);
  33435. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  33436. updateMinMaxGap();
  33437. takeBoundsGap(minGap, maxGap, 1);
  33438. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  33439. updateMinMaxGap();
  33440. if (minGap < 0) {
  33441. squeezeWhenBailout(-minGap);
  33442. }
  33443. if (maxGap < 0) {
  33444. squeezeWhenBailout(maxGap);
  33445. }
  33446. function updateMinMaxGap() {
  33447. minGap = first.rect[xyDim] - minBound;
  33448. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  33449. }
  33450. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  33451. if (gapThisBound < 0) {
  33452. // Move from other gap if can.
  33453. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  33454. if (moveFromMaxGap > 0) {
  33455. shiftList(moveFromMaxGap * moveDir, 0, len);
  33456. var remained = moveFromMaxGap + gapThisBound;
  33457. if (remained < 0) {
  33458. squeezeGaps(-remained * moveDir, 1);
  33459. }
  33460. } else {
  33461. squeezeGaps(-gapThisBound * moveDir, 1);
  33462. }
  33463. }
  33464. }
  33465. function shiftList(delta, start, end) {
  33466. if (delta !== 0) {
  33467. adjusted = true;
  33468. }
  33469. for (var i = start; i < end; i++) {
  33470. var item = list[i];
  33471. var rect = item.rect;
  33472. rect[xyDim] += delta;
  33473. item.label[xyDim] += delta;
  33474. }
  33475. } // Squeeze gaps if the labels exceed margin.
  33476. function squeezeGaps(delta, maxSqeezePercent) {
  33477. var gaps = [];
  33478. var totalGaps = 0;
  33479. for (var i = 1; i < len; i++) {
  33480. var prevItemRect = list[i - 1].rect;
  33481. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  33482. gaps.push(gap);
  33483. totalGaps += gap;
  33484. }
  33485. if (!totalGaps) {
  33486. return;
  33487. }
  33488. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  33489. if (delta > 0) {
  33490. for (var i = 0; i < len - 1; i++) {
  33491. // Distribute the shift delta to all gaps.
  33492. var movement = gaps[i] * squeezePercent; // Forward
  33493. shiftList(movement, 0, i + 1);
  33494. }
  33495. } else {
  33496. // Backward
  33497. for (var i = len - 1; i > 0; i--) {
  33498. // Distribute the shift delta to all gaps.
  33499. var movement = gaps[i - 1] * squeezePercent;
  33500. shiftList(-movement, i, len);
  33501. }
  33502. }
  33503. }
  33504. /**
  33505. * Squeeze to allow overlap if there is no more space available.
  33506. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  33507. */
  33508. function squeezeWhenBailout(delta) {
  33509. var dir = delta < 0 ? -1 : 1;
  33510. delta = Math.abs(delta);
  33511. var moveForEachLabel = Math.ceil(delta / (len - 1));
  33512. for (var i = 0; i < len - 1; i++) {
  33513. if (dir > 0) {
  33514. // Forward
  33515. shiftList(moveForEachLabel, 0, i + 1);
  33516. } else {
  33517. // Backward
  33518. shiftList(-moveForEachLabel, len - i - 1, len);
  33519. }
  33520. delta -= moveForEachLabel;
  33521. if (delta <= 0) {
  33522. return;
  33523. }
  33524. }
  33525. }
  33526. return adjusted;
  33527. }
  33528. /**
  33529. * Adjust labels on x direction to avoid overlap.
  33530. */
  33531. function shiftLayoutOnX(list, leftBound, rightBound, // If average the shifts on all labels and add them to 0
  33532. // TODO: Not sure if should enable it.
  33533. // Pros: The angle of lines will distribute more equally
  33534. // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly.
  33535. balanceShift) {
  33536. return shiftLayout(list, 'x', 'width', leftBound, rightBound, balanceShift);
  33537. }
  33538. /**
  33539. * Adjust labels on y direction to avoid overlap.
  33540. */
  33541. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  33542. balanceShift) {
  33543. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  33544. }
  33545. function hideOverlap(labelList) {
  33546. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  33547. labelList.sort(function (a, b) {
  33548. return b.priority - a.priority;
  33549. });
  33550. var globalRect = new BoundingRect(0, 0, 0, 0);
  33551. function hideEl(el) {
  33552. if (!el.ignore) {
  33553. // Show on emphasis.
  33554. var emphasisState = el.ensureState('emphasis');
  33555. if (emphasisState.ignore == null) {
  33556. emphasisState.ignore = false;
  33557. }
  33558. }
  33559. el.ignore = true;
  33560. }
  33561. for (var i = 0; i < labelList.length; i++) {
  33562. var labelItem = labelList[i];
  33563. var isAxisAligned = labelItem.axisAligned;
  33564. var localRect = labelItem.localRect;
  33565. var transform = labelItem.transform;
  33566. var label = labelItem.label;
  33567. var labelLine = labelItem.labelLine;
  33568. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  33569. globalRect.width -= 0.1;
  33570. globalRect.height -= 0.1;
  33571. globalRect.x += 0.05;
  33572. globalRect.y += 0.05;
  33573. var obb = labelItem.obb;
  33574. var overlapped = false;
  33575. for (var j = 0; j < displayedLabels.length; j++) {
  33576. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  33577. if (!globalRect.intersect(existsTextCfg.rect)) {
  33578. continue;
  33579. }
  33580. if (isAxisAligned && existsTextCfg.axisAligned) {
  33581. // Is overlapped
  33582. overlapped = true;
  33583. break;
  33584. }
  33585. if (!existsTextCfg.obb) {
  33586. // If self is not axis aligned. But other is.
  33587. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  33588. }
  33589. if (!obb) {
  33590. // If self is axis aligned. But other is not.
  33591. obb = new OrientedBoundingRect(localRect, transform);
  33592. }
  33593. if (obb.intersect(existsTextCfg.obb)) {
  33594. overlapped = true;
  33595. break;
  33596. }
  33597. } // TODO Callback to determine if this overlap should be handled?
  33598. if (overlapped) {
  33599. hideEl(label);
  33600. labelLine && hideEl(labelLine);
  33601. } else {
  33602. label.attr('ignore', labelItem.defaultAttr.ignore);
  33603. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  33604. displayedLabels.push(labelItem);
  33605. }
  33606. }
  33607. }
  33608. function cloneArr(points) {
  33609. if (points) {
  33610. var newPoints = [];
  33611. for (var i = 0; i < points.length; i++) {
  33612. newPoints.push(points[i].slice());
  33613. }
  33614. return newPoints;
  33615. }
  33616. }
  33617. function prepareLayoutCallbackParams(labelItem, hostEl) {
  33618. var label = labelItem.label;
  33619. var labelLine = hostEl && hostEl.getTextGuideLine();
  33620. return {
  33621. dataIndex: labelItem.dataIndex,
  33622. dataType: labelItem.dataType,
  33623. seriesIndex: labelItem.seriesModel.seriesIndex,
  33624. text: labelItem.label.style.text,
  33625. rect: labelItem.hostRect,
  33626. labelRect: labelItem.rect,
  33627. // x: labelAttr.x,
  33628. // y: labelAttr.y,
  33629. align: label.style.align,
  33630. verticalAlign: label.style.verticalAlign,
  33631. labelLinePoints: cloneArr(labelLine && labelLine.shape.points)
  33632. };
  33633. }
  33634. var LABEL_OPTION_TO_STYLE_KEYS = ['align', 'verticalAlign', 'width', 'height', 'fontSize'];
  33635. var dummyTransformable = new Transformable();
  33636. var labelLayoutInnerStore = makeInner();
  33637. var labelLineAnimationStore = makeInner();
  33638. function extendWithKeys(target, source, keys) {
  33639. for (var i = 0; i < keys.length; i++) {
  33640. var key = keys[i];
  33641. if (source[key] != null) {
  33642. target[key] = source[key];
  33643. }
  33644. }
  33645. }
  33646. var LABEL_LAYOUT_PROPS = ['x', 'y', 'rotation'];
  33647. var LabelManager =
  33648. /** @class */
  33649. function () {
  33650. function LabelManager() {
  33651. this._labelList = [];
  33652. this._chartViewList = [];
  33653. }
  33654. LabelManager.prototype.clearLabels = function () {
  33655. this._labelList = [];
  33656. this._chartViewList = [];
  33657. };
  33658. /**
  33659. * Add label to manager
  33660. */
  33661. LabelManager.prototype._addLabel = function (dataIndex, dataType, seriesModel, label, layoutOption) {
  33662. var labelStyle = label.style;
  33663. var hostEl = label.__hostTarget;
  33664. var textConfig = hostEl.textConfig || {}; // TODO: If label is in other state.
  33665. var labelTransform = label.getComputedTransform();
  33666. var labelRect = label.getBoundingRect().plain();
  33667. BoundingRect.applyTransform(labelRect, labelRect, labelTransform);
  33668. if (labelTransform) {
  33669. dummyTransformable.setLocalTransform(labelTransform);
  33670. } else {
  33671. // Identity transform.
  33672. dummyTransformable.x = dummyTransformable.y = dummyTransformable.rotation = dummyTransformable.originX = dummyTransformable.originY = 0;
  33673. dummyTransformable.scaleX = dummyTransformable.scaleY = 1;
  33674. }
  33675. var host = label.__hostTarget;
  33676. var hostRect;
  33677. if (host) {
  33678. hostRect = host.getBoundingRect().plain();
  33679. var transform = host.getComputedTransform();
  33680. BoundingRect.applyTransform(hostRect, hostRect, transform);
  33681. }
  33682. var labelGuide = hostRect && host.getTextGuideLine();
  33683. this._labelList.push({
  33684. label: label,
  33685. labelLine: labelGuide,
  33686. seriesModel: seriesModel,
  33687. dataIndex: dataIndex,
  33688. dataType: dataType,
  33689. layoutOption: layoutOption,
  33690. computedLayoutOption: null,
  33691. rect: labelRect,
  33692. hostRect: hostRect,
  33693. // Label with lower priority will be hidden when overlapped
  33694. // Use rect size as default priority
  33695. priority: hostRect ? hostRect.width * hostRect.height : 0,
  33696. // Save default label attributes.
  33697. // For restore if developers want get back to default value in callback.
  33698. defaultAttr: {
  33699. ignore: label.ignore,
  33700. labelGuideIgnore: labelGuide && labelGuide.ignore,
  33701. x: dummyTransformable.x,
  33702. y: dummyTransformable.y,
  33703. scaleX: dummyTransformable.scaleX,
  33704. scaleY: dummyTransformable.scaleY,
  33705. rotation: dummyTransformable.rotation,
  33706. style: {
  33707. x: labelStyle.x,
  33708. y: labelStyle.y,
  33709. align: labelStyle.align,
  33710. verticalAlign: labelStyle.verticalAlign,
  33711. width: labelStyle.width,
  33712. height: labelStyle.height,
  33713. fontSize: labelStyle.fontSize
  33714. },
  33715. cursor: label.cursor,
  33716. attachedPos: textConfig.position,
  33717. attachedRot: textConfig.rotation
  33718. }
  33719. });
  33720. };
  33721. LabelManager.prototype.addLabelsOfSeries = function (chartView) {
  33722. var _this = this;
  33723. this._chartViewList.push(chartView);
  33724. var seriesModel = chartView.__model;
  33725. var layoutOption = seriesModel.get('labelLayout');
  33726. /**
  33727. * Ignore layouting if it's not specified anything.
  33728. */
  33729. if (!(isFunction(layoutOption) || keys(layoutOption).length)) {
  33730. return;
  33731. }
  33732. chartView.group.traverse(function (child) {
  33733. if (child.ignore) {
  33734. return true; // Stop traverse descendants.
  33735. } // Only support label being hosted on graphic elements.
  33736. var textEl = child.getTextContent();
  33737. var ecData = getECData(child); // Can only attach the text on the element with dataIndex
  33738. if (textEl && !textEl.disableLabelLayout) {
  33739. _this._addLabel(ecData.dataIndex, ecData.dataType, seriesModel, textEl, layoutOption);
  33740. }
  33741. });
  33742. };
  33743. LabelManager.prototype.updateLayoutConfig = function (api) {
  33744. var width = api.getWidth();
  33745. var height = api.getHeight();
  33746. function createDragHandler(el, labelLineModel) {
  33747. return function () {
  33748. updateLabelLinePoints(el, labelLineModel);
  33749. };
  33750. }
  33751. for (var i = 0; i < this._labelList.length; i++) {
  33752. var labelItem = this._labelList[i];
  33753. var label = labelItem.label;
  33754. var hostEl = label.__hostTarget;
  33755. var defaultLabelAttr = labelItem.defaultAttr;
  33756. var layoutOption = void 0; // TODO A global layout option?
  33757. if (isFunction(labelItem.layoutOption)) {
  33758. layoutOption = labelItem.layoutOption(prepareLayoutCallbackParams(labelItem, hostEl));
  33759. } else {
  33760. layoutOption = labelItem.layoutOption;
  33761. }
  33762. layoutOption = layoutOption || {};
  33763. labelItem.computedLayoutOption = layoutOption;
  33764. var degreeToRadian = Math.PI / 180; // TODO hostEl should always exists.
  33765. // Or label should not have parent because the x, y is all in global space.
  33766. if (hostEl) {
  33767. hostEl.setTextConfig({
  33768. // Force to set local false.
  33769. local: false,
  33770. // Ignore position and rotation config on the host el if x or y is changed.
  33771. position: layoutOption.x != null || layoutOption.y != null ? null : defaultLabelAttr.attachedPos,
  33772. // Ignore rotation config on the host el if rotation is changed.
  33773. rotation: layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.attachedRot,
  33774. offset: [layoutOption.dx || 0, layoutOption.dy || 0]
  33775. });
  33776. }
  33777. var needsUpdateLabelLine = false;
  33778. if (layoutOption.x != null) {
  33779. // TODO width of chart view.
  33780. label.x = parsePercent$1(layoutOption.x, width);
  33781. label.setStyle('x', 0); // Ignore movement in style. TODO: origin.
  33782. needsUpdateLabelLine = true;
  33783. } else {
  33784. label.x = defaultLabelAttr.x;
  33785. label.setStyle('x', defaultLabelAttr.style.x);
  33786. }
  33787. if (layoutOption.y != null) {
  33788. // TODO height of chart view.
  33789. label.y = parsePercent$1(layoutOption.y, height);
  33790. label.setStyle('y', 0); // Ignore movement in style.
  33791. needsUpdateLabelLine = true;
  33792. } else {
  33793. label.y = defaultLabelAttr.y;
  33794. label.setStyle('y', defaultLabelAttr.style.y);
  33795. }
  33796. if (layoutOption.labelLinePoints) {
  33797. var guideLine = hostEl.getTextGuideLine();
  33798. if (guideLine) {
  33799. guideLine.setShape({
  33800. points: layoutOption.labelLinePoints
  33801. }); // Not update
  33802. needsUpdateLabelLine = false;
  33803. }
  33804. }
  33805. var labelLayoutStore = labelLayoutInnerStore(label);
  33806. labelLayoutStore.needsUpdateLabelLine = needsUpdateLabelLine;
  33807. label.rotation = layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.rotation;
  33808. label.scaleX = defaultLabelAttr.scaleX;
  33809. label.scaleY = defaultLabelAttr.scaleY;
  33810. for (var k = 0; k < LABEL_OPTION_TO_STYLE_KEYS.length; k++) {
  33811. var key = LABEL_OPTION_TO_STYLE_KEYS[k];
  33812. label.setStyle(key, layoutOption[key] != null ? layoutOption[key] : defaultLabelAttr.style[key]);
  33813. }
  33814. if (layoutOption.draggable) {
  33815. label.draggable = true;
  33816. label.cursor = 'move';
  33817. if (hostEl) {
  33818. var hostModel = labelItem.seriesModel;
  33819. if (labelItem.dataIndex != null) {
  33820. var data = labelItem.seriesModel.getData(labelItem.dataType);
  33821. hostModel = data.getItemModel(labelItem.dataIndex);
  33822. }
  33823. label.on('drag', createDragHandler(hostEl, hostModel.getModel('labelLine')));
  33824. }
  33825. } else {
  33826. // TODO Other drag functions?
  33827. label.off('drag');
  33828. label.cursor = defaultLabelAttr.cursor;
  33829. }
  33830. }
  33831. };
  33832. LabelManager.prototype.layout = function (api) {
  33833. var width = api.getWidth();
  33834. var height = api.getHeight();
  33835. var labelList = prepareLayoutList(this._labelList);
  33836. var labelsNeedsAdjustOnX = filter(labelList, function (item) {
  33837. return item.layoutOption.moveOverlap === 'shiftX';
  33838. });
  33839. var labelsNeedsAdjustOnY = filter(labelList, function (item) {
  33840. return item.layoutOption.moveOverlap === 'shiftY';
  33841. });
  33842. shiftLayoutOnX(labelsNeedsAdjustOnX, 0, width);
  33843. shiftLayoutOnY(labelsNeedsAdjustOnY, 0, height);
  33844. var labelsNeedsHideOverlap = filter(labelList, function (item) {
  33845. return item.layoutOption.hideOverlap;
  33846. });
  33847. hideOverlap(labelsNeedsHideOverlap);
  33848. };
  33849. /**
  33850. * Process all labels. Not only labels with layoutOption.
  33851. */
  33852. LabelManager.prototype.processLabelsOverall = function () {
  33853. var _this = this;
  33854. each(this._chartViewList, function (chartView) {
  33855. var seriesModel = chartView.__model;
  33856. var ignoreLabelLineUpdate = chartView.ignoreLabelLineUpdate;
  33857. var animationEnabled = seriesModel.isAnimationEnabled();
  33858. chartView.group.traverse(function (child) {
  33859. if (child.ignore && !child.forceLabelAnimation) {
  33860. return true; // Stop traverse descendants.
  33861. }
  33862. var needsUpdateLabelLine = !ignoreLabelLineUpdate;
  33863. var label = child.getTextContent();
  33864. if (!needsUpdateLabelLine && label) {
  33865. needsUpdateLabelLine = labelLayoutInnerStore(label).needsUpdateLabelLine;
  33866. }
  33867. if (needsUpdateLabelLine) {
  33868. _this._updateLabelLine(child, seriesModel);
  33869. }
  33870. if (animationEnabled) {
  33871. _this._animateLabels(child, seriesModel);
  33872. }
  33873. });
  33874. });
  33875. };
  33876. LabelManager.prototype._updateLabelLine = function (el, seriesModel) {
  33877. // Only support label being hosted on graphic elements.
  33878. var textEl = el.getTextContent(); // Update label line style.
  33879. var ecData = getECData(el);
  33880. var dataIndex = ecData.dataIndex; // Only support labelLine on the labels represent data.
  33881. if (textEl && dataIndex != null) {
  33882. var data = seriesModel.getData(ecData.dataType);
  33883. var itemModel = data.getItemModel(dataIndex);
  33884. var defaultStyle = {};
  33885. var visualStyle = data.getItemVisual(dataIndex, 'style');
  33886. var visualType = data.getVisual('drawType'); // Default to be same with main color
  33887. defaultStyle.stroke = visualStyle[visualType];
  33888. var labelLineModel = itemModel.getModel('labelLine');
  33889. setLabelLineStyle(el, getLabelLineStatesModels(itemModel), defaultStyle);
  33890. updateLabelLinePoints(el, labelLineModel);
  33891. }
  33892. };
  33893. LabelManager.prototype._animateLabels = function (el, seriesModel) {
  33894. var textEl = el.getTextContent();
  33895. var guideLine = el.getTextGuideLine(); // Animate
  33896. if (textEl // `forceLabelAnimation` has the highest priority
  33897. && (el.forceLabelAnimation || !textEl.ignore && !textEl.invisible && !el.disableLabelAnimation && !isElementRemoved(el))) {
  33898. var layoutStore = labelLayoutInnerStore(textEl);
  33899. var oldLayout = layoutStore.oldLayout;
  33900. var ecData = getECData(el);
  33901. var dataIndex = ecData.dataIndex;
  33902. var newProps = {
  33903. x: textEl.x,
  33904. y: textEl.y,
  33905. rotation: textEl.rotation
  33906. };
  33907. var data = seriesModel.getData(ecData.dataType);
  33908. if (!oldLayout) {
  33909. textEl.attr(newProps); // Disable fade in animation if value animation is enabled.
  33910. if (!labelInner(textEl).valueAnimation) {
  33911. var oldOpacity = retrieve2(textEl.style.opacity, 1); // Fade in animation
  33912. textEl.style.opacity = 0;
  33913. initProps(textEl, {
  33914. style: {
  33915. opacity: oldOpacity
  33916. }
  33917. }, seriesModel, dataIndex);
  33918. }
  33919. } else {
  33920. textEl.attr(oldLayout); // Make sure the animation from is in the right status.
  33921. var prevStates = el.prevStates;
  33922. if (prevStates) {
  33923. if (indexOf(prevStates, 'select') >= 0) {
  33924. textEl.attr(layoutStore.oldLayoutSelect);
  33925. }
  33926. if (indexOf(prevStates, 'emphasis') >= 0) {
  33927. textEl.attr(layoutStore.oldLayoutEmphasis);
  33928. }
  33929. }
  33930. updateProps(textEl, newProps, seriesModel, dataIndex);
  33931. }
  33932. layoutStore.oldLayout = newProps;
  33933. if (textEl.states.select) {
  33934. var layoutSelect = layoutStore.oldLayoutSelect = {};
  33935. extendWithKeys(layoutSelect, newProps, LABEL_LAYOUT_PROPS);
  33936. extendWithKeys(layoutSelect, textEl.states.select, LABEL_LAYOUT_PROPS);
  33937. }
  33938. if (textEl.states.emphasis) {
  33939. var layoutEmphasis = layoutStore.oldLayoutEmphasis = {};
  33940. extendWithKeys(layoutEmphasis, newProps, LABEL_LAYOUT_PROPS);
  33941. extendWithKeys(layoutEmphasis, textEl.states.emphasis, LABEL_LAYOUT_PROPS);
  33942. }
  33943. animateLabelValue(textEl, dataIndex, data, seriesModel, seriesModel);
  33944. }
  33945. if (guideLine && !guideLine.ignore && !guideLine.invisible) {
  33946. var layoutStore = labelLineAnimationStore(guideLine);
  33947. var oldLayout = layoutStore.oldLayout;
  33948. var newLayout = {
  33949. points: guideLine.shape.points
  33950. };
  33951. if (!oldLayout) {
  33952. guideLine.setShape(newLayout);
  33953. guideLine.style.strokePercent = 0;
  33954. initProps(guideLine, {
  33955. style: {
  33956. strokePercent: 1
  33957. }
  33958. }, seriesModel);
  33959. } else {
  33960. guideLine.attr({
  33961. shape: oldLayout
  33962. });
  33963. updateProps(guideLine, {
  33964. shape: newLayout
  33965. }, seriesModel);
  33966. }
  33967. layoutStore.oldLayout = newLayout;
  33968. }
  33969. };
  33970. return LabelManager;
  33971. }();
  33972. var getLabelManager = makeInner();
  33973. function installLabelLayout(registers) {
  33974. registers.registerUpdateLifecycle('series:beforeupdate', function (ecModel, api, params) {
  33975. // TODO api provide an namespace that can save stuff per instance
  33976. var labelManager = getLabelManager(api).labelManager;
  33977. if (!labelManager) {
  33978. labelManager = getLabelManager(api).labelManager = new LabelManager();
  33979. }
  33980. labelManager.clearLabels();
  33981. });
  33982. registers.registerUpdateLifecycle('series:layoutlabels', function (ecModel, api, params) {
  33983. var labelManager = getLabelManager(api).labelManager;
  33984. params.updatedSeries.forEach(function (series) {
  33985. labelManager.addLabelsOfSeries(api.getViewOfSeriesModel(series));
  33986. });
  33987. labelManager.updateLayoutConfig(api);
  33988. labelManager.layout(api);
  33989. labelManager.processLabelsOverall();
  33990. });
  33991. }
  33992. var mathSin$4 = Math.sin;
  33993. var mathCos$4 = Math.cos;
  33994. var PI$4 = Math.PI;
  33995. var PI2$7 = Math.PI * 2;
  33996. var degree = 180 / PI$4;
  33997. var SVGPathRebuilder = (function () {
  33998. function SVGPathRebuilder() {
  33999. }
  34000. SVGPathRebuilder.prototype.reset = function (precision) {
  34001. this._start = true;
  34002. this._d = [];
  34003. this._str = '';
  34004. this._p = Math.pow(10, precision || 4);
  34005. };
  34006. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  34007. this._add('M', x, y);
  34008. };
  34009. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  34010. this._add('L', x, y);
  34011. };
  34012. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  34013. this._add('C', x, y, x2, y2, x3, y3);
  34014. };
  34015. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  34016. this._add('Q', x, y, x2, y2);
  34017. };
  34018. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  34019. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  34020. };
  34021. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  34022. var dTheta = endAngle - startAngle;
  34023. var clockwise = !anticlockwise;
  34024. var dThetaPositive = Math.abs(dTheta);
  34025. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  34026. || (clockwise ? dTheta >= PI2$7 : -dTheta >= PI2$7);
  34027. var unifiedTheta = dTheta > 0 ? dTheta % PI2$7 : (dTheta % PI2$7 + PI2$7);
  34028. var large = false;
  34029. if (isCircle) {
  34030. large = true;
  34031. }
  34032. else if (isAroundZero$1(dThetaPositive)) {
  34033. large = false;
  34034. }
  34035. else {
  34036. large = (unifiedTheta >= PI$4) === !!clockwise;
  34037. }
  34038. var x0 = cx + rx * mathCos$4(startAngle);
  34039. var y0 = cy + ry * mathSin$4(startAngle);
  34040. if (this._start) {
  34041. this._add('M', x0, y0);
  34042. }
  34043. var xRot = Math.round(psi * degree);
  34044. if (isCircle) {
  34045. var p = 1 / this._p;
  34046. var dTheta_1 = (clockwise ? 1 : -1) * (PI2$7 - p);
  34047. this._add('A', rx, ry, xRot, 1, +clockwise, cx + rx * mathCos$4(startAngle + dTheta_1), cy + ry * mathSin$4(startAngle + dTheta_1));
  34048. if (p > 1e-2) {
  34049. this._add('A', rx, ry, xRot, 0, +clockwise, x0, y0);
  34050. }
  34051. }
  34052. else {
  34053. var x = cx + rx * mathCos$4(endAngle);
  34054. var y = cy + ry * mathSin$4(endAngle);
  34055. this._add('A', rx, ry, xRot, +large, +clockwise, x, y);
  34056. }
  34057. };
  34058. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  34059. this._add('M', x, y);
  34060. this._add('l', w, 0);
  34061. this._add('l', 0, h);
  34062. this._add('l', -w, 0);
  34063. this._add('Z');
  34064. };
  34065. SVGPathRebuilder.prototype.closePath = function () {
  34066. if (this._d.length > 0) {
  34067. this._add('Z');
  34068. }
  34069. };
  34070. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  34071. var vals = [];
  34072. var p = this._p;
  34073. for (var i = 1; i < arguments.length; i++) {
  34074. var val = arguments[i];
  34075. if (isNaN(val)) {
  34076. this._invalid = true;
  34077. return;
  34078. }
  34079. vals.push(Math.round(val * p) / p);
  34080. }
  34081. this._d.push(cmd + vals.join(' '));
  34082. this._start = cmd === 'Z';
  34083. };
  34084. SVGPathRebuilder.prototype.generateStr = function () {
  34085. this._str = this._invalid ? '' : this._d.join('');
  34086. this._d = [];
  34087. };
  34088. SVGPathRebuilder.prototype.getStr = function () {
  34089. return this._str;
  34090. };
  34091. return SVGPathRebuilder;
  34092. }());
  34093. var NONE = 'none';
  34094. var mathRound$1 = Math.round;
  34095. function pathHasFill(style) {
  34096. var fill = style.fill;
  34097. return fill != null && fill !== NONE;
  34098. }
  34099. function pathHasStroke(style) {
  34100. var stroke = style.stroke;
  34101. return stroke != null && stroke !== NONE;
  34102. }
  34103. var strokeProps = ['lineCap', 'miterLimit', 'lineJoin'];
  34104. var svgStrokeProps = map(strokeProps, function (prop) { return "stroke-" + prop.toLowerCase(); });
  34105. function mapStyleToAttrs(updateAttr, style, el, forceUpdate) {
  34106. var opacity = style.opacity == null ? 1 : style.opacity;
  34107. if (el instanceof ZRImage) {
  34108. updateAttr('opacity', opacity);
  34109. return;
  34110. }
  34111. if (pathHasFill(style)) {
  34112. var fill = normalizeColor(style.fill);
  34113. updateAttr('fill', fill.color);
  34114. var fillOpacity = style.fillOpacity != null
  34115. ? style.fillOpacity * fill.opacity * opacity
  34116. : fill.opacity * opacity;
  34117. if (forceUpdate || fillOpacity < 1) {
  34118. updateAttr('fill-opacity', fillOpacity);
  34119. }
  34120. }
  34121. else {
  34122. updateAttr('fill', NONE);
  34123. }
  34124. if (pathHasStroke(style)) {
  34125. var stroke = normalizeColor(style.stroke);
  34126. updateAttr('stroke', stroke.color);
  34127. var strokeScale = style.strokeNoScale
  34128. ? el.getLineScale()
  34129. : 1;
  34130. var strokeWidth = (strokeScale ? (style.lineWidth || 0) / strokeScale : 0);
  34131. var strokeOpacity = style.strokeOpacity != null
  34132. ? style.strokeOpacity * stroke.opacity * opacity
  34133. : stroke.opacity * opacity;
  34134. var strokeFirst = style.strokeFirst;
  34135. if (forceUpdate || strokeWidth !== 1) {
  34136. updateAttr('stroke-width', strokeWidth);
  34137. }
  34138. if (forceUpdate || strokeFirst) {
  34139. updateAttr('paint-order', strokeFirst ? 'stroke' : 'fill');
  34140. }
  34141. if (forceUpdate || strokeOpacity < 1) {
  34142. updateAttr('stroke-opacity', strokeOpacity);
  34143. }
  34144. if (style.lineDash) {
  34145. var _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  34146. if (lineDash) {
  34147. lineDashOffset = mathRound$1(lineDashOffset || 0);
  34148. updateAttr('stroke-dasharray', lineDash.join(','));
  34149. if (lineDashOffset || forceUpdate) {
  34150. updateAttr('stroke-dashoffset', lineDashOffset);
  34151. }
  34152. }
  34153. }
  34154. else if (forceUpdate) {
  34155. updateAttr('stroke-dasharray', NONE);
  34156. }
  34157. for (var i = 0; i < strokeProps.length; i++) {
  34158. var propName = strokeProps[i];
  34159. if (forceUpdate || style[propName] !== DEFAULT_PATH_STYLE[propName]) {
  34160. var val = style[propName] || DEFAULT_PATH_STYLE[propName];
  34161. val && updateAttr(svgStrokeProps[i], val);
  34162. }
  34163. }
  34164. }
  34165. else if (forceUpdate) {
  34166. updateAttr('stroke', NONE);
  34167. }
  34168. }
  34169. var SVGNS = 'http://www.w3.org/2000/svg';
  34170. var XLINKNS = 'http://www.w3.org/1999/xlink';
  34171. var XMLNS = 'http://www.w3.org/2000/xmlns/';
  34172. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
  34173. function createElement(name) {
  34174. return document.createElementNS(SVGNS, name);
  34175. }
  34176. function createVNode(tag, key, attrs, children, text) {
  34177. return {
  34178. tag: tag,
  34179. attrs: attrs || {},
  34180. children: children,
  34181. text: text,
  34182. key: key
  34183. };
  34184. }
  34185. function createElementOpen(name, attrs) {
  34186. var attrsStr = [];
  34187. if (attrs) {
  34188. for (var key in attrs) {
  34189. var val = attrs[key];
  34190. var part = key;
  34191. if (val === false) {
  34192. continue;
  34193. }
  34194. else if (val !== true && val != null) {
  34195. part += "=\"" + val + "\"";
  34196. }
  34197. attrsStr.push(part);
  34198. }
  34199. }
  34200. return "<" + name + " " + attrsStr.join(' ') + ">";
  34201. }
  34202. function createElementClose(name) {
  34203. return "</" + name + ">";
  34204. }
  34205. function vNodeToString(el, opts) {
  34206. opts = opts || {};
  34207. var S = opts.newline ? '\n' : '';
  34208. function convertElToString(el) {
  34209. var children = el.children, tag = el.tag, attrs = el.attrs, text = el.text;
  34210. return createElementOpen(tag, attrs)
  34211. + (tag !== 'style' ? encodeHTML(text) : text || '')
  34212. + (children ? "" + S + map(children, function (child) { return convertElToString(child); }).join(S) + S : '')
  34213. + createElementClose(tag);
  34214. }
  34215. return convertElToString(el);
  34216. }
  34217. function getCssString(selectorNodes, animationNodes, opts) {
  34218. opts = opts || {};
  34219. var S = opts.newline ? '\n' : '';
  34220. var bracketBegin = " {" + S;
  34221. var bracketEnd = S + "}";
  34222. var selectors = map(keys(selectorNodes), function (className) {
  34223. return className + bracketBegin + map(keys(selectorNodes[className]), function (attrName) {
  34224. return attrName + ":" + selectorNodes[className][attrName] + ";";
  34225. }).join(S) + bracketEnd;
  34226. }).join(S);
  34227. var animations = map(keys(animationNodes), function (animationName) {
  34228. return "@keyframes " + animationName + bracketBegin + map(keys(animationNodes[animationName]), function (percent) {
  34229. return percent + bracketBegin + map(keys(animationNodes[animationName][percent]), function (attrName) {
  34230. var val = animationNodes[animationName][percent][attrName];
  34231. if (attrName === 'd') {
  34232. val = "path(\"" + val + "\")";
  34233. }
  34234. return attrName + ":" + val + ";";
  34235. }).join(S) + bracketEnd;
  34236. }).join(S) + bracketEnd;
  34237. }).join(S);
  34238. if (!selectors && !animations) {
  34239. return '';
  34240. }
  34241. return ['<![CDATA[', selectors, animations, ']]>'].join(S);
  34242. }
  34243. function createBrushScope(zrId) {
  34244. return {
  34245. zrId: zrId,
  34246. shadowCache: {},
  34247. patternCache: {},
  34248. gradientCache: {},
  34249. clipPathCache: {},
  34250. defs: {},
  34251. cssNodes: {},
  34252. cssAnims: {},
  34253. cssClassIdx: 0,
  34254. cssAnimIdx: 0,
  34255. shadowIdx: 0,
  34256. gradientIdx: 0,
  34257. patternIdx: 0,
  34258. clipPathIdx: 0
  34259. };
  34260. }
  34261. function createSVGVNode(width, height, children, useViewBox) {
  34262. return createVNode('svg', 'root', {
  34263. 'width': width,
  34264. 'height': height,
  34265. 'xmlns': SVGNS,
  34266. 'xmlns:xlink': XLINKNS,
  34267. 'version': '1.1',
  34268. 'baseProfile': 'full',
  34269. 'viewBox': useViewBox ? "0 0 " + width + " " + height : false
  34270. }, children);
  34271. }
  34272. var EASING_MAP = {
  34273. cubicIn: '0.32,0,0.67,0',
  34274. cubicOut: '0.33,1,0.68,1',
  34275. cubicInOut: '0.65,0,0.35,1',
  34276. quadraticIn: '0.11,0,0.5,0',
  34277. quadraticOut: '0.5,1,0.89,1',
  34278. quadraticInOut: '0.45,0,0.55,1',
  34279. quarticIn: '0.5,0,0.75,0',
  34280. quarticOut: '0.25,1,0.5,1',
  34281. quarticInOut: '0.76,0,0.24,1',
  34282. quinticIn: '0.64,0,0.78,0',
  34283. quinticOut: '0.22,1,0.36,1',
  34284. quinticInOut: '0.83,0,0.17,1',
  34285. sinusoidalIn: '0.12,0,0.39,0',
  34286. sinusoidalOut: '0.61,1,0.88,1',
  34287. sinusoidalInOut: '0.37,0,0.63,1',
  34288. exponentialIn: '0.7,0,0.84,0',
  34289. exponentialOut: '0.16,1,0.3,1',
  34290. exponentialInOut: '0.87,0,0.13,1',
  34291. circularIn: '0.55,0,1,0.45',
  34292. circularOut: '0,0.55,0.45,1',
  34293. circularInOut: '0.85,0,0.15,1'
  34294. };
  34295. var transformOriginKey = 'transform-origin';
  34296. function buildPathString(el, kfShape, path) {
  34297. var shape = extend({}, el.shape);
  34298. extend(shape, kfShape);
  34299. el.buildPath(path, shape);
  34300. var svgPathBuilder = new SVGPathRebuilder();
  34301. svgPathBuilder.reset(getPathPrecision(el));
  34302. path.rebuildPath(svgPathBuilder, 1);
  34303. svgPathBuilder.generateStr();
  34304. return svgPathBuilder.getStr();
  34305. }
  34306. function setTransformOrigin(target, transform) {
  34307. var originX = transform.originX, originY = transform.originY;
  34308. if (originX || originY) {
  34309. target[transformOriginKey] = originX + "px " + originY + "px";
  34310. }
  34311. }
  34312. var ANIMATE_STYLE_MAP = {
  34313. fill: 'fill',
  34314. opacity: 'opacity',
  34315. lineWidth: 'stroke-width',
  34316. lineDashOffset: 'stroke-dashoffset'
  34317. };
  34318. function addAnimation(cssAnim, scope) {
  34319. var animationName = scope.zrId + '-ani-' + scope.cssAnimIdx++;
  34320. scope.cssAnims[animationName] = cssAnim;
  34321. return animationName;
  34322. }
  34323. function createCompoundPathCSSAnimation(el, attrs, scope) {
  34324. var paths = el.shape.paths;
  34325. var composedAnim = {};
  34326. var cssAnimationCfg;
  34327. var cssAnimationName;
  34328. each(paths, function (path) {
  34329. var subScope = createBrushScope(scope.zrId);
  34330. subScope.animation = true;
  34331. createCSSAnimation(path, {}, subScope, true);
  34332. var cssAnims = subScope.cssAnims;
  34333. var cssNodes = subScope.cssNodes;
  34334. var animNames = keys(cssAnims);
  34335. var len = animNames.length;
  34336. if (!len) {
  34337. return;
  34338. }
  34339. cssAnimationName = animNames[len - 1];
  34340. var lastAnim = cssAnims[cssAnimationName];
  34341. for (var percent in lastAnim) {
  34342. var kf = lastAnim[percent];
  34343. composedAnim[percent] = composedAnim[percent] || { d: '' };
  34344. composedAnim[percent].d += kf.d || '';
  34345. }
  34346. for (var className in cssNodes) {
  34347. var val = cssNodes[className].animation;
  34348. if (val.indexOf(cssAnimationName) >= 0) {
  34349. cssAnimationCfg = val;
  34350. }
  34351. }
  34352. });
  34353. if (!cssAnimationCfg) {
  34354. return;
  34355. }
  34356. attrs.d = false;
  34357. var animationName = addAnimation(composedAnim, scope);
  34358. return cssAnimationCfg.replace(cssAnimationName, animationName);
  34359. }
  34360. function getEasingFunc(easing) {
  34361. return isString(easing)
  34362. ? EASING_MAP[easing]
  34363. ? "cubic-bezier(" + EASING_MAP[easing] + ")"
  34364. : createCubicEasingFunc(easing) ? easing : ''
  34365. : '';
  34366. }
  34367. function createCSSAnimation(el, attrs, scope, onlyShape) {
  34368. var animators = el.animators;
  34369. var len = animators.length;
  34370. var cssAnimations = [];
  34371. if (el instanceof CompoundPath) {
  34372. var animationCfg = createCompoundPathCSSAnimation(el, attrs, scope);
  34373. if (animationCfg) {
  34374. cssAnimations.push(animationCfg);
  34375. }
  34376. else if (!len) {
  34377. return;
  34378. }
  34379. }
  34380. else if (!len) {
  34381. return;
  34382. }
  34383. var groupAnimators = {};
  34384. for (var i = 0; i < len; i++) {
  34385. var animator = animators[i];
  34386. var cfgArr = [animator.getMaxTime() / 1000 + 's'];
  34387. var easing = getEasingFunc(animator.getClip().easing);
  34388. var delay = animator.getDelay();
  34389. if (easing) {
  34390. cfgArr.push(easing);
  34391. }
  34392. else {
  34393. cfgArr.push('linear');
  34394. }
  34395. if (delay) {
  34396. cfgArr.push(delay / 1000 + 's');
  34397. }
  34398. if (animator.getLoop()) {
  34399. cfgArr.push('infinite');
  34400. }
  34401. var cfg = cfgArr.join(' ');
  34402. groupAnimators[cfg] = groupAnimators[cfg] || [cfg, []];
  34403. groupAnimators[cfg][1].push(animator);
  34404. }
  34405. function createSingleCSSAnimation(groupAnimator) {
  34406. var animators = groupAnimator[1];
  34407. var len = animators.length;
  34408. var transformKfs = {};
  34409. var shapeKfs = {};
  34410. var finalKfs = {};
  34411. var animationTimingFunctionAttrName = 'animation-timing-function';
  34412. function saveAnimatorTrackToCssKfs(animator, cssKfs, toCssAttrName) {
  34413. var tracks = animator.getTracks();
  34414. var maxTime = animator.getMaxTime();
  34415. for (var k = 0; k < tracks.length; k++) {
  34416. var track = tracks[k];
  34417. if (track.needsAnimate()) {
  34418. var kfs = track.keyframes;
  34419. var attrName = track.propName;
  34420. toCssAttrName && (attrName = toCssAttrName(attrName));
  34421. if (attrName) {
  34422. for (var i = 0; i < kfs.length; i++) {
  34423. var kf = kfs[i];
  34424. var percent = Math.round(kf.time / maxTime * 100) + '%';
  34425. var kfEasing = getEasingFunc(kf.easing);
  34426. var rawValue = kf.rawValue;
  34427. if (isString(rawValue) || isNumber(rawValue)) {
  34428. cssKfs[percent] = cssKfs[percent] || {};
  34429. cssKfs[percent][attrName] = kf.rawValue;
  34430. if (kfEasing) {
  34431. cssKfs[percent][animationTimingFunctionAttrName] = kfEasing;
  34432. }
  34433. }
  34434. }
  34435. }
  34436. }
  34437. }
  34438. }
  34439. for (var i = 0; i < len; i++) {
  34440. var animator = animators[i];
  34441. var targetProp = animator.targetName;
  34442. if (!targetProp) {
  34443. !onlyShape && saveAnimatorTrackToCssKfs(animator, transformKfs);
  34444. }
  34445. else if (targetProp === 'shape') {
  34446. saveAnimatorTrackToCssKfs(animator, shapeKfs);
  34447. }
  34448. }
  34449. for (var percent in transformKfs) {
  34450. var transform = {};
  34451. copyTransform(transform, el);
  34452. extend(transform, transformKfs[percent]);
  34453. var str = getSRTTransformString(transform);
  34454. var timingFunction = transformKfs[percent][animationTimingFunctionAttrName];
  34455. finalKfs[percent] = str ? {
  34456. transform: str
  34457. } : {};
  34458. setTransformOrigin(finalKfs[percent], transform);
  34459. if (timingFunction) {
  34460. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34461. }
  34462. }
  34463. var path;
  34464. var canAnimateShape = true;
  34465. for (var percent in shapeKfs) {
  34466. finalKfs[percent] = finalKfs[percent] || {};
  34467. var isFirst = !path;
  34468. var timingFunction = shapeKfs[percent][animationTimingFunctionAttrName];
  34469. if (isFirst) {
  34470. path = new PathProxy();
  34471. }
  34472. var len_1 = path.len();
  34473. path.reset();
  34474. finalKfs[percent].d = buildPathString(el, shapeKfs[percent], path);
  34475. var newLen = path.len();
  34476. if (!isFirst && len_1 !== newLen) {
  34477. canAnimateShape = false;
  34478. break;
  34479. }
  34480. if (timingFunction) {
  34481. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34482. }
  34483. }
  34484. if (!canAnimateShape) {
  34485. for (var percent in finalKfs) {
  34486. delete finalKfs[percent].d;
  34487. }
  34488. }
  34489. if (!onlyShape) {
  34490. for (var i = 0; i < len; i++) {
  34491. var animator = animators[i];
  34492. var targetProp = animator.targetName;
  34493. if (targetProp === 'style') {
  34494. saveAnimatorTrackToCssKfs(animator, finalKfs, function (propName) { return ANIMATE_STYLE_MAP[propName]; });
  34495. }
  34496. }
  34497. }
  34498. var percents = keys(finalKfs);
  34499. var allTransformOriginSame = true;
  34500. var transformOrigin;
  34501. for (var i = 1; i < percents.length; i++) {
  34502. var p0 = percents[i - 1];
  34503. var p1 = percents[i];
  34504. if (finalKfs[p0][transformOriginKey] !== finalKfs[p1][transformOriginKey]) {
  34505. allTransformOriginSame = false;
  34506. break;
  34507. }
  34508. transformOrigin = finalKfs[p0][transformOriginKey];
  34509. }
  34510. if (allTransformOriginSame && transformOrigin) {
  34511. for (var percent in finalKfs) {
  34512. if (finalKfs[percent][transformOriginKey]) {
  34513. delete finalKfs[percent][transformOriginKey];
  34514. }
  34515. }
  34516. attrs[transformOriginKey] = transformOrigin;
  34517. }
  34518. if (filter(percents, function (percent) { return keys(finalKfs[percent]).length > 0; }).length) {
  34519. var animationName = addAnimation(finalKfs, scope);
  34520. return animationName + " " + groupAnimator[0] + " both";
  34521. }
  34522. }
  34523. for (var key in groupAnimators) {
  34524. var animationCfg = createSingleCSSAnimation(groupAnimators[key]);
  34525. if (animationCfg) {
  34526. cssAnimations.push(animationCfg);
  34527. }
  34528. }
  34529. if (cssAnimations.length) {
  34530. var className = scope.zrId + '-cls-' + scope.cssClassIdx++;
  34531. scope.cssNodes['.' + className] = {
  34532. animation: cssAnimations.join(',')
  34533. };
  34534. attrs["class"] = className;
  34535. }
  34536. }
  34537. var round$2 = Math.round;
  34538. function isImageLike$1(val) {
  34539. return val && isString(val.src);
  34540. }
  34541. function isCanvasLike(val) {
  34542. return val && isFunction(val.toDataURL);
  34543. }
  34544. function setStyleAttrs(attrs, style, el, scope) {
  34545. mapStyleToAttrs(function (key, val) {
  34546. var isFillStroke = key === 'fill' || key === 'stroke';
  34547. if (isFillStroke && isGradient(val)) {
  34548. setGradient(style, attrs, key, scope);
  34549. }
  34550. else if (isFillStroke && isPattern(val)) {
  34551. setPattern(el, attrs, key, scope);
  34552. }
  34553. else {
  34554. attrs[key] = val;
  34555. }
  34556. }, style, el, false);
  34557. setShadow(el, attrs, scope);
  34558. }
  34559. function noRotateScale(m) {
  34560. return isAroundZero$1(m[0] - 1)
  34561. && isAroundZero$1(m[1])
  34562. && isAroundZero$1(m[2])
  34563. && isAroundZero$1(m[3] - 1);
  34564. }
  34565. function noTranslate(m) {
  34566. return isAroundZero$1(m[4]) && isAroundZero$1(m[5]);
  34567. }
  34568. function setTransform(attrs, m, compress) {
  34569. if (m && !(noTranslate(m) && noRotateScale(m))) {
  34570. var mul = compress ? 10 : 1e4;
  34571. attrs.transform = noRotateScale(m)
  34572. ? "translate(" + round$2(m[4] * mul) / mul + " " + round$2(m[5] * mul) / mul + ")" : getMatrixStr(m);
  34573. }
  34574. }
  34575. function convertPolyShape(shape, attrs, mul) {
  34576. var points = shape.points;
  34577. var strArr = [];
  34578. for (var i = 0; i < points.length; i++) {
  34579. strArr.push(round$2(points[i][0] * mul) / mul);
  34580. strArr.push(round$2(points[i][1] * mul) / mul);
  34581. }
  34582. attrs.points = strArr.join(' ');
  34583. }
  34584. function validatePolyShape(shape) {
  34585. return !shape.smooth;
  34586. }
  34587. function createAttrsConvert(desc) {
  34588. var normalizedDesc = map(desc, function (item) {
  34589. return (typeof item === 'string' ? [item, item] : item);
  34590. });
  34591. return function (shape, attrs, mul) {
  34592. for (var i = 0; i < normalizedDesc.length; i++) {
  34593. var item = normalizedDesc[i];
  34594. var val = shape[item[0]];
  34595. if (val != null) {
  34596. attrs[item[1]] = round$2(val * mul) / mul;
  34597. }
  34598. }
  34599. };
  34600. }
  34601. var builtinShapesDef = {
  34602. circle: [createAttrsConvert(['cx', 'cy', 'r'])],
  34603. polyline: [convertPolyShape, validatePolyShape],
  34604. polygon: [convertPolyShape, validatePolyShape]
  34605. };
  34606. function hasShapeAnimation(el) {
  34607. var animators = el.animators;
  34608. for (var i = 0; i < animators.length; i++) {
  34609. if (animators[i].targetName === 'shape') {
  34610. return true;
  34611. }
  34612. }
  34613. return false;
  34614. }
  34615. function brushSVGPath(el, scope) {
  34616. var style = el.style;
  34617. var shape = el.shape;
  34618. var builtinShpDef = builtinShapesDef[el.type];
  34619. var attrs = {};
  34620. var needsAnimate = scope.animation;
  34621. var svgElType = 'path';
  34622. var strokePercent = el.style.strokePercent;
  34623. var precision = (scope.compress && getPathPrecision(el)) || 4;
  34624. if (builtinShpDef
  34625. && !scope.willUpdate
  34626. && !(builtinShpDef[1] && !builtinShpDef[1](shape))
  34627. && !(needsAnimate && hasShapeAnimation(el))
  34628. && !(strokePercent < 1)) {
  34629. svgElType = el.type;
  34630. var mul = Math.pow(10, precision);
  34631. builtinShpDef[0](shape, attrs, mul);
  34632. }
  34633. else {
  34634. var needBuildPath = !el.path || el.shapeChanged();
  34635. if (!el.path) {
  34636. el.createPathProxy();
  34637. }
  34638. var path = el.path;
  34639. if (needBuildPath) {
  34640. path.beginPath();
  34641. el.buildPath(path, el.shape);
  34642. el.pathUpdated();
  34643. }
  34644. var pathVersion = path.getVersion();
  34645. var elExt = el;
  34646. var svgPathBuilder = elExt.__svgPathBuilder;
  34647. if (elExt.__svgPathVersion !== pathVersion
  34648. || !svgPathBuilder
  34649. || strokePercent !== elExt.__svgPathStrokePercent) {
  34650. if (!svgPathBuilder) {
  34651. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  34652. }
  34653. svgPathBuilder.reset(precision);
  34654. path.rebuildPath(svgPathBuilder, strokePercent);
  34655. svgPathBuilder.generateStr();
  34656. elExt.__svgPathVersion = pathVersion;
  34657. elExt.__svgPathStrokePercent = strokePercent;
  34658. }
  34659. attrs.d = svgPathBuilder.getStr();
  34660. }
  34661. setTransform(attrs, el.transform);
  34662. setStyleAttrs(attrs, style, el, scope);
  34663. scope.animation && createCSSAnimation(el, attrs, scope);
  34664. return createVNode(svgElType, el.id + '', attrs);
  34665. }
  34666. function brushSVGImage(el, scope) {
  34667. var style = el.style;
  34668. var image = style.image;
  34669. if (image && !isString(image)) {
  34670. if (isImageLike$1(image)) {
  34671. image = image.src;
  34672. }
  34673. else if (isCanvasLike(image)) {
  34674. image = image.toDataURL();
  34675. }
  34676. }
  34677. if (!image) {
  34678. return;
  34679. }
  34680. var x = style.x || 0;
  34681. var y = style.y || 0;
  34682. var dw = style.width;
  34683. var dh = style.height;
  34684. var attrs = {
  34685. href: image,
  34686. width: dw,
  34687. height: dh
  34688. };
  34689. if (x) {
  34690. attrs.x = x;
  34691. }
  34692. if (y) {
  34693. attrs.y = y;
  34694. }
  34695. setTransform(attrs, el.transform);
  34696. setStyleAttrs(attrs, style, el, scope);
  34697. scope.animation && createCSSAnimation(el, attrs, scope);
  34698. return createVNode('image', el.id + '', attrs);
  34699. }
  34700. function brushSVGTSpan(el, scope) {
  34701. var style = el.style;
  34702. var text = style.text;
  34703. text != null && (text += '');
  34704. if (!text || isNaN(style.x) || isNaN(style.y)) {
  34705. return;
  34706. }
  34707. var font = style.font || DEFAULT_FONT;
  34708. var x = style.x || 0;
  34709. var y = adjustTextY(style.y || 0, getLineHeight(font), style.textBaseline);
  34710. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  34711. || style.textAlign;
  34712. var attrs = {
  34713. 'dominant-baseline': 'central',
  34714. 'text-anchor': textAlign
  34715. };
  34716. if (hasSeparateFont(style)) {
  34717. var separatedFontStr = '';
  34718. var fontStyle = style.fontStyle;
  34719. var fontSize = parseFontSize(style.fontSize);
  34720. if (!parseFloat(fontSize)) {
  34721. return;
  34722. }
  34723. var fontFamily = style.fontFamily || DEFAULT_FONT_FAMILY;
  34724. var fontWeight = style.fontWeight;
  34725. separatedFontStr += "font-size:" + fontSize + ";font-family:" + fontFamily + ";";
  34726. if (fontStyle && fontStyle !== 'normal') {
  34727. separatedFontStr += "font-style:" + fontStyle + ";";
  34728. }
  34729. if (fontWeight && fontWeight !== 'normal') {
  34730. separatedFontStr += "font-weight:" + fontWeight + ";";
  34731. }
  34732. attrs.style = separatedFontStr;
  34733. }
  34734. else {
  34735. attrs.style = "font: " + font;
  34736. }
  34737. if (text.match(/\s/)) {
  34738. attrs['xml:space'] = 'preserve';
  34739. }
  34740. if (x) {
  34741. attrs.x = x;
  34742. }
  34743. if (y) {
  34744. attrs.y = y;
  34745. }
  34746. setTransform(attrs, el.transform);
  34747. setStyleAttrs(attrs, style, el, scope);
  34748. scope.animation && createCSSAnimation(el, attrs, scope);
  34749. return createVNode('text', el.id + '', attrs, undefined, text);
  34750. }
  34751. function brush$1(el, scope) {
  34752. if (el instanceof Path) {
  34753. return brushSVGPath(el, scope);
  34754. }
  34755. else if (el instanceof ZRImage) {
  34756. return brushSVGImage(el, scope);
  34757. }
  34758. else if (el instanceof TSpan) {
  34759. return brushSVGTSpan(el, scope);
  34760. }
  34761. }
  34762. function setShadow(el, attrs, scope) {
  34763. var style = el.style;
  34764. if (hasShadow(style)) {
  34765. var shadowKey = getShadowKey(el);
  34766. var shadowCache = scope.shadowCache;
  34767. var shadowId = shadowCache[shadowKey];
  34768. if (!shadowId) {
  34769. var globalScale = el.getGlobalScale();
  34770. var scaleX = globalScale[0];
  34771. var scaleY = globalScale[1];
  34772. if (!scaleX || !scaleY) {
  34773. return;
  34774. }
  34775. var offsetX = style.shadowOffsetX || 0;
  34776. var offsetY = style.shadowOffsetY || 0;
  34777. var blur_1 = style.shadowBlur;
  34778. var _a = normalizeColor(style.shadowColor), opacity = _a.opacity, color = _a.color;
  34779. var stdDx = blur_1 / 2 / scaleX;
  34780. var stdDy = blur_1 / 2 / scaleY;
  34781. var stdDeviation = stdDx + ' ' + stdDy;
  34782. shadowId = scope.zrId + '-s' + scope.shadowIdx++;
  34783. scope.defs[shadowId] = createVNode('filter', shadowId, {
  34784. 'id': shadowId,
  34785. 'x': '-100%',
  34786. 'y': '-100%',
  34787. 'width': '300%',
  34788. 'height': '300%'
  34789. }, [
  34790. createVNode('feDropShadow', '', {
  34791. 'dx': offsetX / scaleX,
  34792. 'dy': offsetY / scaleY,
  34793. 'stdDeviation': stdDeviation,
  34794. 'flood-color': color,
  34795. 'flood-opacity': opacity
  34796. })
  34797. ]);
  34798. shadowCache[shadowKey] = shadowId;
  34799. }
  34800. attrs.filter = getIdURL(shadowId);
  34801. }
  34802. }
  34803. function setGradient(style, attrs, target, scope) {
  34804. var val = style[target];
  34805. var gradientTag;
  34806. var gradientAttrs = {
  34807. 'gradientUnits': val.global
  34808. ? 'userSpaceOnUse'
  34809. : 'objectBoundingBox'
  34810. };
  34811. if (isLinearGradient(val)) {
  34812. gradientTag = 'linearGradient';
  34813. gradientAttrs.x1 = val.x;
  34814. gradientAttrs.y1 = val.y;
  34815. gradientAttrs.x2 = val.x2;
  34816. gradientAttrs.y2 = val.y2;
  34817. }
  34818. else if (isRadialGradient(val)) {
  34819. gradientTag = 'radialGradient';
  34820. gradientAttrs.cx = retrieve2(val.x, 0.5);
  34821. gradientAttrs.cy = retrieve2(val.y, 0.5);
  34822. gradientAttrs.r = retrieve2(val.r, 0.5);
  34823. }
  34824. else {
  34825. if ("development" !== 'production') {
  34826. logError('Illegal gradient type.');
  34827. }
  34828. return;
  34829. }
  34830. var colors = val.colorStops;
  34831. var colorStops = [];
  34832. for (var i = 0, len = colors.length; i < len; ++i) {
  34833. var offset = round4(colors[i].offset) * 100 + '%';
  34834. var stopColor = colors[i].color;
  34835. var _a = normalizeColor(stopColor), color = _a.color, opacity = _a.opacity;
  34836. var stopsAttrs = {
  34837. 'offset': offset
  34838. };
  34839. stopsAttrs['stop-color'] = color;
  34840. if (opacity < 1) {
  34841. stopsAttrs['stop-opacity'] = opacity;
  34842. }
  34843. colorStops.push(createVNode('stop', i + '', stopsAttrs));
  34844. }
  34845. var gradientVNode = createVNode(gradientTag, '', gradientAttrs, colorStops);
  34846. var gradientKey = vNodeToString(gradientVNode);
  34847. var gradientCache = scope.gradientCache;
  34848. var gradientId = gradientCache[gradientKey];
  34849. if (!gradientId) {
  34850. gradientId = scope.zrId + '-g' + scope.gradientIdx++;
  34851. gradientCache[gradientKey] = gradientId;
  34852. gradientAttrs.id = gradientId;
  34853. scope.defs[gradientId] = createVNode(gradientTag, gradientId, gradientAttrs, colorStops);
  34854. }
  34855. attrs[target] = getIdURL(gradientId);
  34856. }
  34857. function setPattern(el, attrs, target, scope) {
  34858. var val = el.style[target];
  34859. var boundingRect = el.getBoundingRect();
  34860. var patternAttrs = {};
  34861. var repeat = val.repeat;
  34862. var noRepeat = repeat === 'no-repeat';
  34863. var repeatX = repeat === 'repeat-x';
  34864. var repeatY = repeat === 'repeat-y';
  34865. var child;
  34866. if (isImagePattern(val)) {
  34867. var imageWidth_1 = val.imageWidth;
  34868. var imageHeight_1 = val.imageHeight;
  34869. var imageSrc = void 0;
  34870. var patternImage = val.image;
  34871. if (isString(patternImage)) {
  34872. imageSrc = patternImage;
  34873. }
  34874. else if (isImageLike$1(patternImage)) {
  34875. imageSrc = patternImage.src;
  34876. }
  34877. else if (isCanvasLike(patternImage)) {
  34878. imageSrc = patternImage.toDataURL();
  34879. }
  34880. if (typeof Image === 'undefined') {
  34881. var errMsg = 'Image width/height must been given explictly in svg-ssr renderer.';
  34882. assert(imageWidth_1, errMsg);
  34883. assert(imageHeight_1, errMsg);
  34884. }
  34885. else if (imageWidth_1 == null || imageHeight_1 == null) {
  34886. var setSizeToVNode_1 = function (vNode, img) {
  34887. if (vNode) {
  34888. var svgEl = vNode.elm;
  34889. var width = imageWidth_1 || img.width;
  34890. var height = imageHeight_1 || img.height;
  34891. if (vNode.tag === 'pattern') {
  34892. if (repeatX) {
  34893. height = 1;
  34894. width /= boundingRect.width;
  34895. }
  34896. else if (repeatY) {
  34897. width = 1;
  34898. height /= boundingRect.height;
  34899. }
  34900. }
  34901. vNode.attrs.width = width;
  34902. vNode.attrs.height = height;
  34903. if (svgEl) {
  34904. svgEl.setAttribute('width', width);
  34905. svgEl.setAttribute('height', height);
  34906. }
  34907. }
  34908. };
  34909. var createdImage = createOrUpdateImage(imageSrc, null, el, function (img) {
  34910. noRepeat || setSizeToVNode_1(patternVNode, img);
  34911. setSizeToVNode_1(child, img);
  34912. });
  34913. if (createdImage && createdImage.width && createdImage.height) {
  34914. imageWidth_1 = imageWidth_1 || createdImage.width;
  34915. imageHeight_1 = imageHeight_1 || createdImage.height;
  34916. }
  34917. }
  34918. child = createVNode('image', 'img', {
  34919. href: imageSrc,
  34920. width: imageWidth_1,
  34921. height: imageHeight_1
  34922. });
  34923. patternAttrs.width = imageWidth_1;
  34924. patternAttrs.height = imageHeight_1;
  34925. }
  34926. else if (val.svgElement) {
  34927. child = clone(val.svgElement);
  34928. patternAttrs.width = val.svgWidth;
  34929. patternAttrs.height = val.svgHeight;
  34930. }
  34931. if (!child) {
  34932. return;
  34933. }
  34934. var patternWidth;
  34935. var patternHeight;
  34936. if (noRepeat) {
  34937. patternWidth = patternHeight = 1;
  34938. }
  34939. else if (repeatX) {
  34940. patternHeight = 1;
  34941. patternWidth = patternAttrs.width / boundingRect.width;
  34942. }
  34943. else if (repeatY) {
  34944. patternWidth = 1;
  34945. patternHeight = patternAttrs.height / boundingRect.height;
  34946. }
  34947. else {
  34948. patternAttrs.patternUnits = 'userSpaceOnUse';
  34949. }
  34950. if (patternWidth != null && !isNaN(patternWidth)) {
  34951. patternAttrs.width = patternWidth;
  34952. }
  34953. if (patternHeight != null && !isNaN(patternHeight)) {
  34954. patternAttrs.height = patternHeight;
  34955. }
  34956. var patternTransform = getSRTTransformString(val);
  34957. patternTransform && (patternAttrs.patternTransform = patternTransform);
  34958. var patternVNode = createVNode('pattern', '', patternAttrs, [child]);
  34959. var patternKey = vNodeToString(patternVNode);
  34960. var patternCache = scope.patternCache;
  34961. var patternId = patternCache[patternKey];
  34962. if (!patternId) {
  34963. patternId = scope.zrId + '-p' + scope.patternIdx++;
  34964. patternCache[patternKey] = patternId;
  34965. patternAttrs.id = patternId;
  34966. patternVNode = scope.defs[patternId] = createVNode('pattern', patternId, patternAttrs, [child]);
  34967. }
  34968. attrs[target] = getIdURL(patternId);
  34969. }
  34970. function setClipPath(clipPath, attrs, scope) {
  34971. var clipPathCache = scope.clipPathCache, defs = scope.defs;
  34972. var clipPathId = clipPathCache[clipPath.id];
  34973. if (!clipPathId) {
  34974. clipPathId = scope.zrId + '-c' + scope.clipPathIdx++;
  34975. var clipPathAttrs = {
  34976. id: clipPathId
  34977. };
  34978. clipPathCache[clipPath.id] = clipPathId;
  34979. defs[clipPathId] = createVNode('clipPath', clipPathId, clipPathAttrs, [brushSVGPath(clipPath, scope)]);
  34980. }
  34981. attrs['clip-path'] = getIdURL(clipPathId);
  34982. }
  34983. function createTextNode(text) {
  34984. return document.createTextNode(text);
  34985. }
  34986. function insertBefore(parentNode, newNode, referenceNode) {
  34987. parentNode.insertBefore(newNode, referenceNode);
  34988. }
  34989. function removeChild(node, child) {
  34990. node.removeChild(child);
  34991. }
  34992. function appendChild(node, child) {
  34993. node.appendChild(child);
  34994. }
  34995. function parentNode(node) {
  34996. return node.parentNode;
  34997. }
  34998. function nextSibling(node) {
  34999. return node.nextSibling;
  35000. }
  35001. function setTextContent(node, text) {
  35002. node.textContent = text;
  35003. }
  35004. var colonChar = 58;
  35005. var xChar = 120;
  35006. var emptyNode = createVNode('', '');
  35007. function isUndef(s) {
  35008. return s === undefined;
  35009. }
  35010. function isDef(s) {
  35011. return s !== undefined;
  35012. }
  35013. function createKeyToOldIdx(children, beginIdx, endIdx) {
  35014. var map = {};
  35015. for (var i = beginIdx; i <= endIdx; ++i) {
  35016. var key = children[i].key;
  35017. if (key !== undefined) {
  35018. if ("development" !== 'production') {
  35019. if (map[key] != null) {
  35020. console.error("Duplicate key " + key);
  35021. }
  35022. }
  35023. map[key] = i;
  35024. }
  35025. }
  35026. return map;
  35027. }
  35028. function sameVnode(vnode1, vnode2) {
  35029. var isSameKey = vnode1.key === vnode2.key;
  35030. var isSameTag = vnode1.tag === vnode2.tag;
  35031. return isSameTag && isSameKey;
  35032. }
  35033. function createElm(vnode) {
  35034. var i;
  35035. var children = vnode.children;
  35036. var tag = vnode.tag;
  35037. if (isDef(tag)) {
  35038. var elm = (vnode.elm = createElement(tag));
  35039. updateAttrs(emptyNode, vnode);
  35040. if (isArray(children)) {
  35041. for (i = 0; i < children.length; ++i) {
  35042. var ch = children[i];
  35043. if (ch != null) {
  35044. appendChild(elm, createElm(ch));
  35045. }
  35046. }
  35047. }
  35048. else if (isDef(vnode.text) && !isObject(vnode.text)) {
  35049. appendChild(elm, createTextNode(vnode.text));
  35050. }
  35051. }
  35052. else {
  35053. vnode.elm = createTextNode(vnode.text);
  35054. }
  35055. return vnode.elm;
  35056. }
  35057. function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
  35058. for (; startIdx <= endIdx; ++startIdx) {
  35059. var ch = vnodes[startIdx];
  35060. if (ch != null) {
  35061. insertBefore(parentElm, createElm(ch), before);
  35062. }
  35063. }
  35064. }
  35065. function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
  35066. for (; startIdx <= endIdx; ++startIdx) {
  35067. var ch = vnodes[startIdx];
  35068. if (ch != null) {
  35069. if (isDef(ch.tag)) {
  35070. var parent_1 = parentNode(ch.elm);
  35071. removeChild(parent_1, ch.elm);
  35072. }
  35073. else {
  35074. removeChild(parentElm, ch.elm);
  35075. }
  35076. }
  35077. }
  35078. }
  35079. function updateAttrs(oldVnode, vnode) {
  35080. var key;
  35081. var elm = vnode.elm;
  35082. var oldAttrs = oldVnode && oldVnode.attrs || {};
  35083. var attrs = vnode.attrs || {};
  35084. if (oldAttrs === attrs) {
  35085. return;
  35086. }
  35087. for (key in attrs) {
  35088. var cur = attrs[key];
  35089. var old = oldAttrs[key];
  35090. if (old !== cur) {
  35091. if (cur === true) {
  35092. elm.setAttribute(key, '');
  35093. }
  35094. else if (cur === false) {
  35095. elm.removeAttribute(key);
  35096. }
  35097. else {
  35098. if (key.charCodeAt(0) !== xChar) {
  35099. elm.setAttribute(key, cur);
  35100. }
  35101. else if (key === 'xmlns:xlink' || key === 'xmlns') {
  35102. elm.setAttributeNS(XMLNS, key, cur);
  35103. }
  35104. else if (key.charCodeAt(3) === colonChar) {
  35105. elm.setAttributeNS(XML_NAMESPACE, key, cur);
  35106. }
  35107. else if (key.charCodeAt(5) === colonChar) {
  35108. elm.setAttributeNS(XLINKNS, key, cur);
  35109. }
  35110. else {
  35111. elm.setAttribute(key, cur);
  35112. }
  35113. }
  35114. }
  35115. }
  35116. for (key in oldAttrs) {
  35117. if (!(key in attrs)) {
  35118. elm.removeAttribute(key);
  35119. }
  35120. }
  35121. }
  35122. function updateChildren(parentElm, oldCh, newCh) {
  35123. var oldStartIdx = 0;
  35124. var newStartIdx = 0;
  35125. var oldEndIdx = oldCh.length - 1;
  35126. var oldStartVnode = oldCh[0];
  35127. var oldEndVnode = oldCh[oldEndIdx];
  35128. var newEndIdx = newCh.length - 1;
  35129. var newStartVnode = newCh[0];
  35130. var newEndVnode = newCh[newEndIdx];
  35131. var oldKeyToIdx;
  35132. var idxInOld;
  35133. var elmToMove;
  35134. var before;
  35135. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  35136. if (oldStartVnode == null) {
  35137. oldStartVnode = oldCh[++oldStartIdx];
  35138. }
  35139. else if (oldEndVnode == null) {
  35140. oldEndVnode = oldCh[--oldEndIdx];
  35141. }
  35142. else if (newStartVnode == null) {
  35143. newStartVnode = newCh[++newStartIdx];
  35144. }
  35145. else if (newEndVnode == null) {
  35146. newEndVnode = newCh[--newEndIdx];
  35147. }
  35148. else if (sameVnode(oldStartVnode, newStartVnode)) {
  35149. patchVnode(oldStartVnode, newStartVnode);
  35150. oldStartVnode = oldCh[++oldStartIdx];
  35151. newStartVnode = newCh[++newStartIdx];
  35152. }
  35153. else if (sameVnode(oldEndVnode, newEndVnode)) {
  35154. patchVnode(oldEndVnode, newEndVnode);
  35155. oldEndVnode = oldCh[--oldEndIdx];
  35156. newEndVnode = newCh[--newEndIdx];
  35157. }
  35158. else if (sameVnode(oldStartVnode, newEndVnode)) {
  35159. patchVnode(oldStartVnode, newEndVnode);
  35160. insertBefore(parentElm, oldStartVnode.elm, nextSibling(oldEndVnode.elm));
  35161. oldStartVnode = oldCh[++oldStartIdx];
  35162. newEndVnode = newCh[--newEndIdx];
  35163. }
  35164. else if (sameVnode(oldEndVnode, newStartVnode)) {
  35165. patchVnode(oldEndVnode, newStartVnode);
  35166. insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
  35167. oldEndVnode = oldCh[--oldEndIdx];
  35168. newStartVnode = newCh[++newStartIdx];
  35169. }
  35170. else {
  35171. if (isUndef(oldKeyToIdx)) {
  35172. oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
  35173. }
  35174. idxInOld = oldKeyToIdx[newStartVnode.key];
  35175. if (isUndef(idxInOld)) {
  35176. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35177. }
  35178. else {
  35179. elmToMove = oldCh[idxInOld];
  35180. if (elmToMove.tag !== newStartVnode.tag) {
  35181. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35182. }
  35183. else {
  35184. patchVnode(elmToMove, newStartVnode);
  35185. oldCh[idxInOld] = undefined;
  35186. insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);
  35187. }
  35188. }
  35189. newStartVnode = newCh[++newStartIdx];
  35190. }
  35191. }
  35192. if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
  35193. if (oldStartIdx > oldEndIdx) {
  35194. before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm;
  35195. addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx);
  35196. }
  35197. else {
  35198. removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
  35199. }
  35200. }
  35201. }
  35202. function patchVnode(oldVnode, vnode) {
  35203. var elm = (vnode.elm = oldVnode.elm);
  35204. var oldCh = oldVnode.children;
  35205. var ch = vnode.children;
  35206. if (oldVnode === vnode) {
  35207. return;
  35208. }
  35209. updateAttrs(oldVnode, vnode);
  35210. if (isUndef(vnode.text)) {
  35211. if (isDef(oldCh) && isDef(ch)) {
  35212. if (oldCh !== ch) {
  35213. updateChildren(elm, oldCh, ch);
  35214. }
  35215. }
  35216. else if (isDef(ch)) {
  35217. if (isDef(oldVnode.text)) {
  35218. setTextContent(elm, '');
  35219. }
  35220. addVnodes(elm, null, ch, 0, ch.length - 1);
  35221. }
  35222. else if (isDef(oldCh)) {
  35223. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35224. }
  35225. else if (isDef(oldVnode.text)) {
  35226. setTextContent(elm, '');
  35227. }
  35228. }
  35229. else if (oldVnode.text !== vnode.text) {
  35230. if (isDef(oldCh)) {
  35231. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35232. }
  35233. setTextContent(elm, vnode.text);
  35234. }
  35235. }
  35236. function patch(oldVnode, vnode) {
  35237. if (sameVnode(oldVnode, vnode)) {
  35238. patchVnode(oldVnode, vnode);
  35239. }
  35240. else {
  35241. var elm = oldVnode.elm;
  35242. var parent_2 = parentNode(elm);
  35243. createElm(vnode);
  35244. if (parent_2 !== null) {
  35245. insertBefore(parent_2, vnode.elm, nextSibling(elm));
  35246. removeVnodes(parent_2, [oldVnode], 0, 0);
  35247. }
  35248. }
  35249. return vnode;
  35250. }
  35251. var svgId = 0;
  35252. var SVGPainter = (function () {
  35253. function SVGPainter(root, storage, opts) {
  35254. this.type = 'svg';
  35255. this.refreshHover = createMethodNotSupport('refreshHover');
  35256. this.configLayer = createMethodNotSupport('configLayer');
  35257. this.storage = storage;
  35258. this._opts = opts = extend({}, opts);
  35259. this.root = root;
  35260. this._id = 'zr' + svgId++;
  35261. this._oldVNode = createSVGVNode(opts.width, opts.height);
  35262. if (root && !opts.ssr) {
  35263. var viewport = this._viewport = document.createElement('div');
  35264. viewport.style.cssText = 'position:relative;overflow:hidden';
  35265. var svgDom = this._svgDom = this._oldVNode.elm = createElement('svg');
  35266. updateAttrs(null, this._oldVNode);
  35267. viewport.appendChild(svgDom);
  35268. root.appendChild(viewport);
  35269. }
  35270. this.resize(opts.width, opts.height);
  35271. }
  35272. SVGPainter.prototype.getType = function () {
  35273. return this.type;
  35274. };
  35275. SVGPainter.prototype.getViewportRoot = function () {
  35276. return this._viewport;
  35277. };
  35278. SVGPainter.prototype.getViewportRootOffset = function () {
  35279. var viewportRoot = this.getViewportRoot();
  35280. if (viewportRoot) {
  35281. return {
  35282. offsetLeft: viewportRoot.offsetLeft || 0,
  35283. offsetTop: viewportRoot.offsetTop || 0
  35284. };
  35285. }
  35286. };
  35287. SVGPainter.prototype.getSvgDom = function () {
  35288. return this._svgDom;
  35289. };
  35290. SVGPainter.prototype.refresh = function () {
  35291. if (this.root) {
  35292. var vnode = this.renderToVNode({
  35293. willUpdate: true
  35294. });
  35295. vnode.attrs.style = 'position:absolute;left:0;top:0;user-select:none';
  35296. patch(this._oldVNode, vnode);
  35297. this._oldVNode = vnode;
  35298. }
  35299. };
  35300. SVGPainter.prototype.renderOneToVNode = function (el) {
  35301. return brush$1(el, createBrushScope(this._id));
  35302. };
  35303. SVGPainter.prototype.renderToVNode = function (opts) {
  35304. opts = opts || {};
  35305. var list = this.storage.getDisplayList(true);
  35306. var width = this._width;
  35307. var height = this._height;
  35308. var scope = createBrushScope(this._id);
  35309. scope.animation = opts.animation;
  35310. scope.willUpdate = opts.willUpdate;
  35311. scope.compress = opts.compress;
  35312. var children = [];
  35313. var bgVNode = this._bgVNode = createBackgroundVNode(width, height, this._backgroundColor, scope);
  35314. bgVNode && children.push(bgVNode);
  35315. var mainVNode = !opts.compress
  35316. ? (this._mainVNode = createVNode('g', 'main', {}, [])) : null;
  35317. this._paintList(list, scope, mainVNode ? mainVNode.children : children);
  35318. mainVNode && children.push(mainVNode);
  35319. var defs = map(keys(scope.defs), function (id) { return scope.defs[id]; });
  35320. if (defs.length) {
  35321. children.push(createVNode('defs', 'defs', {}, defs));
  35322. }
  35323. if (opts.animation) {
  35324. var animationCssStr = getCssString(scope.cssNodes, scope.cssAnims, { newline: true });
  35325. if (animationCssStr) {
  35326. var styleNode = createVNode('style', 'stl', {}, [], animationCssStr);
  35327. children.push(styleNode);
  35328. }
  35329. }
  35330. return createSVGVNode(width, height, children, opts.useViewBox);
  35331. };
  35332. SVGPainter.prototype.renderToString = function (opts) {
  35333. opts = opts || {};
  35334. return vNodeToString(this.renderToVNode({
  35335. animation: retrieve2(opts.cssAnimation, true),
  35336. willUpdate: false,
  35337. compress: true,
  35338. useViewBox: retrieve2(opts.useViewBox, true)
  35339. }), { newline: true });
  35340. };
  35341. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  35342. this._backgroundColor = backgroundColor;
  35343. };
  35344. SVGPainter.prototype.getSvgRoot = function () {
  35345. return this._mainVNode && this._mainVNode.elm;
  35346. };
  35347. SVGPainter.prototype._paintList = function (list, scope, out) {
  35348. var listLen = list.length;
  35349. var clipPathsGroupsStack = [];
  35350. var clipPathsGroupsStackDepth = 0;
  35351. var currentClipPathGroup;
  35352. var prevClipPaths;
  35353. var clipGroupNodeIdx = 0;
  35354. for (var i = 0; i < listLen; i++) {
  35355. var displayable = list[i];
  35356. if (!displayable.invisible) {
  35357. var clipPaths = displayable.__clipPaths;
  35358. var len = clipPaths && clipPaths.length || 0;
  35359. var prevLen = prevClipPaths && prevClipPaths.length || 0;
  35360. var lca = void 0;
  35361. for (lca = Math.max(len - 1, prevLen - 1); lca >= 0; lca--) {
  35362. if (clipPaths && prevClipPaths
  35363. && clipPaths[lca] === prevClipPaths[lca]) {
  35364. break;
  35365. }
  35366. }
  35367. for (var i_1 = prevLen - 1; i_1 > lca; i_1--) {
  35368. clipPathsGroupsStackDepth--;
  35369. currentClipPathGroup = clipPathsGroupsStack[clipPathsGroupsStackDepth - 1];
  35370. }
  35371. for (var i_2 = lca + 1; i_2 < len; i_2++) {
  35372. var groupAttrs = {};
  35373. setClipPath(clipPaths[i_2], groupAttrs, scope);
  35374. var g = createVNode('g', 'clip-g-' + clipGroupNodeIdx++, groupAttrs, []);
  35375. (currentClipPathGroup ? currentClipPathGroup.children : out).push(g);
  35376. clipPathsGroupsStack[clipPathsGroupsStackDepth++] = g;
  35377. currentClipPathGroup = g;
  35378. }
  35379. prevClipPaths = clipPaths;
  35380. var ret = brush$1(displayable, scope);
  35381. if (ret) {
  35382. (currentClipPathGroup ? currentClipPathGroup.children : out).push(ret);
  35383. }
  35384. }
  35385. }
  35386. };
  35387. SVGPainter.prototype.resize = function (width, height) {
  35388. var opts = this._opts;
  35389. var root = this.root;
  35390. var viewport = this._viewport;
  35391. width != null && (opts.width = width);
  35392. height != null && (opts.height = height);
  35393. if (root && viewport) {
  35394. viewport.style.display = 'none';
  35395. width = getSize(root, 0, opts);
  35396. height = getSize(root, 1, opts);
  35397. viewport.style.display = '';
  35398. }
  35399. if (this._width !== width || this._height !== height) {
  35400. this._width = width;
  35401. this._height = height;
  35402. if (viewport) {
  35403. var viewportStyle = viewport.style;
  35404. viewportStyle.width = width + 'px';
  35405. viewportStyle.height = height + 'px';
  35406. }
  35407. if (!isPattern(this._backgroundColor)) {
  35408. var svgDom = this._svgDom;
  35409. if (svgDom) {
  35410. svgDom.setAttribute('width', width);
  35411. svgDom.setAttribute('height', height);
  35412. }
  35413. var bgEl = this._bgVNode && this._bgVNode.elm;
  35414. if (bgEl) {
  35415. bgEl.setAttribute('width', width);
  35416. bgEl.setAttribute('height', height);
  35417. }
  35418. }
  35419. else {
  35420. this.refresh();
  35421. }
  35422. }
  35423. };
  35424. SVGPainter.prototype.getWidth = function () {
  35425. return this._width;
  35426. };
  35427. SVGPainter.prototype.getHeight = function () {
  35428. return this._height;
  35429. };
  35430. SVGPainter.prototype.dispose = function () {
  35431. if (this.root) {
  35432. this.root.innerHTML = '';
  35433. }
  35434. this._svgDom =
  35435. this._viewport =
  35436. this.storage =
  35437. this._oldVNode =
  35438. this._bgVNode =
  35439. this._mainVNode = null;
  35440. };
  35441. SVGPainter.prototype.clear = function () {
  35442. if (this._svgDom) {
  35443. this._svgDom.innerHTML = null;
  35444. }
  35445. this._oldVNode = null;
  35446. };
  35447. SVGPainter.prototype.toDataURL = function (base64) {
  35448. var str = this.renderToString();
  35449. var prefix = 'data:image/svg+xml;';
  35450. if (base64) {
  35451. str = encodeBase64(str);
  35452. return str && prefix + 'base64,' + str;
  35453. }
  35454. return prefix + 'charset=UTF-8,' + encodeURIComponent(str);
  35455. };
  35456. return SVGPainter;
  35457. }());
  35458. function createMethodNotSupport(method) {
  35459. return function () {
  35460. if ("development" !== 'production') {
  35461. logError('In SVG mode painter not support method "' + method + '"');
  35462. }
  35463. };
  35464. }
  35465. function createBackgroundVNode(width, height, backgroundColor, scope) {
  35466. var bgVNode;
  35467. if (backgroundColor && backgroundColor !== 'none') {
  35468. bgVNode = createVNode('rect', 'bg', {
  35469. width: width,
  35470. height: height,
  35471. x: '0',
  35472. y: '0',
  35473. id: '0'
  35474. });
  35475. if (isGradient(backgroundColor)) {
  35476. setGradient({ fill: backgroundColor }, bgVNode.attrs, 'fill', scope);
  35477. }
  35478. else if (isPattern(backgroundColor)) {
  35479. setPattern({
  35480. style: {
  35481. fill: backgroundColor
  35482. },
  35483. dirty: noop,
  35484. getBoundingRect: function () { return ({ width: width, height: height }); }
  35485. }, bgVNode.attrs, 'fill', scope);
  35486. }
  35487. else {
  35488. var _a = normalizeColor(backgroundColor), color = _a.color, opacity = _a.opacity;
  35489. bgVNode.attrs.fill = color;
  35490. opacity < 1 && (bgVNode.attrs['fill-opacity'] = opacity);
  35491. }
  35492. }
  35493. return bgVNode;
  35494. }
  35495. function install(registers) {
  35496. registers.registerPainter('svg', SVGPainter);
  35497. }
  35498. function createDom(id, painter, dpr) {
  35499. var newDom = platformApi.createCanvas();
  35500. var width = painter.getWidth();
  35501. var height = painter.getHeight();
  35502. var newDomStyle = newDom.style;
  35503. if (newDomStyle) {
  35504. newDomStyle.position = 'absolute';
  35505. newDomStyle.left = '0';
  35506. newDomStyle.top = '0';
  35507. newDomStyle.width = width + 'px';
  35508. newDomStyle.height = height + 'px';
  35509. newDom.setAttribute('data-zr-dom-id', id);
  35510. }
  35511. newDom.width = width * dpr;
  35512. newDom.height = height * dpr;
  35513. return newDom;
  35514. }
  35515. var Layer = (function (_super) {
  35516. __extends(Layer, _super);
  35517. function Layer(id, painter, dpr) {
  35518. var _this = _super.call(this) || this;
  35519. _this.motionBlur = false;
  35520. _this.lastFrameAlpha = 0.7;
  35521. _this.dpr = 1;
  35522. _this.virtual = false;
  35523. _this.config = {};
  35524. _this.incremental = false;
  35525. _this.zlevel = 0;
  35526. _this.maxRepaintRectCount = 5;
  35527. _this.__dirty = true;
  35528. _this.__firstTimePaint = true;
  35529. _this.__used = false;
  35530. _this.__drawIndex = 0;
  35531. _this.__startIndex = 0;
  35532. _this.__endIndex = 0;
  35533. _this.__prevStartIndex = null;
  35534. _this.__prevEndIndex = null;
  35535. var dom;
  35536. dpr = dpr || devicePixelRatio;
  35537. if (typeof id === 'string') {
  35538. dom = createDom(id, painter, dpr);
  35539. }
  35540. else if (isObject(id)) {
  35541. dom = id;
  35542. id = dom.id;
  35543. }
  35544. _this.id = id;
  35545. _this.dom = dom;
  35546. var domStyle = dom.style;
  35547. if (domStyle) {
  35548. disableUserSelect(dom);
  35549. dom.onselectstart = function () { return false; };
  35550. domStyle.padding = '0';
  35551. domStyle.margin = '0';
  35552. domStyle.borderWidth = '0';
  35553. }
  35554. _this.painter = painter;
  35555. _this.dpr = dpr;
  35556. return _this;
  35557. }
  35558. Layer.prototype.getElementCount = function () {
  35559. return this.__endIndex - this.__startIndex;
  35560. };
  35561. Layer.prototype.afterBrush = function () {
  35562. this.__prevStartIndex = this.__startIndex;
  35563. this.__prevEndIndex = this.__endIndex;
  35564. };
  35565. Layer.prototype.initContext = function () {
  35566. this.ctx = this.dom.getContext('2d');
  35567. this.ctx.dpr = this.dpr;
  35568. };
  35569. Layer.prototype.setUnpainted = function () {
  35570. this.__firstTimePaint = true;
  35571. };
  35572. Layer.prototype.createBackBuffer = function () {
  35573. var dpr = this.dpr;
  35574. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  35575. this.ctxBack = this.domBack.getContext('2d');
  35576. if (dpr !== 1) {
  35577. this.ctxBack.scale(dpr, dpr);
  35578. }
  35579. };
  35580. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  35581. if (this.__firstTimePaint) {
  35582. this.__firstTimePaint = false;
  35583. return null;
  35584. }
  35585. var mergedRepaintRects = [];
  35586. var maxRepaintRectCount = this.maxRepaintRectCount;
  35587. var full = false;
  35588. var pendingRect = new BoundingRect(0, 0, 0, 0);
  35589. function addRectToMergePool(rect) {
  35590. if (!rect.isFinite() || rect.isZero()) {
  35591. return;
  35592. }
  35593. if (mergedRepaintRects.length === 0) {
  35594. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35595. boundingRect.copy(rect);
  35596. mergedRepaintRects.push(boundingRect);
  35597. }
  35598. else {
  35599. var isMerged = false;
  35600. var minDeltaArea = Infinity;
  35601. var bestRectToMergeIdx = 0;
  35602. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  35603. var mergedRect = mergedRepaintRects[i];
  35604. if (mergedRect.intersect(rect)) {
  35605. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  35606. pendingRect_1.copy(mergedRect);
  35607. pendingRect_1.union(rect);
  35608. mergedRepaintRects[i] = pendingRect_1;
  35609. isMerged = true;
  35610. break;
  35611. }
  35612. else if (full) {
  35613. pendingRect.copy(rect);
  35614. pendingRect.union(mergedRect);
  35615. var aArea = rect.width * rect.height;
  35616. var bArea = mergedRect.width * mergedRect.height;
  35617. var pendingArea = pendingRect.width * pendingRect.height;
  35618. var deltaArea = pendingArea - aArea - bArea;
  35619. if (deltaArea < minDeltaArea) {
  35620. minDeltaArea = deltaArea;
  35621. bestRectToMergeIdx = i;
  35622. }
  35623. }
  35624. }
  35625. if (full) {
  35626. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  35627. isMerged = true;
  35628. }
  35629. if (!isMerged) {
  35630. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35631. boundingRect.copy(rect);
  35632. mergedRepaintRects.push(boundingRect);
  35633. }
  35634. if (!full) {
  35635. full = mergedRepaintRects.length >= maxRepaintRectCount;
  35636. }
  35637. }
  35638. }
  35639. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  35640. var el = displayList[i];
  35641. if (el) {
  35642. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  35643. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  35644. ? el.getPrevPaintRect()
  35645. : null;
  35646. if (prevRect) {
  35647. addRectToMergePool(prevRect);
  35648. }
  35649. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  35650. ? el.getPaintRect()
  35651. : null;
  35652. if (curRect) {
  35653. addRectToMergePool(curRect);
  35654. }
  35655. }
  35656. }
  35657. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  35658. var el = prevList[i];
  35659. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  35660. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  35661. var prevRect = el.getPrevPaintRect();
  35662. if (prevRect) {
  35663. addRectToMergePool(prevRect);
  35664. }
  35665. }
  35666. }
  35667. var hasIntersections;
  35668. do {
  35669. hasIntersections = false;
  35670. for (var i = 0; i < mergedRepaintRects.length;) {
  35671. if (mergedRepaintRects[i].isZero()) {
  35672. mergedRepaintRects.splice(i, 1);
  35673. continue;
  35674. }
  35675. for (var j = i + 1; j < mergedRepaintRects.length;) {
  35676. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  35677. hasIntersections = true;
  35678. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  35679. mergedRepaintRects.splice(j, 1);
  35680. }
  35681. else {
  35682. j++;
  35683. }
  35684. }
  35685. i++;
  35686. }
  35687. } while (hasIntersections);
  35688. this._paintRects = mergedRepaintRects;
  35689. return mergedRepaintRects;
  35690. };
  35691. Layer.prototype.debugGetPaintRects = function () {
  35692. return (this._paintRects || []).slice();
  35693. };
  35694. Layer.prototype.resize = function (width, height) {
  35695. var dpr = this.dpr;
  35696. var dom = this.dom;
  35697. var domStyle = dom.style;
  35698. var domBack = this.domBack;
  35699. if (domStyle) {
  35700. domStyle.width = width + 'px';
  35701. domStyle.height = height + 'px';
  35702. }
  35703. dom.width = width * dpr;
  35704. dom.height = height * dpr;
  35705. if (domBack) {
  35706. domBack.width = width * dpr;
  35707. domBack.height = height * dpr;
  35708. if (dpr !== 1) {
  35709. this.ctxBack.scale(dpr, dpr);
  35710. }
  35711. }
  35712. };
  35713. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  35714. var dom = this.dom;
  35715. var ctx = this.ctx;
  35716. var width = dom.width;
  35717. var height = dom.height;
  35718. clearColor = clearColor || this.clearColor;
  35719. var haveMotionBLur = this.motionBlur && !clearAll;
  35720. var lastFrameAlpha = this.lastFrameAlpha;
  35721. var dpr = this.dpr;
  35722. var self = this;
  35723. if (haveMotionBLur) {
  35724. if (!this.domBack) {
  35725. this.createBackBuffer();
  35726. }
  35727. this.ctxBack.globalCompositeOperation = 'copy';
  35728. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  35729. }
  35730. var domBack = this.domBack;
  35731. function doClear(x, y, width, height) {
  35732. ctx.clearRect(x, y, width, height);
  35733. if (clearColor && clearColor !== 'transparent') {
  35734. var clearColorGradientOrPattern = void 0;
  35735. if (isGradientObject(clearColor)) {
  35736. var shouldCache = clearColor.global || (clearColor.__width === width
  35737. && clearColor.__height === height);
  35738. clearColorGradientOrPattern = shouldCache
  35739. && clearColor.__canvasGradient
  35740. || getCanvasGradient(ctx, clearColor, {
  35741. x: 0,
  35742. y: 0,
  35743. width: width,
  35744. height: height
  35745. });
  35746. clearColor.__canvasGradient = clearColorGradientOrPattern;
  35747. clearColor.__width = width;
  35748. clearColor.__height = height;
  35749. }
  35750. else if (isImagePatternObject(clearColor)) {
  35751. clearColor.scaleX = clearColor.scaleX || dpr;
  35752. clearColor.scaleY = clearColor.scaleY || dpr;
  35753. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  35754. dirty: function () {
  35755. self.setUnpainted();
  35756. self.__painter.refresh();
  35757. }
  35758. });
  35759. }
  35760. ctx.save();
  35761. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  35762. ctx.fillRect(x, y, width, height);
  35763. ctx.restore();
  35764. }
  35765. if (haveMotionBLur) {
  35766. ctx.save();
  35767. ctx.globalAlpha = lastFrameAlpha;
  35768. ctx.drawImage(domBack, x, y, width, height);
  35769. ctx.restore();
  35770. }
  35771. }
  35772. if (!repaintRects || haveMotionBLur) {
  35773. doClear(0, 0, width, height);
  35774. }
  35775. else if (repaintRects.length) {
  35776. each(repaintRects, function (rect) {
  35777. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  35778. });
  35779. }
  35780. };
  35781. return Layer;
  35782. }(Eventful));
  35783. var HOVER_LAYER_ZLEVEL = 1e5;
  35784. var CANVAS_ZLEVEL = 314159;
  35785. var EL_AFTER_INCREMENTAL_INC = 0.01;
  35786. var INCREMENTAL_INC = 0.001;
  35787. function isLayerValid(layer) {
  35788. if (!layer) {
  35789. return false;
  35790. }
  35791. if (layer.__builtin__) {
  35792. return true;
  35793. }
  35794. if (typeof (layer.resize) !== 'function'
  35795. || typeof (layer.refresh) !== 'function') {
  35796. return false;
  35797. }
  35798. return true;
  35799. }
  35800. function createRoot(width, height) {
  35801. var domRoot = document.createElement('div');
  35802. domRoot.style.cssText = [
  35803. 'position:relative',
  35804. 'width:' + width + 'px',
  35805. 'height:' + height + 'px',
  35806. 'padding:0',
  35807. 'margin:0',
  35808. 'border-width:0'
  35809. ].join(';') + ';';
  35810. return domRoot;
  35811. }
  35812. var CanvasPainter = (function () {
  35813. function CanvasPainter(root, storage, opts, id) {
  35814. this.type = 'canvas';
  35815. this._zlevelList = [];
  35816. this._prevDisplayList = [];
  35817. this._layers = {};
  35818. this._layerConfig = {};
  35819. this._needsManuallyCompositing = false;
  35820. this.type = 'canvas';
  35821. var singleCanvas = !root.nodeName
  35822. || root.nodeName.toUpperCase() === 'CANVAS';
  35823. this._opts = opts = extend({}, opts || {});
  35824. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  35825. this._singleCanvas = singleCanvas;
  35826. this.root = root;
  35827. var rootStyle = root.style;
  35828. if (rootStyle) {
  35829. disableUserSelect(root);
  35830. root.innerHTML = '';
  35831. }
  35832. this.storage = storage;
  35833. var zlevelList = this._zlevelList;
  35834. this._prevDisplayList = [];
  35835. var layers = this._layers;
  35836. if (!singleCanvas) {
  35837. this._width = getSize(root, 0, opts);
  35838. this._height = getSize(root, 1, opts);
  35839. var domRoot = this._domRoot = createRoot(this._width, this._height);
  35840. root.appendChild(domRoot);
  35841. }
  35842. else {
  35843. var rootCanvas = root;
  35844. var width = rootCanvas.width;
  35845. var height = rootCanvas.height;
  35846. if (opts.width != null) {
  35847. width = opts.width;
  35848. }
  35849. if (opts.height != null) {
  35850. height = opts.height;
  35851. }
  35852. this.dpr = opts.devicePixelRatio || 1;
  35853. rootCanvas.width = width * this.dpr;
  35854. rootCanvas.height = height * this.dpr;
  35855. this._width = width;
  35856. this._height = height;
  35857. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  35858. mainLayer.__builtin__ = true;
  35859. mainLayer.initContext();
  35860. layers[CANVAS_ZLEVEL] = mainLayer;
  35861. mainLayer.zlevel = CANVAS_ZLEVEL;
  35862. zlevelList.push(CANVAS_ZLEVEL);
  35863. this._domRoot = root;
  35864. }
  35865. }
  35866. CanvasPainter.prototype.getType = function () {
  35867. return 'canvas';
  35868. };
  35869. CanvasPainter.prototype.isSingleCanvas = function () {
  35870. return this._singleCanvas;
  35871. };
  35872. CanvasPainter.prototype.getViewportRoot = function () {
  35873. return this._domRoot;
  35874. };
  35875. CanvasPainter.prototype.getViewportRootOffset = function () {
  35876. var viewportRoot = this.getViewportRoot();
  35877. if (viewportRoot) {
  35878. return {
  35879. offsetLeft: viewportRoot.offsetLeft || 0,
  35880. offsetTop: viewportRoot.offsetTop || 0
  35881. };
  35882. }
  35883. };
  35884. CanvasPainter.prototype.refresh = function (paintAll) {
  35885. var list = this.storage.getDisplayList(true);
  35886. var prevList = this._prevDisplayList;
  35887. var zlevelList = this._zlevelList;
  35888. this._redrawId = Math.random();
  35889. this._paintList(list, prevList, paintAll, this._redrawId);
  35890. for (var i = 0; i < zlevelList.length; i++) {
  35891. var z = zlevelList[i];
  35892. var layer = this._layers[z];
  35893. if (!layer.__builtin__ && layer.refresh) {
  35894. var clearColor = i === 0 ? this._backgroundColor : null;
  35895. layer.refresh(clearColor);
  35896. }
  35897. }
  35898. if (this._opts.useDirtyRect) {
  35899. this._prevDisplayList = list.slice();
  35900. }
  35901. return this;
  35902. };
  35903. CanvasPainter.prototype.refreshHover = function () {
  35904. this._paintHoverList(this.storage.getDisplayList(false));
  35905. };
  35906. CanvasPainter.prototype._paintHoverList = function (list) {
  35907. var len = list.length;
  35908. var hoverLayer = this._hoverlayer;
  35909. hoverLayer && hoverLayer.clear();
  35910. if (!len) {
  35911. return;
  35912. }
  35913. var scope = {
  35914. inHover: true,
  35915. viewWidth: this._width,
  35916. viewHeight: this._height
  35917. };
  35918. var ctx;
  35919. for (var i = 0; i < len; i++) {
  35920. var el = list[i];
  35921. if (el.__inHover) {
  35922. if (!hoverLayer) {
  35923. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  35924. }
  35925. if (!ctx) {
  35926. ctx = hoverLayer.ctx;
  35927. ctx.save();
  35928. }
  35929. brush(ctx, el, scope, i === len - 1);
  35930. }
  35931. }
  35932. if (ctx) {
  35933. ctx.restore();
  35934. }
  35935. };
  35936. CanvasPainter.prototype.getHoverLayer = function () {
  35937. return this.getLayer(HOVER_LAYER_ZLEVEL);
  35938. };
  35939. CanvasPainter.prototype.paintOne = function (ctx, el) {
  35940. brushSingle(ctx, el);
  35941. };
  35942. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  35943. if (this._redrawId !== redrawId) {
  35944. return;
  35945. }
  35946. paintAll = paintAll || false;
  35947. this._updateLayerStatus(list);
  35948. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  35949. if (this._needsManuallyCompositing) {
  35950. this._compositeManually();
  35951. }
  35952. if (needsRefreshHover) {
  35953. this._paintHoverList(list);
  35954. }
  35955. if (!finished) {
  35956. var self_1 = this;
  35957. requestAnimationFrame$1(function () {
  35958. self_1._paintList(list, prevList, paintAll, redrawId);
  35959. });
  35960. }
  35961. else {
  35962. this.eachLayer(function (layer) {
  35963. layer.afterBrush && layer.afterBrush();
  35964. });
  35965. }
  35966. };
  35967. CanvasPainter.prototype._compositeManually = function () {
  35968. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  35969. var width = this._domRoot.width;
  35970. var height = this._domRoot.height;
  35971. ctx.clearRect(0, 0, width, height);
  35972. this.eachBuiltinLayer(function (layer) {
  35973. if (layer.virtual) {
  35974. ctx.drawImage(layer.dom, 0, 0, width, height);
  35975. }
  35976. });
  35977. };
  35978. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  35979. var _this = this;
  35980. var layerList = [];
  35981. var useDirtyRect = this._opts.useDirtyRect;
  35982. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  35983. var zlevel = this._zlevelList[zi];
  35984. var layer = this._layers[zlevel];
  35985. if (layer.__builtin__
  35986. && layer !== this._hoverlayer
  35987. && (layer.__dirty || paintAll)) {
  35988. layerList.push(layer);
  35989. }
  35990. }
  35991. var finished = true;
  35992. var needsRefreshHover = false;
  35993. var _loop_1 = function (k) {
  35994. var layer = layerList[k];
  35995. var ctx = layer.ctx;
  35996. var repaintRects = useDirtyRect
  35997. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  35998. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  35999. var useTimer = !paintAll && layer.incremental && Date.now;
  36000. var startTime = useTimer && Date.now();
  36001. var clearColor = layer.zlevel === this_1._zlevelList[0]
  36002. ? this_1._backgroundColor : null;
  36003. if (layer.__startIndex === layer.__endIndex) {
  36004. layer.clear(false, clearColor, repaintRects);
  36005. }
  36006. else if (start === layer.__startIndex) {
  36007. var firstEl = list[start];
  36008. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  36009. layer.clear(false, clearColor, repaintRects);
  36010. }
  36011. }
  36012. if (start === -1) {
  36013. console.error('For some unknown reason. drawIndex is -1');
  36014. start = layer.__startIndex;
  36015. }
  36016. var i;
  36017. var repaint = function (repaintRect) {
  36018. var scope = {
  36019. inHover: false,
  36020. allClipped: false,
  36021. prevEl: null,
  36022. viewWidth: _this._width,
  36023. viewHeight: _this._height
  36024. };
  36025. for (i = start; i < layer.__endIndex; i++) {
  36026. var el = list[i];
  36027. if (el.__inHover) {
  36028. needsRefreshHover = true;
  36029. }
  36030. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  36031. if (useTimer) {
  36032. var dTime = Date.now() - startTime;
  36033. if (dTime > 15) {
  36034. break;
  36035. }
  36036. }
  36037. }
  36038. if (scope.prevElClipPaths) {
  36039. ctx.restore();
  36040. }
  36041. };
  36042. if (repaintRects) {
  36043. if (repaintRects.length === 0) {
  36044. i = layer.__endIndex;
  36045. }
  36046. else {
  36047. var dpr = this_1.dpr;
  36048. for (var r = 0; r < repaintRects.length; ++r) {
  36049. var rect = repaintRects[r];
  36050. ctx.save();
  36051. ctx.beginPath();
  36052. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  36053. ctx.clip();
  36054. repaint(rect);
  36055. ctx.restore();
  36056. }
  36057. }
  36058. }
  36059. else {
  36060. ctx.save();
  36061. repaint();
  36062. ctx.restore();
  36063. }
  36064. layer.__drawIndex = i;
  36065. if (layer.__drawIndex < layer.__endIndex) {
  36066. finished = false;
  36067. }
  36068. };
  36069. var this_1 = this;
  36070. for (var k = 0; k < layerList.length; k++) {
  36071. _loop_1(k);
  36072. }
  36073. if (env.wxa) {
  36074. each(this._layers, function (layer) {
  36075. if (layer && layer.ctx && layer.ctx.draw) {
  36076. layer.ctx.draw();
  36077. }
  36078. });
  36079. }
  36080. return {
  36081. finished: finished,
  36082. needsRefreshHover: needsRefreshHover
  36083. };
  36084. };
  36085. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  36086. var ctx = currentLayer.ctx;
  36087. if (useDirtyRect) {
  36088. var paintRect = el.getPaintRect();
  36089. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  36090. brush(ctx, el, scope, isLast);
  36091. el.setPrevPaintRect(paintRect);
  36092. }
  36093. }
  36094. else {
  36095. brush(ctx, el, scope, isLast);
  36096. }
  36097. };
  36098. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  36099. if (this._singleCanvas && !this._needsManuallyCompositing) {
  36100. zlevel = CANVAS_ZLEVEL;
  36101. }
  36102. var layer = this._layers[zlevel];
  36103. if (!layer) {
  36104. layer = new Layer('zr_' + zlevel, this, this.dpr);
  36105. layer.zlevel = zlevel;
  36106. layer.__builtin__ = true;
  36107. if (this._layerConfig[zlevel]) {
  36108. merge(layer, this._layerConfig[zlevel], true);
  36109. }
  36110. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  36111. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  36112. }
  36113. if (virtual) {
  36114. layer.virtual = virtual;
  36115. }
  36116. this.insertLayer(zlevel, layer);
  36117. layer.initContext();
  36118. }
  36119. return layer;
  36120. };
  36121. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  36122. var layersMap = this._layers;
  36123. var zlevelList = this._zlevelList;
  36124. var len = zlevelList.length;
  36125. var domRoot = this._domRoot;
  36126. var prevLayer = null;
  36127. var i = -1;
  36128. if (layersMap[zlevel]) {
  36129. if ("development" !== 'production') {
  36130. logError('ZLevel ' + zlevel + ' has been used already');
  36131. }
  36132. return;
  36133. }
  36134. if (!isLayerValid(layer)) {
  36135. if ("development" !== 'production') {
  36136. logError('Layer of zlevel ' + zlevel + ' is not valid');
  36137. }
  36138. return;
  36139. }
  36140. if (len > 0 && zlevel > zlevelList[0]) {
  36141. for (i = 0; i < len - 1; i++) {
  36142. if (zlevelList[i] < zlevel
  36143. && zlevelList[i + 1] > zlevel) {
  36144. break;
  36145. }
  36146. }
  36147. prevLayer = layersMap[zlevelList[i]];
  36148. }
  36149. zlevelList.splice(i + 1, 0, zlevel);
  36150. layersMap[zlevel] = layer;
  36151. if (!layer.virtual) {
  36152. if (prevLayer) {
  36153. var prevDom = prevLayer.dom;
  36154. if (prevDom.nextSibling) {
  36155. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  36156. }
  36157. else {
  36158. domRoot.appendChild(layer.dom);
  36159. }
  36160. }
  36161. else {
  36162. if (domRoot.firstChild) {
  36163. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  36164. }
  36165. else {
  36166. domRoot.appendChild(layer.dom);
  36167. }
  36168. }
  36169. }
  36170. layer.__painter = this;
  36171. };
  36172. CanvasPainter.prototype.eachLayer = function (cb, context) {
  36173. var zlevelList = this._zlevelList;
  36174. for (var i = 0; i < zlevelList.length; i++) {
  36175. var z = zlevelList[i];
  36176. cb.call(context, this._layers[z], z);
  36177. }
  36178. };
  36179. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  36180. var zlevelList = this._zlevelList;
  36181. for (var i = 0; i < zlevelList.length; i++) {
  36182. var z = zlevelList[i];
  36183. var layer = this._layers[z];
  36184. if (layer.__builtin__) {
  36185. cb.call(context, layer, z);
  36186. }
  36187. }
  36188. };
  36189. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  36190. var zlevelList = this._zlevelList;
  36191. for (var i = 0; i < zlevelList.length; i++) {
  36192. var z = zlevelList[i];
  36193. var layer = this._layers[z];
  36194. if (!layer.__builtin__) {
  36195. cb.call(context, layer, z);
  36196. }
  36197. }
  36198. };
  36199. CanvasPainter.prototype.getLayers = function () {
  36200. return this._layers;
  36201. };
  36202. CanvasPainter.prototype._updateLayerStatus = function (list) {
  36203. this.eachBuiltinLayer(function (layer, z) {
  36204. layer.__dirty = layer.__used = false;
  36205. });
  36206. function updatePrevLayer(idx) {
  36207. if (prevLayer) {
  36208. if (prevLayer.__endIndex !== idx) {
  36209. prevLayer.__dirty = true;
  36210. }
  36211. prevLayer.__endIndex = idx;
  36212. }
  36213. }
  36214. if (this._singleCanvas) {
  36215. for (var i_1 = 1; i_1 < list.length; i_1++) {
  36216. var el = list[i_1];
  36217. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  36218. this._needsManuallyCompositing = true;
  36219. break;
  36220. }
  36221. }
  36222. }
  36223. var prevLayer = null;
  36224. var incrementalLayerCount = 0;
  36225. var prevZlevel;
  36226. var i;
  36227. for (i = 0; i < list.length; i++) {
  36228. var el = list[i];
  36229. var zlevel = el.zlevel;
  36230. var layer = void 0;
  36231. if (prevZlevel !== zlevel) {
  36232. prevZlevel = zlevel;
  36233. incrementalLayerCount = 0;
  36234. }
  36235. if (el.incremental) {
  36236. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  36237. layer.incremental = true;
  36238. incrementalLayerCount = 1;
  36239. }
  36240. else {
  36241. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  36242. }
  36243. if (!layer.__builtin__) {
  36244. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  36245. }
  36246. if (layer !== prevLayer) {
  36247. layer.__used = true;
  36248. if (layer.__startIndex !== i) {
  36249. layer.__dirty = true;
  36250. }
  36251. layer.__startIndex = i;
  36252. if (!layer.incremental) {
  36253. layer.__drawIndex = i;
  36254. }
  36255. else {
  36256. layer.__drawIndex = -1;
  36257. }
  36258. updatePrevLayer(i);
  36259. prevLayer = layer;
  36260. }
  36261. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  36262. layer.__dirty = true;
  36263. if (layer.incremental && layer.__drawIndex < 0) {
  36264. layer.__drawIndex = i;
  36265. }
  36266. }
  36267. }
  36268. updatePrevLayer(i);
  36269. this.eachBuiltinLayer(function (layer, z) {
  36270. if (!layer.__used && layer.getElementCount() > 0) {
  36271. layer.__dirty = true;
  36272. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  36273. }
  36274. if (layer.__dirty && layer.__drawIndex < 0) {
  36275. layer.__drawIndex = layer.__startIndex;
  36276. }
  36277. });
  36278. };
  36279. CanvasPainter.prototype.clear = function () {
  36280. this.eachBuiltinLayer(this._clearLayer);
  36281. return this;
  36282. };
  36283. CanvasPainter.prototype._clearLayer = function (layer) {
  36284. layer.clear();
  36285. };
  36286. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  36287. this._backgroundColor = backgroundColor;
  36288. each(this._layers, function (layer) {
  36289. layer.setUnpainted();
  36290. });
  36291. };
  36292. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  36293. if (config) {
  36294. var layerConfig = this._layerConfig;
  36295. if (!layerConfig[zlevel]) {
  36296. layerConfig[zlevel] = config;
  36297. }
  36298. else {
  36299. merge(layerConfig[zlevel], config, true);
  36300. }
  36301. for (var i = 0; i < this._zlevelList.length; i++) {
  36302. var _zlevel = this._zlevelList[i];
  36303. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  36304. var layer = this._layers[_zlevel];
  36305. merge(layer, layerConfig[zlevel], true);
  36306. }
  36307. }
  36308. }
  36309. };
  36310. CanvasPainter.prototype.delLayer = function (zlevel) {
  36311. var layers = this._layers;
  36312. var zlevelList = this._zlevelList;
  36313. var layer = layers[zlevel];
  36314. if (!layer) {
  36315. return;
  36316. }
  36317. layer.dom.parentNode.removeChild(layer.dom);
  36318. delete layers[zlevel];
  36319. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  36320. };
  36321. CanvasPainter.prototype.resize = function (width, height) {
  36322. if (!this._domRoot.style) {
  36323. if (width == null || height == null) {
  36324. return;
  36325. }
  36326. this._width = width;
  36327. this._height = height;
  36328. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  36329. }
  36330. else {
  36331. var domRoot = this._domRoot;
  36332. domRoot.style.display = 'none';
  36333. var opts = this._opts;
  36334. var root = this.root;
  36335. width != null && (opts.width = width);
  36336. height != null && (opts.height = height);
  36337. width = getSize(root, 0, opts);
  36338. height = getSize(root, 1, opts);
  36339. domRoot.style.display = '';
  36340. if (this._width !== width || height !== this._height) {
  36341. domRoot.style.width = width + 'px';
  36342. domRoot.style.height = height + 'px';
  36343. for (var id in this._layers) {
  36344. if (this._layers.hasOwnProperty(id)) {
  36345. this._layers[id].resize(width, height);
  36346. }
  36347. }
  36348. this.refresh(true);
  36349. }
  36350. this._width = width;
  36351. this._height = height;
  36352. }
  36353. return this;
  36354. };
  36355. CanvasPainter.prototype.clearLayer = function (zlevel) {
  36356. var layer = this._layers[zlevel];
  36357. if (layer) {
  36358. layer.clear();
  36359. }
  36360. };
  36361. CanvasPainter.prototype.dispose = function () {
  36362. this.root.innerHTML = '';
  36363. this.root =
  36364. this.storage =
  36365. this._domRoot =
  36366. this._layers = null;
  36367. };
  36368. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  36369. opts = opts || {};
  36370. if (this._singleCanvas && !this._compositeManually) {
  36371. return this._layers[CANVAS_ZLEVEL].dom;
  36372. }
  36373. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  36374. imageLayer.initContext();
  36375. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  36376. var ctx = imageLayer.ctx;
  36377. if (opts.pixelRatio <= this.dpr) {
  36378. this.refresh();
  36379. var width_1 = imageLayer.dom.width;
  36380. var height_1 = imageLayer.dom.height;
  36381. this.eachLayer(function (layer) {
  36382. if (layer.__builtin__) {
  36383. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  36384. }
  36385. else if (layer.renderToCanvas) {
  36386. ctx.save();
  36387. layer.renderToCanvas(ctx);
  36388. ctx.restore();
  36389. }
  36390. });
  36391. }
  36392. else {
  36393. var scope = {
  36394. inHover: false,
  36395. viewWidth: this._width,
  36396. viewHeight: this._height
  36397. };
  36398. var displayList = this.storage.getDisplayList(true);
  36399. for (var i = 0, len = displayList.length; i < len; i++) {
  36400. var el = displayList[i];
  36401. brush(ctx, el, scope, i === len - 1);
  36402. }
  36403. }
  36404. return imageLayer.dom;
  36405. };
  36406. CanvasPainter.prototype.getWidth = function () {
  36407. return this._width;
  36408. };
  36409. CanvasPainter.prototype.getHeight = function () {
  36410. return this._height;
  36411. };
  36412. return CanvasPainter;
  36413. }());
  36414. function install$1(registers) {
  36415. registers.registerPainter('canvas', CanvasPainter);
  36416. }
  36417. var LineSeriesModel =
  36418. /** @class */
  36419. function (_super) {
  36420. __extends(LineSeriesModel, _super);
  36421. function LineSeriesModel() {
  36422. var _this = _super !== null && _super.apply(this, arguments) || this;
  36423. _this.type = LineSeriesModel.type;
  36424. _this.hasSymbolVisual = true;
  36425. return _this;
  36426. }
  36427. LineSeriesModel.prototype.getInitialData = function (option) {
  36428. if ("development" !== 'production') {
  36429. var coordSys = option.coordinateSystem;
  36430. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  36431. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  36432. }
  36433. }
  36434. return createSeriesData(null, this, {
  36435. useEncodeDefaulter: true
  36436. });
  36437. };
  36438. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  36439. var group = new Group();
  36440. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  36441. group.add(line);
  36442. line.setStyle(opt.lineStyle);
  36443. var visualType = this.getData().getVisual('symbol');
  36444. var visualRotate = this.getData().getVisual('symbolRotate');
  36445. var symbolType = visualType === 'none' ? 'circle' : visualType; // Symbol size is 80% when there is a line
  36446. var size = opt.itemHeight * 0.8;
  36447. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  36448. group.add(symbol);
  36449. symbol.setStyle(opt.itemStyle);
  36450. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  36451. symbol.rotation = symbolRotate * Math.PI / 180;
  36452. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  36453. if (symbolType.indexOf('empty') > -1) {
  36454. symbol.style.stroke = symbol.style.fill;
  36455. symbol.style.fill = '#fff';
  36456. symbol.style.lineWidth = 2;
  36457. }
  36458. return group;
  36459. };
  36460. LineSeriesModel.type = 'series.line';
  36461. LineSeriesModel.dependencies = ['grid', 'polar'];
  36462. LineSeriesModel.defaultOption = {
  36463. // zlevel: 0,
  36464. z: 3,
  36465. coordinateSystem: 'cartesian2d',
  36466. legendHoverLink: true,
  36467. clip: true,
  36468. label: {
  36469. position: 'top'
  36470. },
  36471. // itemStyle: {
  36472. // },
  36473. endLabel: {
  36474. show: false,
  36475. valueAnimation: true,
  36476. distance: 8
  36477. },
  36478. lineStyle: {
  36479. width: 2,
  36480. type: 'solid'
  36481. },
  36482. emphasis: {
  36483. scale: true
  36484. },
  36485. // areaStyle: {
  36486. // origin of areaStyle. Valid values:
  36487. // `'auto'/null/undefined`: from axisLine to data
  36488. // `'start'`: from min to data
  36489. // `'end'`: from data to max
  36490. // origin: 'auto'
  36491. // },
  36492. // false, 'start', 'end', 'middle'
  36493. step: false,
  36494. // Disabled if step is true
  36495. smooth: false,
  36496. smoothMonotone: null,
  36497. symbol: 'emptyCircle',
  36498. symbolSize: 4,
  36499. symbolRotate: null,
  36500. showSymbol: true,
  36501. // `false`: follow the label interval strategy.
  36502. // `true`: show all symbols.
  36503. // `'auto'`: If possible, show all symbols, otherwise
  36504. // follow the label interval strategy.
  36505. showAllSymbol: 'auto',
  36506. // Whether to connect break point.
  36507. connectNulls: false,
  36508. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  36509. sampling: 'none',
  36510. animationEasing: 'linear',
  36511. // Disable progressive
  36512. progressive: 0,
  36513. hoverLayerThreshold: Infinity,
  36514. universalTransition: {
  36515. divideShape: 'clone'
  36516. },
  36517. triggerLineEvent: false
  36518. };
  36519. return LineSeriesModel;
  36520. }(SeriesModel);
  36521. /**
  36522. * @return label string. Not null/undefined
  36523. */
  36524. function getDefaultLabel(data, dataIndex) {
  36525. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36526. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  36527. if (len === 1) {
  36528. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  36529. return rawVal != null ? rawVal + '' : null;
  36530. } else if (len) {
  36531. var vals = [];
  36532. for (var i = 0; i < labelDims.length; i++) {
  36533. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  36534. }
  36535. return vals.join(' ');
  36536. }
  36537. }
  36538. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  36539. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36540. if (!isArray(interpolatedValue)) {
  36541. return interpolatedValue + '';
  36542. }
  36543. var vals = [];
  36544. for (var i = 0; i < labelDims.length; i++) {
  36545. var dimIndex = data.getDimensionIndex(labelDims[i]);
  36546. if (dimIndex >= 0) {
  36547. vals.push(interpolatedValue[dimIndex]);
  36548. }
  36549. }
  36550. return vals.join(' ');
  36551. }
  36552. var Symbol =
  36553. /** @class */
  36554. function (_super) {
  36555. __extends(Symbol, _super);
  36556. function Symbol(data, idx, seriesScope, opts) {
  36557. var _this = _super.call(this) || this;
  36558. _this.updateData(data, idx, seriesScope, opts);
  36559. return _this;
  36560. }
  36561. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  36562. // Remove paths created before
  36563. this.removeAll(); // let symbolPath = createSymbol(
  36564. // symbolType, -0.5, -0.5, 1, 1, color
  36565. // );
  36566. // If width/height are set too small (e.g., set to 1) on ios10
  36567. // and macOS Sierra, a circle stroke become a rect, no matter what
  36568. // the scale is set. So we set width/height as 2. See #4150.
  36569. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  36570. symbolPath.attr({
  36571. z2: 100,
  36572. culling: true,
  36573. scaleX: symbolSize[0] / 2,
  36574. scaleY: symbolSize[1] / 2
  36575. }); // Rewrite drift method
  36576. symbolPath.drift = driftSymbol;
  36577. this._symbolType = symbolType;
  36578. this.add(symbolPath);
  36579. };
  36580. /**
  36581. * Stop animation
  36582. * @param {boolean} toLastFrame
  36583. */
  36584. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  36585. this.childAt(0).stopAnimation(null, toLastFrame);
  36586. };
  36587. Symbol.prototype.getSymbolType = function () {
  36588. return this._symbolType;
  36589. };
  36590. /**
  36591. * FIXME:
  36592. * Caution: This method breaks the encapsulation of this module,
  36593. * but it indeed brings convenience. So do not use the method
  36594. * unless you detailedly know all the implements of `Symbol`,
  36595. * especially animation.
  36596. *
  36597. * Get symbol path element.
  36598. */
  36599. Symbol.prototype.getSymbolPath = function () {
  36600. return this.childAt(0);
  36601. };
  36602. /**
  36603. * Highlight symbol
  36604. */
  36605. Symbol.prototype.highlight = function () {
  36606. enterEmphasis(this.childAt(0));
  36607. };
  36608. /**
  36609. * Downplay symbol
  36610. */
  36611. Symbol.prototype.downplay = function () {
  36612. leaveEmphasis(this.childAt(0));
  36613. };
  36614. /**
  36615. * @param {number} zlevel
  36616. * @param {number} z
  36617. */
  36618. Symbol.prototype.setZ = function (zlevel, z) {
  36619. var symbolPath = this.childAt(0);
  36620. symbolPath.zlevel = zlevel;
  36621. symbolPath.z = z;
  36622. };
  36623. Symbol.prototype.setDraggable = function (draggable, hasCursorOption) {
  36624. var symbolPath = this.childAt(0);
  36625. symbolPath.draggable = draggable;
  36626. symbolPath.cursor = !hasCursorOption && draggable ? 'move' : symbolPath.cursor;
  36627. };
  36628. /**
  36629. * Update symbol properties
  36630. */
  36631. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  36632. this.silent = false;
  36633. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  36634. var seriesModel = data.hostModel;
  36635. var symbolSize = Symbol.getSymbolSize(data, idx);
  36636. var isInit = symbolType !== this._symbolType;
  36637. var disableAnimation = opts && opts.disableAnimation;
  36638. if (isInit) {
  36639. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  36640. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  36641. } else {
  36642. var symbolPath = this.childAt(0);
  36643. symbolPath.silent = false;
  36644. var target = {
  36645. scaleX: symbolSize[0] / 2,
  36646. scaleY: symbolSize[1] / 2
  36647. };
  36648. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  36649. saveOldStyle(symbolPath);
  36650. }
  36651. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  36652. if (isInit) {
  36653. var symbolPath = this.childAt(0);
  36654. if (!disableAnimation) {
  36655. var target = {
  36656. scaleX: this._sizeX,
  36657. scaleY: this._sizeY,
  36658. style: {
  36659. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  36660. opacity: symbolPath.style.opacity
  36661. }
  36662. };
  36663. symbolPath.scaleX = symbolPath.scaleY = 0;
  36664. symbolPath.style.opacity = 0;
  36665. initProps(symbolPath, target, seriesModel, idx);
  36666. }
  36667. }
  36668. if (disableAnimation) {
  36669. // Must stop leave transition manually if don't call initProps or updateProps.
  36670. this.childAt(0).stopAnimation('leave');
  36671. }
  36672. };
  36673. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  36674. var symbolPath = this.childAt(0);
  36675. var seriesModel = data.hostModel;
  36676. var emphasisItemStyle;
  36677. var blurItemStyle;
  36678. var selectItemStyle;
  36679. var focus;
  36680. var blurScope;
  36681. var emphasisDisabled;
  36682. var labelStatesModels;
  36683. var hoverScale;
  36684. var cursorStyle;
  36685. if (seriesScope) {
  36686. emphasisItemStyle = seriesScope.emphasisItemStyle;
  36687. blurItemStyle = seriesScope.blurItemStyle;
  36688. selectItemStyle = seriesScope.selectItemStyle;
  36689. focus = seriesScope.focus;
  36690. blurScope = seriesScope.blurScope;
  36691. labelStatesModels = seriesScope.labelStatesModels;
  36692. hoverScale = seriesScope.hoverScale;
  36693. cursorStyle = seriesScope.cursorStyle;
  36694. emphasisDisabled = seriesScope.emphasisDisabled;
  36695. }
  36696. if (!seriesScope || data.hasItemOption) {
  36697. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  36698. var emphasisModel = itemModel.getModel('emphasis');
  36699. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  36700. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  36701. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  36702. focus = emphasisModel.get('focus');
  36703. blurScope = emphasisModel.get('blurScope');
  36704. emphasisDisabled = emphasisModel.get('disabled');
  36705. labelStatesModels = getLabelStatesModels(itemModel);
  36706. hoverScale = emphasisModel.getShallow('scale');
  36707. cursorStyle = itemModel.getShallow('cursor');
  36708. }
  36709. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  36710. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  36711. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  36712. if (symbolOffset) {
  36713. symbolPath.x = symbolOffset[0];
  36714. symbolPath.y = symbolOffset[1];
  36715. }
  36716. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  36717. var symbolStyle = data.getItemVisual(idx, 'style');
  36718. var visualColor = symbolStyle.fill;
  36719. if (symbolPath instanceof ZRImage) {
  36720. var pathStyle = symbolPath.style;
  36721. symbolPath.useStyle(extend({
  36722. // TODO other properties like x, y ?
  36723. image: pathStyle.image,
  36724. x: pathStyle.x,
  36725. y: pathStyle.y,
  36726. width: pathStyle.width,
  36727. height: pathStyle.height
  36728. }, symbolStyle));
  36729. } else {
  36730. if (symbolPath.__isEmptyBrush) {
  36731. // fill and stroke will be swapped if it's empty.
  36732. // So we cloned a new style to avoid it affecting the original style in visual storage.
  36733. // TODO Better implementation. No empty logic!
  36734. symbolPath.useStyle(extend({}, symbolStyle));
  36735. } else {
  36736. symbolPath.useStyle(symbolStyle);
  36737. } // Disable decal because symbol scale will been applied on the decal.
  36738. symbolPath.style.decal = null;
  36739. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  36740. symbolPath.style.strokeNoScale = true;
  36741. }
  36742. var liftZ = data.getItemVisual(idx, 'liftZ');
  36743. var z2Origin = this._z2;
  36744. if (liftZ != null) {
  36745. if (z2Origin == null) {
  36746. this._z2 = symbolPath.z2;
  36747. symbolPath.z2 += liftZ;
  36748. }
  36749. } else if (z2Origin != null) {
  36750. symbolPath.z2 = z2Origin;
  36751. this._z2 = null;
  36752. }
  36753. var useNameLabel = opts && opts.useNameLabel;
  36754. setLabelStyle(symbolPath, labelStatesModels, {
  36755. labelFetcher: seriesModel,
  36756. labelDataIndex: idx,
  36757. defaultText: getLabelDefaultText,
  36758. inheritColor: visualColor,
  36759. defaultOpacity: symbolStyle.opacity
  36760. }); // Do not execute util needed.
  36761. function getLabelDefaultText(idx) {
  36762. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  36763. }
  36764. this._sizeX = symbolSize[0] / 2;
  36765. this._sizeY = symbolSize[1] / 2;
  36766. var emphasisState = symbolPath.ensureState('emphasis');
  36767. emphasisState.style = emphasisItemStyle;
  36768. symbolPath.ensureState('select').style = selectItemStyle;
  36769. symbolPath.ensureState('blur').style = blurItemStyle; // null / undefined / true means to use default strategy.
  36770. // 0 / false / negative number / NaN / Infinity means no scale.
  36771. var scaleRatio = hoverScale == null || hoverScale === true ? Math.max(1.1, 3 / this._sizeY) // PENDING: restrict hoverScale > 1? It seems unreasonable to scale down
  36772. : isFinite(hoverScale) && hoverScale > 0 ? +hoverScale : 1; // always set scale to allow resetting
  36773. emphasisState.scaleX = this._sizeX * scaleRatio;
  36774. emphasisState.scaleY = this._sizeY * scaleRatio;
  36775. this.setSymbolScale(1);
  36776. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  36777. };
  36778. Symbol.prototype.setSymbolScale = function (scale) {
  36779. this.scaleX = this.scaleY = scale;
  36780. };
  36781. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  36782. var symbolPath = this.childAt(0);
  36783. var dataIndex = getECData(this).dataIndex;
  36784. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  36785. this.silent = symbolPath.silent = true; // Not show text when animating
  36786. if (opt && opt.fadeLabel) {
  36787. var textContent = symbolPath.getTextContent();
  36788. if (textContent) {
  36789. removeElement(textContent, {
  36790. style: {
  36791. opacity: 0
  36792. }
  36793. }, seriesModel, {
  36794. dataIndex: dataIndex,
  36795. removeOpt: animationOpt,
  36796. cb: function () {
  36797. symbolPath.removeTextContent();
  36798. }
  36799. });
  36800. }
  36801. } else {
  36802. symbolPath.removeTextContent();
  36803. }
  36804. removeElement(symbolPath, {
  36805. style: {
  36806. opacity: 0
  36807. },
  36808. scaleX: 0,
  36809. scaleY: 0
  36810. }, seriesModel, {
  36811. dataIndex: dataIndex,
  36812. cb: cb,
  36813. removeOpt: animationOpt
  36814. });
  36815. };
  36816. Symbol.getSymbolSize = function (data, idx) {
  36817. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  36818. };
  36819. return Symbol;
  36820. }(Group);
  36821. function driftSymbol(dx, dy) {
  36822. this.parent.drift(dx, dy);
  36823. }
  36824. function symbolNeedsDraw(data, point, idx, opt) {
  36825. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx)) // We do not set clipShape on group, because it will cut part of
  36826. // the symbol element shape. We use the same clip shape here as
  36827. // the line clip.
  36828. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  36829. }
  36830. function normalizeUpdateOpt(opt) {
  36831. if (opt != null && !isObject(opt)) {
  36832. opt = {
  36833. isIgnore: opt
  36834. };
  36835. }
  36836. return opt || {};
  36837. }
  36838. function makeSeriesScope(data) {
  36839. var seriesModel = data.hostModel;
  36840. var emphasisModel = seriesModel.getModel('emphasis');
  36841. return {
  36842. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  36843. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  36844. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  36845. focus: emphasisModel.get('focus'),
  36846. blurScope: emphasisModel.get('blurScope'),
  36847. emphasisDisabled: emphasisModel.get('disabled'),
  36848. hoverScale: emphasisModel.get('scale'),
  36849. labelStatesModels: getLabelStatesModels(seriesModel),
  36850. cursorStyle: seriesModel.get('cursor')
  36851. };
  36852. }
  36853. var SymbolDraw =
  36854. /** @class */
  36855. function () {
  36856. function SymbolDraw(SymbolCtor) {
  36857. this.group = new Group();
  36858. this._SymbolCtor = SymbolCtor || Symbol;
  36859. }
  36860. /**
  36861. * Update symbols draw by new data
  36862. */
  36863. SymbolDraw.prototype.updateData = function (data, opt) {
  36864. // Remove progressive els.
  36865. this._progressiveEls = null;
  36866. opt = normalizeUpdateOpt(opt);
  36867. var group = this.group;
  36868. var seriesModel = data.hostModel;
  36869. var oldData = this._data;
  36870. var SymbolCtor = this._SymbolCtor;
  36871. var disableAnimation = opt.disableAnimation;
  36872. var seriesScope = makeSeriesScope(data);
  36873. var symbolUpdateOpt = {
  36874. disableAnimation: disableAnimation
  36875. };
  36876. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  36877. return data.getItemLayout(idx);
  36878. }; // There is no oldLineData only when first rendering or switching from
  36879. // stream mode to normal mode, where previous elements should be removed.
  36880. if (!oldData) {
  36881. group.removeAll();
  36882. }
  36883. data.diff(oldData).add(function (newIdx) {
  36884. var point = getSymbolPoint(newIdx);
  36885. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  36886. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36887. symbolEl.setPosition(point);
  36888. data.setItemGraphicEl(newIdx, symbolEl);
  36889. group.add(symbolEl);
  36890. }
  36891. }).update(function (newIdx, oldIdx) {
  36892. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36893. var point = getSymbolPoint(newIdx);
  36894. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  36895. group.remove(symbolEl);
  36896. return;
  36897. }
  36898. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  36899. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  36900. if (!symbolEl // Create a new if symbol type changed.
  36901. || oldSymbolType && oldSymbolType !== newSymbolType) {
  36902. group.remove(symbolEl);
  36903. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36904. symbolEl.setPosition(point);
  36905. } else {
  36906. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  36907. var target = {
  36908. x: point[0],
  36909. y: point[1]
  36910. };
  36911. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  36912. } // Add back
  36913. group.add(symbolEl);
  36914. data.setItemGraphicEl(newIdx, symbolEl);
  36915. }).remove(function (oldIdx) {
  36916. var el = oldData.getItemGraphicEl(oldIdx);
  36917. el && el.fadeOut(function () {
  36918. group.remove(el);
  36919. }, seriesModel);
  36920. }).execute();
  36921. this._getSymbolPoint = getSymbolPoint;
  36922. this._data = data;
  36923. };
  36924. SymbolDraw.prototype.updateLayout = function () {
  36925. var _this = this;
  36926. var data = this._data;
  36927. if (data) {
  36928. // Not use animation
  36929. data.eachItemGraphicEl(function (el, idx) {
  36930. var point = _this._getSymbolPoint(idx);
  36931. el.setPosition(point);
  36932. el.markRedraw();
  36933. });
  36934. }
  36935. };
  36936. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  36937. this._seriesScope = makeSeriesScope(data);
  36938. this._data = null;
  36939. this.group.removeAll();
  36940. };
  36941. /**
  36942. * Update symbols draw by new data
  36943. */
  36944. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  36945. // Clear
  36946. this._progressiveEls = [];
  36947. opt = normalizeUpdateOpt(opt);
  36948. function updateIncrementalAndHover(el) {
  36949. if (!el.isGroup) {
  36950. el.incremental = true;
  36951. el.ensureState('emphasis').hoverLayer = true;
  36952. }
  36953. }
  36954. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  36955. var point = data.getItemLayout(idx);
  36956. if (symbolNeedsDraw(data, point, idx, opt)) {
  36957. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  36958. el.traverse(updateIncrementalAndHover);
  36959. el.setPosition(point);
  36960. this.group.add(el);
  36961. data.setItemGraphicEl(idx, el);
  36962. this._progressiveEls.push(el);
  36963. }
  36964. }
  36965. };
  36966. SymbolDraw.prototype.eachRendered = function (cb) {
  36967. traverseElements(this._progressiveEls || this.group, cb);
  36968. };
  36969. SymbolDraw.prototype.remove = function (enableAnimation) {
  36970. var group = this.group;
  36971. var data = this._data; // Incremental model do not have this._data.
  36972. if (data && enableAnimation) {
  36973. data.eachItemGraphicEl(function (el) {
  36974. el.fadeOut(function () {
  36975. group.remove(el);
  36976. }, data.hostModel);
  36977. });
  36978. } else {
  36979. group.removeAll();
  36980. }
  36981. };
  36982. return SymbolDraw;
  36983. }();
  36984. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  36985. var baseAxis = coordSys.getBaseAxis();
  36986. var valueAxis = coordSys.getOtherAxis(baseAxis);
  36987. var valueStart = getValueStart(valueAxis, valueOrigin);
  36988. var baseAxisDim = baseAxis.dim;
  36989. var valueAxisDim = valueAxis.dim;
  36990. var valueDim = data.mapDimension(valueAxisDim);
  36991. var baseDim = data.mapDimension(baseAxisDim);
  36992. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  36993. var dims = map(coordSys.dimensions, function (coordDim) {
  36994. return data.mapDimension(coordDim);
  36995. });
  36996. var stacked = false;
  36997. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  36998. if (isDimensionStacked(data, dims[0]
  36999. /* , dims[1] */
  37000. )) {
  37001. // jshint ignore:line
  37002. stacked = true;
  37003. dims[0] = stackResultDim;
  37004. }
  37005. if (isDimensionStacked(data, dims[1]
  37006. /* , dims[0] */
  37007. )) {
  37008. // jshint ignore:line
  37009. stacked = true;
  37010. dims[1] = stackResultDim;
  37011. }
  37012. return {
  37013. dataDimsForPoint: dims,
  37014. valueStart: valueStart,
  37015. valueAxisDim: valueAxisDim,
  37016. baseAxisDim: baseAxisDim,
  37017. stacked: !!stacked,
  37018. valueDim: valueDim,
  37019. baseDim: baseDim,
  37020. baseDataOffset: baseDataOffset,
  37021. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  37022. };
  37023. }
  37024. function getValueStart(valueAxis, valueOrigin) {
  37025. var valueStart = 0;
  37026. var extent = valueAxis.scale.getExtent();
  37027. if (valueOrigin === 'start') {
  37028. valueStart = extent[0];
  37029. } else if (valueOrigin === 'end') {
  37030. valueStart = extent[1];
  37031. } // If origin is specified as a number, use it as
  37032. // valueStart directly
  37033. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  37034. valueStart = valueOrigin;
  37035. } // auto
  37036. else {
  37037. // Both positive
  37038. if (extent[0] > 0) {
  37039. valueStart = extent[0];
  37040. } // Both negative
  37041. else if (extent[1] < 0) {
  37042. valueStart = extent[1];
  37043. } // If is one positive, and one negative, onZero shall be true
  37044. }
  37045. return valueStart;
  37046. }
  37047. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  37048. var value = NaN;
  37049. if (dataCoordInfo.stacked) {
  37050. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  37051. }
  37052. if (isNaN(value)) {
  37053. value = dataCoordInfo.valueStart;
  37054. }
  37055. var baseDataOffset = dataCoordInfo.baseDataOffset;
  37056. var stackedData = [];
  37057. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  37058. stackedData[1 - baseDataOffset] = value;
  37059. return coordSys.dataToPoint(stackedData);
  37060. }
  37061. function diffData(oldData, newData) {
  37062. var diffResult = [];
  37063. newData.diff(oldData).add(function (idx) {
  37064. diffResult.push({
  37065. cmd: '+',
  37066. idx: idx
  37067. });
  37068. }).update(function (newIdx, oldIdx) {
  37069. diffResult.push({
  37070. cmd: '=',
  37071. idx: oldIdx,
  37072. idx1: newIdx
  37073. });
  37074. }).remove(function (idx) {
  37075. diffResult.push({
  37076. cmd: '-',
  37077. idx: idx
  37078. });
  37079. }).execute();
  37080. return diffResult;
  37081. }
  37082. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  37083. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  37084. // let oldIdList = oldData.mapArray(oldData.getId);
  37085. // convertToIntId(newIdList, oldIdList);
  37086. // // FIXME One data ?
  37087. // diff = arrayDiff(oldIdList, newIdList);
  37088. var currPoints = [];
  37089. var nextPoints = []; // Points for stacking base line
  37090. var currStackedPoints = [];
  37091. var nextStackedPoints = [];
  37092. var status = [];
  37093. var sortedIndices = [];
  37094. var rawIndices = [];
  37095. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin); // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  37096. var oldPoints = oldData.getLayout('points') || [];
  37097. var newPoints = newData.getLayout('points') || [];
  37098. for (var i = 0; i < diff.length; i++) {
  37099. var diffItem = diff[i];
  37100. var pointAdded = true;
  37101. var oldIdx2 = void 0;
  37102. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  37103. // Which is in case remvoing or add more than one data in the tail or head
  37104. switch (diffItem.cmd) {
  37105. case '=':
  37106. oldIdx2 = diffItem.idx * 2;
  37107. newIdx2 = diffItem.idx1 * 2;
  37108. var currentX = oldPoints[oldIdx2];
  37109. var currentY = oldPoints[oldIdx2 + 1];
  37110. var nextX = newPoints[newIdx2];
  37111. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  37112. if (isNaN(currentX) || isNaN(currentY)) {
  37113. currentX = nextX;
  37114. currentY = nextY;
  37115. }
  37116. currPoints.push(currentX, currentY);
  37117. nextPoints.push(nextX, nextY);
  37118. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  37119. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37120. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  37121. break;
  37122. case '+':
  37123. var newIdx = diffItem.idx;
  37124. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  37125. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  37126. newIdx2 = newIdx * 2;
  37127. currPoints.push(oldPt[0], oldPt[1]);
  37128. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  37129. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  37130. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  37131. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37132. rawIndices.push(newData.getRawIndex(newIdx));
  37133. break;
  37134. case '-':
  37135. pointAdded = false;
  37136. } // Original indices
  37137. if (pointAdded) {
  37138. status.push(diffItem);
  37139. sortedIndices.push(sortedIndices.length);
  37140. }
  37141. } // Diff result may be crossed if all items are changed
  37142. // Sort by data index
  37143. sortedIndices.sort(function (a, b) {
  37144. return rawIndices[a] - rawIndices[b];
  37145. });
  37146. var len = currPoints.length;
  37147. var sortedCurrPoints = createFloat32Array(len);
  37148. var sortedNextPoints = createFloat32Array(len);
  37149. var sortedCurrStackedPoints = createFloat32Array(len);
  37150. var sortedNextStackedPoints = createFloat32Array(len);
  37151. var sortedStatus = [];
  37152. for (var i = 0; i < sortedIndices.length; i++) {
  37153. var idx = sortedIndices[i];
  37154. var i2 = i * 2;
  37155. var idx2 = idx * 2;
  37156. sortedCurrPoints[i2] = currPoints[idx2];
  37157. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  37158. sortedNextPoints[i2] = nextPoints[idx2];
  37159. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  37160. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  37161. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  37162. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  37163. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  37164. sortedStatus[i] = status[idx];
  37165. }
  37166. return {
  37167. current: sortedCurrPoints,
  37168. next: sortedNextPoints,
  37169. stackedOnCurrent: sortedCurrStackedPoints,
  37170. stackedOnNext: sortedNextStackedPoints,
  37171. status: sortedStatus
  37172. };
  37173. }
  37174. var mathMin$5 = Math.min;
  37175. var mathMax$5 = Math.max;
  37176. function isPointNull(x, y) {
  37177. return isNaN(x) || isNaN(y);
  37178. }
  37179. /**
  37180. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  37181. * situations. This should be used when points are non-monotone neither in x or
  37182. * y dimension.
  37183. */
  37184. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  37185. var prevX;
  37186. var prevY;
  37187. var cpx0;
  37188. var cpy0;
  37189. var cpx1;
  37190. var cpy1;
  37191. var idx = start;
  37192. var k = 0;
  37193. for (; k < segLen; k++) {
  37194. var x = points[idx * 2];
  37195. var y = points[idx * 2 + 1];
  37196. if (idx >= allLen || idx < 0) {
  37197. break;
  37198. }
  37199. if (isPointNull(x, y)) {
  37200. if (connectNulls) {
  37201. idx += dir;
  37202. continue;
  37203. }
  37204. break;
  37205. }
  37206. if (idx === start) {
  37207. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  37208. cpx0 = x;
  37209. cpy0 = y;
  37210. } else {
  37211. var dx = x - prevX;
  37212. var dy = y - prevY; // Ignore tiny segment.
  37213. if (dx * dx + dy * dy < 0.5) {
  37214. idx += dir;
  37215. continue;
  37216. }
  37217. if (smooth > 0) {
  37218. var nextIdx = idx + dir;
  37219. var nextX = points[nextIdx * 2];
  37220. var nextY = points[nextIdx * 2 + 1]; // Ignore duplicate point
  37221. while (nextX === x && nextY === y && k < segLen) {
  37222. k++;
  37223. nextIdx += dir;
  37224. idx += dir;
  37225. nextX = points[nextIdx * 2];
  37226. nextY = points[nextIdx * 2 + 1];
  37227. x = points[idx * 2];
  37228. y = points[idx * 2 + 1];
  37229. dx = x - prevX;
  37230. dy = y - prevY;
  37231. }
  37232. var tmpK = k + 1;
  37233. if (connectNulls) {
  37234. // Find next point not null
  37235. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  37236. tmpK++;
  37237. nextIdx += dir;
  37238. nextX = points[nextIdx * 2];
  37239. nextY = points[nextIdx * 2 + 1];
  37240. }
  37241. }
  37242. var ratioNextSeg = 0.5;
  37243. var vx = 0;
  37244. var vy = 0;
  37245. var nextCpx0 = void 0;
  37246. var nextCpy0 = void 0; // Is last point
  37247. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  37248. cpx1 = x;
  37249. cpy1 = y;
  37250. } else {
  37251. vx = nextX - prevX;
  37252. vy = nextY - prevY;
  37253. var dx0 = x - prevX;
  37254. var dx1 = nextX - x;
  37255. var dy0 = y - prevY;
  37256. var dy1 = nextY - y;
  37257. var lenPrevSeg = void 0;
  37258. var lenNextSeg = void 0;
  37259. if (smoothMonotone === 'x') {
  37260. lenPrevSeg = Math.abs(dx0);
  37261. lenNextSeg = Math.abs(dx1);
  37262. var dir_1 = vx > 0 ? 1 : -1;
  37263. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  37264. cpy1 = y;
  37265. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  37266. nextCpy0 = y;
  37267. } else if (smoothMonotone === 'y') {
  37268. lenPrevSeg = Math.abs(dy0);
  37269. lenNextSeg = Math.abs(dy1);
  37270. var dir_2 = vy > 0 ? 1 : -1;
  37271. cpx1 = x;
  37272. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  37273. nextCpx0 = x;
  37274. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  37275. } else {
  37276. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  37277. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  37278. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  37279. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  37280. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  37281. nextCpx0 = x + vx * smooth * ratioNextSeg;
  37282. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  37283. // Avoid exceeding extreme after smoothing.
  37284. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  37285. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  37286. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  37287. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  37288. vx = nextCpx0 - x;
  37289. vy = nextCpy0 - y;
  37290. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  37291. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  37292. // Avoid exceeding extreme after smoothing.
  37293. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  37294. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  37295. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  37296. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  37297. vx = x - cpx1;
  37298. vy = y - cpy1;
  37299. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  37300. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  37301. }
  37302. }
  37303. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  37304. cpx0 = nextCpx0;
  37305. cpy0 = nextCpy0;
  37306. } else {
  37307. ctx.lineTo(x, y);
  37308. }
  37309. }
  37310. prevX = x;
  37311. prevY = y;
  37312. idx += dir;
  37313. }
  37314. return k;
  37315. }
  37316. var ECPolylineShape =
  37317. /** @class */
  37318. function () {
  37319. function ECPolylineShape() {
  37320. this.smooth = 0;
  37321. this.smoothConstraint = true;
  37322. }
  37323. return ECPolylineShape;
  37324. }();
  37325. var ECPolyline =
  37326. /** @class */
  37327. function (_super) {
  37328. __extends(ECPolyline, _super);
  37329. function ECPolyline(opts) {
  37330. var _this = _super.call(this, opts) || this;
  37331. _this.type = 'ec-polyline';
  37332. return _this;
  37333. }
  37334. ECPolyline.prototype.getDefaultStyle = function () {
  37335. return {
  37336. stroke: '#000',
  37337. fill: null
  37338. };
  37339. };
  37340. ECPolyline.prototype.getDefaultShape = function () {
  37341. return new ECPolylineShape();
  37342. };
  37343. ECPolyline.prototype.buildPath = function (ctx, shape) {
  37344. var points = shape.points;
  37345. var i = 0;
  37346. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  37347. if (shape.connectNulls) {
  37348. // Must remove first and last null values avoid draw error in polygon
  37349. for (; len > 0; len--) {
  37350. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37351. break;
  37352. }
  37353. }
  37354. for (; i < len; i++) {
  37355. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37356. break;
  37357. }
  37358. }
  37359. }
  37360. while (i < len) {
  37361. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  37362. }
  37363. };
  37364. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  37365. if (!this.path) {
  37366. this.createPathProxy();
  37367. this.buildPath(this.path, this.shape);
  37368. }
  37369. var path = this.path;
  37370. var data = path.data;
  37371. var CMD = PathProxy.CMD;
  37372. var x0;
  37373. var y0;
  37374. var isDimX = dim === 'x';
  37375. var roots = [];
  37376. for (var i = 0; i < data.length;) {
  37377. var cmd = data[i++];
  37378. var x = void 0;
  37379. var y = void 0;
  37380. var x2 = void 0;
  37381. var y2 = void 0;
  37382. var x3 = void 0;
  37383. var y3 = void 0;
  37384. var t = void 0;
  37385. switch (cmd) {
  37386. case CMD.M:
  37387. x0 = data[i++];
  37388. y0 = data[i++];
  37389. break;
  37390. case CMD.L:
  37391. x = data[i++];
  37392. y = data[i++];
  37393. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  37394. if (t <= 1 && t >= 0) {
  37395. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  37396. return isDimX ? [xOrY, val] : [val, xOrY];
  37397. }
  37398. x0 = x;
  37399. y0 = y;
  37400. break;
  37401. case CMD.C:
  37402. x = data[i++];
  37403. y = data[i++];
  37404. x2 = data[i++];
  37405. y2 = data[i++];
  37406. x3 = data[i++];
  37407. y3 = data[i++];
  37408. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  37409. if (nRoot > 0) {
  37410. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  37411. var t_1 = roots[i_1];
  37412. if (t_1 <= 1 && t_1 >= 0) {
  37413. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  37414. return isDimX ? [xOrY, val] : [val, xOrY];
  37415. }
  37416. }
  37417. }
  37418. x0 = x3;
  37419. y0 = y3;
  37420. break;
  37421. }
  37422. }
  37423. };
  37424. return ECPolyline;
  37425. }(Path);
  37426. var ECPolygonShape =
  37427. /** @class */
  37428. function (_super) {
  37429. __extends(ECPolygonShape, _super);
  37430. function ECPolygonShape() {
  37431. return _super !== null && _super.apply(this, arguments) || this;
  37432. }
  37433. return ECPolygonShape;
  37434. }(ECPolylineShape);
  37435. var ECPolygon =
  37436. /** @class */
  37437. function (_super) {
  37438. __extends(ECPolygon, _super);
  37439. function ECPolygon(opts) {
  37440. var _this = _super.call(this, opts) || this;
  37441. _this.type = 'ec-polygon';
  37442. return _this;
  37443. }
  37444. ECPolygon.prototype.getDefaultShape = function () {
  37445. return new ECPolygonShape();
  37446. };
  37447. ECPolygon.prototype.buildPath = function (ctx, shape) {
  37448. var points = shape.points;
  37449. var stackedOnPoints = shape.stackedOnPoints;
  37450. var i = 0;
  37451. var len = points.length / 2;
  37452. var smoothMonotone = shape.smoothMonotone;
  37453. if (shape.connectNulls) {
  37454. // Must remove first and last null values avoid draw error in polygon
  37455. for (; len > 0; len--) {
  37456. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37457. break;
  37458. }
  37459. }
  37460. for (; i < len; i++) {
  37461. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37462. break;
  37463. }
  37464. }
  37465. }
  37466. while (i < len) {
  37467. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  37468. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  37469. i += k + 1;
  37470. ctx.closePath();
  37471. }
  37472. };
  37473. return ECPolygon;
  37474. }(Path);
  37475. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  37476. var rect = cartesian.getArea();
  37477. var x = rect.x;
  37478. var y = rect.y;
  37479. var width = rect.width;
  37480. var height = rect.height;
  37481. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  37482. x -= lineWidth / 2;
  37483. y -= lineWidth / 2;
  37484. width += lineWidth;
  37485. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  37486. x = Math.floor(x);
  37487. width = Math.round(width);
  37488. var clipPath = new Rect({
  37489. shape: {
  37490. x: x,
  37491. y: y,
  37492. width: width,
  37493. height: height
  37494. }
  37495. });
  37496. if (hasAnimation) {
  37497. var baseAxis = cartesian.getBaseAxis();
  37498. var isHorizontal = baseAxis.isHorizontal();
  37499. var isAxisInversed = baseAxis.inverse;
  37500. if (isHorizontal) {
  37501. if (isAxisInversed) {
  37502. clipPath.shape.x += width;
  37503. }
  37504. clipPath.shape.width = 0;
  37505. } else {
  37506. if (!isAxisInversed) {
  37507. clipPath.shape.y += height;
  37508. }
  37509. clipPath.shape.height = 0;
  37510. }
  37511. var duringCb = isFunction(during) ? function (percent) {
  37512. during(percent, clipPath);
  37513. } : null;
  37514. initProps(clipPath, {
  37515. shape: {
  37516. width: width,
  37517. height: height,
  37518. x: x,
  37519. y: y
  37520. }
  37521. }, seriesModel, null, done, duringCb);
  37522. }
  37523. return clipPath;
  37524. }
  37525. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  37526. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  37527. var r0 = round(sectorArea.r0, 1);
  37528. var r = round(sectorArea.r, 1);
  37529. var clipPath = new Sector({
  37530. shape: {
  37531. cx: round(polar.cx, 1),
  37532. cy: round(polar.cy, 1),
  37533. r0: r0,
  37534. r: r,
  37535. startAngle: sectorArea.startAngle,
  37536. endAngle: sectorArea.endAngle,
  37537. clockwise: sectorArea.clockwise
  37538. }
  37539. });
  37540. if (hasAnimation) {
  37541. var isRadial = polar.getBaseAxis().dim === 'angle';
  37542. if (isRadial) {
  37543. clipPath.shape.endAngle = sectorArea.startAngle;
  37544. } else {
  37545. clipPath.shape.r = r0;
  37546. }
  37547. initProps(clipPath, {
  37548. shape: {
  37549. endAngle: sectorArea.endAngle,
  37550. r: r
  37551. }
  37552. }, seriesModel);
  37553. }
  37554. return clipPath;
  37555. }
  37556. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  37557. if (!coordSys) {
  37558. return null;
  37559. } else if (coordSys.type === 'polar') {
  37560. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37561. } else if (coordSys.type === 'cartesian2d') {
  37562. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  37563. }
  37564. return null;
  37565. }
  37566. /*
  37567. * Licensed to the Apache Software Foundation (ASF) under one
  37568. * or more contributor license agreements. See the NOTICE file
  37569. * distributed with this work for additional information
  37570. * regarding copyright ownership. The ASF licenses this file
  37571. * to you under the Apache License, Version 2.0 (the
  37572. * "License"); you may not use this file except in compliance
  37573. * with the License. You may obtain a copy of the License at
  37574. *
  37575. * http://www.apache.org/licenses/LICENSE-2.0
  37576. *
  37577. * Unless required by applicable law or agreed to in writing,
  37578. * software distributed under the License is distributed on an
  37579. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37580. * KIND, either express or implied. See the License for the
  37581. * specific language governing permissions and limitations
  37582. * under the License.
  37583. */
  37584. /**
  37585. * AUTO-GENERATED FILE. DO NOT MODIFY.
  37586. */
  37587. /*
  37588. * Licensed to the Apache Software Foundation (ASF) under one
  37589. * or more contributor license agreements. See the NOTICE file
  37590. * distributed with this work for additional information
  37591. * regarding copyright ownership. The ASF licenses this file
  37592. * to you under the Apache License, Version 2.0 (the
  37593. * "License"); you may not use this file except in compliance
  37594. * with the License. You may obtain a copy of the License at
  37595. *
  37596. * http://www.apache.org/licenses/LICENSE-2.0
  37597. *
  37598. * Unless required by applicable law or agreed to in writing,
  37599. * software distributed under the License is distributed on an
  37600. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37601. * KIND, either express or implied. See the License for the
  37602. * specific language governing permissions and limitations
  37603. * under the License.
  37604. */
  37605. function isCoordinateSystemType(coordSys, type) {
  37606. return coordSys.type === type;
  37607. }
  37608. function isPointsSame(points1, points2) {
  37609. if (points1.length !== points2.length) {
  37610. return;
  37611. }
  37612. for (var i = 0; i < points1.length; i++) {
  37613. if (points1[i] !== points2[i]) {
  37614. return;
  37615. }
  37616. }
  37617. return true;
  37618. }
  37619. function bboxFromPoints(points) {
  37620. var minX = Infinity;
  37621. var minY = Infinity;
  37622. var maxX = -Infinity;
  37623. var maxY = -Infinity;
  37624. for (var i = 0; i < points.length;) {
  37625. var x = points[i++];
  37626. var y = points[i++];
  37627. if (!isNaN(x)) {
  37628. minX = Math.min(x, minX);
  37629. maxX = Math.max(x, maxX);
  37630. }
  37631. if (!isNaN(y)) {
  37632. minY = Math.min(y, minY);
  37633. maxY = Math.max(y, maxY);
  37634. }
  37635. }
  37636. return [[minX, minY], [maxX, maxY]];
  37637. }
  37638. function getBoundingDiff(points1, points2) {
  37639. var _a = bboxFromPoints(points1),
  37640. min1 = _a[0],
  37641. max1 = _a[1];
  37642. var _b = bboxFromPoints(points2),
  37643. min2 = _b[0],
  37644. max2 = _b[1]; // Get a max value from each corner of two boundings.
  37645. return Math.max(Math.abs(min1[0] - min2[0]), Math.abs(min1[1] - min2[1]), Math.abs(max1[0] - max2[0]), Math.abs(max1[1] - max2[1]));
  37646. }
  37647. function getSmooth(smooth) {
  37648. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  37649. }
  37650. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  37651. if (!dataCoordInfo.valueDim) {
  37652. return [];
  37653. }
  37654. var len = data.count();
  37655. var points = createFloat32Array(len * 2);
  37656. for (var idx = 0; idx < len; idx++) {
  37657. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  37658. points[idx * 2] = pt[0];
  37659. points[idx * 2 + 1] = pt[1];
  37660. }
  37661. return points;
  37662. }
  37663. function turnPointsIntoStep(points, coordSys, stepTurnAt, connectNulls) {
  37664. var baseAxis = coordSys.getBaseAxis();
  37665. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  37666. var stepPoints = [];
  37667. var i = 0;
  37668. var stepPt = [];
  37669. var pt = [];
  37670. var nextPt = [];
  37671. var filteredPoints = [];
  37672. if (connectNulls) {
  37673. for (i = 0; i < points.length; i += 2) {
  37674. if (!isNaN(points[i]) && !isNaN(points[i + 1])) {
  37675. filteredPoints.push(points[i], points[i + 1]);
  37676. }
  37677. }
  37678. points = filteredPoints;
  37679. }
  37680. for (i = 0; i < points.length - 2; i += 2) {
  37681. nextPt[0] = points[i + 2];
  37682. nextPt[1] = points[i + 3];
  37683. pt[0] = points[i];
  37684. pt[1] = points[i + 1];
  37685. stepPoints.push(pt[0], pt[1]);
  37686. switch (stepTurnAt) {
  37687. case 'end':
  37688. stepPt[baseIndex] = nextPt[baseIndex];
  37689. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37690. stepPoints.push(stepPt[0], stepPt[1]);
  37691. break;
  37692. case 'middle':
  37693. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  37694. var stepPt2 = [];
  37695. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  37696. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37697. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  37698. stepPoints.push(stepPt[0], stepPt[1]);
  37699. stepPoints.push(stepPt2[0], stepPt2[1]);
  37700. break;
  37701. default:
  37702. // default is start
  37703. stepPt[baseIndex] = pt[baseIndex];
  37704. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  37705. stepPoints.push(stepPt[0], stepPt[1]);
  37706. }
  37707. } // Last points
  37708. stepPoints.push(points[i++], points[i++]);
  37709. return stepPoints;
  37710. }
  37711. /**
  37712. * Clip color stops to edge. Avoid creating too large gradients.
  37713. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  37714. *
  37715. * The stops has been sorted from small to large.
  37716. */
  37717. function clipColorStops(colorStops, maxSize) {
  37718. var newColorStops = [];
  37719. var len = colorStops.length; // coord will always < 0 in prevOutOfRangeColorStop.
  37720. var prevOutOfRangeColorStop;
  37721. var prevInRangeColorStop;
  37722. function lerpStop(stop0, stop1, clippedCoord) {
  37723. var coord0 = stop0.coord;
  37724. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  37725. var color = lerp$1(p, [stop0.color, stop1.color]);
  37726. return {
  37727. coord: clippedCoord,
  37728. color: color
  37729. };
  37730. }
  37731. for (var i = 0; i < len; i++) {
  37732. var stop_1 = colorStops[i];
  37733. var coord = stop_1.coord;
  37734. if (coord < 0) {
  37735. prevOutOfRangeColorStop = stop_1;
  37736. } else if (coord > maxSize) {
  37737. if (prevInRangeColorStop) {
  37738. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  37739. } else if (prevOutOfRangeColorStop) {
  37740. // If there are two stops and coord range is between these two stops
  37741. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  37742. } // All following stop will be out of range. So just ignore them.
  37743. break;
  37744. } else {
  37745. if (prevOutOfRangeColorStop) {
  37746. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0)); // Reset
  37747. prevOutOfRangeColorStop = null;
  37748. }
  37749. newColorStops.push(stop_1);
  37750. prevInRangeColorStop = stop_1;
  37751. }
  37752. }
  37753. return newColorStops;
  37754. }
  37755. function getVisualGradient(data, coordSys, api) {
  37756. var visualMetaList = data.getVisual('visualMeta');
  37757. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  37758. // When data.count() is 0, gradient range can not be calculated.
  37759. return;
  37760. }
  37761. if (coordSys.type !== 'cartesian2d') {
  37762. if ("development" !== 'production') {
  37763. console.warn('Visual map on line style is only supported on cartesian2d.');
  37764. }
  37765. return;
  37766. }
  37767. var coordDim;
  37768. var visualMeta;
  37769. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  37770. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  37771. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  37772. if (coordDim === 'x' || coordDim === 'y') {
  37773. visualMeta = visualMetaList[i];
  37774. break;
  37775. }
  37776. }
  37777. if (!visualMeta) {
  37778. if ("development" !== 'production') {
  37779. console.warn('Visual map on line style only support x or y dimension.');
  37780. }
  37781. return;
  37782. } // If the area to be rendered is bigger than area defined by LinearGradient,
  37783. // the canvas spec prescribes that the color of the first stop and the last
  37784. // stop should be used. But if two stops are added at offset 0, in effect
  37785. // browsers use the color of the second stop to render area outside
  37786. // LinearGradient. So we can only infinitesimally extend area defined in
  37787. // LinearGradient to render `outerColors`.
  37788. var axis = coordSys.getAxis(coordDim); // dataToCoord mapping may not be linear, but must be monotonic.
  37789. var colorStops = map(visualMeta.stops, function (stop) {
  37790. // offset will be calculated later.
  37791. return {
  37792. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  37793. color: stop.color
  37794. };
  37795. });
  37796. var stopLen = colorStops.length;
  37797. var outerColors = visualMeta.outerColors.slice();
  37798. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  37799. colorStops.reverse();
  37800. outerColors.reverse();
  37801. }
  37802. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  37803. var inRangeStopLen = colorStopsInRange.length;
  37804. if (!inRangeStopLen && stopLen) {
  37805. // All stops are out of range. All will be the same color.
  37806. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  37807. }
  37808. var tinyExtent = 10; // Arbitrary value: 10px
  37809. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  37810. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  37811. var coordSpan = maxCoord - minCoord;
  37812. if (coordSpan < 1e-3) {
  37813. return 'transparent';
  37814. }
  37815. each(colorStopsInRange, function (stop) {
  37816. stop.offset = (stop.coord - minCoord) / coordSpan;
  37817. });
  37818. colorStopsInRange.push({
  37819. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  37820. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  37821. color: outerColors[1] || 'transparent'
  37822. });
  37823. colorStopsInRange.unshift({
  37824. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  37825. color: outerColors[0] || 'transparent'
  37826. });
  37827. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  37828. gradient[coordDim] = minCoord;
  37829. gradient[coordDim + '2'] = maxCoord;
  37830. return gradient;
  37831. }
  37832. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  37833. var showAllSymbol = seriesModel.get('showAllSymbol');
  37834. var isAuto = showAllSymbol === 'auto';
  37835. if (showAllSymbol && !isAuto) {
  37836. return;
  37837. }
  37838. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  37839. if (!categoryAxis) {
  37840. return;
  37841. } // Note that category label interval strategy might bring some weird effect
  37842. // in some scenario: users may wonder why some of the symbols are not
  37843. // displayed. So we show all symbols as possible as we can.
  37844. if (isAuto // Simplify the logic, do not determine label overlap here.
  37845. && canShowAllSymbolForCategory(categoryAxis, data)) {
  37846. return;
  37847. } // Otherwise follow the label interval strategy on category axis.
  37848. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  37849. var labelMap = {};
  37850. each(categoryAxis.getViewLabels(), function (labelItem) {
  37851. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  37852. labelMap[ordinalNumber] = 1;
  37853. });
  37854. return function (dataIndex) {
  37855. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  37856. };
  37857. }
  37858. function canShowAllSymbolForCategory(categoryAxis, data) {
  37859. // In most cases, line is monotonous on category axis, and the label size
  37860. // is close with each other. So we check the symbol size and some of the
  37861. // label size alone with the category axis to estimate whether all symbol
  37862. // can be shown without overlap.
  37863. var axisExtent = categoryAxis.getExtent();
  37864. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  37865. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  37866. // Sampling some points, max 5.
  37867. var dataLen = data.count();
  37868. var step = Math.max(1, Math.round(dataLen / 5));
  37869. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  37870. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  37871. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  37872. * 1.5 > availSize) {
  37873. return false;
  37874. }
  37875. }
  37876. return true;
  37877. }
  37878. function isPointNull$1(x, y) {
  37879. return isNaN(x) || isNaN(y);
  37880. }
  37881. function getLastIndexNotNull(points) {
  37882. var len = points.length / 2;
  37883. for (; len > 0; len--) {
  37884. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  37885. break;
  37886. }
  37887. }
  37888. return len - 1;
  37889. }
  37890. function getPointAtIndex(points, idx) {
  37891. return [points[idx * 2], points[idx * 2 + 1]];
  37892. }
  37893. function getIndexRange(points, xOrY, dim) {
  37894. var len = points.length / 2;
  37895. var dimIdx = dim === 'x' ? 0 : 1;
  37896. var a;
  37897. var b;
  37898. var prevIndex = 0;
  37899. var nextIndex = -1;
  37900. for (var i = 0; i < len; i++) {
  37901. b = points[i * 2 + dimIdx];
  37902. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  37903. continue;
  37904. }
  37905. if (i === 0) {
  37906. a = b;
  37907. continue;
  37908. }
  37909. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  37910. nextIndex = i;
  37911. break;
  37912. }
  37913. prevIndex = i;
  37914. a = b;
  37915. }
  37916. return {
  37917. range: [prevIndex, nextIndex],
  37918. t: (xOrY - a) / (b - a)
  37919. };
  37920. }
  37921. function anyStateShowEndLabel(seriesModel) {
  37922. if (seriesModel.get(['endLabel', 'show'])) {
  37923. return true;
  37924. }
  37925. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  37926. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  37927. return true;
  37928. }
  37929. }
  37930. return false;
  37931. }
  37932. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  37933. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  37934. var endLabelModel_1 = seriesModel.getModel('endLabel');
  37935. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  37936. var data_1 = seriesModel.getData();
  37937. var labelAnimationRecord_1 = {
  37938. lastFrameIndex: 0
  37939. };
  37940. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  37941. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  37942. } : null;
  37943. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  37944. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  37945. var endLabel = lineView._endLabel;
  37946. if (endLabel && hasAnimation) {
  37947. if (labelAnimationRecord_1.originalX != null) {
  37948. endLabel.attr({
  37949. x: labelAnimationRecord_1.originalX,
  37950. y: labelAnimationRecord_1.originalY
  37951. });
  37952. }
  37953. }
  37954. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  37955. if (!seriesModel.get('clip', true)) {
  37956. var rectShape = clipPath.shape;
  37957. var expandSize = Math.max(rectShape.width, rectShape.height);
  37958. if (isHorizontal) {
  37959. rectShape.y -= expandSize;
  37960. rectShape.height += expandSize * 2;
  37961. } else {
  37962. rectShape.x -= expandSize;
  37963. rectShape.width += expandSize * 2;
  37964. }
  37965. } // Set to the final frame. To make sure label layout is right.
  37966. if (during) {
  37967. during(1, clipPath);
  37968. }
  37969. return clipPath;
  37970. } else {
  37971. if ("development" !== 'production') {
  37972. if (seriesModel.get(['endLabel', 'show'])) {
  37973. console.warn('endLabel is not supported for lines in polar systems.');
  37974. }
  37975. }
  37976. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37977. }
  37978. }
  37979. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  37980. var baseAxis = coordSys.getBaseAxis();
  37981. var isHorizontal = baseAxis.isHorizontal();
  37982. var isBaseInversed = baseAxis.inverse;
  37983. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  37984. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  37985. return {
  37986. normal: {
  37987. align: endLabelModel.get('align') || align,
  37988. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  37989. }
  37990. };
  37991. }
  37992. var LineView =
  37993. /** @class */
  37994. function (_super) {
  37995. __extends(LineView, _super);
  37996. function LineView() {
  37997. return _super !== null && _super.apply(this, arguments) || this;
  37998. }
  37999. LineView.prototype.init = function () {
  38000. var lineGroup = new Group();
  38001. var symbolDraw = new SymbolDraw();
  38002. this.group.add(symbolDraw.group);
  38003. this._symbolDraw = symbolDraw;
  38004. this._lineGroup = lineGroup;
  38005. };
  38006. LineView.prototype.render = function (seriesModel, ecModel, api) {
  38007. var _this = this;
  38008. var coordSys = seriesModel.coordinateSystem;
  38009. var group = this.group;
  38010. var data = seriesModel.getData();
  38011. var lineStyleModel = seriesModel.getModel('lineStyle');
  38012. var areaStyleModel = seriesModel.getModel('areaStyle');
  38013. var points = data.getLayout('points') || [];
  38014. var isCoordSysPolar = coordSys.type === 'polar';
  38015. var prevCoordSys = this._coordSys;
  38016. var symbolDraw = this._symbolDraw;
  38017. var polyline = this._polyline;
  38018. var polygon = this._polygon;
  38019. var lineGroup = this._lineGroup;
  38020. var hasAnimation = !ecModel.ssr && seriesModel.isAnimationEnabled();
  38021. var isAreaChart = !areaStyleModel.isEmpty();
  38022. var valueOrigin = areaStyleModel.get('origin');
  38023. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  38024. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  38025. var showSymbol = seriesModel.get('showSymbol');
  38026. var connectNulls = seriesModel.get('connectNulls');
  38027. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  38028. var oldData = this._data;
  38029. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38030. if (el.__temp) {
  38031. group.remove(el);
  38032. oldData.setItemGraphicEl(idx, null);
  38033. }
  38034. }); // Remove previous created symbols if showSymbol changed to false
  38035. if (!showSymbol) {
  38036. symbolDraw.remove();
  38037. }
  38038. group.add(lineGroup); // FIXME step not support polar
  38039. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  38040. var clipShapeForSymbol;
  38041. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  38042. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  38043. // See #7913 and `test/dataZoom-clip.html`.
  38044. if (clipShapeForSymbol.width != null) {
  38045. clipShapeForSymbol.x -= 0.1;
  38046. clipShapeForSymbol.y -= 0.1;
  38047. clipShapeForSymbol.width += 0.2;
  38048. clipShapeForSymbol.height += 0.2;
  38049. } else if (clipShapeForSymbol.r0) {
  38050. clipShapeForSymbol.r0 -= 0.5;
  38051. clipShapeForSymbol.r += 0.5;
  38052. }
  38053. }
  38054. this._clipShapeForSymbol = clipShapeForSymbol;
  38055. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  38056. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  38057. showSymbol && symbolDraw.updateData(data, {
  38058. isIgnore: isIgnoreFunc,
  38059. clipShape: clipShapeForSymbol,
  38060. disableAnimation: true,
  38061. getSymbolPoint: function (idx) {
  38062. return [points[idx * 2], points[idx * 2 + 1]];
  38063. }
  38064. });
  38065. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  38066. if (step) {
  38067. // TODO If stacked series is not step
  38068. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  38069. if (stackedOnPoints) {
  38070. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  38071. }
  38072. }
  38073. polyline = this._newPolyline(points);
  38074. if (isAreaChart) {
  38075. polygon = this._newPolygon(points, stackedOnPoints);
  38076. } // If areaStyle is removed
  38077. else if (polygon) {
  38078. lineGroup.remove(polygon);
  38079. polygon = this._polygon = null;
  38080. } // NOTE: Must update _endLabel before setClipPath.
  38081. if (!isCoordSysPolar) {
  38082. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38083. }
  38084. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38085. } else {
  38086. if (isAreaChart && !polygon) {
  38087. // If areaStyle is added
  38088. polygon = this._newPolygon(points, stackedOnPoints);
  38089. } else if (polygon && !isAreaChart) {
  38090. // If areaStyle is removed
  38091. lineGroup.remove(polygon);
  38092. polygon = this._polygon = null;
  38093. } // NOTE: Must update _endLabel before setClipPath.
  38094. if (!isCoordSysPolar) {
  38095. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38096. } // Update clipPath
  38097. var oldClipPath = lineGroup.getClipPath();
  38098. if (oldClipPath) {
  38099. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  38100. initProps(oldClipPath, {
  38101. shape: newClipPath.shape
  38102. }, seriesModel);
  38103. } else {
  38104. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38105. } // Always update, or it is wrong in the case turning on legend
  38106. // because points are not changed.
  38107. showSymbol && symbolDraw.updateData(data, {
  38108. isIgnore: isIgnoreFunc,
  38109. clipShape: clipShapeForSymbol,
  38110. disableAnimation: true,
  38111. getSymbolPoint: function (idx) {
  38112. return [points[idx * 2], points[idx * 2 + 1]];
  38113. }
  38114. }); // In the case data zoom triggered refreshing frequently
  38115. // Data may not change if line has a category axis. So it should animate nothing.
  38116. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  38117. if (hasAnimation) {
  38118. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  38119. } else {
  38120. // Not do it in update with animation
  38121. if (step) {
  38122. // TODO If stacked series is not step
  38123. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  38124. if (stackedOnPoints) {
  38125. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  38126. }
  38127. }
  38128. polyline.setShape({
  38129. points: points
  38130. });
  38131. polygon && polygon.setShape({
  38132. points: points,
  38133. stackedOnPoints: stackedOnPoints
  38134. });
  38135. }
  38136. }
  38137. }
  38138. var emphasisModel = seriesModel.getModel('emphasis');
  38139. var focus = emphasisModel.get('focus');
  38140. var blurScope = emphasisModel.get('blurScope');
  38141. var emphasisDisabled = emphasisModel.get('disabled');
  38142. polyline.useStyle(defaults( // Use color in lineStyle first
  38143. lineStyleModel.getLineStyle(), {
  38144. fill: 'none',
  38145. stroke: visualColor,
  38146. lineJoin: 'bevel'
  38147. }));
  38148. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  38149. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  38150. var emphasisLineStyle = polyline.getState('emphasis').style;
  38151. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  38152. } // Needs seriesIndex for focus
  38153. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  38154. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  38155. var smooth = getSmooth(seriesModel.get('smooth'));
  38156. var smoothMonotone = seriesModel.get('smoothMonotone');
  38157. polyline.setShape({
  38158. smooth: smooth,
  38159. smoothMonotone: smoothMonotone,
  38160. connectNulls: connectNulls
  38161. });
  38162. if (polygon) {
  38163. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  38164. var stackedOnSmooth = 0;
  38165. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  38166. fill: visualColor,
  38167. opacity: 0.7,
  38168. lineJoin: 'bevel',
  38169. decal: data.getVisual('style').decal
  38170. }));
  38171. if (stackedOnSeries) {
  38172. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  38173. }
  38174. polygon.setShape({
  38175. smooth: smooth,
  38176. stackedOnSmooth: stackedOnSmooth,
  38177. smoothMonotone: smoothMonotone,
  38178. connectNulls: connectNulls
  38179. });
  38180. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  38181. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  38182. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  38183. }
  38184. var changePolyState = function (toState) {
  38185. _this._changePolyState(toState);
  38186. };
  38187. data.eachItemGraphicEl(function (el) {
  38188. // Switch polyline / polygon state if element changed its state.
  38189. el && (el.onHoverStateChange = changePolyState);
  38190. });
  38191. this._polyline.onHoverStateChange = changePolyState;
  38192. this._data = data; // Save the coordinate system for transition animation when data changed
  38193. this._coordSys = coordSys;
  38194. this._stackedOnPoints = stackedOnPoints;
  38195. this._points = points;
  38196. this._step = step;
  38197. this._valueOrigin = valueOrigin;
  38198. if (seriesModel.get('triggerLineEvent')) {
  38199. this.packEventData(seriesModel, polyline);
  38200. polygon && this.packEventData(seriesModel, polygon);
  38201. }
  38202. };
  38203. LineView.prototype.packEventData = function (seriesModel, el) {
  38204. getECData(el).eventData = {
  38205. componentType: 'series',
  38206. componentSubType: 'line',
  38207. componentIndex: seriesModel.componentIndex,
  38208. seriesIndex: seriesModel.seriesIndex,
  38209. seriesName: seriesModel.name,
  38210. seriesType: 'line'
  38211. };
  38212. };
  38213. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  38214. var data = seriesModel.getData();
  38215. var dataIndex = queryDataIndex(data, payload);
  38216. this._changePolyState('emphasis');
  38217. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  38218. var points = data.getLayout('points');
  38219. var symbol = data.getItemGraphicEl(dataIndex);
  38220. if (!symbol) {
  38221. // Create a temporary symbol if it is not exists
  38222. var x = points[dataIndex * 2];
  38223. var y = points[dataIndex * 2 + 1];
  38224. if (isNaN(x) || isNaN(y)) {
  38225. // Null data
  38226. return;
  38227. } // fix #11360: shouldn't draw symbol outside clipShapeForSymbol
  38228. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  38229. return;
  38230. }
  38231. var zlevel = seriesModel.get('zlevel') || 0;
  38232. var z = seriesModel.get('z') || 0;
  38233. symbol = new Symbol(data, dataIndex);
  38234. symbol.x = x;
  38235. symbol.y = y;
  38236. symbol.setZ(zlevel, z); // ensure label text of the temporary symbol is in front of line and area polygon
  38237. var symbolLabel = symbol.getSymbolPath().getTextContent();
  38238. if (symbolLabel) {
  38239. symbolLabel.zlevel = zlevel;
  38240. symbolLabel.z = z;
  38241. symbolLabel.z2 = this._polyline.z2 + 1;
  38242. }
  38243. symbol.__temp = true;
  38244. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  38245. symbol.stopSymbolAnimation(true);
  38246. this.group.add(symbol);
  38247. }
  38248. symbol.highlight();
  38249. } else {
  38250. // Highlight whole series
  38251. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  38252. }
  38253. };
  38254. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  38255. var data = seriesModel.getData();
  38256. var dataIndex = queryDataIndex(data, payload);
  38257. this._changePolyState('normal');
  38258. if (dataIndex != null && dataIndex >= 0) {
  38259. var symbol = data.getItemGraphicEl(dataIndex);
  38260. if (symbol) {
  38261. if (symbol.__temp) {
  38262. data.setItemGraphicEl(dataIndex, null);
  38263. this.group.remove(symbol);
  38264. } else {
  38265. symbol.downplay();
  38266. }
  38267. }
  38268. } else {
  38269. // FIXME
  38270. // can not downplay completely.
  38271. // Downplay whole series
  38272. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  38273. }
  38274. };
  38275. LineView.prototype._changePolyState = function (toState) {
  38276. var polygon = this._polygon;
  38277. setStatesFlag(this._polyline, toState);
  38278. polygon && setStatesFlag(polygon, toState);
  38279. };
  38280. LineView.prototype._newPolyline = function (points) {
  38281. var polyline = this._polyline; // Remove previous created polyline
  38282. if (polyline) {
  38283. this._lineGroup.remove(polyline);
  38284. }
  38285. polyline = new ECPolyline({
  38286. shape: {
  38287. points: points
  38288. },
  38289. segmentIgnoreThreshold: 2,
  38290. z2: 10
  38291. });
  38292. this._lineGroup.add(polyline);
  38293. this._polyline = polyline;
  38294. return polyline;
  38295. };
  38296. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  38297. var polygon = this._polygon; // Remove previous created polygon
  38298. if (polygon) {
  38299. this._lineGroup.remove(polygon);
  38300. }
  38301. polygon = new ECPolygon({
  38302. shape: {
  38303. points: points,
  38304. stackedOnPoints: stackedOnPoints
  38305. },
  38306. segmentIgnoreThreshold: 2
  38307. });
  38308. this._lineGroup.add(polygon);
  38309. this._polygon = polygon;
  38310. return polygon;
  38311. };
  38312. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  38313. var isHorizontalOrRadial;
  38314. var isCoordSysPolar;
  38315. var baseAxis = coordSys.getBaseAxis();
  38316. var isAxisInverse = baseAxis.inverse;
  38317. if (coordSys.type === 'cartesian2d') {
  38318. isHorizontalOrRadial = baseAxis.isHorizontal();
  38319. isCoordSysPolar = false;
  38320. } else if (coordSys.type === 'polar') {
  38321. isHorizontalOrRadial = baseAxis.dim === 'angle';
  38322. isCoordSysPolar = true;
  38323. }
  38324. var seriesModel = data.hostModel;
  38325. var seriesDuration = seriesModel.get('animationDuration');
  38326. if (isFunction(seriesDuration)) {
  38327. seriesDuration = seriesDuration(null);
  38328. }
  38329. var seriesDelay = seriesModel.get('animationDelay') || 0;
  38330. var seriesDelayValue = isFunction(seriesDelay) ? seriesDelay(null) : seriesDelay;
  38331. data.eachItemGraphicEl(function (symbol, idx) {
  38332. var el = symbol;
  38333. if (el) {
  38334. var point = [symbol.x, symbol.y];
  38335. var start = void 0;
  38336. var end = void 0;
  38337. var current = void 0;
  38338. if (clipShape) {
  38339. if (isCoordSysPolar) {
  38340. var polarClip = clipShape;
  38341. var coord = coordSys.pointToCoord(point);
  38342. if (isHorizontalOrRadial) {
  38343. start = polarClip.startAngle;
  38344. end = polarClip.endAngle;
  38345. current = -coord[1] / 180 * Math.PI;
  38346. } else {
  38347. start = polarClip.r0;
  38348. end = polarClip.r;
  38349. current = coord[0];
  38350. }
  38351. } else {
  38352. var gridClip = clipShape;
  38353. if (isHorizontalOrRadial) {
  38354. start = gridClip.x;
  38355. end = gridClip.x + gridClip.width;
  38356. current = symbol.x;
  38357. } else {
  38358. start = gridClip.y + gridClip.height;
  38359. end = gridClip.y;
  38360. current = symbol.y;
  38361. }
  38362. }
  38363. }
  38364. var ratio = end === start ? 0 : (current - start) / (end - start);
  38365. if (isAxisInverse) {
  38366. ratio = 1 - ratio;
  38367. }
  38368. var delay = isFunction(seriesDelay) ? seriesDelay(idx) : seriesDuration * ratio + seriesDelayValue;
  38369. var symbolPath = el.getSymbolPath();
  38370. var text = symbolPath.getTextContent();
  38371. el.attr({
  38372. scaleX: 0,
  38373. scaleY: 0
  38374. });
  38375. el.animateTo({
  38376. scaleX: 1,
  38377. scaleY: 1
  38378. }, {
  38379. duration: 200,
  38380. setToFinal: true,
  38381. delay: delay
  38382. });
  38383. if (text) {
  38384. text.animateFrom({
  38385. style: {
  38386. opacity: 0
  38387. }
  38388. }, {
  38389. duration: 300,
  38390. delay: delay
  38391. });
  38392. }
  38393. symbolPath.disableLabelAnimation = true;
  38394. }
  38395. });
  38396. };
  38397. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  38398. var endLabelModel = seriesModel.getModel('endLabel');
  38399. if (anyStateShowEndLabel(seriesModel)) {
  38400. var data_2 = seriesModel.getData();
  38401. var polyline = this._polyline; // series may be filtered.
  38402. var points = data_2.getLayout('points');
  38403. if (!points) {
  38404. polyline.removeTextContent();
  38405. this._endLabel = null;
  38406. return;
  38407. }
  38408. var endLabel = this._endLabel;
  38409. if (!endLabel) {
  38410. endLabel = this._endLabel = new ZRText({
  38411. z2: 200 // should be higher than item symbol
  38412. });
  38413. endLabel.ignoreClip = true;
  38414. polyline.setTextContent(this._endLabel);
  38415. polyline.disableLabelAnimation = true;
  38416. } // Find last non-NaN data to display data
  38417. var dataIndex = getLastIndexNotNull(points);
  38418. if (dataIndex >= 0) {
  38419. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  38420. inheritColor: inheritColor,
  38421. labelFetcher: seriesModel,
  38422. labelDataIndex: dataIndex,
  38423. defaultText: function (dataIndex, opt, interpolatedValue) {
  38424. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  38425. },
  38426. enableTextSetter: true
  38427. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  38428. polyline.textConfig.position = null;
  38429. }
  38430. } else if (this._endLabel) {
  38431. this._polyline.removeTextContent();
  38432. this._endLabel = null;
  38433. }
  38434. };
  38435. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  38436. var endLabel = this._endLabel;
  38437. var polyline = this._polyline;
  38438. if (endLabel) {
  38439. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  38440. // The label is not prepared at this time.
  38441. if (percent < 1 && animationRecord.originalX == null) {
  38442. animationRecord.originalX = endLabel.x;
  38443. animationRecord.originalY = endLabel.y;
  38444. }
  38445. var points = data.getLayout('points');
  38446. var seriesModel = data.hostModel;
  38447. var connectNulls = seriesModel.get('connectNulls');
  38448. var precision = endLabelModel.get('precision');
  38449. var distance = endLabelModel.get('distance') || 0;
  38450. var baseAxis = coordSys.getBaseAxis();
  38451. var isHorizontal = baseAxis.isHorizontal();
  38452. var isBaseInversed = baseAxis.inverse;
  38453. var clipShape = clipRect.shape;
  38454. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  38455. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  38456. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  38457. var dim = isHorizontal ? 'x' : 'y';
  38458. var dataIndexRange = getIndexRange(points, xOrY, dim);
  38459. var indices = dataIndexRange.range;
  38460. var diff = indices[1] - indices[0];
  38461. var value = void 0;
  38462. if (diff >= 1) {
  38463. // diff > 1 && connectNulls, which is on the null data.
  38464. if (diff > 1 && !connectNulls) {
  38465. var pt = getPointAtIndex(points, indices[0]);
  38466. endLabel.attr({
  38467. x: pt[0] + distanceX,
  38468. y: pt[1] + distanceY
  38469. });
  38470. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  38471. } else {
  38472. var pt = polyline.getPointOn(xOrY, dim);
  38473. pt && endLabel.attr({
  38474. x: pt[0] + distanceX,
  38475. y: pt[1] + distanceY
  38476. });
  38477. var startValue = seriesModel.getRawValue(indices[0]);
  38478. var endValue = seriesModel.getRawValue(indices[1]);
  38479. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  38480. }
  38481. animationRecord.lastFrameIndex = indices[0];
  38482. } else {
  38483. // If diff <= 0, which is the range is not found(Include NaN)
  38484. // Choose the first point or last point.
  38485. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  38486. var pt = getPointAtIndex(points, idx);
  38487. valueAnimation && (value = seriesModel.getRawValue(idx));
  38488. endLabel.attr({
  38489. x: pt[0] + distanceX,
  38490. y: pt[1] + distanceY
  38491. });
  38492. }
  38493. if (valueAnimation) {
  38494. labelInner(endLabel).setLabelText(value);
  38495. }
  38496. }
  38497. };
  38498. /**
  38499. * @private
  38500. */
  38501. // FIXME Two value axis
  38502. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  38503. var polyline = this._polyline;
  38504. var polygon = this._polygon;
  38505. var seriesModel = data.hostModel;
  38506. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  38507. var current = diff.current;
  38508. var stackedOnCurrent = diff.stackedOnCurrent;
  38509. var next = diff.next;
  38510. var stackedOnNext = diff.stackedOnNext;
  38511. if (step) {
  38512. // TODO If stacked series is not step
  38513. current = turnPointsIntoStep(diff.current, coordSys, step, connectNulls);
  38514. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step, connectNulls);
  38515. next = turnPointsIntoStep(diff.next, coordSys, step, connectNulls);
  38516. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step, connectNulls);
  38517. } // Don't apply animation if diff is large.
  38518. // For better result and avoid memory explosion problems like
  38519. // https://github.com/apache/incubator-echarts/issues/12229
  38520. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  38521. polyline.stopAnimation();
  38522. polyline.setShape({
  38523. points: next
  38524. });
  38525. if (polygon) {
  38526. polygon.stopAnimation();
  38527. polygon.setShape({
  38528. points: next,
  38529. stackedOnPoints: stackedOnNext
  38530. });
  38531. }
  38532. return;
  38533. }
  38534. polyline.shape.__points = diff.current;
  38535. polyline.shape.points = current;
  38536. var target = {
  38537. shape: {
  38538. points: next
  38539. }
  38540. }; // Also animate the original points.
  38541. // If points reference is changed when turning into step line.
  38542. if (diff.current !== current) {
  38543. target.shape.__points = diff.next;
  38544. } // Stop previous animation.
  38545. polyline.stopAnimation();
  38546. updateProps(polyline, target, seriesModel);
  38547. if (polygon) {
  38548. polygon.setShape({
  38549. // Reuse the points with polyline.
  38550. points: current,
  38551. stackedOnPoints: stackedOnCurrent
  38552. });
  38553. polygon.stopAnimation();
  38554. updateProps(polygon, {
  38555. shape: {
  38556. stackedOnPoints: stackedOnNext
  38557. }
  38558. }, seriesModel); // If use attr directly in updateProps.
  38559. if (polyline.shape.points !== polygon.shape.points) {
  38560. polygon.shape.points = polyline.shape.points;
  38561. }
  38562. }
  38563. var updatedDataInfo = [];
  38564. var diffStatus = diff.status;
  38565. for (var i = 0; i < diffStatus.length; i++) {
  38566. var cmd = diffStatus[i].cmd;
  38567. if (cmd === '=') {
  38568. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  38569. if (el) {
  38570. updatedDataInfo.push({
  38571. el: el,
  38572. ptIdx: i // Index of points
  38573. });
  38574. }
  38575. }
  38576. }
  38577. if (polyline.animators && polyline.animators.length) {
  38578. polyline.animators[0].during(function () {
  38579. polygon && polygon.dirtyShape();
  38580. var points = polyline.shape.__points;
  38581. for (var i = 0; i < updatedDataInfo.length; i++) {
  38582. var el = updatedDataInfo[i].el;
  38583. var offset = updatedDataInfo[i].ptIdx * 2;
  38584. el.x = points[offset];
  38585. el.y = points[offset + 1];
  38586. el.markRedraw();
  38587. }
  38588. });
  38589. }
  38590. };
  38591. LineView.prototype.remove = function (ecModel) {
  38592. var group = this.group;
  38593. var oldData = this._data;
  38594. this._lineGroup.removeAll();
  38595. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  38596. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38597. if (el.__temp) {
  38598. group.remove(el);
  38599. oldData.setItemGraphicEl(idx, null);
  38600. }
  38601. });
  38602. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  38603. };
  38604. LineView.type = 'line';
  38605. return LineView;
  38606. }(ChartView);
  38607. function pointsLayout(seriesType, forceStoreInTypedArray) {
  38608. return {
  38609. seriesType: seriesType,
  38610. plan: createRenderPlanner(),
  38611. reset: function (seriesModel) {
  38612. var data = seriesModel.getData();
  38613. var coordSys = seriesModel.coordinateSystem;
  38614. var pipelineContext = seriesModel.pipelineContext;
  38615. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  38616. if (!coordSys) {
  38617. return;
  38618. }
  38619. var dims = map(coordSys.dimensions, function (dim) {
  38620. return data.mapDimension(dim);
  38621. }).slice(0, 2);
  38622. var dimLen = dims.length;
  38623. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  38624. if (isDimensionStacked(data, dims[0])) {
  38625. dims[0] = stackResultDim;
  38626. }
  38627. if (isDimensionStacked(data, dims[1])) {
  38628. dims[1] = stackResultDim;
  38629. }
  38630. var store = data.getStore();
  38631. var dimIdx0 = data.getDimensionIndex(dims[0]);
  38632. var dimIdx1 = data.getDimensionIndex(dims[1]);
  38633. return dimLen && {
  38634. progress: function (params, data) {
  38635. var segCount = params.end - params.start;
  38636. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  38637. var tmpIn = [];
  38638. var tmpOut = [];
  38639. for (var i = params.start, offset = 0; i < params.end; i++) {
  38640. var point = void 0;
  38641. if (dimLen === 1) {
  38642. var x = store.get(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  38643. point = coordSys.dataToPoint(x, null, tmpOut);
  38644. } else {
  38645. tmpIn[0] = store.get(dimIdx0, i);
  38646. tmpIn[1] = store.get(dimIdx1, i); // Let coordinate system to handle the NaN data.
  38647. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  38648. }
  38649. if (useTypedArray) {
  38650. points[offset++] = point[0];
  38651. points[offset++] = point[1];
  38652. } else {
  38653. data.setItemLayout(i, point.slice());
  38654. }
  38655. }
  38656. useTypedArray && data.setLayout('points', points);
  38657. }
  38658. };
  38659. }
  38660. };
  38661. }
  38662. var samplers = {
  38663. average: function (frame) {
  38664. var sum = 0;
  38665. var count = 0;
  38666. for (var i = 0; i < frame.length; i++) {
  38667. if (!isNaN(frame[i])) {
  38668. sum += frame[i];
  38669. count++;
  38670. }
  38671. } // Return NaN if count is 0
  38672. return count === 0 ? NaN : sum / count;
  38673. },
  38674. sum: function (frame) {
  38675. var sum = 0;
  38676. for (var i = 0; i < frame.length; i++) {
  38677. // Ignore NaN
  38678. sum += frame[i] || 0;
  38679. }
  38680. return sum;
  38681. },
  38682. max: function (frame) {
  38683. var max = -Infinity;
  38684. for (var i = 0; i < frame.length; i++) {
  38685. frame[i] > max && (max = frame[i]);
  38686. } // NaN will cause illegal axis extent.
  38687. return isFinite(max) ? max : NaN;
  38688. },
  38689. min: function (frame) {
  38690. var min = Infinity;
  38691. for (var i = 0; i < frame.length; i++) {
  38692. frame[i] < min && (min = frame[i]);
  38693. } // NaN will cause illegal axis extent.
  38694. return isFinite(min) ? min : NaN;
  38695. },
  38696. // TODO
  38697. // Median
  38698. nearest: function (frame) {
  38699. return frame[0];
  38700. }
  38701. };
  38702. var indexSampler = function (frame) {
  38703. return Math.round(frame.length / 2);
  38704. };
  38705. function dataSample(seriesType) {
  38706. return {
  38707. seriesType: seriesType,
  38708. // FIXME:TS never used, so comment it
  38709. // modifyOutputEnd: true,
  38710. reset: function (seriesModel, ecModel, api) {
  38711. var data = seriesModel.getData();
  38712. var sampling = seriesModel.get('sampling');
  38713. var coordSys = seriesModel.coordinateSystem;
  38714. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  38715. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  38716. var baseAxis = coordSys.getBaseAxis();
  38717. var valueAxis = coordSys.getOtherAxis(baseAxis);
  38718. var extent = baseAxis.getExtent();
  38719. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  38720. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  38721. var rate = Math.round(count / size);
  38722. if (isFinite(rate) && rate > 1) {
  38723. if (sampling === 'lttb') {
  38724. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  38725. }
  38726. var sampler = void 0;
  38727. if (isString(sampling)) {
  38728. sampler = samplers[sampling];
  38729. } else if (isFunction(sampling)) {
  38730. sampler = sampling;
  38731. }
  38732. if (sampler) {
  38733. // Only support sample the first dim mapped from value axis.
  38734. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  38735. }
  38736. }
  38737. }
  38738. }
  38739. };
  38740. }
  38741. function install$2(registers) {
  38742. registers.registerChartView(LineView);
  38743. registers.registerSeriesModel(LineSeriesModel);
  38744. registers.registerLayout(pointsLayout('line', true));
  38745. registers.registerVisual({
  38746. seriesType: 'line',
  38747. reset: function (seriesModel) {
  38748. var data = seriesModel.getData(); // Visual coding for legend
  38749. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  38750. if (lineStyle && !lineStyle.stroke) {
  38751. // Fill in visual should be palette color if
  38752. // has color callback
  38753. lineStyle.stroke = data.getVisual('style').fill;
  38754. }
  38755. data.setVisual('legendLineStyle', lineStyle);
  38756. }
  38757. }); // Down sample after filter
  38758. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  38759. }
  38760. var BaseBarSeriesModel =
  38761. /** @class */
  38762. function (_super) {
  38763. __extends(BaseBarSeriesModel, _super);
  38764. function BaseBarSeriesModel() {
  38765. var _this = _super !== null && _super.apply(this, arguments) || this;
  38766. _this.type = BaseBarSeriesModel.type;
  38767. return _this;
  38768. }
  38769. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  38770. return createSeriesData(null, this, {
  38771. useEncodeDefaulter: true
  38772. });
  38773. };
  38774. BaseBarSeriesModel.prototype.getMarkerPosition = function (value, dims, startingAtTick) {
  38775. var coordSys = this.coordinateSystem;
  38776. if (coordSys && coordSys.clampData) {
  38777. // PENDING if clamp ?
  38778. var clampData_1 = coordSys.clampData(value);
  38779. var pt_1 = coordSys.dataToPoint(clampData_1);
  38780. if (startingAtTick) {
  38781. each(coordSys.getAxes(), function (axis, idx) {
  38782. // If axis type is category, use tick coords instead
  38783. if (axis.type === 'category' && dims != null) {
  38784. var tickCoords = axis.getTicksCoords();
  38785. var targetTickId = clampData_1[idx]; // The index of rightmost tick of markArea is 1 larger than x1/y1 index
  38786. var isEnd = dims[idx] === 'x1' || dims[idx] === 'y1';
  38787. if (isEnd) {
  38788. targetTickId += 1;
  38789. } // The only contains one tick, tickCoords is
  38790. // like [{coord: 0, tickValue: 0}, {coord: 0}]
  38791. // to the length should always be larger than 1
  38792. if (tickCoords.length < 2) {
  38793. return;
  38794. } else if (tickCoords.length === 2) {
  38795. // The left value and right value of the axis are
  38796. // the same. coord is 0 in both items. Use the max
  38797. // value of the axis as the coord
  38798. pt_1[idx] = axis.toGlobalCoord(axis.getExtent()[isEnd ? 1 : 0]);
  38799. return;
  38800. }
  38801. var leftCoord = void 0;
  38802. var coord = void 0;
  38803. var stepTickValue = 1;
  38804. for (var i = 0; i < tickCoords.length; i++) {
  38805. var tickCoord = tickCoords[i].coord; // The last item of tickCoords doesn't contain
  38806. // tickValue
  38807. var tickValue = i === tickCoords.length - 1 ? tickCoords[i - 1].tickValue + stepTickValue : tickCoords[i].tickValue;
  38808. if (tickValue === targetTickId) {
  38809. coord = tickCoord;
  38810. break;
  38811. } else if (tickValue < targetTickId) {
  38812. leftCoord = tickCoord;
  38813. } else if (leftCoord != null && tickValue > targetTickId) {
  38814. coord = (tickCoord + leftCoord) / 2;
  38815. break;
  38816. }
  38817. if (i === 1) {
  38818. // Here we assume the step of category axes is
  38819. // the same
  38820. stepTickValue = tickValue - tickCoords[0].tickValue;
  38821. }
  38822. }
  38823. if (coord == null) {
  38824. if (!leftCoord) {
  38825. // targetTickId is smaller than all tick ids in the
  38826. // visible area, use the leftmost tick coord
  38827. coord = tickCoords[0].coord;
  38828. } else if (leftCoord) {
  38829. // targetTickId is larger than all tick ids in the
  38830. // visible area, use the rightmost tick coord
  38831. coord = tickCoords[tickCoords.length - 1].coord;
  38832. }
  38833. }
  38834. pt_1[idx] = axis.toGlobalCoord(coord);
  38835. }
  38836. });
  38837. } else {
  38838. var data = this.getData();
  38839. var offset = data.getLayout('offset');
  38840. var size = data.getLayout('size');
  38841. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  38842. pt_1[offsetIndex] += offset + size / 2;
  38843. }
  38844. return pt_1;
  38845. }
  38846. return [NaN, NaN];
  38847. };
  38848. BaseBarSeriesModel.type = 'series.__base_bar__';
  38849. BaseBarSeriesModel.defaultOption = {
  38850. // zlevel: 0,
  38851. z: 2,
  38852. coordinateSystem: 'cartesian2d',
  38853. legendHoverLink: true,
  38854. // stack: null
  38855. // Cartesian coordinate system
  38856. // xAxisIndex: 0,
  38857. // yAxisIndex: 0,
  38858. barMinHeight: 0,
  38859. barMinAngle: 0,
  38860. // cursor: null,
  38861. large: false,
  38862. largeThreshold: 400,
  38863. progressive: 3e3,
  38864. progressiveChunkMode: 'mod'
  38865. };
  38866. return BaseBarSeriesModel;
  38867. }(SeriesModel);
  38868. SeriesModel.registerClass(BaseBarSeriesModel);
  38869. var BarSeriesModel =
  38870. /** @class */
  38871. function (_super) {
  38872. __extends(BarSeriesModel, _super);
  38873. function BarSeriesModel() {
  38874. var _this = _super !== null && _super.apply(this, arguments) || this;
  38875. _this.type = BarSeriesModel.type;
  38876. return _this;
  38877. }
  38878. BarSeriesModel.prototype.getInitialData = function () {
  38879. return createSeriesData(null, this, {
  38880. useEncodeDefaulter: true,
  38881. createInvertedIndices: !!this.get('realtimeSort', true) || null
  38882. });
  38883. };
  38884. /**
  38885. * @override
  38886. */
  38887. BarSeriesModel.prototype.getProgressive = function () {
  38888. // Do not support progressive in normal mode.
  38889. return this.get('large') ? this.get('progressive') : false;
  38890. };
  38891. /**
  38892. * @override
  38893. */
  38894. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  38895. // Do not support progressive in normal mode.
  38896. var progressiveThreshold = this.get('progressiveThreshold');
  38897. var largeThreshold = this.get('largeThreshold');
  38898. if (largeThreshold > progressiveThreshold) {
  38899. progressiveThreshold = largeThreshold;
  38900. }
  38901. return progressiveThreshold;
  38902. };
  38903. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  38904. return selectors.rect(data.getItemLayout(dataIndex));
  38905. };
  38906. BarSeriesModel.type = 'series.bar';
  38907. BarSeriesModel.dependencies = ['grid', 'polar'];
  38908. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  38909. // If clipped
  38910. // Only available on cartesian2d
  38911. clip: true,
  38912. roundCap: false,
  38913. showBackground: false,
  38914. backgroundStyle: {
  38915. color: 'rgba(180, 180, 180, 0.2)',
  38916. borderColor: null,
  38917. borderWidth: 0,
  38918. borderType: 'solid',
  38919. borderRadius: 0,
  38920. shadowBlur: 0,
  38921. shadowColor: null,
  38922. shadowOffsetX: 0,
  38923. shadowOffsetY: 0,
  38924. opacity: 1
  38925. },
  38926. select: {
  38927. itemStyle: {
  38928. borderColor: '#212121'
  38929. }
  38930. },
  38931. realtimeSort: false
  38932. });
  38933. return BarSeriesModel;
  38934. }(BaseBarSeriesModel);
  38935. /**
  38936. * Sausage: similar to sector, but have half circle on both sides
  38937. */
  38938. var SausageShape =
  38939. /** @class */
  38940. function () {
  38941. function SausageShape() {
  38942. this.cx = 0;
  38943. this.cy = 0;
  38944. this.r0 = 0;
  38945. this.r = 0;
  38946. this.startAngle = 0;
  38947. this.endAngle = Math.PI * 2;
  38948. this.clockwise = true;
  38949. }
  38950. return SausageShape;
  38951. }();
  38952. var SausagePath =
  38953. /** @class */
  38954. function (_super) {
  38955. __extends(SausagePath, _super);
  38956. function SausagePath(opts) {
  38957. var _this = _super.call(this, opts) || this;
  38958. _this.type = 'sausage';
  38959. return _this;
  38960. }
  38961. SausagePath.prototype.getDefaultShape = function () {
  38962. return new SausageShape();
  38963. };
  38964. SausagePath.prototype.buildPath = function (ctx, shape) {
  38965. var cx = shape.cx;
  38966. var cy = shape.cy;
  38967. var r0 = Math.max(shape.r0 || 0, 0);
  38968. var r = Math.max(shape.r, 0);
  38969. var dr = (r - r0) * 0.5;
  38970. var rCenter = r0 + dr;
  38971. var startAngle = shape.startAngle;
  38972. var endAngle = shape.endAngle;
  38973. var clockwise = shape.clockwise;
  38974. var PI2 = Math.PI * 2;
  38975. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  38976. if (!lessThanCircle) {
  38977. // Normalize angles
  38978. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  38979. }
  38980. var unitStartX = Math.cos(startAngle);
  38981. var unitStartY = Math.sin(startAngle);
  38982. var unitEndX = Math.cos(endAngle);
  38983. var unitEndY = Math.sin(endAngle);
  38984. if (lessThanCircle) {
  38985. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  38986. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  38987. } else {
  38988. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  38989. }
  38990. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  38991. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  38992. if (r0 !== 0) {
  38993. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  38994. } // ctx.closePath();
  38995. };
  38996. return SausagePath;
  38997. }(Path);
  38998. function createSectorCalculateTextPosition(positionMapping, opts) {
  38999. opts = opts || {};
  39000. var isRoundCap = opts.isRoundCap;
  39001. return function (out, opts, boundingRect) {
  39002. var textPosition = opts.position;
  39003. if (!textPosition || textPosition instanceof Array) {
  39004. return calculateTextPosition(out, opts, boundingRect);
  39005. }
  39006. var mappedSectorPosition = positionMapping(textPosition);
  39007. var distance = opts.distance != null ? opts.distance : 5;
  39008. var sector = this.shape;
  39009. var cx = sector.cx;
  39010. var cy = sector.cy;
  39011. var r = sector.r;
  39012. var r0 = sector.r0;
  39013. var middleR = (r + r0) / 2;
  39014. var startAngle = sector.startAngle;
  39015. var endAngle = sector.endAngle;
  39016. var middleAngle = (startAngle + endAngle) / 2;
  39017. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  39018. var mathCos = Math.cos;
  39019. var mathSin = Math.sin; // base position: top-left
  39020. var x = cx + r * mathCos(startAngle);
  39021. var y = cy + r * mathSin(startAngle);
  39022. var textAlign = 'left';
  39023. var textVerticalAlign = 'top';
  39024. switch (mappedSectorPosition) {
  39025. case 'startArc':
  39026. x = cx + (r0 - distance) * mathCos(middleAngle);
  39027. y = cy + (r0 - distance) * mathSin(middleAngle);
  39028. textAlign = 'center';
  39029. textVerticalAlign = 'top';
  39030. break;
  39031. case 'insideStartArc':
  39032. x = cx + (r0 + distance) * mathCos(middleAngle);
  39033. y = cy + (r0 + distance) * mathSin(middleAngle);
  39034. textAlign = 'center';
  39035. textVerticalAlign = 'bottom';
  39036. break;
  39037. case 'startAngle':
  39038. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  39039. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  39040. textAlign = 'right';
  39041. textVerticalAlign = 'middle';
  39042. break;
  39043. case 'insideStartAngle':
  39044. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  39045. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  39046. textAlign = 'left';
  39047. textVerticalAlign = 'middle';
  39048. break;
  39049. case 'middle':
  39050. x = cx + middleR * mathCos(middleAngle);
  39051. y = cy + middleR * mathSin(middleAngle);
  39052. textAlign = 'center';
  39053. textVerticalAlign = 'middle';
  39054. break;
  39055. case 'endArc':
  39056. x = cx + (r + distance) * mathCos(middleAngle);
  39057. y = cy + (r + distance) * mathSin(middleAngle);
  39058. textAlign = 'center';
  39059. textVerticalAlign = 'bottom';
  39060. break;
  39061. case 'insideEndArc':
  39062. x = cx + (r - distance) * mathCos(middleAngle);
  39063. y = cy + (r - distance) * mathSin(middleAngle);
  39064. textAlign = 'center';
  39065. textVerticalAlign = 'top';
  39066. break;
  39067. case 'endAngle':
  39068. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  39069. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  39070. textAlign = 'left';
  39071. textVerticalAlign = 'middle';
  39072. break;
  39073. case 'insideEndAngle':
  39074. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  39075. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  39076. textAlign = 'right';
  39077. textVerticalAlign = 'middle';
  39078. break;
  39079. default:
  39080. return calculateTextPosition(out, opts, boundingRect);
  39081. }
  39082. out = out || {};
  39083. out.x = x;
  39084. out.y = y;
  39085. out.align = textAlign;
  39086. out.verticalAlign = textVerticalAlign;
  39087. return out;
  39088. };
  39089. }
  39090. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  39091. if (isNumber(rotateType)) {
  39092. // user-set rotation
  39093. sector.setTextConfig({
  39094. rotation: rotateType
  39095. });
  39096. return;
  39097. } else if (isArray(textPosition)) {
  39098. // user-set position, use 0 as auto rotation
  39099. sector.setTextConfig({
  39100. rotation: 0
  39101. });
  39102. return;
  39103. }
  39104. var shape = sector.shape;
  39105. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  39106. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  39107. var middleAngle = (startAngle + endAngle) / 2;
  39108. var anchorAngle;
  39109. var mappedSectorPosition = positionMapping(textPosition);
  39110. switch (mappedSectorPosition) {
  39111. case 'startArc':
  39112. case 'insideStartArc':
  39113. case 'middle':
  39114. case 'insideEndArc':
  39115. case 'endArc':
  39116. anchorAngle = middleAngle;
  39117. break;
  39118. case 'startAngle':
  39119. case 'insideStartAngle':
  39120. anchorAngle = startAngle;
  39121. break;
  39122. case 'endAngle':
  39123. case 'insideEndAngle':
  39124. anchorAngle = endAngle;
  39125. break;
  39126. default:
  39127. sector.setTextConfig({
  39128. rotation: 0
  39129. });
  39130. return;
  39131. }
  39132. var rotate = Math.PI * 1.5 - anchorAngle;
  39133. /**
  39134. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  39135. * half round flipped to increase readability. However, only middle
  39136. * position supports this for now, because in other positions, the
  39137. * anchor point is not at the center of the text, so the positions
  39138. * after rotating is not as expected.
  39139. */
  39140. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  39141. rotate -= Math.PI;
  39142. }
  39143. sector.setTextConfig({
  39144. rotation: rotate
  39145. });
  39146. }
  39147. function adjustAngleDistanceX(angle, distance, isEnd) {
  39148. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  39149. }
  39150. function adjustAngleDistanceY(angle, distance, isEnd) {
  39151. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  39152. }
  39153. function getSectorCornerRadius(model, shape, zeroIfNull) {
  39154. var cornerRadius = model.get('borderRadius');
  39155. if (cornerRadius == null) {
  39156. return zeroIfNull ? {
  39157. cornerRadius: 0
  39158. } : null;
  39159. }
  39160. if (!isArray(cornerRadius)) {
  39161. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  39162. }
  39163. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  39164. return {
  39165. cornerRadius: map(cornerRadius, function (cr) {
  39166. return parsePercent(cr, dr);
  39167. })
  39168. };
  39169. }
  39170. var mathMax$6 = Math.max;
  39171. var mathMin$6 = Math.min;
  39172. function getClipArea(coord, data) {
  39173. var coordSysClipArea = coord.getArea && coord.getArea();
  39174. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39175. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  39176. // We should not clip this part.
  39177. // See test/bar2.html
  39178. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  39179. var expandWidth = data.getLayout('bandWidth');
  39180. if (baseAxis.isHorizontal()) {
  39181. coordSysClipArea.x -= expandWidth;
  39182. coordSysClipArea.width += expandWidth * 2;
  39183. } else {
  39184. coordSysClipArea.y -= expandWidth;
  39185. coordSysClipArea.height += expandWidth * 2;
  39186. }
  39187. }
  39188. }
  39189. return coordSysClipArea;
  39190. }
  39191. var BarView =
  39192. /** @class */
  39193. function (_super) {
  39194. __extends(BarView, _super);
  39195. function BarView() {
  39196. var _this = _super.call(this) || this;
  39197. _this.type = BarView.type;
  39198. _this._isFirstFrame = true;
  39199. return _this;
  39200. }
  39201. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  39202. this._model = seriesModel;
  39203. this._removeOnRenderedListener(api);
  39204. this._updateDrawMode(seriesModel);
  39205. var coordinateSystemType = seriesModel.get('coordinateSystem');
  39206. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  39207. // Clear previously rendered progressive elements.
  39208. this._progressiveEls = null;
  39209. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  39210. } else if ("development" !== 'production') {
  39211. warn('Only cartesian2d and polar supported for bar.');
  39212. }
  39213. };
  39214. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  39215. this._clear();
  39216. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  39217. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  39218. this._updateLargeClip(seriesModel);
  39219. };
  39220. BarView.prototype.incrementalRender = function (params, seriesModel) {
  39221. // Reset
  39222. this._progressiveEls = []; // Do not support progressive in normal mode.
  39223. this._incrementalRenderLarge(params, seriesModel);
  39224. };
  39225. BarView.prototype.eachRendered = function (cb) {
  39226. traverseElements(this._progressiveEls || this.group, cb);
  39227. };
  39228. BarView.prototype._updateDrawMode = function (seriesModel) {
  39229. var isLargeDraw = seriesModel.pipelineContext.large;
  39230. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  39231. this._isLargeDraw = isLargeDraw;
  39232. this._clear();
  39233. }
  39234. };
  39235. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  39236. var group = this.group;
  39237. var data = seriesModel.getData();
  39238. var oldData = this._data;
  39239. var coord = seriesModel.coordinateSystem;
  39240. var baseAxis = coord.getBaseAxis();
  39241. var isHorizontalOrRadial;
  39242. if (coord.type === 'cartesian2d') {
  39243. isHorizontalOrRadial = baseAxis.isHorizontal();
  39244. } else if (coord.type === 'polar') {
  39245. isHorizontalOrRadial = baseAxis.dim === 'angle';
  39246. }
  39247. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  39248. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  39249. if (realtimeSortCfg) {
  39250. this._enableRealtimeSort(realtimeSortCfg, data, api);
  39251. }
  39252. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  39253. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  39254. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  39255. // And don't want the label are clipped.
  39256. var roundCap = seriesModel.get('roundCap', true);
  39257. var drawBackground = seriesModel.get('showBackground', true);
  39258. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39259. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  39260. var bgEls = [];
  39261. var oldBgEls = this._backgroundEls;
  39262. var isInitSort = payload && payload.isInitSort;
  39263. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  39264. function createBackground(dataIndex) {
  39265. var bgLayout = getLayout[coord.type](data, dataIndex);
  39266. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  39267. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  39268. if (coord.type === 'cartesian2d') {
  39269. bgEl.setShape('r', barBorderRadius);
  39270. } else {
  39271. bgEl.setShape('cornerRadius', barBorderRadius);
  39272. }
  39273. bgEls[dataIndex] = bgEl;
  39274. return bgEl;
  39275. }
  39276. data.diff(oldData).add(function (dataIndex) {
  39277. var itemModel = data.getItemModel(dataIndex);
  39278. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  39279. if (drawBackground) {
  39280. createBackground(dataIndex);
  39281. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  39282. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  39283. return;
  39284. }
  39285. var isClipped = false;
  39286. if (needsClip) {
  39287. // Clip will modify the layout params.
  39288. // And return a boolean to determine if the shape are fully clipped.
  39289. isClipped = clip[coord.type](coordSysClipArea, layout);
  39290. }
  39291. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  39292. if (realtimeSortCfg) {
  39293. /**
  39294. * Force label animation because even if the element is
  39295. * ignored because it's clipped, it may not be clipped after
  39296. * changing order. Then, if not using forceLabelAnimation,
  39297. * the label animation was never started, in which case,
  39298. * the label will be the final value and doesn't have label
  39299. * animation.
  39300. */
  39301. el.forceLabelAnimation = true;
  39302. }
  39303. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39304. if (isInitSort) {
  39305. el.attr({
  39306. shape: layout
  39307. });
  39308. } else if (realtimeSortCfg) {
  39309. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  39310. } else {
  39311. initProps(el, {
  39312. shape: layout
  39313. }, seriesModel, dataIndex);
  39314. }
  39315. data.setItemGraphicEl(dataIndex, el);
  39316. group.add(el);
  39317. el.ignore = isClipped;
  39318. }).update(function (newIndex, oldIndex) {
  39319. var itemModel = data.getItemModel(newIndex);
  39320. var layout = getLayout[coord.type](data, newIndex, itemModel);
  39321. if (drawBackground) {
  39322. var bgEl = void 0;
  39323. if (oldBgEls.length === 0) {
  39324. bgEl = createBackground(oldIndex);
  39325. } else {
  39326. bgEl = oldBgEls[oldIndex];
  39327. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  39328. if (coord.type === 'cartesian2d') {
  39329. bgEl.setShape('r', barBorderRadius);
  39330. } else {
  39331. bgEl.setShape('cornerRadius', barBorderRadius);
  39332. }
  39333. bgEls[newIndex] = bgEl;
  39334. }
  39335. var bgLayout = getLayout[coord.type](data, newIndex);
  39336. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  39337. updateProps(bgEl, {
  39338. shape: shape
  39339. }, animationModel, newIndex);
  39340. }
  39341. var el = oldData.getItemGraphicEl(oldIndex);
  39342. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  39343. group.remove(el);
  39344. return;
  39345. }
  39346. var isClipped = false;
  39347. if (needsClip) {
  39348. isClipped = clip[coord.type](coordSysClipArea, layout);
  39349. if (isClipped) {
  39350. group.remove(el);
  39351. }
  39352. }
  39353. if (!el) {
  39354. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  39355. } else {
  39356. saveOldStyle(el);
  39357. }
  39358. if (realtimeSortCfg) {
  39359. el.forceLabelAnimation = true;
  39360. }
  39361. if (isChangeOrder) {
  39362. var textEl = el.getTextContent();
  39363. if (textEl) {
  39364. var labelInnerStore = labelInner(textEl);
  39365. if (labelInnerStore.prevValue != null) {
  39366. /**
  39367. * Set preValue to be value so that no new label
  39368. * should be started, otherwise, it will take a full
  39369. * `animationDurationUpdate` time to finish the
  39370. * animation, which is not expected.
  39371. */
  39372. labelInnerStore.prevValue = labelInnerStore.value;
  39373. }
  39374. }
  39375. } // Not change anything if only order changed.
  39376. // Especially not change label.
  39377. else {
  39378. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39379. }
  39380. if (isInitSort) {
  39381. el.attr({
  39382. shape: layout
  39383. });
  39384. } else if (realtimeSortCfg) {
  39385. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  39386. } else {
  39387. updateProps(el, {
  39388. shape: layout
  39389. }, seriesModel, newIndex, null);
  39390. }
  39391. data.setItemGraphicEl(newIndex, el);
  39392. el.ignore = isClipped;
  39393. group.add(el);
  39394. }).remove(function (dataIndex) {
  39395. var el = oldData.getItemGraphicEl(dataIndex);
  39396. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  39397. }).execute();
  39398. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  39399. bgGroup.removeAll();
  39400. for (var i = 0; i < bgEls.length; ++i) {
  39401. bgGroup.add(bgEls[i]);
  39402. }
  39403. group.add(bgGroup);
  39404. this._backgroundEls = bgEls;
  39405. this._data = data;
  39406. };
  39407. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  39408. this._clear();
  39409. createLarge(seriesModel, this.group);
  39410. this._updateLargeClip(seriesModel);
  39411. };
  39412. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  39413. this._removeBackground();
  39414. createLarge(seriesModel, this.group, this._progressiveEls, true);
  39415. };
  39416. BarView.prototype._updateLargeClip = function (seriesModel) {
  39417. // Use clipPath in large mode.
  39418. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  39419. var group = this.group;
  39420. if (clipPath) {
  39421. group.setClipPath(clipPath);
  39422. } else {
  39423. group.removeClipPath();
  39424. }
  39425. };
  39426. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  39427. var _this = this; // If no data in the first frame, wait for data to initSort
  39428. if (!data.count()) {
  39429. return;
  39430. }
  39431. var baseAxis = realtimeSortCfg.baseAxis;
  39432. if (this._isFirstFrame) {
  39433. this._dispatchInitSort(data, realtimeSortCfg, api);
  39434. this._isFirstFrame = false;
  39435. } else {
  39436. var orderMapping_1 = function (idx) {
  39437. var el = data.getItemGraphicEl(idx);
  39438. var shape = el && el.shape;
  39439. return shape && // The result should be consistent with the initial sort by data value.
  39440. // Do not support the case that both positive and negative exist.
  39441. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width) // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  39442. || 0;
  39443. };
  39444. this._onRendered = function () {
  39445. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  39446. };
  39447. api.getZr().on('rendered', this._onRendered);
  39448. }
  39449. };
  39450. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  39451. var info = [];
  39452. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  39453. var mappedValue = orderMapping(dataIdx);
  39454. mappedValue = mappedValue == null ? NaN : mappedValue;
  39455. info.push({
  39456. dataIndex: dataIdx,
  39457. mappedValue: mappedValue,
  39458. ordinalNumber: ordinalNumber
  39459. });
  39460. });
  39461. info.sort(function (a, b) {
  39462. // If NaN, it will be treated as min val.
  39463. return b.mappedValue - a.mappedValue;
  39464. });
  39465. return {
  39466. ordinalNumbers: map(info, function (item) {
  39467. return item.ordinalNumber;
  39468. })
  39469. };
  39470. };
  39471. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  39472. var scale = baseAxis.scale;
  39473. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  39474. var lastValue = Number.MAX_VALUE;
  39475. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  39476. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  39477. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  39478. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  39479. : orderMapping(data.indexOfRawIndex(rawIdx));
  39480. if (value > lastValue) {
  39481. return true;
  39482. }
  39483. lastValue = value;
  39484. }
  39485. return false;
  39486. };
  39487. /*
  39488. * Consider the case when A and B changed order, whose representing
  39489. * bars are both out of sight, we don't wish to trigger reorder action
  39490. * as long as the order in the view doesn't change.
  39491. */
  39492. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  39493. var scale = baseAxis.scale;
  39494. var extent = scale.getExtent();
  39495. var tickNum = Math.max(0, extent[0]);
  39496. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  39497. for (; tickNum <= tickMax; ++tickNum) {
  39498. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  39499. return true;
  39500. }
  39501. }
  39502. };
  39503. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  39504. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  39505. return;
  39506. }
  39507. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  39508. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  39509. this._removeOnRenderedListener(api);
  39510. api.dispatchAction({
  39511. type: 'changeAxisOrder',
  39512. componentType: baseAxis.dim + 'Axis',
  39513. axisId: baseAxis.index,
  39514. sortInfo: sortInfo
  39515. });
  39516. }
  39517. };
  39518. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  39519. var baseAxis = realtimeSortCfg.baseAxis;
  39520. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  39521. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  39522. });
  39523. api.dispatchAction({
  39524. type: 'changeAxisOrder',
  39525. componentType: baseAxis.dim + 'Axis',
  39526. isInitSort: true,
  39527. axisId: baseAxis.index,
  39528. sortInfo: sortResult
  39529. });
  39530. };
  39531. BarView.prototype.remove = function (ecModel, api) {
  39532. this._clear(this._model);
  39533. this._removeOnRenderedListener(api);
  39534. };
  39535. BarView.prototype.dispose = function (ecModel, api) {
  39536. this._removeOnRenderedListener(api);
  39537. };
  39538. BarView.prototype._removeOnRenderedListener = function (api) {
  39539. if (this._onRendered) {
  39540. api.getZr().off('rendered', this._onRendered);
  39541. this._onRendered = null;
  39542. }
  39543. };
  39544. BarView.prototype._clear = function (model) {
  39545. var group = this.group;
  39546. var data = this._data;
  39547. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  39548. this._removeBackground();
  39549. this._backgroundEls = [];
  39550. data.eachItemGraphicEl(function (el) {
  39551. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  39552. });
  39553. } else {
  39554. group.removeAll();
  39555. }
  39556. this._data = null;
  39557. this._isFirstFrame = true;
  39558. };
  39559. BarView.prototype._removeBackground = function () {
  39560. this.group.remove(this._backgroundGroup);
  39561. this._backgroundGroup = null;
  39562. };
  39563. BarView.type = 'bar';
  39564. return BarView;
  39565. }(ChartView);
  39566. var clip = {
  39567. cartesian2d: function (coordSysBoundingRect, layout) {
  39568. var signWidth = layout.width < 0 ? -1 : 1;
  39569. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  39570. if (signWidth < 0) {
  39571. layout.x += layout.width;
  39572. layout.width = -layout.width;
  39573. }
  39574. if (signHeight < 0) {
  39575. layout.y += layout.height;
  39576. layout.height = -layout.height;
  39577. }
  39578. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  39579. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  39580. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  39581. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  39582. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  39583. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  39584. var xClipped = x2 < x;
  39585. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  39586. // But we should also place the element at the edge of the coord sys bounding rect.
  39587. // Because if data changed and the bar shows again, its transition animation
  39588. // will begin at this place.
  39589. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  39590. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  39591. layout.width = xClipped ? 0 : x2 - x;
  39592. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  39593. if (signWidth < 0) {
  39594. layout.x += layout.width;
  39595. layout.width = -layout.width;
  39596. }
  39597. if (signHeight < 0) {
  39598. layout.y += layout.height;
  39599. layout.height = -layout.height;
  39600. }
  39601. return xClipped || yClipped;
  39602. },
  39603. polar: function (coordSysClipArea, layout) {
  39604. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  39605. if (signR < 0) {
  39606. var tmp = layout.r;
  39607. layout.r = layout.r0;
  39608. layout.r0 = tmp;
  39609. }
  39610. var r = mathMin$6(layout.r, coordSysClipArea.r);
  39611. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  39612. layout.r = r;
  39613. layout.r0 = r0;
  39614. var clipped = r - r0 < 0; // Reverse back
  39615. if (signR < 0) {
  39616. var tmp = layout.r;
  39617. layout.r = layout.r0;
  39618. layout.r0 = tmp;
  39619. }
  39620. return clipped;
  39621. }
  39622. };
  39623. var elementCreator = {
  39624. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  39625. var rect = new Rect({
  39626. shape: extend({}, layout),
  39627. z2: 1
  39628. });
  39629. rect.__dataIndex = newIndex;
  39630. rect.name = 'item';
  39631. if (animationModel) {
  39632. var rectShape = rect.shape;
  39633. var animateProperty = isHorizontal ? 'height' : 'width';
  39634. rectShape[animateProperty] = 0;
  39635. }
  39636. return rect;
  39637. },
  39638. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  39639. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  39640. var sector = new ShapeClass({
  39641. shape: layout,
  39642. z2: 1
  39643. });
  39644. sector.name = 'item';
  39645. var positionMap = createPolarPositionMapping(isRadial);
  39646. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  39647. isRoundCap: ShapeClass === SausagePath
  39648. }); // Animation
  39649. if (animationModel) {
  39650. var sectorShape = sector.shape;
  39651. var animateProperty = isRadial ? 'r' : 'endAngle';
  39652. var animateTarget = {};
  39653. sectorShape[animateProperty] = isRadial ? layout.r0 : layout.startAngle;
  39654. animateTarget[animateProperty] = layout[animateProperty];
  39655. (isUpdate ? updateProps : initProps)(sector, {
  39656. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  39657. }, animationModel);
  39658. }
  39659. return sector;
  39660. }
  39661. };
  39662. function shouldRealtimeSort(seriesModel, coordSys) {
  39663. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  39664. var baseAxis = coordSys.getBaseAxis();
  39665. if ("development" !== 'production') {
  39666. if (realtimeSortOption) {
  39667. if (baseAxis.type !== 'category') {
  39668. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  39669. }
  39670. if (coordSys.type !== 'cartesian2d') {
  39671. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  39672. }
  39673. }
  39674. }
  39675. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  39676. return {
  39677. baseAxis: baseAxis,
  39678. otherAxis: coordSys.getOtherAxis(baseAxis)
  39679. };
  39680. }
  39681. }
  39682. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  39683. var seriesTarget;
  39684. var axisTarget;
  39685. if (isHorizontal) {
  39686. axisTarget = {
  39687. x: layout.x,
  39688. width: layout.width
  39689. };
  39690. seriesTarget = {
  39691. y: layout.y,
  39692. height: layout.height
  39693. };
  39694. } else {
  39695. axisTarget = {
  39696. y: layout.y,
  39697. height: layout.height
  39698. };
  39699. seriesTarget = {
  39700. x: layout.x,
  39701. width: layout.width
  39702. };
  39703. }
  39704. if (!isChangeOrder) {
  39705. // Keep the original growth animation if only axis order changed.
  39706. // Not start a new animation.
  39707. (isUpdate ? updateProps : initProps)(el, {
  39708. shape: seriesTarget
  39709. }, seriesAnimationModel, newIndex, null);
  39710. }
  39711. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  39712. (isUpdate ? updateProps : initProps)(el, {
  39713. shape: axisTarget
  39714. }, axisAnimationModel, newIndex);
  39715. }
  39716. function checkPropertiesNotValid(obj, props) {
  39717. for (var i = 0; i < props.length; i++) {
  39718. if (!isFinite(obj[props[i]])) {
  39719. return true;
  39720. }
  39721. }
  39722. return false;
  39723. }
  39724. var rectPropties = ['x', 'y', 'width', 'height'];
  39725. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  39726. var isValidLayout = {
  39727. cartesian2d: function (layout) {
  39728. return !checkPropertiesNotValid(layout, rectPropties);
  39729. },
  39730. polar: function (layout) {
  39731. return !checkPropertiesNotValid(layout, polarPropties);
  39732. }
  39733. };
  39734. var getLayout = {
  39735. // itemModel is only used to get borderWidth, which is not needed
  39736. // when calculating bar background layout.
  39737. cartesian2d: function (data, dataIndex, itemModel) {
  39738. var layout = data.getItemLayout(dataIndex);
  39739. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  39740. var signX = layout.width > 0 ? 1 : -1;
  39741. var signY = layout.height > 0 ? 1 : -1;
  39742. return {
  39743. x: layout.x + signX * fixedLineWidth / 2,
  39744. y: layout.y + signY * fixedLineWidth / 2,
  39745. width: layout.width - signX * fixedLineWidth,
  39746. height: layout.height - signY * fixedLineWidth
  39747. };
  39748. },
  39749. polar: function (data, dataIndex, itemModel) {
  39750. var layout = data.getItemLayout(dataIndex);
  39751. return {
  39752. cx: layout.cx,
  39753. cy: layout.cy,
  39754. r0: layout.r0,
  39755. r: layout.r,
  39756. startAngle: layout.startAngle,
  39757. endAngle: layout.endAngle,
  39758. clockwise: layout.clockwise
  39759. };
  39760. }
  39761. };
  39762. function isZeroOnPolar(layout) {
  39763. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  39764. }
  39765. function createPolarPositionMapping(isRadial) {
  39766. return function (isRadial) {
  39767. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  39768. return function (position) {
  39769. switch (position) {
  39770. case 'start':
  39771. case 'insideStart':
  39772. case 'end':
  39773. case 'insideEnd':
  39774. return position + arcOrAngle;
  39775. default:
  39776. return position;
  39777. }
  39778. };
  39779. }(isRadial);
  39780. }
  39781. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  39782. var style = data.getItemVisual(dataIndex, 'style');
  39783. if (!isPolar) {
  39784. var borderRadius = itemModel.get(['itemStyle', 'borderRadius']) || 0;
  39785. el.setShape('r', borderRadius);
  39786. } else if (!seriesModel.get('roundCap')) {
  39787. var sectorShape = el.shape;
  39788. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  39789. extend(sectorShape, cornerRadius);
  39790. el.setShape(sectorShape);
  39791. }
  39792. el.useStyle(style);
  39793. var cursorStyle = itemModel.getShallow('cursor');
  39794. cursorStyle && el.attr('cursor', cursorStyle);
  39795. var labelPositionOutside = isPolar ? isHorizontalOrRadial ? layout.r >= layout.r0 ? 'endArc' : 'startArc' : layout.endAngle >= layout.startAngle ? 'endAngle' : 'startAngle' : isHorizontalOrRadial ? layout.height >= 0 ? 'bottom' : 'top' : layout.width >= 0 ? 'right' : 'left';
  39796. var labelStatesModels = getLabelStatesModels(itemModel);
  39797. setLabelStyle(el, labelStatesModels, {
  39798. labelFetcher: seriesModel,
  39799. labelDataIndex: dataIndex,
  39800. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  39801. inheritColor: style.fill,
  39802. defaultOpacity: style.opacity,
  39803. defaultOutsidePosition: labelPositionOutside
  39804. });
  39805. var label = el.getTextContent();
  39806. if (isPolar && label) {
  39807. var position = itemModel.get(['label', 'position']);
  39808. el.textConfig.inside = position === 'middle' ? true : null;
  39809. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  39810. }
  39811. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  39812. return getDefaultInterpolatedLabel(data, value);
  39813. });
  39814. var emphasisModel = itemModel.getModel(['emphasis']);
  39815. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  39816. setStatesStylesFromModel(el, itemModel);
  39817. if (isZeroOnPolar(layout)) {
  39818. el.style.fill = 'none';
  39819. el.style.stroke = 'none';
  39820. each(el.states, function (state) {
  39821. if (state.style) {
  39822. state.style.fill = state.style.stroke = 'none';
  39823. }
  39824. });
  39825. }
  39826. } // In case width or height are too small.
  39827. function getLineWidth(itemModel, rawLayout) {
  39828. // Has no border.
  39829. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  39830. if (!borderColor || borderColor === 'none') {
  39831. return 0;
  39832. }
  39833. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0; // width or height may be NaN for empty data
  39834. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  39835. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  39836. return Math.min(lineWidth, width, height);
  39837. }
  39838. var LagePathShape =
  39839. /** @class */
  39840. function () {
  39841. function LagePathShape() {}
  39842. return LagePathShape;
  39843. }();
  39844. var LargePath =
  39845. /** @class */
  39846. function (_super) {
  39847. __extends(LargePath, _super);
  39848. function LargePath(opts) {
  39849. var _this = _super.call(this, opts) || this;
  39850. _this.type = 'largeBar';
  39851. return _this;
  39852. }
  39853. LargePath.prototype.getDefaultShape = function () {
  39854. return new LagePathShape();
  39855. };
  39856. LargePath.prototype.buildPath = function (ctx, shape) {
  39857. // Drawing lines is more efficient than drawing
  39858. // a whole line or drawing rects.
  39859. var points = shape.points;
  39860. var baseDimIdx = this.baseDimIdx;
  39861. var valueDimIdx = 1 - this.baseDimIdx;
  39862. var startPoint = [];
  39863. var size = [];
  39864. var barWidth = this.barWidth;
  39865. for (var i = 0; i < points.length; i += 3) {
  39866. size[baseDimIdx] = barWidth;
  39867. size[valueDimIdx] = points[i + 2];
  39868. startPoint[baseDimIdx] = points[i + baseDimIdx];
  39869. startPoint[valueDimIdx] = points[i + valueDimIdx];
  39870. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  39871. }
  39872. };
  39873. return LargePath;
  39874. }(Path);
  39875. function createLarge(seriesModel, group, progressiveEls, incremental) {
  39876. // TODO support polar
  39877. var data = seriesModel.getData();
  39878. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  39879. var largeDataIndices = data.getLayout('largeDataIndices');
  39880. var barWidth = data.getLayout('size');
  39881. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39882. var bgPoints = data.getLayout('largeBackgroundPoints');
  39883. if (bgPoints) {
  39884. var bgEl = new LargePath({
  39885. shape: {
  39886. points: bgPoints
  39887. },
  39888. incremental: !!incremental,
  39889. silent: true,
  39890. z2: 0
  39891. });
  39892. bgEl.baseDimIdx = baseDimIdx;
  39893. bgEl.largeDataIndices = largeDataIndices;
  39894. bgEl.barWidth = barWidth;
  39895. bgEl.useStyle(backgroundModel.getItemStyle());
  39896. group.add(bgEl);
  39897. progressiveEls && progressiveEls.push(bgEl);
  39898. }
  39899. var el = new LargePath({
  39900. shape: {
  39901. points: data.getLayout('largePoints')
  39902. },
  39903. incremental: !!incremental,
  39904. ignoreCoarsePointer: true,
  39905. z2: 1
  39906. });
  39907. el.baseDimIdx = baseDimIdx;
  39908. el.largeDataIndices = largeDataIndices;
  39909. el.barWidth = barWidth;
  39910. group.add(el);
  39911. el.useStyle(data.getVisual('style')); // Enable tooltip and user mouse/touch event handlers.
  39912. getECData(el).seriesIndex = seriesModel.seriesIndex;
  39913. if (!seriesModel.get('silent')) {
  39914. el.on('mousedown', largePathUpdateDataIndex);
  39915. el.on('mousemove', largePathUpdateDataIndex);
  39916. }
  39917. progressiveEls && progressiveEls.push(el);
  39918. } // Use throttle to avoid frequently traverse to find dataIndex.
  39919. var largePathUpdateDataIndex = throttle(function (event) {
  39920. var largePath = this;
  39921. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  39922. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  39923. }, 30, false);
  39924. function largePathFindDataIndex(largePath, x, y) {
  39925. var baseDimIdx = largePath.baseDimIdx;
  39926. var valueDimIdx = 1 - baseDimIdx;
  39927. var points = largePath.shape.points;
  39928. var largeDataIndices = largePath.largeDataIndices;
  39929. var startPoint = [];
  39930. var size = [];
  39931. var barWidth = largePath.barWidth;
  39932. for (var i = 0, len = points.length / 3; i < len; i++) {
  39933. var ii = i * 3;
  39934. size[baseDimIdx] = barWidth;
  39935. size[valueDimIdx] = points[ii + 2];
  39936. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  39937. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  39938. if (size[valueDimIdx] < 0) {
  39939. startPoint[valueDimIdx] += size[valueDimIdx];
  39940. size[valueDimIdx] = -size[valueDimIdx];
  39941. }
  39942. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  39943. return largeDataIndices[i];
  39944. }
  39945. }
  39946. return -1;
  39947. }
  39948. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  39949. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39950. var rectShape = layout;
  39951. var coordLayout = coord.getArea();
  39952. return {
  39953. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  39954. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  39955. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  39956. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  39957. };
  39958. } else {
  39959. var coordLayout = coord.getArea();
  39960. var sectorShape = layout;
  39961. return {
  39962. cx: coordLayout.cx,
  39963. cy: coordLayout.cy,
  39964. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  39965. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  39966. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  39967. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  39968. };
  39969. }
  39970. }
  39971. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  39972. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  39973. return new ElementClz({
  39974. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  39975. silent: true,
  39976. z2: 0
  39977. });
  39978. }
  39979. function install$3(registers) {
  39980. registers.registerChartView(BarView);
  39981. registers.registerSeriesModel(BarSeriesModel);
  39982. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Do layout after other overall layout, which can prepare some information.
  39983. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar')); // Down sample after filter
  39984. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  39985. /**
  39986. * @payload
  39987. * @property {string} [componentType=series]
  39988. * @property {number} [dx]
  39989. * @property {number} [dy]
  39990. * @property {number} [zoom]
  39991. * @property {number} [originX]
  39992. * @property {number} [originY]
  39993. */
  39994. registers.registerAction({
  39995. type: 'changeAxisOrder',
  39996. event: 'changeAxisOrder',
  39997. update: 'update'
  39998. }, function (payload, ecModel) {
  39999. var componentType = payload.componentType || 'series';
  40000. ecModel.eachComponent({
  40001. mainType: componentType,
  40002. query: payload
  40003. }, function (componentModel) {
  40004. if (payload.sortInfo) {
  40005. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  40006. }
  40007. });
  40008. });
  40009. }
  40010. var PI2$8 = Math.PI * 2;
  40011. var RADIAN = Math.PI / 180;
  40012. function getViewRect(seriesModel, api) {
  40013. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  40014. width: api.getWidth(),
  40015. height: api.getHeight()
  40016. });
  40017. }
  40018. function getBasicPieLayout(seriesModel, api) {
  40019. var viewRect = getViewRect(seriesModel, api); // center can be string or number when coordinateSystem is specified
  40020. var center = seriesModel.get('center');
  40021. var radius = seriesModel.get('radius');
  40022. if (!isArray(radius)) {
  40023. radius = [0, radius];
  40024. }
  40025. var width = parsePercent$1(viewRect.width, api.getWidth());
  40026. var height = parsePercent$1(viewRect.height, api.getHeight());
  40027. var size = Math.min(width, height);
  40028. var r0 = parsePercent$1(radius[0], size / 2);
  40029. var r = parsePercent$1(radius[1], size / 2);
  40030. var cx;
  40031. var cy;
  40032. var coordSys = seriesModel.coordinateSystem;
  40033. if (coordSys) {
  40034. // percentage is not allowed when coordinate system is specified
  40035. var point = coordSys.dataToPoint(center);
  40036. cx = point[0] || 0;
  40037. cy = point[1] || 0;
  40038. } else {
  40039. if (!isArray(center)) {
  40040. center = [center, center];
  40041. }
  40042. cx = parsePercent$1(center[0], width) + viewRect.x;
  40043. cy = parsePercent$1(center[1], height) + viewRect.y;
  40044. }
  40045. return {
  40046. cx: cx,
  40047. cy: cy,
  40048. r0: r0,
  40049. r: r
  40050. };
  40051. }
  40052. function pieLayout(seriesType, ecModel, api) {
  40053. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  40054. var data = seriesModel.getData();
  40055. var valueDim = data.mapDimension('value');
  40056. var viewRect = getViewRect(seriesModel, api);
  40057. var _a = getBasicPieLayout(seriesModel, api),
  40058. cx = _a.cx,
  40059. cy = _a.cy,
  40060. r = _a.r,
  40061. r0 = _a.r0;
  40062. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  40063. var minAngle = seriesModel.get('minAngle') * RADIAN;
  40064. var validDataCount = 0;
  40065. data.each(valueDim, function (value) {
  40066. !isNaN(value) && validDataCount++;
  40067. });
  40068. var sum = data.getSum(valueDim); // Sum may be 0
  40069. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  40070. var clockwise = seriesModel.get('clockwise');
  40071. var roseType = seriesModel.get('roseType');
  40072. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  40073. var extent = data.getDataExtent(valueDim);
  40074. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  40075. var restAngle = PI2$8;
  40076. var valueSumLargerThanMinAngle = 0;
  40077. var currentAngle = startAngle;
  40078. var dir = clockwise ? 1 : -1;
  40079. data.setLayout({
  40080. viewRect: viewRect,
  40081. r: r
  40082. });
  40083. data.each(valueDim, function (value, idx) {
  40084. var angle;
  40085. if (isNaN(value)) {
  40086. data.setItemLayout(idx, {
  40087. angle: NaN,
  40088. startAngle: NaN,
  40089. endAngle: NaN,
  40090. clockwise: clockwise,
  40091. cx: cx,
  40092. cy: cy,
  40093. r0: r0,
  40094. r: roseType ? NaN : r
  40095. });
  40096. return;
  40097. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  40098. if (roseType !== 'area') {
  40099. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  40100. } else {
  40101. angle = PI2$8 / validDataCount;
  40102. }
  40103. if (angle < minAngle) {
  40104. angle = minAngle;
  40105. restAngle -= minAngle;
  40106. } else {
  40107. valueSumLargerThanMinAngle += value;
  40108. }
  40109. var endAngle = currentAngle + dir * angle;
  40110. data.setItemLayout(idx, {
  40111. angle: angle,
  40112. startAngle: currentAngle,
  40113. endAngle: endAngle,
  40114. clockwise: clockwise,
  40115. cx: cx,
  40116. cy: cy,
  40117. r0: r0,
  40118. r: roseType ? linearMap(value, extent, [r0, r]) : r
  40119. });
  40120. currentAngle = endAngle;
  40121. }); // Some sector is constrained by minAngle
  40122. // Rest sectors needs recalculate angle
  40123. if (restAngle < PI2$8 && validDataCount) {
  40124. // Average the angle if rest angle is not enough after all angles is
  40125. // Constrained by minAngle
  40126. if (restAngle <= 1e-3) {
  40127. var angle_1 = PI2$8 / validDataCount;
  40128. data.each(valueDim, function (value, idx) {
  40129. if (!isNaN(value)) {
  40130. var layout_1 = data.getItemLayout(idx);
  40131. layout_1.angle = angle_1;
  40132. layout_1.startAngle = startAngle + dir * idx * angle_1;
  40133. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  40134. }
  40135. });
  40136. } else {
  40137. unitRadian = restAngle / valueSumLargerThanMinAngle;
  40138. currentAngle = startAngle;
  40139. data.each(valueDim, function (value, idx) {
  40140. if (!isNaN(value)) {
  40141. var layout_2 = data.getItemLayout(idx);
  40142. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  40143. layout_2.startAngle = currentAngle;
  40144. layout_2.endAngle = currentAngle + dir * angle;
  40145. currentAngle += dir * angle;
  40146. }
  40147. });
  40148. }
  40149. }
  40150. });
  40151. }
  40152. /*
  40153. * Licensed to the Apache Software Foundation (ASF) under one
  40154. * or more contributor license agreements. See the NOTICE file
  40155. * distributed with this work for additional information
  40156. * regarding copyright ownership. The ASF licenses this file
  40157. * to you under the Apache License, Version 2.0 (the
  40158. * "License"); you may not use this file except in compliance
  40159. * with the License. You may obtain a copy of the License at
  40160. *
  40161. * http://www.apache.org/licenses/LICENSE-2.0
  40162. *
  40163. * Unless required by applicable law or agreed to in writing,
  40164. * software distributed under the License is distributed on an
  40165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40166. * KIND, either express or implied. See the License for the
  40167. * specific language governing permissions and limitations
  40168. * under the License.
  40169. */
  40170. /**
  40171. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40172. */
  40173. /*
  40174. * Licensed to the Apache Software Foundation (ASF) under one
  40175. * or more contributor license agreements. See the NOTICE file
  40176. * distributed with this work for additional information
  40177. * regarding copyright ownership. The ASF licenses this file
  40178. * to you under the Apache License, Version 2.0 (the
  40179. * "License"); you may not use this file except in compliance
  40180. * with the License. You may obtain a copy of the License at
  40181. *
  40182. * http://www.apache.org/licenses/LICENSE-2.0
  40183. *
  40184. * Unless required by applicable law or agreed to in writing,
  40185. * software distributed under the License is distributed on an
  40186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40187. * KIND, either express or implied. See the License for the
  40188. * specific language governing permissions and limitations
  40189. * under the License.
  40190. */
  40191. function dataFilter(seriesType) {
  40192. return {
  40193. seriesType: seriesType,
  40194. reset: function (seriesModel, ecModel) {
  40195. var legendModels = ecModel.findComponents({
  40196. mainType: 'legend'
  40197. });
  40198. if (!legendModels || !legendModels.length) {
  40199. return;
  40200. }
  40201. var data = seriesModel.getData();
  40202. data.filterSelf(function (idx) {
  40203. var name = data.getName(idx); // If in any legend component the status is not selected.
  40204. for (var i = 0; i < legendModels.length; i++) {
  40205. // @ts-ignore FIXME: LegendModel
  40206. if (!legendModels[i].isSelected(name)) {
  40207. return false;
  40208. }
  40209. }
  40210. return true;
  40211. });
  40212. }
  40213. };
  40214. }
  40215. var RADIAN$1 = Math.PI / 180;
  40216. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  40217. if (list.length < 2) {
  40218. return;
  40219. }
  40220. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  40221. var rB = semi.rB;
  40222. var rB2 = rB * rB;
  40223. for (var i = 0; i < semi.list.length; i++) {
  40224. var item = semi.list[i];
  40225. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  40226. var rA = r + item.len;
  40227. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  40228. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  40229. var newX = cx + (dx + item.len2) * dir;
  40230. var deltaX = newX - item.label.x;
  40231. var newTargetWidth = item.targetTextWidth - deltaX * dir; // text x is changed, so need to recalculate width.
  40232. constrainTextWidth(item, newTargetWidth, true);
  40233. item.label.x = newX;
  40234. }
  40235. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  40236. function recalculateX(items) {
  40237. // Extremes of
  40238. var topSemi = {
  40239. list: [],
  40240. maxY: 0
  40241. };
  40242. var bottomSemi = {
  40243. list: [],
  40244. maxY: 0
  40245. };
  40246. for (var i = 0; i < items.length; i++) {
  40247. if (items[i].labelAlignTo !== 'none') {
  40248. continue;
  40249. }
  40250. var item = items[i];
  40251. var semi = item.label.y > cy ? bottomSemi : topSemi;
  40252. var dy = Math.abs(item.label.y - cy);
  40253. if (dy >= semi.maxY) {
  40254. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  40255. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  40256. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  40257. semi.rB = rB;
  40258. semi.maxY = dy;
  40259. }
  40260. semi.list.push(item);
  40261. }
  40262. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  40263. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  40264. }
  40265. var len = list.length;
  40266. for (var i = 0; i < len; i++) {
  40267. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  40268. var dx = list[i].label.x - farthestX;
  40269. list[i].linePoints[1][0] += dx;
  40270. list[i].label.x = farthestX;
  40271. }
  40272. }
  40273. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  40274. recalculateX(list);
  40275. }
  40276. }
  40277. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  40278. var leftList = [];
  40279. var rightList = [];
  40280. var leftmostX = Number.MAX_VALUE;
  40281. var rightmostX = -Number.MAX_VALUE;
  40282. for (var i = 0; i < labelLayoutList.length; i++) {
  40283. var label = labelLayoutList[i].label;
  40284. if (isPositionCenter(labelLayoutList[i])) {
  40285. continue;
  40286. }
  40287. if (label.x < cx) {
  40288. leftmostX = Math.min(leftmostX, label.x);
  40289. leftList.push(labelLayoutList[i]);
  40290. } else {
  40291. rightmostX = Math.max(rightmostX, label.x);
  40292. rightList.push(labelLayoutList[i]);
  40293. }
  40294. }
  40295. for (var i = 0; i < labelLayoutList.length; i++) {
  40296. var layout = labelLayoutList[i];
  40297. if (!isPositionCenter(layout) && layout.linePoints) {
  40298. if (layout.labelStyleWidth != null) {
  40299. continue;
  40300. }
  40301. var label = layout.label;
  40302. var linePoints = layout.linePoints;
  40303. var targetTextWidth = void 0;
  40304. if (layout.labelAlignTo === 'edge') {
  40305. if (label.x < cx) {
  40306. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  40307. } else {
  40308. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  40309. }
  40310. } else if (layout.labelAlignTo === 'labelLine') {
  40311. if (label.x < cx) {
  40312. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  40313. } else {
  40314. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  40315. }
  40316. } else {
  40317. if (label.x < cx) {
  40318. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  40319. } else {
  40320. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  40321. }
  40322. }
  40323. layout.targetTextWidth = targetTextWidth;
  40324. constrainTextWidth(layout, targetTextWidth);
  40325. }
  40326. }
  40327. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  40328. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  40329. for (var i = 0; i < labelLayoutList.length; i++) {
  40330. var layout = labelLayoutList[i];
  40331. if (!isPositionCenter(layout) && layout.linePoints) {
  40332. var label = layout.label;
  40333. var linePoints = layout.linePoints;
  40334. var isAlignToEdge = layout.labelAlignTo === 'edge';
  40335. var padding = label.style.padding;
  40336. var paddingH = padding ? padding[1] + padding[3] : 0; // textRect.width already contains paddingH if bgColor is set
  40337. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  40338. var realTextWidth = layout.rect.width + extraPaddingH;
  40339. var dist = linePoints[1][0] - linePoints[2][0];
  40340. if (isAlignToEdge) {
  40341. if (label.x < cx) {
  40342. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  40343. } else {
  40344. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  40345. }
  40346. } else {
  40347. if (label.x < cx) {
  40348. linePoints[2][0] = label.x + layout.labelDistance;
  40349. } else {
  40350. linePoints[2][0] = label.x - layout.labelDistance;
  40351. }
  40352. linePoints[1][0] = linePoints[2][0] + dist;
  40353. }
  40354. linePoints[1][1] = linePoints[2][1] = label.y;
  40355. }
  40356. }
  40357. }
  40358. /**
  40359. * Set max width of each label, and then wrap each label to the max width.
  40360. *
  40361. * @param layout label layout
  40362. * @param availableWidth max width for the label to display
  40363. * @param forceRecalculate recaculate the text layout even if the current width
  40364. * is smaller than `availableWidth`. This is useful when the text was previously
  40365. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  40366. * which case, previous wrapping should be redo.
  40367. */
  40368. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  40369. if (forceRecalculate === void 0) {
  40370. forceRecalculate = false;
  40371. }
  40372. if (layout.labelStyleWidth != null) {
  40373. // User-defined style.width has the highest priority.
  40374. return;
  40375. }
  40376. var label = layout.label;
  40377. var style = label.style;
  40378. var textRect = layout.rect;
  40379. var bgColor = style.backgroundColor;
  40380. var padding = style.padding;
  40381. var paddingH = padding ? padding[1] + padding[3] : 0;
  40382. var overflow = style.overflow; // textRect.width already contains paddingH if bgColor is set
  40383. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  40384. if (availableWidth < oldOuterWidth || forceRecalculate) {
  40385. var oldHeight = textRect.height;
  40386. if (overflow && overflow.match('break')) {
  40387. // Temporarily set background to be null to calculate
  40388. // the bounding box without background.
  40389. label.setStyle('backgroundColor', null); // Set constraining width
  40390. label.setStyle('width', availableWidth - paddingH); // This is the real bounding box of the text without padding.
  40391. var innerRect = label.getBoundingRect();
  40392. label.setStyle('width', Math.ceil(innerRect.width));
  40393. label.setStyle('backgroundColor', bgColor);
  40394. } else {
  40395. var availableInnerWidth = availableWidth - paddingH;
  40396. var newWidth = availableWidth < oldOuterWidth // Current text is too wide, use `availableWidth` as max width.
  40397. ? availableInnerWidth : // Current available width is enough, but the text may have
  40398. // already been wrapped with a smaller available width.
  40399. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth // Current available is larger than text width,
  40400. // so don't constrain width (otherwise it may have
  40401. // empty space in the background).
  40402. ? null // Current available is smaller than text width, so
  40403. // use the current available width as constraining
  40404. // width.
  40405. : availableInnerWidth : // Current available width is enough, so no need to
  40406. // constrain.
  40407. null;
  40408. label.setStyle('width', newWidth);
  40409. }
  40410. var newRect = label.getBoundingRect();
  40411. textRect.width = newRect.width;
  40412. var margin = (label.style.margin || 0) + 2.1;
  40413. textRect.height = newRect.height + margin;
  40414. textRect.y -= (textRect.height - oldHeight) / 2;
  40415. }
  40416. }
  40417. function isPositionCenter(sectorShape) {
  40418. // Not change x for center label
  40419. return sectorShape.position === 'center';
  40420. }
  40421. function pieLabelLayout(seriesModel) {
  40422. var data = seriesModel.getData();
  40423. var labelLayoutList = [];
  40424. var cx;
  40425. var cy;
  40426. var hasLabelRotate = false;
  40427. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  40428. var viewRect = data.getLayout('viewRect');
  40429. var r = data.getLayout('r');
  40430. var viewWidth = viewRect.width;
  40431. var viewLeft = viewRect.x;
  40432. var viewTop = viewRect.y;
  40433. var viewHeight = viewRect.height;
  40434. function setNotShow(el) {
  40435. el.ignore = true;
  40436. }
  40437. function isLabelShown(label) {
  40438. if (!label.ignore) {
  40439. return true;
  40440. }
  40441. for (var key in label.states) {
  40442. if (label.states[key].ignore === false) {
  40443. return true;
  40444. }
  40445. }
  40446. return false;
  40447. }
  40448. data.each(function (idx) {
  40449. var sector = data.getItemGraphicEl(idx);
  40450. var sectorShape = sector.shape;
  40451. var label = sector.getTextContent();
  40452. var labelLine = sector.getTextGuideLine();
  40453. var itemModel = data.getItemModel(idx);
  40454. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  40455. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  40456. var labelDistance = labelModel.get('distanceToLabelLine');
  40457. var labelAlignTo = labelModel.get('alignTo');
  40458. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  40459. var bleedMargin = labelModel.get('bleedMargin');
  40460. var labelLineModel = itemModel.getModel('labelLine');
  40461. var labelLineLen = labelLineModel.get('length');
  40462. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  40463. var labelLineLen2 = labelLineModel.get('length2');
  40464. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  40465. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  40466. each(label.states, setNotShow);
  40467. label.ignore = true;
  40468. if (labelLine) {
  40469. each(labelLine.states, setNotShow);
  40470. labelLine.ignore = true;
  40471. }
  40472. return;
  40473. }
  40474. if (!isLabelShown(label)) {
  40475. return;
  40476. }
  40477. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  40478. var nx = Math.cos(midAngle);
  40479. var ny = Math.sin(midAngle);
  40480. var textX;
  40481. var textY;
  40482. var linePoints;
  40483. var textAlign;
  40484. cx = sectorShape.cx;
  40485. cy = sectorShape.cy;
  40486. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  40487. if (labelPosition === 'center') {
  40488. textX = sectorShape.cx;
  40489. textY = sectorShape.cy;
  40490. textAlign = 'center';
  40491. } else {
  40492. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  40493. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  40494. textX = x1 + nx * 3;
  40495. textY = y1 + ny * 3;
  40496. if (!isLabelInside) {
  40497. // For roseType
  40498. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  40499. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  40500. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  40501. var y3 = y2;
  40502. if (labelAlignTo === 'edge') {
  40503. // Adjust textX because text align of edge is opposite
  40504. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  40505. } else {
  40506. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  40507. }
  40508. textY = y3;
  40509. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  40510. }
  40511. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  40512. }
  40513. var PI = Math.PI;
  40514. var labelRotate = 0;
  40515. var rotate = labelModel.get('rotate');
  40516. if (isNumber(rotate)) {
  40517. labelRotate = rotate * (PI / 180);
  40518. } else if (labelPosition === 'center') {
  40519. labelRotate = 0;
  40520. } else if (rotate === 'radial' || rotate === true) {
  40521. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  40522. labelRotate = radialAngle;
  40523. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  40524. var rad = Math.atan2(nx, ny);
  40525. if (rad < 0) {
  40526. rad = PI * 2 + rad;
  40527. }
  40528. var isDown = ny > 0;
  40529. if (isDown) {
  40530. rad = PI + rad;
  40531. }
  40532. labelRotate = rad - PI;
  40533. }
  40534. hasLabelRotate = !!labelRotate;
  40535. label.x = textX;
  40536. label.y = textY;
  40537. label.rotation = labelRotate;
  40538. label.setStyle({
  40539. verticalAlign: 'middle'
  40540. }); // Not sectorShape the inside label
  40541. if (!isLabelInside) {
  40542. var textRect = label.getBoundingRect().clone();
  40543. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  40544. var margin = (label.style.margin || 0) + 2.1;
  40545. textRect.y -= margin / 2;
  40546. textRect.height += margin;
  40547. labelLayoutList.push({
  40548. label: label,
  40549. labelLine: labelLine,
  40550. position: labelPosition,
  40551. len: labelLineLen,
  40552. len2: labelLineLen2,
  40553. minTurnAngle: labelLineModel.get('minTurnAngle'),
  40554. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  40555. surfaceNormal: new Point(nx, ny),
  40556. linePoints: linePoints,
  40557. textAlign: textAlign,
  40558. labelDistance: labelDistance,
  40559. labelAlignTo: labelAlignTo,
  40560. edgeDistance: edgeDistance,
  40561. bleedMargin: bleedMargin,
  40562. rect: textRect,
  40563. unconstrainedWidth: textRect.width,
  40564. labelStyleWidth: label.style.width
  40565. });
  40566. } else {
  40567. label.setStyle({
  40568. align: textAlign
  40569. });
  40570. var selectState = label.states.select;
  40571. if (selectState) {
  40572. selectState.x += label.x;
  40573. selectState.y += label.y;
  40574. }
  40575. }
  40576. sector.setTextConfig({
  40577. inside: isLabelInside
  40578. });
  40579. });
  40580. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  40581. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  40582. }
  40583. for (var i = 0; i < labelLayoutList.length; i++) {
  40584. var layout = labelLayoutList[i];
  40585. var label = layout.label;
  40586. var labelLine = layout.labelLine;
  40587. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  40588. if (label) {
  40589. label.setStyle({
  40590. align: layout.textAlign
  40591. });
  40592. if (notShowLabel) {
  40593. each(label.states, setNotShow);
  40594. label.ignore = true;
  40595. }
  40596. var selectState = label.states.select;
  40597. if (selectState) {
  40598. selectState.x += label.x;
  40599. selectState.y += label.y;
  40600. }
  40601. }
  40602. if (labelLine) {
  40603. var linePoints = layout.linePoints;
  40604. if (notShowLabel || !linePoints) {
  40605. each(labelLine.states, setNotShow);
  40606. labelLine.ignore = true;
  40607. } else {
  40608. limitTurnAngle(linePoints, layout.minTurnAngle);
  40609. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  40610. labelLine.setShape({
  40611. points: linePoints
  40612. }); // Set the anchor to the midpoint of sector
  40613. label.__hostTarget.textGuideLineConfig = {
  40614. anchor: new Point(linePoints[0][0], linePoints[0][1])
  40615. };
  40616. }
  40617. }
  40618. }
  40619. }
  40620. /**
  40621. * Piece of pie including Sector, Label, LabelLine
  40622. */
  40623. var PiePiece =
  40624. /** @class */
  40625. function (_super) {
  40626. __extends(PiePiece, _super);
  40627. function PiePiece(data, idx, startAngle) {
  40628. var _this = _super.call(this) || this;
  40629. _this.z2 = 2;
  40630. var text = new ZRText();
  40631. _this.setTextContent(text);
  40632. _this.updateData(data, idx, startAngle, true);
  40633. return _this;
  40634. }
  40635. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  40636. var sector = this;
  40637. var seriesModel = data.hostModel;
  40638. var itemModel = data.getItemModel(idx);
  40639. var emphasisModel = itemModel.getModel('emphasis');
  40640. var layout = data.getItemLayout(idx); // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  40641. // see `setItemLayout` in `pieLayout.ts`.
  40642. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout); // Ignore NaN data.
  40643. if (isNaN(sectorShape.startAngle)) {
  40644. // Use NaN shape to avoid drawing shape.
  40645. sector.setShape(sectorShape);
  40646. return;
  40647. }
  40648. if (firstCreate) {
  40649. sector.setShape(sectorShape);
  40650. var animationType = seriesModel.getShallow('animationType');
  40651. if (seriesModel.ecModel.ssr) {
  40652. // Use scale animation in SSR mode(opacity?)
  40653. // Because CSS SVG animation doesn't support very customized shape animation.
  40654. initProps(sector, {
  40655. scaleX: 0,
  40656. scaleY: 0
  40657. }, seriesModel, {
  40658. dataIndex: idx,
  40659. isFrom: true
  40660. });
  40661. sector.originX = sectorShape.cx;
  40662. sector.originY = sectorShape.cy;
  40663. } else if (animationType === 'scale') {
  40664. sector.shape.r = layout.r0;
  40665. initProps(sector, {
  40666. shape: {
  40667. r: layout.r
  40668. }
  40669. }, seriesModel, idx);
  40670. } // Expansion
  40671. else {
  40672. if (startAngle != null) {
  40673. sector.setShape({
  40674. startAngle: startAngle,
  40675. endAngle: startAngle
  40676. });
  40677. initProps(sector, {
  40678. shape: {
  40679. startAngle: layout.startAngle,
  40680. endAngle: layout.endAngle
  40681. }
  40682. }, seriesModel, idx);
  40683. } else {
  40684. sector.shape.endAngle = layout.startAngle;
  40685. updateProps(sector, {
  40686. shape: {
  40687. endAngle: layout.endAngle
  40688. }
  40689. }, seriesModel, idx);
  40690. }
  40691. }
  40692. } else {
  40693. saveOldStyle(sector); // Transition animation from the old shape
  40694. updateProps(sector, {
  40695. shape: sectorShape
  40696. }, seriesModel, idx);
  40697. }
  40698. sector.useStyle(data.getItemVisual(idx, 'style'));
  40699. setStatesStylesFromModel(sector, itemModel);
  40700. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  40701. var offset = seriesModel.get('selectedOffset');
  40702. var dx = Math.cos(midAngle) * offset;
  40703. var dy = Math.sin(midAngle) * offset;
  40704. var cursorStyle = itemModel.getShallow('cursor');
  40705. cursorStyle && sector.attr('cursor', cursorStyle);
  40706. this._updateLabel(seriesModel, data, idx);
  40707. sector.ensureState('emphasis').shape = extend({
  40708. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  40709. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  40710. extend(sector.ensureState('select'), {
  40711. x: dx,
  40712. y: dy,
  40713. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  40714. });
  40715. extend(sector.ensureState('blur'), {
  40716. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  40717. });
  40718. var labelLine = sector.getTextGuideLine();
  40719. var labelText = sector.getTextContent();
  40720. labelLine && extend(labelLine.ensureState('select'), {
  40721. x: dx,
  40722. y: dy
  40723. }); // TODO: needs dx, dy in zrender?
  40724. extend(labelText.ensureState('select'), {
  40725. x: dx,
  40726. y: dy
  40727. });
  40728. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  40729. };
  40730. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  40731. var sector = this;
  40732. var itemModel = data.getItemModel(idx);
  40733. var labelLineModel = itemModel.getModel('labelLine');
  40734. var style = data.getItemVisual(idx, 'style');
  40735. var visualColor = style && style.fill;
  40736. var visualOpacity = style && style.opacity;
  40737. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  40738. labelFetcher: data.hostModel,
  40739. labelDataIndex: idx,
  40740. inheritColor: visualColor,
  40741. defaultOpacity: visualOpacity,
  40742. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  40743. });
  40744. var labelText = sector.getTextContent(); // Set textConfig on sector.
  40745. sector.setTextConfig({
  40746. // reset position, rotation
  40747. position: null,
  40748. rotation: null
  40749. }); // Make sure update style on labelText after setLabelStyle.
  40750. // Because setLabelStyle will replace a new style on it.
  40751. labelText.attr({
  40752. z2: 10
  40753. });
  40754. var labelPosition = seriesModel.get(['label', 'position']);
  40755. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  40756. sector.removeTextGuideLine();
  40757. } else {
  40758. var polyline = this.getTextGuideLine();
  40759. if (!polyline) {
  40760. polyline = new Polyline();
  40761. this.setTextGuideLine(polyline);
  40762. } // Default use item visual color
  40763. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  40764. stroke: visualColor,
  40765. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  40766. });
  40767. }
  40768. };
  40769. return PiePiece;
  40770. }(Sector); // Pie view
  40771. var PieView =
  40772. /** @class */
  40773. function (_super) {
  40774. __extends(PieView, _super);
  40775. function PieView() {
  40776. var _this = _super !== null && _super.apply(this, arguments) || this;
  40777. _this.ignoreLabelLineUpdate = true;
  40778. return _this;
  40779. }
  40780. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  40781. var data = seriesModel.getData();
  40782. var oldData = this._data;
  40783. var group = this.group;
  40784. var startAngle; // First render
  40785. if (!oldData && data.count() > 0) {
  40786. var shape = data.getItemLayout(0);
  40787. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  40788. shape = data.getItemLayout(s);
  40789. }
  40790. if (shape) {
  40791. startAngle = shape.startAngle;
  40792. }
  40793. } // remove empty-circle if it exists
  40794. if (this._emptyCircleSector) {
  40795. group.remove(this._emptyCircleSector);
  40796. } // when all data are filtered, show lightgray empty circle
  40797. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  40798. var sector = new Sector({
  40799. shape: getBasicPieLayout(seriesModel, api)
  40800. });
  40801. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  40802. this._emptyCircleSector = sector;
  40803. group.add(sector);
  40804. }
  40805. data.diff(oldData).add(function (idx) {
  40806. var piePiece = new PiePiece(data, idx, startAngle);
  40807. data.setItemGraphicEl(idx, piePiece);
  40808. group.add(piePiece);
  40809. }).update(function (newIdx, oldIdx) {
  40810. var piePiece = oldData.getItemGraphicEl(oldIdx);
  40811. piePiece.updateData(data, newIdx, startAngle);
  40812. piePiece.off('click');
  40813. group.add(piePiece);
  40814. data.setItemGraphicEl(newIdx, piePiece);
  40815. }).remove(function (idx) {
  40816. var piePiece = oldData.getItemGraphicEl(idx);
  40817. removeElementWithFadeOut(piePiece, seriesModel, idx);
  40818. }).execute();
  40819. pieLabelLayout(seriesModel); // Always use initial animation.
  40820. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  40821. this._data = data;
  40822. }
  40823. };
  40824. PieView.prototype.dispose = function () {};
  40825. PieView.prototype.containPoint = function (point, seriesModel) {
  40826. var data = seriesModel.getData();
  40827. var itemLayout = data.getItemLayout(0);
  40828. if (itemLayout) {
  40829. var dx = point[0] - itemLayout.cx;
  40830. var dy = point[1] - itemLayout.cy;
  40831. var radius = Math.sqrt(dx * dx + dy * dy);
  40832. return radius <= itemLayout.r && radius >= itemLayout.r0;
  40833. }
  40834. };
  40835. PieView.type = 'pie';
  40836. return PieView;
  40837. }(ChartView);
  40838. /**
  40839. * [Usage]:
  40840. * (1)
  40841. * createListSimply(seriesModel, ['value']);
  40842. * (2)
  40843. * createListSimply(seriesModel, {
  40844. * coordDimensions: ['value'],
  40845. * dimensionsCount: 5
  40846. * });
  40847. */
  40848. function createSeriesDataSimply(seriesModel, opt, nameList) {
  40849. opt = isArray(opt) && {
  40850. coordDimensions: opt
  40851. } || extend({
  40852. encodeDefine: seriesModel.getEncode()
  40853. }, opt);
  40854. var source = seriesModel.getSource();
  40855. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  40856. var list = new SeriesData(dimensions, seriesModel);
  40857. list.initData(source, nameList);
  40858. return list;
  40859. }
  40860. /*
  40861. * Licensed to the Apache Software Foundation (ASF) under one
  40862. * or more contributor license agreements. See the NOTICE file
  40863. * distributed with this work for additional information
  40864. * regarding copyright ownership. The ASF licenses this file
  40865. * to you under the Apache License, Version 2.0 (the
  40866. * "License"); you may not use this file except in compliance
  40867. * with the License. You may obtain a copy of the License at
  40868. *
  40869. * http://www.apache.org/licenses/LICENSE-2.0
  40870. *
  40871. * Unless required by applicable law or agreed to in writing,
  40872. * software distributed under the License is distributed on an
  40873. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40874. * KIND, either express or implied. See the License for the
  40875. * specific language governing permissions and limitations
  40876. * under the License.
  40877. */
  40878. /**
  40879. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40880. */
  40881. /*
  40882. * Licensed to the Apache Software Foundation (ASF) under one
  40883. * or more contributor license agreements. See the NOTICE file
  40884. * distributed with this work for additional information
  40885. * regarding copyright ownership. The ASF licenses this file
  40886. * to you under the Apache License, Version 2.0 (the
  40887. * "License"); you may not use this file except in compliance
  40888. * with the License. You may obtain a copy of the License at
  40889. *
  40890. * http://www.apache.org/licenses/LICENSE-2.0
  40891. *
  40892. * Unless required by applicable law or agreed to in writing,
  40893. * software distributed under the License is distributed on an
  40894. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40895. * KIND, either express or implied. See the License for the
  40896. * specific language governing permissions and limitations
  40897. * under the License.
  40898. */
  40899. /**
  40900. * LegendVisualProvider is an bridge that pick encoded color from data and
  40901. * provide to the legend component.
  40902. */
  40903. var LegendVisualProvider =
  40904. /** @class */
  40905. function () {
  40906. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  40907. getDataWithEncodedVisual, // Function to get raw data before filtered.
  40908. getRawData) {
  40909. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  40910. this._getRawData = getRawData;
  40911. }
  40912. LegendVisualProvider.prototype.getAllNames = function () {
  40913. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  40914. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  40915. return rawData.mapArray(rawData.getName);
  40916. };
  40917. LegendVisualProvider.prototype.containName = function (name) {
  40918. var rawData = this._getRawData();
  40919. return rawData.indexOfName(name) >= 0;
  40920. };
  40921. LegendVisualProvider.prototype.indexOfName = function (name) {
  40922. // Only get data when necessary.
  40923. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  40924. // Invoking Series#getData immediately will throw an error.
  40925. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  40926. return dataWithEncodedVisual.indexOfName(name);
  40927. };
  40928. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  40929. // Get encoded visual properties from final filtered data.
  40930. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  40931. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  40932. };
  40933. return LegendVisualProvider;
  40934. }();
  40935. var innerData = makeInner();
  40936. var PieSeriesModel =
  40937. /** @class */
  40938. function (_super) {
  40939. __extends(PieSeriesModel, _super);
  40940. function PieSeriesModel() {
  40941. return _super !== null && _super.apply(this, arguments) || this;
  40942. }
  40943. /**
  40944. * @overwrite
  40945. */
  40946. PieSeriesModel.prototype.init = function (option) {
  40947. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  40948. // Use a function instead of direct access because data reference may changed
  40949. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  40950. this._defaultLabelLine(option);
  40951. };
  40952. /**
  40953. * @overwrite
  40954. */
  40955. PieSeriesModel.prototype.mergeOption = function () {
  40956. _super.prototype.mergeOption.apply(this, arguments);
  40957. };
  40958. /**
  40959. * @overwrite
  40960. */
  40961. PieSeriesModel.prototype.getInitialData = function () {
  40962. return createSeriesDataSimply(this, {
  40963. coordDimensions: ['value'],
  40964. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  40965. });
  40966. };
  40967. /**
  40968. * @overwrite
  40969. */
  40970. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  40971. var data = this.getData(); // update seats when data is changed
  40972. var dataInner = innerData(data);
  40973. var seats = dataInner.seats;
  40974. if (!seats) {
  40975. var valueList_1 = [];
  40976. data.each(data.mapDimension('value'), function (value) {
  40977. valueList_1.push(value);
  40978. });
  40979. seats = dataInner.seats = getPercentSeats(valueList_1, data.hostModel.get('percentPrecision'));
  40980. }
  40981. var params = _super.prototype.getDataParams.call(this, dataIndex); // seats may be empty when sum is 0
  40982. params.percent = seats[dataIndex] || 0;
  40983. params.$vars.push('percent');
  40984. return params;
  40985. };
  40986. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  40987. // Extend labelLine emphasis
  40988. defaultEmphasis(option, 'labelLine', ['show']);
  40989. var labelLineNormalOpt = option.labelLine;
  40990. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  40991. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  40992. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  40993. };
  40994. PieSeriesModel.type = 'series.pie';
  40995. PieSeriesModel.defaultOption = {
  40996. // zlevel: 0,
  40997. z: 2,
  40998. legendHoverLink: true,
  40999. colorBy: 'data',
  41000. // 默认全局居中
  41001. center: ['50%', '50%'],
  41002. radius: [0, '75%'],
  41003. // 默认顺时针
  41004. clockwise: true,
  41005. startAngle: 90,
  41006. // 最小角度改为0
  41007. minAngle: 0,
  41008. // If the angle of a sector less than `minShowLabelAngle`,
  41009. // the label will not be displayed.
  41010. minShowLabelAngle: 0,
  41011. // 选中时扇区偏移量
  41012. selectedOffset: 10,
  41013. // 选择模式,默认关闭,可选single,multiple
  41014. // selectedMode: false,
  41015. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  41016. // roseType: null,
  41017. percentPrecision: 2,
  41018. // If still show when all data zero.
  41019. stillShowZeroSum: true,
  41020. // cursor: null,
  41021. left: 0,
  41022. top: 0,
  41023. right: 0,
  41024. bottom: 0,
  41025. width: null,
  41026. height: null,
  41027. label: {
  41028. // color: 'inherit',
  41029. // If rotate around circle
  41030. rotate: 0,
  41031. show: true,
  41032. overflow: 'truncate',
  41033. // 'outer', 'inside', 'center'
  41034. position: 'outer',
  41035. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  41036. alignTo: 'none',
  41037. // Closest distance between label and chart edge.
  41038. // Works only position is 'outer' and alignTo is 'edge'.
  41039. edgeDistance: '25%',
  41040. // Works only position is 'outer' and alignTo is not 'edge'.
  41041. bleedMargin: 10,
  41042. // Distance between text and label line.
  41043. distanceToLabelLine: 5 // formatter: 标签文本格式器,同 tooltip.formatter,不支持异步回调
  41044. // 默认使用全局文本样式,详见 textStyle
  41045. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  41046. },
  41047. // Enabled when label.normal.position is 'outer'
  41048. labelLine: {
  41049. show: true,
  41050. // 引导线两段中的第一段长度
  41051. length: 15,
  41052. // 引导线两段中的第二段长度
  41053. length2: 15,
  41054. smooth: false,
  41055. minTurnAngle: 90,
  41056. maxSurfaceAngle: 90,
  41057. lineStyle: {
  41058. // color: 各异,
  41059. width: 1,
  41060. type: 'solid'
  41061. }
  41062. },
  41063. itemStyle: {
  41064. borderWidth: 1,
  41065. borderJoin: 'round'
  41066. },
  41067. showEmptyCircle: true,
  41068. emptyCircleStyle: {
  41069. color: 'lightgray',
  41070. opacity: 1
  41071. },
  41072. labelLayout: {
  41073. // Hide the overlapped label.
  41074. hideOverlap: true
  41075. },
  41076. emphasis: {
  41077. scale: true,
  41078. scaleSize: 5
  41079. },
  41080. // If use strategy to avoid label overlapping
  41081. avoidLabelOverlap: true,
  41082. // Animation type. Valid values: expansion, scale
  41083. animationType: 'expansion',
  41084. animationDuration: 1000,
  41085. // Animation type when update. Valid values: transition, expansion
  41086. animationTypeUpdate: 'transition',
  41087. animationEasingUpdate: 'cubicInOut',
  41088. animationDurationUpdate: 500,
  41089. animationEasing: 'cubicInOut'
  41090. };
  41091. return PieSeriesModel;
  41092. }(SeriesModel);
  41093. function negativeDataFilter(seriesType) {
  41094. return {
  41095. seriesType: seriesType,
  41096. reset: function (seriesModel, ecModel) {
  41097. var data = seriesModel.getData();
  41098. data.filterSelf(function (idx) {
  41099. // handle negative value condition
  41100. var valueDim = data.mapDimension('value');
  41101. var curValue = data.get(valueDim, idx);
  41102. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  41103. return false;
  41104. }
  41105. return true;
  41106. });
  41107. }
  41108. };
  41109. }
  41110. function install$4(registers) {
  41111. registers.registerChartView(PieView);
  41112. registers.registerSeriesModel(PieSeriesModel);
  41113. createLegacyDataSelectAction('pie', registers.registerAction);
  41114. registers.registerLayout(curry(pieLayout, 'pie'));
  41115. registers.registerProcessor(dataFilter('pie'));
  41116. registers.registerProcessor(negativeDataFilter('pie'));
  41117. }
  41118. var ScatterSeriesModel =
  41119. /** @class */
  41120. function (_super) {
  41121. __extends(ScatterSeriesModel, _super);
  41122. function ScatterSeriesModel() {
  41123. var _this = _super !== null && _super.apply(this, arguments) || this;
  41124. _this.type = ScatterSeriesModel.type;
  41125. _this.hasSymbolVisual = true;
  41126. return _this;
  41127. }
  41128. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  41129. return createSeriesData(null, this, {
  41130. useEncodeDefaulter: true
  41131. });
  41132. };
  41133. ScatterSeriesModel.prototype.getProgressive = function () {
  41134. var progressive = this.option.progressive;
  41135. if (progressive == null) {
  41136. // PENDING
  41137. return this.option.large ? 5e3 : this.get('progressive');
  41138. }
  41139. return progressive;
  41140. };
  41141. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  41142. var progressiveThreshold = this.option.progressiveThreshold;
  41143. if (progressiveThreshold == null) {
  41144. // PENDING
  41145. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  41146. }
  41147. return progressiveThreshold;
  41148. };
  41149. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  41150. return selectors.point(data.getItemLayout(dataIndex));
  41151. };
  41152. ScatterSeriesModel.prototype.getZLevelKey = function () {
  41153. // Each progressive series has individual key.
  41154. return this.getData().count() > this.getProgressiveThreshold() ? this.id : '';
  41155. };
  41156. ScatterSeriesModel.type = 'series.scatter';
  41157. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  41158. ScatterSeriesModel.defaultOption = {
  41159. coordinateSystem: 'cartesian2d',
  41160. // zlevel: 0,
  41161. z: 2,
  41162. legendHoverLink: true,
  41163. symbolSize: 10,
  41164. // symbolRotate: null, // 图形旋转控制
  41165. large: false,
  41166. // Available when large is true
  41167. largeThreshold: 2000,
  41168. // cursor: null,
  41169. itemStyle: {
  41170. opacity: 0.8 // color: 各异
  41171. },
  41172. emphasis: {
  41173. scale: true
  41174. },
  41175. // If clip the overflow graphics
  41176. // Works on cartesian / polar series
  41177. clip: true,
  41178. select: {
  41179. itemStyle: {
  41180. borderColor: '#212121'
  41181. }
  41182. },
  41183. universalTransition: {
  41184. divideShape: 'clone'
  41185. } // progressive: null
  41186. };
  41187. return ScatterSeriesModel;
  41188. }(SeriesModel);
  41189. var BOOST_SIZE_THRESHOLD = 4;
  41190. var LargeSymbolPathShape =
  41191. /** @class */
  41192. function () {
  41193. function LargeSymbolPathShape() {}
  41194. return LargeSymbolPathShape;
  41195. }();
  41196. var LargeSymbolPath =
  41197. /** @class */
  41198. function (_super) {
  41199. __extends(LargeSymbolPath, _super);
  41200. function LargeSymbolPath(opts) {
  41201. var _this = _super.call(this, opts) || this;
  41202. _this._off = 0;
  41203. _this.hoverDataIdx = -1;
  41204. return _this;
  41205. }
  41206. LargeSymbolPath.prototype.getDefaultShape = function () {
  41207. return new LargeSymbolPathShape();
  41208. };
  41209. LargeSymbolPath.prototype.reset = function () {
  41210. this.notClear = false;
  41211. this._off = 0;
  41212. };
  41213. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  41214. var points = shape.points;
  41215. var size = shape.size;
  41216. var symbolProxy = this.symbolProxy;
  41217. var symbolProxyShape = symbolProxy.shape;
  41218. var ctx = path.getContext ? path.getContext() : path;
  41219. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  41220. var softClipShape = this.softClipShape;
  41221. var i; // Do draw in afterBrush.
  41222. if (canBoost) {
  41223. this._ctx = ctx;
  41224. return;
  41225. }
  41226. this._ctx = null;
  41227. for (i = this._off; i < points.length;) {
  41228. var x = points[i++];
  41229. var y = points[i++];
  41230. if (isNaN(x) || isNaN(y)) {
  41231. continue;
  41232. }
  41233. if (softClipShape && !softClipShape.contain(x, y)) {
  41234. continue;
  41235. }
  41236. symbolProxyShape.x = x - size[0] / 2;
  41237. symbolProxyShape.y = y - size[1] / 2;
  41238. symbolProxyShape.width = size[0];
  41239. symbolProxyShape.height = size[1];
  41240. symbolProxy.buildPath(path, symbolProxyShape, true);
  41241. }
  41242. if (this.incremental) {
  41243. this._off = i;
  41244. this.notClear = true;
  41245. }
  41246. };
  41247. LargeSymbolPath.prototype.afterBrush = function () {
  41248. var shape = this.shape;
  41249. var points = shape.points;
  41250. var size = shape.size;
  41251. var ctx = this._ctx;
  41252. var softClipShape = this.softClipShape;
  41253. var i;
  41254. if (!ctx) {
  41255. return;
  41256. } // PENDING If style or other canvas status changed?
  41257. for (i = this._off; i < points.length;) {
  41258. var x = points[i++];
  41259. var y = points[i++];
  41260. if (isNaN(x) || isNaN(y)) {
  41261. continue;
  41262. }
  41263. if (softClipShape && !softClipShape.contain(x, y)) {
  41264. continue;
  41265. } // fillRect is faster than building a rect path and draw.
  41266. // And it support light globalCompositeOperation.
  41267. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  41268. }
  41269. if (this.incremental) {
  41270. this._off = i;
  41271. this.notClear = true;
  41272. }
  41273. };
  41274. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  41275. // TODO ???
  41276. // Consider transform
  41277. var shape = this.shape;
  41278. var points = shape.points;
  41279. var size = shape.size;
  41280. var w = Math.max(size[0], 4);
  41281. var h = Math.max(size[1], 4); // Not consider transform
  41282. // Treat each element as a rect
  41283. // top down traverse
  41284. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  41285. var i = idx * 2;
  41286. var x0 = points[i] - w / 2;
  41287. var y0 = points[i + 1] - h / 2;
  41288. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  41289. return idx;
  41290. }
  41291. }
  41292. return -1;
  41293. };
  41294. LargeSymbolPath.prototype.contain = function (x, y) {
  41295. var localPos = this.transformCoordToLocal(x, y);
  41296. var rect = this.getBoundingRect();
  41297. x = localPos[0];
  41298. y = localPos[1];
  41299. if (rect.contain(x, y)) {
  41300. // Cache found data index.
  41301. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  41302. return dataIdx >= 0;
  41303. }
  41304. this.hoverDataIdx = -1;
  41305. return false;
  41306. };
  41307. LargeSymbolPath.prototype.getBoundingRect = function () {
  41308. // Ignore stroke for large symbol draw.
  41309. var rect = this._rect;
  41310. if (!rect) {
  41311. var shape = this.shape;
  41312. var points = shape.points;
  41313. var size = shape.size;
  41314. var w = size[0];
  41315. var h = size[1];
  41316. var minX = Infinity;
  41317. var minY = Infinity;
  41318. var maxX = -Infinity;
  41319. var maxY = -Infinity;
  41320. for (var i = 0; i < points.length;) {
  41321. var x = points[i++];
  41322. var y = points[i++];
  41323. minX = Math.min(x, minX);
  41324. maxX = Math.max(x, maxX);
  41325. minY = Math.min(y, minY);
  41326. maxY = Math.max(y, maxY);
  41327. }
  41328. rect = this._rect = new BoundingRect(minX - w / 2, minY - h / 2, maxX - minX + w, maxY - minY + h);
  41329. }
  41330. return rect;
  41331. };
  41332. return LargeSymbolPath;
  41333. }(Path);
  41334. var LargeSymbolDraw =
  41335. /** @class */
  41336. function () {
  41337. function LargeSymbolDraw() {
  41338. this.group = new Group();
  41339. }
  41340. /**
  41341. * Update symbols draw by new data
  41342. */
  41343. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  41344. this._clear();
  41345. var symbolEl = this._create();
  41346. symbolEl.setShape({
  41347. points: data.getLayout('points')
  41348. });
  41349. this._setCommon(symbolEl, data, opt);
  41350. };
  41351. LargeSymbolDraw.prototype.updateLayout = function (data) {
  41352. var points = data.getLayout('points');
  41353. this.group.eachChild(function (child) {
  41354. if (child.startIndex != null) {
  41355. var len = (child.endIndex - child.startIndex) * 2;
  41356. var byteOffset = child.startIndex * 4 * 2;
  41357. points = new Float32Array(points.buffer, byteOffset, len);
  41358. }
  41359. child.setShape('points', points); // Reset draw cursor.
  41360. child.reset();
  41361. });
  41362. };
  41363. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  41364. this._clear();
  41365. };
  41366. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  41367. var lastAdded = this._newAdded[0];
  41368. var points = data.getLayout('points');
  41369. var oldPoints = lastAdded && lastAdded.shape.points; // Merging the exists. Each element has 1e4 points.
  41370. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  41371. if (oldPoints && oldPoints.length < 2e4) {
  41372. var oldLen = oldPoints.length;
  41373. var newPoints = new Float32Array(oldLen + points.length); // Concat two array
  41374. newPoints.set(oldPoints);
  41375. newPoints.set(points, oldLen); // Update endIndex
  41376. lastAdded.endIndex = taskParams.end;
  41377. lastAdded.setShape({
  41378. points: newPoints
  41379. });
  41380. } else {
  41381. // Clear
  41382. this._newAdded = [];
  41383. var symbolEl = this._create();
  41384. symbolEl.startIndex = taskParams.start;
  41385. symbolEl.endIndex = taskParams.end;
  41386. symbolEl.incremental = true;
  41387. symbolEl.setShape({
  41388. points: points
  41389. });
  41390. this._setCommon(symbolEl, data, opt);
  41391. }
  41392. };
  41393. LargeSymbolDraw.prototype.eachRendered = function (cb) {
  41394. this._newAdded[0] && cb(this._newAdded[0]);
  41395. };
  41396. LargeSymbolDraw.prototype._create = function () {
  41397. var symbolEl = new LargeSymbolPath({
  41398. cursor: 'default'
  41399. });
  41400. symbolEl.ignoreCoarsePointer = true;
  41401. this.group.add(symbolEl);
  41402. this._newAdded.push(symbolEl);
  41403. return symbolEl;
  41404. };
  41405. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, opt) {
  41406. var hostModel = data.hostModel;
  41407. opt = opt || {};
  41408. var size = data.getVisual('symbolSize');
  41409. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  41410. symbolEl.softClipShape = opt.clipShape || null; // Create symbolProxy to build path for each data
  41411. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0); // Use symbolProxy setColor method
  41412. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  41413. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  41414. symbolEl.useStyle( // Draw shadow when doing fillRect is extremely slow.
  41415. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  41416. var globalStyle = data.getVisual('style');
  41417. var visualColor = globalStyle && globalStyle.fill;
  41418. if (visualColor) {
  41419. symbolEl.setColor(visualColor);
  41420. }
  41421. var ecData = getECData(symbolEl); // Enable tooltip
  41422. // PENDING May have performance issue when path is extremely large
  41423. ecData.seriesIndex = hostModel.seriesIndex;
  41424. symbolEl.on('mousemove', function (e) {
  41425. ecData.dataIndex = null;
  41426. var dataIndex = symbolEl.hoverDataIdx;
  41427. if (dataIndex >= 0) {
  41428. // Provide dataIndex for tooltip
  41429. ecData.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  41430. }
  41431. });
  41432. };
  41433. LargeSymbolDraw.prototype.remove = function () {
  41434. this._clear();
  41435. };
  41436. LargeSymbolDraw.prototype._clear = function () {
  41437. this._newAdded = [];
  41438. this.group.removeAll();
  41439. };
  41440. return LargeSymbolDraw;
  41441. }();
  41442. var ScatterView =
  41443. /** @class */
  41444. function (_super) {
  41445. __extends(ScatterView, _super);
  41446. function ScatterView() {
  41447. var _this = _super !== null && _super.apply(this, arguments) || this;
  41448. _this.type = ScatterView.type;
  41449. return _this;
  41450. }
  41451. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  41452. var data = seriesModel.getData();
  41453. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41454. symbolDraw.updateData(data, {
  41455. // TODO
  41456. // If this parameter should be a shape or a bounding volume
  41457. // shape will be more general.
  41458. // But bounding volume like bounding rect will be much faster in the contain calculation
  41459. clipShape: this._getClipShape(seriesModel)
  41460. });
  41461. this._finished = true;
  41462. };
  41463. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  41464. var data = seriesModel.getData();
  41465. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41466. symbolDraw.incrementalPrepareUpdate(data);
  41467. this._finished = false;
  41468. };
  41469. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  41470. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  41471. clipShape: this._getClipShape(seriesModel)
  41472. });
  41473. this._finished = taskParams.end === seriesModel.getData().count();
  41474. };
  41475. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  41476. var data = seriesModel.getData(); // Must mark group dirty and make sure the incremental layer will be cleared
  41477. // PENDING
  41478. this.group.dirty();
  41479. if (!this._finished || data.count() > 1e4) {
  41480. return {
  41481. update: true
  41482. };
  41483. } else {
  41484. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  41485. if (res.progress) {
  41486. res.progress({
  41487. start: 0,
  41488. end: data.count(),
  41489. count: data.count()
  41490. }, data);
  41491. }
  41492. this._symbolDraw.updateLayout(data);
  41493. }
  41494. };
  41495. ScatterView.prototype.eachRendered = function (cb) {
  41496. this._symbolDraw && this._symbolDraw.eachRendered(cb);
  41497. };
  41498. ScatterView.prototype._getClipShape = function (seriesModel) {
  41499. var coordSys = seriesModel.coordinateSystem;
  41500. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  41501. return seriesModel.get('clip', true) ? clipArea : null;
  41502. };
  41503. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  41504. var symbolDraw = this._symbolDraw;
  41505. var pipelineContext = seriesModel.pipelineContext;
  41506. var isLargeDraw = pipelineContext.large;
  41507. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  41508. symbolDraw && symbolDraw.remove();
  41509. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  41510. this._isLargeDraw = isLargeDraw;
  41511. this.group.removeAll();
  41512. }
  41513. this.group.add(symbolDraw.group);
  41514. return symbolDraw;
  41515. };
  41516. ScatterView.prototype.remove = function (ecModel, api) {
  41517. this._symbolDraw && this._symbolDraw.remove(true);
  41518. this._symbolDraw = null;
  41519. };
  41520. ScatterView.prototype.dispose = function () {};
  41521. ScatterView.type = 'scatter';
  41522. return ScatterView;
  41523. }(ChartView);
  41524. var GridModel =
  41525. /** @class */
  41526. function (_super) {
  41527. __extends(GridModel, _super);
  41528. function GridModel() {
  41529. return _super !== null && _super.apply(this, arguments) || this;
  41530. }
  41531. GridModel.type = 'grid';
  41532. GridModel.dependencies = ['xAxis', 'yAxis'];
  41533. GridModel.layoutMode = 'box';
  41534. GridModel.defaultOption = {
  41535. show: false,
  41536. // zlevel: 0,
  41537. z: 0,
  41538. left: '10%',
  41539. top: 60,
  41540. right: '10%',
  41541. bottom: 70,
  41542. // If grid size contain label
  41543. containLabel: false,
  41544. // width: {totalWidth} - left - right,
  41545. // height: {totalHeight} - top - bottom,
  41546. backgroundColor: 'rgba(0,0,0,0)',
  41547. borderWidth: 1,
  41548. borderColor: '#ccc'
  41549. };
  41550. return GridModel;
  41551. }(ComponentModel);
  41552. var CartesianAxisModel =
  41553. /** @class */
  41554. function (_super) {
  41555. __extends(CartesianAxisModel, _super);
  41556. function CartesianAxisModel() {
  41557. return _super !== null && _super.apply(this, arguments) || this;
  41558. }
  41559. CartesianAxisModel.prototype.getCoordSysModel = function () {
  41560. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  41561. };
  41562. CartesianAxisModel.type = 'cartesian2dAxis';
  41563. return CartesianAxisModel;
  41564. }(ComponentModel);
  41565. mixin(CartesianAxisModel, AxisModelCommonMixin);
  41566. var defaultOption = {
  41567. show: true,
  41568. // zlevel: 0,
  41569. z: 0,
  41570. // Inverse the axis.
  41571. inverse: false,
  41572. // Axis name displayed.
  41573. name: '',
  41574. // 'start' | 'middle' | 'end'
  41575. nameLocation: 'end',
  41576. // By degree. By default auto rotate by nameLocation.
  41577. nameRotate: null,
  41578. nameTruncate: {
  41579. maxWidth: null,
  41580. ellipsis: '...',
  41581. placeholder: '.'
  41582. },
  41583. // Use global text style by default.
  41584. nameTextStyle: {},
  41585. // The gap between axisName and axisLine.
  41586. nameGap: 15,
  41587. // Default `false` to support tooltip.
  41588. silent: false,
  41589. // Default `false` to avoid legacy user event listener fail.
  41590. triggerEvent: false,
  41591. tooltip: {
  41592. show: false
  41593. },
  41594. axisPointer: {},
  41595. axisLine: {
  41596. show: true,
  41597. onZero: true,
  41598. onZeroAxisIndex: null,
  41599. lineStyle: {
  41600. color: '#6E7079',
  41601. width: 1,
  41602. type: 'solid'
  41603. },
  41604. // The arrow at both ends the the axis.
  41605. symbol: ['none', 'none'],
  41606. symbolSize: [10, 15]
  41607. },
  41608. axisTick: {
  41609. show: true,
  41610. // Whether axisTick is inside the grid or outside the grid.
  41611. inside: false,
  41612. // The length of axisTick.
  41613. length: 5,
  41614. lineStyle: {
  41615. width: 1
  41616. }
  41617. },
  41618. axisLabel: {
  41619. show: true,
  41620. // Whether axisLabel is inside the grid or outside the grid.
  41621. inside: false,
  41622. rotate: 0,
  41623. // true | false | null/undefined (auto)
  41624. showMinLabel: null,
  41625. // true | false | null/undefined (auto)
  41626. showMaxLabel: null,
  41627. margin: 8,
  41628. // formatter: null,
  41629. fontSize: 12
  41630. },
  41631. splitLine: {
  41632. show: true,
  41633. lineStyle: {
  41634. color: ['#E0E6F1'],
  41635. width: 1,
  41636. type: 'solid'
  41637. }
  41638. },
  41639. splitArea: {
  41640. show: false,
  41641. areaStyle: {
  41642. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  41643. }
  41644. }
  41645. };
  41646. var categoryAxis = merge({
  41647. // The gap at both ends of the axis. For categoryAxis, boolean.
  41648. boundaryGap: true,
  41649. // Set false to faster category collection.
  41650. deduplication: null,
  41651. // splitArea: {
  41652. // show: false
  41653. // },
  41654. splitLine: {
  41655. show: false
  41656. },
  41657. axisTick: {
  41658. // If tick is align with label when boundaryGap is true
  41659. alignWithLabel: false,
  41660. interval: 'auto'
  41661. },
  41662. axisLabel: {
  41663. interval: 'auto'
  41664. }
  41665. }, defaultOption);
  41666. var valueAxis = merge({
  41667. boundaryGap: [0, 0],
  41668. axisLine: {
  41669. // Not shown when other axis is categoryAxis in cartesian
  41670. show: 'auto'
  41671. },
  41672. axisTick: {
  41673. // Not shown when other axis is categoryAxis in cartesian
  41674. show: 'auto'
  41675. },
  41676. // TODO
  41677. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  41678. splitNumber: 5,
  41679. minorTick: {
  41680. // Minor tick, not available for cateogry axis.
  41681. show: false,
  41682. // Split number of minor ticks. The value should be in range of (0, 100)
  41683. splitNumber: 5,
  41684. // Length of minor tick
  41685. length: 3,
  41686. // Line style
  41687. lineStyle: {// Default to be same with axisTick
  41688. }
  41689. },
  41690. minorSplitLine: {
  41691. show: false,
  41692. lineStyle: {
  41693. color: '#F4F7FD',
  41694. width: 1
  41695. }
  41696. }
  41697. }, defaultOption);
  41698. var timeAxis = merge({
  41699. splitNumber: 6,
  41700. axisLabel: {
  41701. // To eliminate labels that are not nice
  41702. showMinLabel: false,
  41703. showMaxLabel: false,
  41704. rich: {
  41705. primary: {
  41706. fontWeight: 'bold'
  41707. }
  41708. }
  41709. },
  41710. splitLine: {
  41711. show: false
  41712. }
  41713. }, valueAxis);
  41714. var logAxis = defaults({
  41715. logBase: 10
  41716. }, valueAxis);
  41717. var axisDefault = {
  41718. category: categoryAxis,
  41719. value: valueAxis,
  41720. time: timeAxis,
  41721. log: logAxis
  41722. };
  41723. /*
  41724. * Licensed to the Apache Software Foundation (ASF) under one
  41725. * or more contributor license agreements. See the NOTICE file
  41726. * distributed with this work for additional information
  41727. * regarding copyright ownership. The ASF licenses this file
  41728. * to you under the Apache License, Version 2.0 (the
  41729. * "License"); you may not use this file except in compliance
  41730. * with the License. You may obtain a copy of the License at
  41731. *
  41732. * http://www.apache.org/licenses/LICENSE-2.0
  41733. *
  41734. * Unless required by applicable law or agreed to in writing,
  41735. * software distributed under the License is distributed on an
  41736. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41737. * KIND, either express or implied. See the License for the
  41738. * specific language governing permissions and limitations
  41739. * under the License.
  41740. */
  41741. /**
  41742. * AUTO-GENERATED FILE. DO NOT MODIFY.
  41743. */
  41744. /*
  41745. * Licensed to the Apache Software Foundation (ASF) under one
  41746. * or more contributor license agreements. See the NOTICE file
  41747. * distributed with this work for additional information
  41748. * regarding copyright ownership. The ASF licenses this file
  41749. * to you under the Apache License, Version 2.0 (the
  41750. * "License"); you may not use this file except in compliance
  41751. * with the License. You may obtain a copy of the License at
  41752. *
  41753. * http://www.apache.org/licenses/LICENSE-2.0
  41754. *
  41755. * Unless required by applicable law or agreed to in writing,
  41756. * software distributed under the License is distributed on an
  41757. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41758. * KIND, either express or implied. See the License for the
  41759. * specific language governing permissions and limitations
  41760. * under the License.
  41761. */
  41762. var AXIS_TYPES = {
  41763. value: 1,
  41764. category: 1,
  41765. time: 1,
  41766. log: 1
  41767. };
  41768. /**
  41769. * Generate sub axis model class
  41770. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  41771. */
  41772. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  41773. each(AXIS_TYPES, function (v, axisType) {
  41774. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  41775. var AxisModel =
  41776. /** @class */
  41777. function (_super) {
  41778. __extends(AxisModel, _super);
  41779. function AxisModel() {
  41780. var _this = _super !== null && _super.apply(this, arguments) || this;
  41781. _this.type = axisName + 'Axis.' + axisType;
  41782. return _this;
  41783. }
  41784. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  41785. var layoutMode = fetchLayoutMode(this);
  41786. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  41787. var themeModel = ecModel.getTheme();
  41788. merge(option, themeModel.get(axisType + 'Axis'));
  41789. merge(option, this.getDefaultOption());
  41790. option.type = getAxisType(option);
  41791. if (layoutMode) {
  41792. mergeLayoutParam(option, inputPositionParams, layoutMode);
  41793. }
  41794. };
  41795. AxisModel.prototype.optionUpdated = function () {
  41796. var thisOption = this.option;
  41797. if (thisOption.type === 'category') {
  41798. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  41799. }
  41800. };
  41801. /**
  41802. * Should not be called before all of 'getInitailData' finished.
  41803. * Because categories are collected during initializing data.
  41804. */
  41805. AxisModel.prototype.getCategories = function (rawData) {
  41806. var option = this.option; // FIXME
  41807. // warning if called before all of 'getInitailData' finished.
  41808. if (option.type === 'category') {
  41809. if (rawData) {
  41810. return option.data;
  41811. }
  41812. return this.__ordinalMeta.categories;
  41813. }
  41814. };
  41815. AxisModel.prototype.getOrdinalMeta = function () {
  41816. return this.__ordinalMeta;
  41817. };
  41818. AxisModel.type = axisName + 'Axis.' + axisType;
  41819. AxisModel.defaultOption = defaultOption;
  41820. return AxisModel;
  41821. }(BaseAxisModelClass);
  41822. registers.registerComponentModel(AxisModel);
  41823. });
  41824. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  41825. }
  41826. function getAxisType(option) {
  41827. // Default axis with data is category axis
  41828. return option.type || (option.data ? 'category' : 'value');
  41829. }
  41830. var Cartesian =
  41831. /** @class */
  41832. function () {
  41833. function Cartesian(name) {
  41834. this.type = 'cartesian';
  41835. this._dimList = [];
  41836. this._axes = {};
  41837. this.name = name || '';
  41838. }
  41839. Cartesian.prototype.getAxis = function (dim) {
  41840. return this._axes[dim];
  41841. };
  41842. Cartesian.prototype.getAxes = function () {
  41843. return map(this._dimList, function (dim) {
  41844. return this._axes[dim];
  41845. }, this);
  41846. };
  41847. Cartesian.prototype.getAxesByScale = function (scaleType) {
  41848. scaleType = scaleType.toLowerCase();
  41849. return filter(this.getAxes(), function (axis) {
  41850. return axis.scale.type === scaleType;
  41851. });
  41852. };
  41853. Cartesian.prototype.addAxis = function (axis) {
  41854. var dim = axis.dim;
  41855. this._axes[dim] = axis;
  41856. this._dimList.push(dim);
  41857. };
  41858. return Cartesian;
  41859. }();
  41860. var cartesian2DDimensions = ['x', 'y'];
  41861. function canCalculateAffineTransform(scale) {
  41862. return scale.type === 'interval' || scale.type === 'time';
  41863. }
  41864. var Cartesian2D =
  41865. /** @class */
  41866. function (_super) {
  41867. __extends(Cartesian2D, _super);
  41868. function Cartesian2D() {
  41869. var _this = _super !== null && _super.apply(this, arguments) || this;
  41870. _this.type = 'cartesian2d';
  41871. _this.dimensions = cartesian2DDimensions;
  41872. return _this;
  41873. }
  41874. /**
  41875. * Calculate an affine transform matrix if two axes are time or value.
  41876. * It's mainly for accelartion on the large time series data.
  41877. */
  41878. Cartesian2D.prototype.calcAffineTransform = function () {
  41879. this._transform = this._invTransform = null;
  41880. var xAxisScale = this.getAxis('x').scale;
  41881. var yAxisScale = this.getAxis('y').scale;
  41882. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  41883. return;
  41884. }
  41885. var xScaleExtent = xAxisScale.getExtent();
  41886. var yScaleExtent = yAxisScale.getExtent();
  41887. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  41888. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  41889. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  41890. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  41891. if (!xScaleSpan || !yScaleSpan) {
  41892. return;
  41893. } // Accelerate data to point calculation on the special large time series data.
  41894. var scaleX = (end[0] - start[0]) / xScaleSpan;
  41895. var scaleY = (end[1] - start[1]) / yScaleSpan;
  41896. var translateX = start[0] - xScaleExtent[0] * scaleX;
  41897. var translateY = start[1] - yScaleExtent[0] * scaleY;
  41898. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  41899. this._invTransform = invert([], m);
  41900. };
  41901. /**
  41902. * Base axis will be used on stacking.
  41903. */
  41904. Cartesian2D.prototype.getBaseAxis = function () {
  41905. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  41906. };
  41907. Cartesian2D.prototype.containPoint = function (point) {
  41908. var axisX = this.getAxis('x');
  41909. var axisY = this.getAxis('y');
  41910. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  41911. };
  41912. Cartesian2D.prototype.containData = function (data) {
  41913. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  41914. };
  41915. Cartesian2D.prototype.containZone = function (data1, data2) {
  41916. var zoneDiag1 = this.dataToPoint(data1);
  41917. var zoneDiag2 = this.dataToPoint(data2);
  41918. var area = this.getArea();
  41919. var zone = new BoundingRect(zoneDiag1[0], zoneDiag1[1], zoneDiag2[0] - zoneDiag1[0], zoneDiag2[1] - zoneDiag1[1]);
  41920. return area.intersect(zone);
  41921. };
  41922. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  41923. out = out || [];
  41924. var xVal = data[0];
  41925. var yVal = data[1]; // Fast path
  41926. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  41927. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  41928. return applyTransform(out, data, this._transform);
  41929. }
  41930. var xAxis = this.getAxis('x');
  41931. var yAxis = this.getAxis('y');
  41932. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  41933. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  41934. return out;
  41935. };
  41936. Cartesian2D.prototype.clampData = function (data, out) {
  41937. var xScale = this.getAxis('x').scale;
  41938. var yScale = this.getAxis('y').scale;
  41939. var xAxisExtent = xScale.getExtent();
  41940. var yAxisExtent = yScale.getExtent();
  41941. var x = xScale.parse(data[0]);
  41942. var y = yScale.parse(data[1]);
  41943. out = out || [];
  41944. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  41945. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  41946. return out;
  41947. };
  41948. Cartesian2D.prototype.pointToData = function (point, clamp) {
  41949. var out = [];
  41950. if (this._invTransform) {
  41951. return applyTransform(out, point, this._invTransform);
  41952. }
  41953. var xAxis = this.getAxis('x');
  41954. var yAxis = this.getAxis('y');
  41955. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  41956. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  41957. return out;
  41958. };
  41959. Cartesian2D.prototype.getOtherAxis = function (axis) {
  41960. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  41961. };
  41962. /**
  41963. * Get rect area of cartesian.
  41964. * Area will have a contain function to determine if a point is in the coordinate system.
  41965. */
  41966. Cartesian2D.prototype.getArea = function () {
  41967. var xExtent = this.getAxis('x').getGlobalExtent();
  41968. var yExtent = this.getAxis('y').getGlobalExtent();
  41969. var x = Math.min(xExtent[0], xExtent[1]);
  41970. var y = Math.min(yExtent[0], yExtent[1]);
  41971. var width = Math.max(xExtent[0], xExtent[1]) - x;
  41972. var height = Math.max(yExtent[0], yExtent[1]) - y;
  41973. return new BoundingRect(x, y, width, height);
  41974. };
  41975. return Cartesian2D;
  41976. }(Cartesian);
  41977. var Axis2D =
  41978. /** @class */
  41979. function (_super) {
  41980. __extends(Axis2D, _super);
  41981. function Axis2D(dim, scale, coordExtent, axisType, position) {
  41982. var _this = _super.call(this, dim, scale, coordExtent) || this;
  41983. /**
  41984. * Index of axis, can be used as key
  41985. * Injected outside.
  41986. */
  41987. _this.index = 0;
  41988. _this.type = axisType || 'value';
  41989. _this.position = position || 'bottom';
  41990. return _this;
  41991. }
  41992. Axis2D.prototype.isHorizontal = function () {
  41993. var position = this.position;
  41994. return position === 'top' || position === 'bottom';
  41995. };
  41996. /**
  41997. * Each item cooresponds to this.getExtent(), which
  41998. * means globalExtent[0] may greater than globalExtent[1],
  41999. * unless `asc` is input.
  42000. *
  42001. * @param {boolean} [asc]
  42002. * @return {Array.<number>}
  42003. */
  42004. Axis2D.prototype.getGlobalExtent = function (asc) {
  42005. var ret = this.getExtent();
  42006. ret[0] = this.toGlobalCoord(ret[0]);
  42007. ret[1] = this.toGlobalCoord(ret[1]);
  42008. asc && ret[0] > ret[1] && ret.reverse();
  42009. return ret;
  42010. };
  42011. Axis2D.prototype.pointToData = function (point, clamp) {
  42012. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  42013. };
  42014. /**
  42015. * Set ordinalSortInfo
  42016. * @param info new OrdinalSortInfo
  42017. */
  42018. Axis2D.prototype.setCategorySortInfo = function (info) {
  42019. if (this.type !== 'category') {
  42020. return false;
  42021. }
  42022. this.model.option.categorySortInfo = info;
  42023. this.scale.setSortInfo(info);
  42024. };
  42025. return Axis2D;
  42026. }(Axis);
  42027. /**
  42028. * Can only be called after coordinate system creation stage.
  42029. * (Can be called before coordinate system update stage).
  42030. */
  42031. function layout$1(gridModel, axisModel, opt) {
  42032. opt = opt || {};
  42033. var grid = gridModel.coordinateSystem;
  42034. var axis = axisModel.axis;
  42035. var layout = {};
  42036. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  42037. var rawAxisPosition = axis.position;
  42038. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  42039. var axisDim = axis.dim;
  42040. var rect = grid.getRect();
  42041. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  42042. var idx = {
  42043. left: 0,
  42044. right: 1,
  42045. top: 0,
  42046. bottom: 1,
  42047. onZero: 2
  42048. };
  42049. var axisOffset = axisModel.get('offset') || 0;
  42050. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  42051. if (otherAxisOnZeroOf) {
  42052. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  42053. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  42054. } // Axis position
  42055. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  42056. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  42057. var dirMap = {
  42058. top: -1,
  42059. bottom: 1,
  42060. left: -1,
  42061. right: 1
  42062. };
  42063. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  42064. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  42065. if (axisModel.get(['axisTick', 'inside'])) {
  42066. layout.tickDirection = -layout.tickDirection;
  42067. }
  42068. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  42069. layout.labelDirection = -layout.labelDirection;
  42070. } // Special label rotation
  42071. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  42072. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  42073. layout.z2 = 1;
  42074. return layout;
  42075. }
  42076. function isCartesian2DSeries(seriesModel) {
  42077. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  42078. }
  42079. function findAxisModels(seriesModel) {
  42080. var axisModelMap = {
  42081. xAxisModel: null,
  42082. yAxisModel: null
  42083. };
  42084. each(axisModelMap, function (v, key) {
  42085. var axisType = key.replace(/Model$/, '');
  42086. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  42087. if ("development" !== 'production') {
  42088. if (!axisModel) {
  42089. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  42090. }
  42091. }
  42092. axisModelMap[key] = axisModel;
  42093. });
  42094. return axisModelMap;
  42095. }
  42096. var mathLog$1 = Math.log;
  42097. function alignScaleTicks(scale, axisModel, alignToScale) {
  42098. var intervalScaleProto = IntervalScale.prototype; // NOTE: There is a precondition for log scale here:
  42099. // In log scale we store _interval and _extent of exponent value.
  42100. // So if we use the method of InternalScale to set/get these data.
  42101. // It process the exponent value, which is linear and what we want here.
  42102. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  42103. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, true);
  42104. var alignToSplitNumber = alignToTicks.length - 1;
  42105. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  42106. var scaleExtent = getScaleExtent(scale, axisModel);
  42107. var rawExtent = scaleExtent.extent;
  42108. var isMinFixed = scaleExtent.fixMin;
  42109. var isMaxFixed = scaleExtent.fixMax;
  42110. if (scale.type === 'log') {
  42111. var logBase = mathLog$1(scale.base);
  42112. rawExtent = [mathLog$1(rawExtent[0]) / logBase, mathLog$1(rawExtent[1]) / logBase];
  42113. }
  42114. scale.setExtent(rawExtent[0], rawExtent[1]);
  42115. scale.calcNiceExtent({
  42116. splitNumber: alignToSplitNumber,
  42117. fixMin: isMinFixed,
  42118. fixMax: isMaxFixed
  42119. });
  42120. var extent = intervalScaleProto.getExtent.call(scale); // Need to update the rawExtent.
  42121. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  42122. if (isMinFixed) {
  42123. rawExtent[0] = extent[0];
  42124. }
  42125. if (isMaxFixed) {
  42126. rawExtent[1] = extent[1];
  42127. }
  42128. var interval = intervalScaleProto.getInterval.call(scale);
  42129. var min = rawExtent[0];
  42130. var max = rawExtent[1];
  42131. if (isMinFixed && isMaxFixed) {
  42132. // User set min, max, divide to get new interval
  42133. interval = (max - min) / alignToSplitNumber;
  42134. } else if (isMinFixed) {
  42135. max = rawExtent[0] + interval * alignToSplitNumber; // User set min, expand extent on the other side
  42136. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  42137. interval = increaseInterval(interval);
  42138. max = rawExtent[0] + interval * alignToSplitNumber;
  42139. }
  42140. } else if (isMaxFixed) {
  42141. // User set max, expand extent on the other side
  42142. min = rawExtent[1] - interval * alignToSplitNumber;
  42143. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  42144. interval = increaseInterval(interval);
  42145. min = rawExtent[1] - interval * alignToSplitNumber;
  42146. }
  42147. } else {
  42148. var nicedSplitNumber = scale.getTicks().length - 1;
  42149. if (nicedSplitNumber > alignToSplitNumber) {
  42150. interval = increaseInterval(interval);
  42151. }
  42152. var range = interval * alignToSplitNumber;
  42153. max = Math.ceil(rawExtent[1] / interval) * interval;
  42154. min = round(max - range); // Not change the result that crossing zero.
  42155. if (min < 0 && rawExtent[0] >= 0) {
  42156. min = 0;
  42157. max = round(range);
  42158. } else if (max > 0 && rawExtent[1] <= 0) {
  42159. max = 0;
  42160. min = -round(range);
  42161. }
  42162. } // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  42163. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  42164. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval; // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  42165. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  42166. intervalScaleProto.setInterval.call(scale, interval);
  42167. if (t0 || t1) {
  42168. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  42169. }
  42170. if ("development" !== 'production') {
  42171. var ticks = intervalScaleProto.getTicks.call(scale);
  42172. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  42173. warn( // eslint-disable-next-line
  42174. "The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + " and alignTicks: true");
  42175. }
  42176. }
  42177. }
  42178. var Grid =
  42179. /** @class */
  42180. function () {
  42181. function Grid(gridModel, ecModel, api) {
  42182. // FIXME:TS where used (different from registered type 'cartesian2d')?
  42183. this.type = 'grid';
  42184. this._coordsMap = {};
  42185. this._coordsList = [];
  42186. this._axesMap = {};
  42187. this._axesList = [];
  42188. this.axisPointerEnabled = true;
  42189. this.dimensions = cartesian2DDimensions;
  42190. this._initCartesian(gridModel, ecModel, api);
  42191. this.model = gridModel;
  42192. }
  42193. Grid.prototype.getRect = function () {
  42194. return this._rect;
  42195. };
  42196. Grid.prototype.update = function (ecModel, api) {
  42197. var axesMap = this._axesMap;
  42198. this._updateScale(ecModel, this.model);
  42199. function updateAxisTicks(axes) {
  42200. var alignTo; // Axis is added in order of axisIndex.
  42201. var axesIndices = keys(axes);
  42202. var len = axesIndices.length;
  42203. if (!len) {
  42204. return;
  42205. }
  42206. var axisNeedsAlign = []; // Process once and calculate the ticks for those don't use alignTicks.
  42207. for (var i = len - 1; i >= 0; i--) {
  42208. var idx = +axesIndices[i]; // Convert to number.
  42209. var axis = axes[idx];
  42210. var model = axis.model;
  42211. var scale = axis.scale;
  42212. if ( // Only value and log axis without interval support alignTicks.
  42213. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  42214. axisNeedsAlign.push(axis);
  42215. } else {
  42216. niceScaleExtent(scale, model);
  42217. if (isIntervalOrLogScale(scale)) {
  42218. // Can only align to interval or log axis.
  42219. alignTo = axis;
  42220. }
  42221. }
  42222. }
  42223. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  42224. if (axisNeedsAlign.length) {
  42225. if (!alignTo) {
  42226. alignTo = axisNeedsAlign.pop();
  42227. niceScaleExtent(alignTo.scale, alignTo.model);
  42228. }
  42229. each(axisNeedsAlign, function (axis) {
  42230. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  42231. });
  42232. }
  42233. }
  42234. updateAxisTicks(axesMap.x);
  42235. updateAxisTicks(axesMap.y); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  42236. var onZeroRecords = {};
  42237. each(axesMap.x, function (xAxis) {
  42238. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  42239. });
  42240. each(axesMap.y, function (yAxis) {
  42241. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  42242. }); // Resize again if containLabel is enabled
  42243. // FIXME It may cause getting wrong grid size in data processing stage
  42244. this.resize(this.model, api);
  42245. };
  42246. /**
  42247. * Resize the grid
  42248. */
  42249. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  42250. var boxLayoutParams = gridModel.getBoxLayoutParams();
  42251. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  42252. var gridRect = getLayoutRect(boxLayoutParams, {
  42253. width: api.getWidth(),
  42254. height: api.getHeight()
  42255. });
  42256. this._rect = gridRect;
  42257. var axesList = this._axesList;
  42258. adjustAxes(); // Minus label size
  42259. if (isContainLabel) {
  42260. each(axesList, function (axis) {
  42261. if (!axis.model.get(['axisLabel', 'inside'])) {
  42262. var labelUnionRect = estimateLabelUnionRect(axis);
  42263. if (labelUnionRect) {
  42264. var dim = axis.isHorizontal() ? 'height' : 'width';
  42265. var margin = axis.model.get(['axisLabel', 'margin']);
  42266. gridRect[dim] -= labelUnionRect[dim] + margin;
  42267. if (axis.position === 'top') {
  42268. gridRect.y += labelUnionRect.height + margin;
  42269. } else if (axis.position === 'left') {
  42270. gridRect.x += labelUnionRect.width + margin;
  42271. }
  42272. }
  42273. }
  42274. });
  42275. adjustAxes();
  42276. }
  42277. each(this._coordsList, function (coord) {
  42278. // Calculate affine matrix to accelerate the data to point transform.
  42279. // If all the axes scales are time or value.
  42280. coord.calcAffineTransform();
  42281. });
  42282. function adjustAxes() {
  42283. each(axesList, function (axis) {
  42284. var isHorizontal = axis.isHorizontal();
  42285. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  42286. var idx = axis.inverse ? 1 : 0;
  42287. axis.setExtent(extent[idx], extent[1 - idx]);
  42288. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  42289. });
  42290. }
  42291. };
  42292. Grid.prototype.getAxis = function (dim, axisIndex) {
  42293. var axesMapOnDim = this._axesMap[dim];
  42294. if (axesMapOnDim != null) {
  42295. return axesMapOnDim[axisIndex || 0];
  42296. }
  42297. };
  42298. Grid.prototype.getAxes = function () {
  42299. return this._axesList.slice();
  42300. };
  42301. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  42302. if (xAxisIndex != null && yAxisIndex != null) {
  42303. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42304. return this._coordsMap[key];
  42305. }
  42306. if (isObject(xAxisIndex)) {
  42307. yAxisIndex = xAxisIndex.yAxisIndex;
  42308. xAxisIndex = xAxisIndex.xAxisIndex;
  42309. }
  42310. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  42311. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  42312. return coordList[i];
  42313. }
  42314. }
  42315. };
  42316. Grid.prototype.getCartesians = function () {
  42317. return this._coordsList.slice();
  42318. };
  42319. /**
  42320. * @implements
  42321. */
  42322. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  42323. var target = this._findConvertTarget(finder);
  42324. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  42325. };
  42326. /**
  42327. * @implements
  42328. */
  42329. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  42330. var target = this._findConvertTarget(finder);
  42331. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  42332. };
  42333. Grid.prototype._findConvertTarget = function (finder) {
  42334. var seriesModel = finder.seriesModel;
  42335. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  42336. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  42337. var gridModel = finder.gridModel;
  42338. var coordsList = this._coordsList;
  42339. var cartesian;
  42340. var axis;
  42341. if (seriesModel) {
  42342. cartesian = seriesModel.coordinateSystem;
  42343. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  42344. } else if (xAxisModel && yAxisModel) {
  42345. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42346. } else if (xAxisModel) {
  42347. axis = this.getAxis('x', xAxisModel.componentIndex);
  42348. } else if (yAxisModel) {
  42349. axis = this.getAxis('y', yAxisModel.componentIndex);
  42350. } // Lowest priority.
  42351. else if (gridModel) {
  42352. var grid = gridModel.coordinateSystem;
  42353. if (grid === this) {
  42354. cartesian = this._coordsList[0];
  42355. }
  42356. }
  42357. return {
  42358. cartesian: cartesian,
  42359. axis: axis
  42360. };
  42361. };
  42362. /**
  42363. * @implements
  42364. */
  42365. Grid.prototype.containPoint = function (point) {
  42366. var coord = this._coordsList[0];
  42367. if (coord) {
  42368. return coord.containPoint(point);
  42369. }
  42370. };
  42371. /**
  42372. * Initialize cartesian coordinate systems
  42373. */
  42374. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  42375. var _this = this;
  42376. var grid = this;
  42377. var axisPositionUsed = {
  42378. left: false,
  42379. right: false,
  42380. top: false,
  42381. bottom: false
  42382. };
  42383. var axesMap = {
  42384. x: {},
  42385. y: {}
  42386. };
  42387. var axesCount = {
  42388. x: 0,
  42389. y: 0
  42390. }; // Create axis
  42391. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  42392. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  42393. if (!axesCount.x || !axesCount.y) {
  42394. // Roll back when there no either x or y axis
  42395. this._axesMap = {};
  42396. this._axesList = [];
  42397. return;
  42398. }
  42399. this._axesMap = axesMap; // Create cartesian2d
  42400. each(axesMap.x, function (xAxis, xAxisIndex) {
  42401. each(axesMap.y, function (yAxis, yAxisIndex) {
  42402. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42403. var cartesian = new Cartesian2D(key);
  42404. cartesian.master = _this;
  42405. cartesian.model = gridModel;
  42406. _this._coordsMap[key] = cartesian;
  42407. _this._coordsList.push(cartesian);
  42408. cartesian.addAxis(xAxis);
  42409. cartesian.addAxis(yAxis);
  42410. });
  42411. });
  42412. function createAxisCreator(dimName) {
  42413. return function (axisModel, idx) {
  42414. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  42415. return;
  42416. }
  42417. var axisPosition = axisModel.get('position');
  42418. if (dimName === 'x') {
  42419. // Fix position
  42420. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  42421. // Default bottom of X
  42422. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  42423. }
  42424. } else {
  42425. // Fix position
  42426. if (axisPosition !== 'left' && axisPosition !== 'right') {
  42427. // Default left of Y
  42428. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  42429. }
  42430. }
  42431. axisPositionUsed[axisPosition] = true;
  42432. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  42433. var isCategory = axis.type === 'category';
  42434. axis.onBand = isCategory && axisModel.get('boundaryGap');
  42435. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  42436. axisModel.axis = axis; // Inject axisModel into axis
  42437. axis.model = axisModel; // Inject grid info axis
  42438. axis.grid = grid; // Index of axis, can be used as key
  42439. axis.index = idx;
  42440. grid._axesList.push(axis);
  42441. axesMap[dimName][idx] = axis;
  42442. axesCount[dimName]++;
  42443. };
  42444. }
  42445. };
  42446. /**
  42447. * Update cartesian properties from series.
  42448. */
  42449. Grid.prototype._updateScale = function (ecModel, gridModel) {
  42450. // Reset scale
  42451. each(this._axesList, function (axis) {
  42452. axis.scale.setExtent(Infinity, -Infinity);
  42453. if (axis.type === 'category') {
  42454. var categorySortInfo = axis.model.get('categorySortInfo');
  42455. axis.scale.setSortInfo(categorySortInfo);
  42456. }
  42457. });
  42458. ecModel.eachSeries(function (seriesModel) {
  42459. if (isCartesian2DSeries(seriesModel)) {
  42460. var axesModelMap = findAxisModels(seriesModel);
  42461. var xAxisModel = axesModelMap.xAxisModel;
  42462. var yAxisModel = axesModelMap.yAxisModel;
  42463. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  42464. return;
  42465. }
  42466. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42467. var data = seriesModel.getData();
  42468. var xAxis = cartesian.getAxis('x');
  42469. var yAxis = cartesian.getAxis('y');
  42470. unionExtent(data, xAxis);
  42471. unionExtent(data, yAxis);
  42472. }
  42473. }, this);
  42474. function unionExtent(data, axis) {
  42475. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  42476. axis.scale.unionExtentFromData(data, dim);
  42477. });
  42478. }
  42479. };
  42480. /**
  42481. * @param dim 'x' or 'y' or 'auto' or null/undefined
  42482. */
  42483. Grid.prototype.getTooltipAxes = function (dim) {
  42484. var baseAxes = [];
  42485. var otherAxes = [];
  42486. each(this.getCartesians(), function (cartesian) {
  42487. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  42488. var otherAxis = cartesian.getOtherAxis(baseAxis);
  42489. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  42490. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  42491. });
  42492. return {
  42493. baseAxes: baseAxes,
  42494. otherAxes: otherAxes
  42495. };
  42496. };
  42497. Grid.create = function (ecModel, api) {
  42498. var grids = [];
  42499. ecModel.eachComponent('grid', function (gridModel, idx) {
  42500. var grid = new Grid(gridModel, ecModel, api);
  42501. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  42502. // should be performed in create stage.
  42503. grid.resize(gridModel, api, true);
  42504. gridModel.coordinateSystem = grid;
  42505. grids.push(grid);
  42506. }); // Inject the coordinateSystems into seriesModel
  42507. ecModel.eachSeries(function (seriesModel) {
  42508. if (!isCartesian2DSeries(seriesModel)) {
  42509. return;
  42510. }
  42511. var axesModelMap = findAxisModels(seriesModel);
  42512. var xAxisModel = axesModelMap.xAxisModel;
  42513. var yAxisModel = axesModelMap.yAxisModel;
  42514. var gridModel = xAxisModel.getCoordSysModel();
  42515. if ("development" !== 'production') {
  42516. if (!gridModel) {
  42517. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  42518. }
  42519. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  42520. throw new Error('xAxis and yAxis must use the same grid');
  42521. }
  42522. }
  42523. var grid = gridModel.coordinateSystem;
  42524. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42525. });
  42526. return grids;
  42527. }; // For deciding which dimensions to use when creating list data
  42528. Grid.dimensions = cartesian2DDimensions;
  42529. return Grid;
  42530. }();
  42531. /**
  42532. * Check if the axis is used in the specified grid.
  42533. */
  42534. function isAxisUsedInTheGrid(axisModel, gridModel) {
  42535. return axisModel.getCoordSysModel() === gridModel;
  42536. }
  42537. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  42538. onZeroRecords) {
  42539. axis.getAxesOnZeroOf = function () {
  42540. // TODO: onZero of multiple axes.
  42541. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  42542. }; // onZero can not be enabled in these two situations:
  42543. // 1. When any other axis is a category axis.
  42544. // 2. When no axis is cross 0 point.
  42545. var otherAxes = axesMap[otherAxisDim];
  42546. var otherAxisOnZeroOf;
  42547. var axisModel = axis.model;
  42548. var onZero = axisModel.get(['axisLine', 'onZero']);
  42549. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  42550. if (!onZero) {
  42551. return;
  42552. } // If target axis is specified.
  42553. if (onZeroAxisIndex != null) {
  42554. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  42555. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  42556. }
  42557. } else {
  42558. // Find the first available other axis.
  42559. for (var idx in otherAxes) {
  42560. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  42561. // if both onZero, the two Y axes overlap.
  42562. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  42563. otherAxisOnZeroOf = otherAxes[idx];
  42564. break;
  42565. }
  42566. }
  42567. }
  42568. if (otherAxisOnZeroOf) {
  42569. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  42570. }
  42571. function getOnZeroRecordKey(axis) {
  42572. return axis.dim + '_' + axis.index;
  42573. }
  42574. }
  42575. function canOnZeroToAxis(axis) {
  42576. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  42577. }
  42578. function updateAxisTransform(axis, coordBase) {
  42579. var axisExtent = axis.getExtent();
  42580. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  42581. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  42582. return coord + coordBase;
  42583. } : function (coord) {
  42584. return axisExtentSum - coord + coordBase;
  42585. };
  42586. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  42587. return coord - coordBase;
  42588. } : function (coord) {
  42589. return axisExtentSum - coord + coordBase;
  42590. };
  42591. }
  42592. var PI$5 = Math.PI;
  42593. /**
  42594. * A final axis is translated and rotated from a "standard axis".
  42595. * So opt.position and opt.rotation is required.
  42596. *
  42597. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  42598. * for example: (0, 0) ------------> (0, 50)
  42599. *
  42600. * nameDirection or tickDirection or labelDirection is 1 means tick
  42601. * or label is below the standard axis, whereas is -1 means above
  42602. * the standard axis. labelOffset means offset between label and axis,
  42603. * which is useful when 'onZero', where axisLabel is in the grid and
  42604. * label in outside grid.
  42605. *
  42606. * Tips: like always,
  42607. * positive rotation represents anticlockwise, and negative rotation
  42608. * represents clockwise.
  42609. * The direction of position coordinate is the same as the direction
  42610. * of screen coordinate.
  42611. *
  42612. * Do not need to consider axis 'inverse', which is auto processed by
  42613. * axis extent.
  42614. */
  42615. var AxisBuilder =
  42616. /** @class */
  42617. function () {
  42618. function AxisBuilder(axisModel, opt) {
  42619. this.group = new Group();
  42620. this.opt = opt;
  42621. this.axisModel = axisModel; // Default value
  42622. defaults(opt, {
  42623. labelOffset: 0,
  42624. nameDirection: 1,
  42625. tickDirection: 1,
  42626. labelDirection: 1,
  42627. silent: true,
  42628. handleAutoShown: function () {
  42629. return true;
  42630. }
  42631. }); // FIXME Not use a separate text group?
  42632. var transformGroup = new Group({
  42633. x: opt.position[0],
  42634. y: opt.position[1],
  42635. rotation: opt.rotation
  42636. }); // this.group.add(transformGroup);
  42637. // this._transformGroup = transformGroup;
  42638. transformGroup.updateTransform();
  42639. this._transformGroup = transformGroup;
  42640. }
  42641. AxisBuilder.prototype.hasBuilder = function (name) {
  42642. return !!builders[name];
  42643. };
  42644. AxisBuilder.prototype.add = function (name) {
  42645. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  42646. };
  42647. AxisBuilder.prototype.getGroup = function () {
  42648. return this.group;
  42649. };
  42650. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  42651. var rotationDiff = remRadian(textRotation - axisRotation);
  42652. var textAlign;
  42653. var textVerticalAlign;
  42654. if (isRadianAroundZero(rotationDiff)) {
  42655. // Label is parallel with axis line.
  42656. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  42657. textAlign = 'center';
  42658. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  42659. // Label is inverse parallel with axis line.
  42660. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  42661. textAlign = 'center';
  42662. } else {
  42663. textVerticalAlign = 'middle';
  42664. if (rotationDiff > 0 && rotationDiff < PI$5) {
  42665. textAlign = direction > 0 ? 'right' : 'left';
  42666. } else {
  42667. textAlign = direction > 0 ? 'left' : 'right';
  42668. }
  42669. }
  42670. return {
  42671. rotation: rotationDiff,
  42672. textAlign: textAlign,
  42673. textVerticalAlign: textVerticalAlign
  42674. };
  42675. };
  42676. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  42677. var eventData = {
  42678. componentType: axisModel.mainType,
  42679. componentIndex: axisModel.componentIndex
  42680. };
  42681. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  42682. return eventData;
  42683. };
  42684. AxisBuilder.isLabelSilent = function (axisModel) {
  42685. var tooltipOpt = axisModel.get('tooltip');
  42686. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  42687. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  42688. };
  42689. return AxisBuilder;
  42690. }();
  42691. var builders = {
  42692. axisLine: function (opt, axisModel, group, transformGroup) {
  42693. var shown = axisModel.get(['axisLine', 'show']);
  42694. if (shown === 'auto' && opt.handleAutoShown) {
  42695. shown = opt.handleAutoShown('axisLine');
  42696. }
  42697. if (!shown) {
  42698. return;
  42699. }
  42700. var extent = axisModel.axis.getExtent();
  42701. var matrix = transformGroup.transform;
  42702. var pt1 = [extent[0], 0];
  42703. var pt2 = [extent[1], 0];
  42704. var inverse = pt1[0] > pt2[0];
  42705. if (matrix) {
  42706. applyTransform(pt1, pt1, matrix);
  42707. applyTransform(pt2, pt2, matrix);
  42708. }
  42709. var lineStyle = extend({
  42710. lineCap: 'round'
  42711. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  42712. var line = new Line({
  42713. shape: {
  42714. x1: pt1[0],
  42715. y1: pt1[1],
  42716. x2: pt2[0],
  42717. y2: pt2[1]
  42718. },
  42719. style: lineStyle,
  42720. strokeContainThreshold: opt.strokeContainThreshold || 5,
  42721. silent: true,
  42722. z2: 1
  42723. });
  42724. subPixelOptimizeLine$1(line.shape, line.style.lineWidth);
  42725. line.anid = 'line';
  42726. group.add(line);
  42727. var arrows = axisModel.get(['axisLine', 'symbol']);
  42728. if (arrows != null) {
  42729. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  42730. if (isString(arrows)) {
  42731. // Use the same arrow for start and end point
  42732. arrows = [arrows, arrows];
  42733. }
  42734. if (isString(arrowSize) || isNumber(arrowSize)) {
  42735. // Use the same size for width and height
  42736. arrowSize = [arrowSize, arrowSize];
  42737. }
  42738. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  42739. var symbolWidth_1 = arrowSize[0];
  42740. var symbolHeight_1 = arrowSize[1];
  42741. each([{
  42742. rotate: opt.rotation + Math.PI / 2,
  42743. offset: arrowOffset[0],
  42744. r: 0
  42745. }, {
  42746. rotate: opt.rotation - Math.PI / 2,
  42747. offset: arrowOffset[1],
  42748. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  42749. }], function (point, index) {
  42750. if (arrows[index] !== 'none' && arrows[index] != null) {
  42751. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  42752. var r = point.r + point.offset;
  42753. var pt = inverse ? pt2 : pt1;
  42754. symbol.attr({
  42755. rotation: point.rotate,
  42756. x: pt[0] + r * Math.cos(opt.rotation),
  42757. y: pt[1] - r * Math.sin(opt.rotation),
  42758. silent: true,
  42759. z2: 11
  42760. });
  42761. group.add(symbol);
  42762. }
  42763. });
  42764. }
  42765. },
  42766. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  42767. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  42768. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  42769. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  42770. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection); // This bit fixes the label overlap issue for the time chart.
  42771. // See https://github.com/apache/echarts/issues/14266 for more.
  42772. if (axisModel.get(['axisLabel', 'hideOverlap'])) {
  42773. var labelList = prepareLayoutList(map(labelEls, function (label) {
  42774. return {
  42775. label: label,
  42776. priority: label.z2,
  42777. defaultAttr: {
  42778. ignore: label.ignore
  42779. }
  42780. };
  42781. }));
  42782. hideOverlap(labelList);
  42783. }
  42784. },
  42785. axisName: function (opt, axisModel, group, transformGroup) {
  42786. var name = retrieve(opt.axisName, axisModel.get('name'));
  42787. if (!name) {
  42788. return;
  42789. }
  42790. var nameLocation = axisModel.get('nameLocation');
  42791. var nameDirection = opt.nameDirection;
  42792. var textStyleModel = axisModel.getModel('nameTextStyle');
  42793. var gap = axisModel.get('nameGap') || 0;
  42794. var extent = axisModel.axis.getExtent();
  42795. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  42796. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  42797. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  42798. var labelLayout;
  42799. var nameRotation = axisModel.get('nameRotate');
  42800. if (nameRotation != null) {
  42801. nameRotation = nameRotation * PI$5 / 180; // To radian.
  42802. }
  42803. var axisNameAvailableWidth;
  42804. if (isNameLocationCenter(nameLocation)) {
  42805. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  42806. nameDirection);
  42807. } else {
  42808. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  42809. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  42810. if (axisNameAvailableWidth != null) {
  42811. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  42812. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  42813. }
  42814. }
  42815. var textFont = textStyleModel.getFont();
  42816. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  42817. var ellipsis = truncateOpt.ellipsis;
  42818. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  42819. var textEl = new ZRText({
  42820. x: pos[0],
  42821. y: pos[1],
  42822. rotation: labelLayout.rotation,
  42823. silent: AxisBuilder.isLabelSilent(axisModel),
  42824. style: createTextStyle(textStyleModel, {
  42825. text: name,
  42826. font: textFont,
  42827. overflow: 'truncate',
  42828. width: maxWidth,
  42829. ellipsis: ellipsis,
  42830. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  42831. align: textStyleModel.get('align') || labelLayout.textAlign,
  42832. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  42833. }),
  42834. z2: 1
  42835. });
  42836. setTooltipConfig({
  42837. el: textEl,
  42838. componentModel: axisModel,
  42839. itemName: name
  42840. });
  42841. textEl.__fullText = name; // Id for animation
  42842. textEl.anid = 'name';
  42843. if (axisModel.get('triggerEvent')) {
  42844. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  42845. eventData.targetType = 'axisName';
  42846. eventData.name = name;
  42847. getECData(textEl).eventData = eventData;
  42848. } // FIXME
  42849. transformGroup.add(textEl);
  42850. textEl.updateTransform();
  42851. group.add(textEl);
  42852. textEl.decomposeTransform();
  42853. }
  42854. };
  42855. function endTextLayout(rotation, textPosition, textRotate, extent) {
  42856. var rotationDiff = remRadian(textRotate - rotation);
  42857. var textAlign;
  42858. var textVerticalAlign;
  42859. var inverse = extent[0] > extent[1];
  42860. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  42861. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  42862. textVerticalAlign = onLeft ? 'bottom' : 'top';
  42863. textAlign = 'center';
  42864. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  42865. textVerticalAlign = onLeft ? 'top' : 'bottom';
  42866. textAlign = 'center';
  42867. } else {
  42868. textVerticalAlign = 'middle';
  42869. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  42870. textAlign = onLeft ? 'left' : 'right';
  42871. } else {
  42872. textAlign = onLeft ? 'right' : 'left';
  42873. }
  42874. }
  42875. return {
  42876. rotation: rotationDiff,
  42877. textAlign: textAlign,
  42878. textVerticalAlign: textVerticalAlign
  42879. };
  42880. }
  42881. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  42882. if (shouldShowAllLabels(axisModel.axis)) {
  42883. return;
  42884. } // If min or max are user set, we need to check
  42885. // If the tick on min(max) are overlap on their neighbour tick
  42886. // If they are overlapped, we need to hide the min(max) tick label
  42887. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  42888. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  42889. // Have not consider onBand yet, where tick els is more than label els.
  42890. labelEls = labelEls || [];
  42891. tickEls = tickEls || [];
  42892. var firstLabel = labelEls[0];
  42893. var nextLabel = labelEls[1];
  42894. var lastLabel = labelEls[labelEls.length - 1];
  42895. var prevLabel = labelEls[labelEls.length - 2];
  42896. var firstTick = tickEls[0];
  42897. var nextTick = tickEls[1];
  42898. var lastTick = tickEls[tickEls.length - 1];
  42899. var prevTick = tickEls[tickEls.length - 2];
  42900. if (showMinLabel === false) {
  42901. ignoreEl(firstLabel);
  42902. ignoreEl(firstTick);
  42903. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  42904. if (showMinLabel) {
  42905. ignoreEl(nextLabel);
  42906. ignoreEl(nextTick);
  42907. } else {
  42908. ignoreEl(firstLabel);
  42909. ignoreEl(firstTick);
  42910. }
  42911. }
  42912. if (showMaxLabel === false) {
  42913. ignoreEl(lastLabel);
  42914. ignoreEl(lastTick);
  42915. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  42916. if (showMaxLabel) {
  42917. ignoreEl(prevLabel);
  42918. ignoreEl(prevTick);
  42919. } else {
  42920. ignoreEl(lastLabel);
  42921. ignoreEl(lastTick);
  42922. }
  42923. }
  42924. }
  42925. function ignoreEl(el) {
  42926. el && (el.ignore = true);
  42927. }
  42928. function isTwoLabelOverlapped(current, next) {
  42929. // current and next has the same rotation.
  42930. var firstRect = current && current.getBoundingRect().clone();
  42931. var nextRect = next && next.getBoundingRect().clone();
  42932. if (!firstRect || !nextRect) {
  42933. return;
  42934. } // When checking intersect of two rotated labels, we use mRotationBack
  42935. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  42936. var mRotationBack = identity([]);
  42937. rotate(mRotationBack, mRotationBack, -current.rotation);
  42938. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  42939. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  42940. return firstRect.intersect(nextRect);
  42941. }
  42942. function isNameLocationCenter(nameLocation) {
  42943. return nameLocation === 'middle' || nameLocation === 'center';
  42944. }
  42945. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  42946. var tickEls = [];
  42947. var pt1 = [];
  42948. var pt2 = [];
  42949. for (var i = 0; i < ticksCoords.length; i++) {
  42950. var tickCoord = ticksCoords[i].coord;
  42951. pt1[0] = tickCoord;
  42952. pt1[1] = 0;
  42953. pt2[0] = tickCoord;
  42954. pt2[1] = tickEndCoord;
  42955. if (tickTransform) {
  42956. applyTransform(pt1, pt1, tickTransform);
  42957. applyTransform(pt2, pt2, tickTransform);
  42958. } // Tick line, Not use group transform to have better line draw
  42959. var tickEl = new Line({
  42960. shape: {
  42961. x1: pt1[0],
  42962. y1: pt1[1],
  42963. x2: pt2[0],
  42964. y2: pt2[1]
  42965. },
  42966. style: tickLineStyle,
  42967. z2: 2,
  42968. autoBatch: true,
  42969. silent: true
  42970. });
  42971. subPixelOptimizeLine$1(tickEl.shape, tickEl.style.lineWidth);
  42972. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  42973. tickEls.push(tickEl);
  42974. }
  42975. return tickEls;
  42976. }
  42977. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  42978. var axis = axisModel.axis;
  42979. var tickModel = axisModel.getModel('axisTick');
  42980. var shown = tickModel.get('show');
  42981. if (shown === 'auto' && opt.handleAutoShown) {
  42982. shown = opt.handleAutoShown('axisTick');
  42983. }
  42984. if (!shown || axis.scale.isBlank()) {
  42985. return;
  42986. }
  42987. var lineStyleModel = tickModel.getModel('lineStyle');
  42988. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  42989. var ticksCoords = axis.getTicksCoords();
  42990. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  42991. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  42992. }), 'ticks');
  42993. for (var i = 0; i < ticksEls.length; i++) {
  42994. group.add(ticksEls[i]);
  42995. }
  42996. return ticksEls;
  42997. }
  42998. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  42999. var axis = axisModel.axis;
  43000. var minorTickModel = axisModel.getModel('minorTick');
  43001. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  43002. return;
  43003. }
  43004. var minorTicksCoords = axis.getMinorTicksCoords();
  43005. if (!minorTicksCoords.length) {
  43006. return;
  43007. }
  43008. var lineStyleModel = minorTickModel.getModel('lineStyle');
  43009. var tickEndCoord = tickDirection * minorTickModel.get('length');
  43010. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  43011. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43012. }));
  43013. for (var i = 0; i < minorTicksCoords.length; i++) {
  43014. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  43015. for (var k = 0; k < minorTicksEls.length; k++) {
  43016. group.add(minorTicksEls[k]);
  43017. }
  43018. }
  43019. }
  43020. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  43021. var axis = axisModel.axis;
  43022. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  43023. if (!show || axis.scale.isBlank()) {
  43024. return;
  43025. }
  43026. var labelModel = axisModel.getModel('axisLabel');
  43027. var labelMargin = labelModel.get('margin');
  43028. var labels = axis.getViewLabels(); // Special label rotate.
  43029. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  43030. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  43031. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  43032. var labelEls = [];
  43033. var silent = AxisBuilder.isLabelSilent(axisModel);
  43034. var triggerEvent = axisModel.get('triggerEvent');
  43035. each(labels, function (labelItem, index) {
  43036. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  43037. var formattedLabel = labelItem.formattedLabel;
  43038. var rawLabel = labelItem.rawLabel;
  43039. var itemLabelModel = labelModel;
  43040. if (rawCategoryData && rawCategoryData[tickValue]) {
  43041. var rawCategoryItem = rawCategoryData[tickValue];
  43042. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  43043. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  43044. }
  43045. }
  43046. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  43047. var tickCoord = axis.dataToCoord(tickValue);
  43048. var textEl = new ZRText({
  43049. x: tickCoord,
  43050. y: opt.labelOffset + opt.labelDirection * labelMargin,
  43051. rotation: labelLayout.rotation,
  43052. silent: silent,
  43053. z2: 10 + (labelItem.level || 0),
  43054. style: createTextStyle(itemLabelModel, {
  43055. text: formattedLabel,
  43056. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  43057. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  43058. fill: isFunction(textColor) ? textColor( // (1) In category axis with data zoom, tick is not the original
  43059. // index of axis.data. So tick should not be exposed to user
  43060. // in category axis.
  43061. // (2) Compatible with previous version, which always use formatted label as
  43062. // input. But in interval scale the formatted label is like '223,445', which
  43063. // maked user replace ','. So we modify it to return original val but remain
  43064. // it as 'string' to avoid error in replacing.
  43065. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  43066. })
  43067. });
  43068. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  43069. if (triggerEvent) {
  43070. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  43071. eventData.targetType = 'axisLabel';
  43072. eventData.value = rawLabel;
  43073. eventData.tickIndex = index;
  43074. if (axis.type === 'category') {
  43075. eventData.dataIndex = tickValue;
  43076. }
  43077. getECData(textEl).eventData = eventData;
  43078. } // FIXME
  43079. transformGroup.add(textEl);
  43080. textEl.updateTransform();
  43081. labelEls.push(textEl);
  43082. group.add(textEl);
  43083. textEl.decomposeTransform();
  43084. });
  43085. return labelEls;
  43086. }
  43087. // allAxesInfo should be updated when setOption performed.
  43088. function collect(ecModel, api) {
  43089. var result = {
  43090. /**
  43091. * key: makeKey(axis.model)
  43092. * value: {
  43093. * axis,
  43094. * coordSys,
  43095. * axisPointerModel,
  43096. * triggerTooltip,
  43097. * involveSeries,
  43098. * snap,
  43099. * seriesModels,
  43100. * seriesDataCount
  43101. * }
  43102. */
  43103. axesInfo: {},
  43104. seriesInvolved: false,
  43105. /**
  43106. * key: makeKey(coordSys.model)
  43107. * value: Object: key makeKey(axis.model), value: axisInfo
  43108. */
  43109. coordSysAxesInfo: {},
  43110. coordSysMap: {}
  43111. };
  43112. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  43113. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  43114. return result;
  43115. }
  43116. function collectAxesInfo(result, ecModel, api) {
  43117. var globalTooltipModel = ecModel.getComponent('tooltip');
  43118. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  43119. var linksOption = globalAxisPointerModel.get('link', true) || [];
  43120. var linkGroups = []; // Collect axes info.
  43121. each(api.getCoordinateSystems(), function (coordSys) {
  43122. // Some coordinate system do not support axes, like geo.
  43123. if (!coordSys.axisPointerEnabled) {
  43124. return;
  43125. }
  43126. var coordSysKey = makeKey(coordSys.model);
  43127. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  43128. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convenient way to show axisPointer
  43129. // for user. So we enable setting tooltip on coordSys model.
  43130. var coordSysModel = coordSys.model;
  43131. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  43132. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  43133. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  43134. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  43135. // show but axisPointer will show as normal.
  43136. && baseTooltipModel.get('show')) {
  43137. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  43138. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  43139. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  43140. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  43141. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  43142. if (triggerAxis || cross) {
  43143. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  43144. }
  43145. if (cross) {
  43146. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  43147. }
  43148. } // fromTooltip: true | false | 'cross'
  43149. // triggerTooltip: true | false | null
  43150. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  43151. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  43152. var axisPointerShow = axisPointerModel.get('show');
  43153. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  43154. return;
  43155. }
  43156. if (triggerTooltip == null) {
  43157. triggerTooltip = axisPointerModel.get('triggerTooltip');
  43158. }
  43159. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  43160. var snap = axisPointerModel.get('snap');
  43161. var axisKey = makeKey(axis.model);
  43162. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  43163. var axisInfo = result.axesInfo[axisKey] = {
  43164. key: axisKey,
  43165. axis: axis,
  43166. coordSys: coordSys,
  43167. axisPointerModel: axisPointerModel,
  43168. triggerTooltip: triggerTooltip,
  43169. involveSeries: involveSeries,
  43170. snap: snap,
  43171. useHandle: isHandleTrigger(axisPointerModel),
  43172. seriesModels: [],
  43173. linkGroup: null
  43174. };
  43175. axesInfoInCoordSys[axisKey] = axisInfo;
  43176. result.seriesInvolved = result.seriesInvolved || involveSeries;
  43177. var groupIndex = getLinkGroupIndex(linksOption, axis);
  43178. if (groupIndex != null) {
  43179. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  43180. axesInfo: {}
  43181. });
  43182. linkGroup.axesInfo[axisKey] = axisInfo;
  43183. linkGroup.mapper = linksOption[groupIndex].mapper;
  43184. axisInfo.linkGroup = linkGroup;
  43185. }
  43186. }
  43187. });
  43188. }
  43189. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  43190. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  43191. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  43192. var volatileOption = {};
  43193. each(fields, function (field) {
  43194. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  43195. }); // category axis do not auto snap, otherwise some tick that do not
  43196. // has value can not be hovered. value/time/log axis default snap if
  43197. // triggered from tooltip and trigger tooltip.
  43198. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatible with previous behavior, tooltip axis does not show label by default.
  43199. // Only these properties can be overridden from tooltip to axisPointer.
  43200. if (tooltipAxisPointerModel.get('type') === 'cross') {
  43201. volatileOption.type = 'line';
  43202. }
  43203. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  43204. labelOption.show == null && (labelOption.show = false);
  43205. if (fromTooltip === 'cross') {
  43206. // When 'cross', both axes show labels.
  43207. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  43208. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  43209. // (cross style is dashed by default)
  43210. if (!triggerTooltip) {
  43211. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  43212. crossStyle && defaults(labelOption, crossStyle.textStyle);
  43213. }
  43214. }
  43215. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  43216. }
  43217. function collectSeriesInfo(result, ecModel) {
  43218. // Prepare data for axis trigger
  43219. ecModel.eachSeries(function (seriesModel) {
  43220. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  43221. var coordSys = seriesModel.coordinateSystem;
  43222. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  43223. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  43224. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  43225. return;
  43226. }
  43227. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  43228. var axis = axisInfo.axis;
  43229. if (coordSys.getAxis(axis.dim) === axis) {
  43230. axisInfo.seriesModels.push(seriesModel);
  43231. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  43232. axisInfo.seriesDataCount += seriesModel.getData().count();
  43233. }
  43234. });
  43235. });
  43236. }
  43237. /**
  43238. * For example:
  43239. * {
  43240. * axisPointer: {
  43241. * links: [{
  43242. * xAxisIndex: [2, 4],
  43243. * yAxisIndex: 'all'
  43244. * }, {
  43245. * xAxisId: ['a5', 'a7'],
  43246. * xAxisName: 'xxx'
  43247. * }]
  43248. * }
  43249. * }
  43250. */
  43251. function getLinkGroupIndex(linksOption, axis) {
  43252. var axisModel = axis.model;
  43253. var dim = axis.dim;
  43254. for (var i = 0; i < linksOption.length; i++) {
  43255. var linkOption = linksOption[i] || {};
  43256. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  43257. return i;
  43258. }
  43259. }
  43260. }
  43261. function checkPropInLink(linkPropValue, axisPropValue) {
  43262. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  43263. }
  43264. function fixValue(axisModel) {
  43265. var axisInfo = getAxisInfo(axisModel);
  43266. if (!axisInfo) {
  43267. return;
  43268. }
  43269. var axisPointerModel = axisInfo.axisPointerModel;
  43270. var scale = axisInfo.axis.scale;
  43271. var option = axisPointerModel.option;
  43272. var status = axisPointerModel.get('status');
  43273. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  43274. if (value != null) {
  43275. value = scale.parse(value);
  43276. }
  43277. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  43278. // and status should be initialized.
  43279. if (status == null) {
  43280. option.status = useHandle ? 'show' : 'hide';
  43281. }
  43282. var extent = scale.getExtent().slice();
  43283. extent[0] > extent[1] && extent.reverse();
  43284. if ( // Pick a value on axis when initializing.
  43285. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  43286. // where we should re-pick a value to keep `handle` displaying normally.
  43287. || value > extent[1]) {
  43288. // Make handle displayed on the end of the axis when init, which looks better.
  43289. value = extent[1];
  43290. }
  43291. if (value < extent[0]) {
  43292. value = extent[0];
  43293. }
  43294. option.value = value;
  43295. if (useHandle) {
  43296. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  43297. }
  43298. }
  43299. function getAxisInfo(axisModel) {
  43300. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  43301. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  43302. }
  43303. function getAxisPointerModel(axisModel) {
  43304. var axisInfo = getAxisInfo(axisModel);
  43305. return axisInfo && axisInfo.axisPointerModel;
  43306. }
  43307. function isHandleTrigger(axisPointerModel) {
  43308. return !!axisPointerModel.get(['handle', 'show']);
  43309. }
  43310. /**
  43311. * @param {module:echarts/model/Model} model
  43312. * @return {string} unique key
  43313. */
  43314. function makeKey(model) {
  43315. return model.type + '||' + model.id;
  43316. }
  43317. var axisPointerClazz = {};
  43318. /**
  43319. * Base class of AxisView.
  43320. */
  43321. var AxisView =
  43322. /** @class */
  43323. function (_super) {
  43324. __extends(AxisView, _super);
  43325. function AxisView() {
  43326. var _this = _super !== null && _super.apply(this, arguments) || this;
  43327. _this.type = AxisView.type;
  43328. return _this;
  43329. }
  43330. /**
  43331. * @override
  43332. */
  43333. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43334. // FIXME
  43335. // This process should proformed after coordinate systems updated
  43336. // (axis scale updated), and should be performed each time update.
  43337. // So put it here temporarily, although it is not appropriate to
  43338. // put a model-writing procedure in `view`.
  43339. this.axisPointerClass && fixValue(axisModel);
  43340. _super.prototype.render.apply(this, arguments);
  43341. this._doUpdateAxisPointerClass(axisModel, api, true);
  43342. };
  43343. /**
  43344. * Action handler.
  43345. */
  43346. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  43347. this._doUpdateAxisPointerClass(axisModel, api, false);
  43348. };
  43349. /**
  43350. * @override
  43351. */
  43352. AxisView.prototype.remove = function (ecModel, api) {
  43353. var axisPointer = this._axisPointer;
  43354. axisPointer && axisPointer.remove(api);
  43355. };
  43356. /**
  43357. * @override
  43358. */
  43359. AxisView.prototype.dispose = function (ecModel, api) {
  43360. this._disposeAxisPointer(api);
  43361. _super.prototype.dispose.apply(this, arguments);
  43362. };
  43363. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  43364. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  43365. if (!Clazz) {
  43366. return;
  43367. }
  43368. var axisPointerModel = getAxisPointerModel(axisModel);
  43369. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  43370. };
  43371. AxisView.prototype._disposeAxisPointer = function (api) {
  43372. this._axisPointer && this._axisPointer.dispose(api);
  43373. this._axisPointer = null;
  43374. };
  43375. AxisView.registerAxisPointerClass = function (type, clazz) {
  43376. if ("development" !== 'production') {
  43377. if (axisPointerClazz[type]) {
  43378. throw new Error('axisPointer ' + type + ' exists');
  43379. }
  43380. }
  43381. axisPointerClazz[type] = clazz;
  43382. };
  43383. AxisView.getAxisPointerClass = function (type) {
  43384. return type && axisPointerClazz[type];
  43385. };
  43386. AxisView.type = 'axis';
  43387. return AxisView;
  43388. }(ComponentView);
  43389. var inner$6 = makeInner();
  43390. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  43391. var axis = axisModel.axis;
  43392. if (axis.scale.isBlank()) {
  43393. return;
  43394. } // TODO: TYPE
  43395. var splitAreaModel = axisModel.getModel('splitArea');
  43396. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  43397. var areaColors = areaStyleModel.get('color');
  43398. var gridRect = gridModel.coordinateSystem.getRect();
  43399. var ticksCoords = axis.getTicksCoords({
  43400. tickModel: splitAreaModel,
  43401. clamp: true
  43402. });
  43403. if (!ticksCoords.length) {
  43404. return;
  43405. } // For Making appropriate splitArea animation, the color and anid
  43406. // should be corresponding to previous one if possible.
  43407. var areaColorsLen = areaColors.length;
  43408. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  43409. var newSplitAreaColors = createHashMap();
  43410. var colorIndex = 0;
  43411. if (lastSplitAreaColors) {
  43412. for (var i = 0; i < ticksCoords.length; i++) {
  43413. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  43414. if (cIndex != null) {
  43415. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  43416. break;
  43417. }
  43418. }
  43419. }
  43420. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  43421. var areaStyle = areaStyleModel.getAreaStyle();
  43422. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  43423. for (var i = 1; i < ticksCoords.length; i++) {
  43424. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43425. var x = void 0;
  43426. var y = void 0;
  43427. var width = void 0;
  43428. var height = void 0;
  43429. if (axis.isHorizontal()) {
  43430. x = prev;
  43431. y = gridRect.y;
  43432. width = tickCoord - x;
  43433. height = gridRect.height;
  43434. prev = x + width;
  43435. } else {
  43436. x = gridRect.x;
  43437. y = prev;
  43438. width = gridRect.width;
  43439. height = tickCoord - y;
  43440. prev = y + height;
  43441. }
  43442. var tickValue = ticksCoords[i - 1].tickValue;
  43443. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  43444. axisGroup.add(new Rect({
  43445. anid: tickValue != null ? 'area_' + tickValue : null,
  43446. shape: {
  43447. x: x,
  43448. y: y,
  43449. width: width,
  43450. height: height
  43451. },
  43452. style: defaults({
  43453. fill: areaColors[colorIndex]
  43454. }, areaStyle),
  43455. autoBatch: true,
  43456. silent: true
  43457. }));
  43458. colorIndex = (colorIndex + 1) % areaColorsLen;
  43459. }
  43460. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  43461. }
  43462. function rectCoordAxisHandleRemove(axisView) {
  43463. inner$6(axisView).splitAreaColors = null;
  43464. }
  43465. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  43466. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  43467. var CartesianAxisView =
  43468. /** @class */
  43469. function (_super) {
  43470. __extends(CartesianAxisView, _super);
  43471. function CartesianAxisView() {
  43472. var _this = _super !== null && _super.apply(this, arguments) || this;
  43473. _this.type = CartesianAxisView.type;
  43474. _this.axisPointerClass = 'CartesianAxisPointer';
  43475. return _this;
  43476. }
  43477. /**
  43478. * @override
  43479. */
  43480. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43481. this.group.removeAll();
  43482. var oldAxisGroup = this._axisGroup;
  43483. this._axisGroup = new Group();
  43484. this.group.add(this._axisGroup);
  43485. if (!axisModel.get('show')) {
  43486. return;
  43487. }
  43488. var gridModel = axisModel.getCoordSysModel();
  43489. var layout = layout$1(gridModel, axisModel);
  43490. var axisBuilder = new AxisBuilder(axisModel, extend({
  43491. handleAutoShown: function (elementType) {
  43492. var cartesians = gridModel.coordinateSystem.getCartesians();
  43493. for (var i = 0; i < cartesians.length; i++) {
  43494. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  43495. // Still show axis tick or axisLine if other axis is value / log
  43496. return true;
  43497. }
  43498. } // Not show axisTick or axisLine if other axis is category / time
  43499. return false;
  43500. }
  43501. }, layout));
  43502. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  43503. this._axisGroup.add(axisBuilder.getGroup());
  43504. each(selfBuilderAttrs, function (name) {
  43505. if (axisModel.get([name, 'show'])) {
  43506. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  43507. }
  43508. }, this); // THIS is a special case for bar racing chart.
  43509. // Update the axis label from the natural initial layout to
  43510. // sorted layout should has no animation.
  43511. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  43512. if (!isInitialSortFromBarRacing) {
  43513. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  43514. }
  43515. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  43516. };
  43517. CartesianAxisView.prototype.remove = function () {
  43518. rectCoordAxisHandleRemove(this);
  43519. };
  43520. CartesianAxisView.type = 'cartesianAxis';
  43521. return CartesianAxisView;
  43522. }(AxisView);
  43523. var axisElementBuilders = {
  43524. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43525. var axis = axisModel.axis;
  43526. if (axis.scale.isBlank()) {
  43527. return;
  43528. }
  43529. var splitLineModel = axisModel.getModel('splitLine');
  43530. var lineStyleModel = splitLineModel.getModel('lineStyle');
  43531. var lineColors = lineStyleModel.get('color');
  43532. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  43533. var gridRect = gridModel.coordinateSystem.getRect();
  43534. var isHorizontal = axis.isHorizontal();
  43535. var lineCount = 0;
  43536. var ticksCoords = axis.getTicksCoords({
  43537. tickModel: splitLineModel
  43538. });
  43539. var p1 = [];
  43540. var p2 = [];
  43541. var lineStyle = lineStyleModel.getLineStyle();
  43542. for (var i = 0; i < ticksCoords.length; i++) {
  43543. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43544. if (isHorizontal) {
  43545. p1[0] = tickCoord;
  43546. p1[1] = gridRect.y;
  43547. p2[0] = tickCoord;
  43548. p2[1] = gridRect.y + gridRect.height;
  43549. } else {
  43550. p1[0] = gridRect.x;
  43551. p1[1] = tickCoord;
  43552. p2[0] = gridRect.x + gridRect.width;
  43553. p2[1] = tickCoord;
  43554. }
  43555. var colorIndex = lineCount++ % lineColors.length;
  43556. var tickValue = ticksCoords[i].tickValue;
  43557. var line = new Line({
  43558. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  43559. autoBatch: true,
  43560. shape: {
  43561. x1: p1[0],
  43562. y1: p1[1],
  43563. x2: p2[0],
  43564. y2: p2[1]
  43565. },
  43566. style: defaults({
  43567. stroke: lineColors[colorIndex]
  43568. }, lineStyle),
  43569. silent: true
  43570. });
  43571. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43572. axisGroup.add(line);
  43573. }
  43574. },
  43575. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43576. var axis = axisModel.axis;
  43577. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  43578. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  43579. var gridRect = gridModel.coordinateSystem.getRect();
  43580. var isHorizontal = axis.isHorizontal();
  43581. var minorTicksCoords = axis.getMinorTicksCoords();
  43582. if (!minorTicksCoords.length) {
  43583. return;
  43584. }
  43585. var p1 = [];
  43586. var p2 = [];
  43587. var lineStyle = lineStyleModel.getLineStyle();
  43588. for (var i = 0; i < minorTicksCoords.length; i++) {
  43589. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  43590. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  43591. if (isHorizontal) {
  43592. p1[0] = tickCoord;
  43593. p1[1] = gridRect.y;
  43594. p2[0] = tickCoord;
  43595. p2[1] = gridRect.y + gridRect.height;
  43596. } else {
  43597. p1[0] = gridRect.x;
  43598. p1[1] = tickCoord;
  43599. p2[0] = gridRect.x + gridRect.width;
  43600. p2[1] = tickCoord;
  43601. }
  43602. var line = new Line({
  43603. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  43604. autoBatch: true,
  43605. shape: {
  43606. x1: p1[0],
  43607. y1: p1[1],
  43608. x2: p2[0],
  43609. y2: p2[1]
  43610. },
  43611. style: lineStyle,
  43612. silent: true
  43613. });
  43614. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43615. axisGroup.add(line);
  43616. }
  43617. }
  43618. },
  43619. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  43620. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  43621. }
  43622. };
  43623. var CartesianXAxisView =
  43624. /** @class */
  43625. function (_super) {
  43626. __extends(CartesianXAxisView, _super);
  43627. function CartesianXAxisView() {
  43628. var _this = _super !== null && _super.apply(this, arguments) || this;
  43629. _this.type = CartesianXAxisView.type;
  43630. return _this;
  43631. }
  43632. CartesianXAxisView.type = 'xAxis';
  43633. return CartesianXAxisView;
  43634. }(CartesianAxisView);
  43635. var CartesianYAxisView =
  43636. /** @class */
  43637. function (_super) {
  43638. __extends(CartesianYAxisView, _super);
  43639. function CartesianYAxisView() {
  43640. var _this = _super !== null && _super.apply(this, arguments) || this;
  43641. _this.type = CartesianXAxisView.type;
  43642. return _this;
  43643. }
  43644. CartesianYAxisView.type = 'yAxis';
  43645. return CartesianYAxisView;
  43646. }(CartesianAxisView);
  43647. var GridView =
  43648. /** @class */
  43649. function (_super) {
  43650. __extends(GridView, _super);
  43651. function GridView() {
  43652. var _this = _super !== null && _super.apply(this, arguments) || this;
  43653. _this.type = 'grid';
  43654. return _this;
  43655. }
  43656. GridView.prototype.render = function (gridModel, ecModel) {
  43657. this.group.removeAll();
  43658. if (gridModel.get('show')) {
  43659. this.group.add(new Rect({
  43660. shape: gridModel.coordinateSystem.getRect(),
  43661. style: defaults({
  43662. fill: gridModel.get('backgroundColor')
  43663. }, gridModel.getItemStyle()),
  43664. silent: true,
  43665. z2: -1
  43666. }));
  43667. }
  43668. };
  43669. GridView.type = 'grid';
  43670. return GridView;
  43671. }(ComponentView);
  43672. var extraOption = {
  43673. // gridIndex: 0,
  43674. // gridId: '',
  43675. offset: 0
  43676. };
  43677. function install$5(registers) {
  43678. registers.registerComponentView(GridView);
  43679. registers.registerComponentModel(GridModel);
  43680. registers.registerCoordinateSystem('cartesian2d', Grid);
  43681. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  43682. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  43683. registers.registerComponentView(CartesianXAxisView);
  43684. registers.registerComponentView(CartesianYAxisView);
  43685. registers.registerPreprocessor(function (option) {
  43686. // Only create grid when need
  43687. if (option.xAxis && option.yAxis && !option.grid) {
  43688. option.grid = {};
  43689. }
  43690. });
  43691. }
  43692. function install$6(registers) {
  43693. // In case developer forget to include grid component
  43694. use(install$5);
  43695. registers.registerSeriesModel(ScatterSeriesModel);
  43696. registers.registerChartView(ScatterView);
  43697. registers.registerLayout(pointsLayout('scatter'));
  43698. }
  43699. function radarLayout(ecModel) {
  43700. ecModel.eachSeriesByType('radar', function (seriesModel) {
  43701. var data = seriesModel.getData();
  43702. var points = [];
  43703. var coordSys = seriesModel.coordinateSystem;
  43704. if (!coordSys) {
  43705. return;
  43706. }
  43707. var axes = coordSys.getIndicatorAxes();
  43708. each(axes, function (axis, axisIndex) {
  43709. data.each(data.mapDimension(axes[axisIndex].dim), function (val, dataIndex) {
  43710. points[dataIndex] = points[dataIndex] || [];
  43711. var point = coordSys.dataToPoint(val, axisIndex);
  43712. points[dataIndex][axisIndex] = isValidPoint(point) ? point : getValueMissingPoint(coordSys);
  43713. });
  43714. }); // Close polygon
  43715. data.each(function (idx) {
  43716. // TODO
  43717. // Is it appropriate to connect to the next data when some data is missing?
  43718. // Or, should trade it like `connectNull` in line chart?
  43719. var firstPoint = find(points[idx], function (point) {
  43720. return isValidPoint(point);
  43721. }) || getValueMissingPoint(coordSys); // Copy the first actual point to the end of the array
  43722. points[idx].push(firstPoint.slice());
  43723. data.setItemLayout(idx, points[idx]);
  43724. });
  43725. });
  43726. }
  43727. function isValidPoint(point) {
  43728. return !isNaN(point[0]) && !isNaN(point[1]);
  43729. }
  43730. function getValueMissingPoint(coordSys) {
  43731. // It is error-prone to input [NaN, NaN] into polygon, polygon.
  43732. // (probably cause problem when refreshing or animating)
  43733. return [coordSys.cx, coordSys.cy];
  43734. }
  43735. function radarBackwardCompat(option) {
  43736. var polarOptArr = option.polar;
  43737. if (polarOptArr) {
  43738. if (!isArray(polarOptArr)) {
  43739. polarOptArr = [polarOptArr];
  43740. }
  43741. var polarNotRadar_1 = [];
  43742. each(polarOptArr, function (polarOpt, idx) {
  43743. if (polarOpt.indicator) {
  43744. if (polarOpt.type && !polarOpt.shape) {
  43745. polarOpt.shape = polarOpt.type;
  43746. }
  43747. option.radar = option.radar || [];
  43748. if (!isArray(option.radar)) {
  43749. option.radar = [option.radar];
  43750. }
  43751. option.radar.push(polarOpt);
  43752. } else {
  43753. polarNotRadar_1.push(polarOpt);
  43754. }
  43755. });
  43756. option.polar = polarNotRadar_1;
  43757. }
  43758. each(option.series, function (seriesOpt) {
  43759. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  43760. seriesOpt.radarIndex = seriesOpt.polarIndex;
  43761. }
  43762. });
  43763. }
  43764. var RadarView =
  43765. /** @class */
  43766. function (_super) {
  43767. __extends(RadarView, _super);
  43768. function RadarView() {
  43769. var _this = _super !== null && _super.apply(this, arguments) || this;
  43770. _this.type = RadarView.type;
  43771. return _this;
  43772. }
  43773. RadarView.prototype.render = function (seriesModel, ecModel, api) {
  43774. var polar = seriesModel.coordinateSystem;
  43775. var group = this.group;
  43776. var data = seriesModel.getData();
  43777. var oldData = this._data;
  43778. function createSymbol$1(data, idx) {
  43779. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  43780. if (symbolType === 'none') {
  43781. return;
  43782. }
  43783. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  43784. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2);
  43785. var symbolRotate = data.getItemVisual(idx, 'symbolRotate') || 0;
  43786. symbolPath.attr({
  43787. style: {
  43788. strokeNoScale: true
  43789. },
  43790. z2: 100,
  43791. scaleX: symbolSize[0] / 2,
  43792. scaleY: symbolSize[1] / 2,
  43793. rotation: symbolRotate * Math.PI / 180 || 0
  43794. });
  43795. return symbolPath;
  43796. }
  43797. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  43798. // Simply rerender all
  43799. symbolGroup.removeAll();
  43800. for (var i = 0; i < newPoints.length - 1; i++) {
  43801. var symbolPath = createSymbol$1(data, idx);
  43802. if (symbolPath) {
  43803. symbolPath.__dimIdx = i;
  43804. if (oldPoints[i]) {
  43805. symbolPath.setPosition(oldPoints[i]);
  43806. graphic[isInit ? 'initProps' : 'updateProps'](symbolPath, {
  43807. x: newPoints[i][0],
  43808. y: newPoints[i][1]
  43809. }, seriesModel, idx);
  43810. } else {
  43811. symbolPath.setPosition(newPoints[i]);
  43812. }
  43813. symbolGroup.add(symbolPath);
  43814. }
  43815. }
  43816. }
  43817. function getInitialPoints(points) {
  43818. return map(points, function (pt) {
  43819. return [polar.cx, polar.cy];
  43820. });
  43821. }
  43822. data.diff(oldData).add(function (idx) {
  43823. var points = data.getItemLayout(idx);
  43824. if (!points) {
  43825. return;
  43826. }
  43827. var polygon = new Polygon();
  43828. var polyline = new Polyline();
  43829. var target = {
  43830. shape: {
  43831. points: points
  43832. }
  43833. };
  43834. polygon.shape.points = getInitialPoints(points);
  43835. polyline.shape.points = getInitialPoints(points);
  43836. initProps(polygon, target, seriesModel, idx);
  43837. initProps(polyline, target, seriesModel, idx);
  43838. var itemGroup = new Group();
  43839. var symbolGroup = new Group();
  43840. itemGroup.add(polyline);
  43841. itemGroup.add(polygon);
  43842. itemGroup.add(symbolGroup);
  43843. updateSymbols(polyline.shape.points, points, symbolGroup, data, idx, true);
  43844. data.setItemGraphicEl(idx, itemGroup);
  43845. }).update(function (newIdx, oldIdx) {
  43846. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  43847. var polyline = itemGroup.childAt(0);
  43848. var polygon = itemGroup.childAt(1);
  43849. var symbolGroup = itemGroup.childAt(2);
  43850. var target = {
  43851. shape: {
  43852. points: data.getItemLayout(newIdx)
  43853. }
  43854. };
  43855. if (!target.shape.points) {
  43856. return;
  43857. }
  43858. updateSymbols(polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false);
  43859. saveOldStyle(polygon);
  43860. saveOldStyle(polyline);
  43861. updateProps(polyline, target, seriesModel);
  43862. updateProps(polygon, target, seriesModel);
  43863. data.setItemGraphicEl(newIdx, itemGroup);
  43864. }).remove(function (idx) {
  43865. group.remove(oldData.getItemGraphicEl(idx));
  43866. }).execute();
  43867. data.eachItemGraphicEl(function (itemGroup, idx) {
  43868. var itemModel = data.getItemModel(idx);
  43869. var polyline = itemGroup.childAt(0);
  43870. var polygon = itemGroup.childAt(1);
  43871. var symbolGroup = itemGroup.childAt(2); // Radar uses the visual encoded from itemStyle.
  43872. var itemStyle = data.getItemVisual(idx, 'style');
  43873. var color = itemStyle.fill;
  43874. group.add(itemGroup);
  43875. polyline.useStyle(defaults(itemModel.getModel('lineStyle').getLineStyle(), {
  43876. fill: 'none',
  43877. stroke: color
  43878. }));
  43879. setStatesStylesFromModel(polyline, itemModel, 'lineStyle');
  43880. setStatesStylesFromModel(polygon, itemModel, 'areaStyle');
  43881. var areaStyleModel = itemModel.getModel('areaStyle');
  43882. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  43883. polygon.ignore = polygonIgnore;
  43884. each(['emphasis', 'select', 'blur'], function (stateName) {
  43885. var stateModel = itemModel.getModel([stateName, 'areaStyle']);
  43886. var stateIgnore = stateModel.isEmpty() && stateModel.parentModel.isEmpty(); // Won't be ignore if normal state is not ignore.
  43887. polygon.ensureState(stateName).ignore = stateIgnore && polygonIgnore;
  43888. });
  43889. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  43890. fill: color,
  43891. opacity: 0.7,
  43892. decal: itemStyle.decal
  43893. }));
  43894. var emphasisModel = itemModel.getModel('emphasis');
  43895. var itemHoverStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  43896. symbolGroup.eachChild(function (symbolPath) {
  43897. if (symbolPath instanceof ZRImage) {
  43898. var pathStyle = symbolPath.style;
  43899. symbolPath.useStyle(extend({
  43900. // TODO other properties like x, y ?
  43901. image: pathStyle.image,
  43902. x: pathStyle.x,
  43903. y: pathStyle.y,
  43904. width: pathStyle.width,
  43905. height: pathStyle.height
  43906. }, itemStyle));
  43907. } else {
  43908. symbolPath.useStyle(itemStyle);
  43909. symbolPath.setColor(color);
  43910. symbolPath.style.strokeNoScale = true;
  43911. }
  43912. var pathEmphasisState = symbolPath.ensureState('emphasis');
  43913. pathEmphasisState.style = clone(itemHoverStyle);
  43914. var defaultText = data.getStore().get(data.getDimensionIndex(symbolPath.__dimIdx), idx);
  43915. (defaultText == null || isNaN(defaultText)) && (defaultText = '');
  43916. setLabelStyle(symbolPath, getLabelStatesModels(itemModel), {
  43917. labelFetcher: data.hostModel,
  43918. labelDataIndex: idx,
  43919. labelDimIndex: symbolPath.__dimIdx,
  43920. defaultText: defaultText,
  43921. inheritColor: color,
  43922. defaultOpacity: itemStyle.opacity
  43923. });
  43924. });
  43925. toggleHoverEmphasis(itemGroup, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  43926. });
  43927. this._data = data;
  43928. };
  43929. RadarView.prototype.remove = function () {
  43930. this.group.removeAll();
  43931. this._data = null;
  43932. };
  43933. RadarView.type = 'radar';
  43934. return RadarView;
  43935. }(ChartView);
  43936. var RadarSeriesModel =
  43937. /** @class */
  43938. function (_super) {
  43939. __extends(RadarSeriesModel, _super);
  43940. function RadarSeriesModel() {
  43941. var _this = _super !== null && _super.apply(this, arguments) || this;
  43942. _this.type = RadarSeriesModel.type;
  43943. _this.hasSymbolVisual = true;
  43944. return _this;
  43945. } // Overwrite
  43946. RadarSeriesModel.prototype.init = function (option) {
  43947. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  43948. // Use a function instead of direct access because data reference may changed
  43949. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  43950. };
  43951. RadarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  43952. return createSeriesDataSimply(this, {
  43953. generateCoord: 'indicator_',
  43954. generateCoordCount: Infinity
  43955. });
  43956. };
  43957. RadarSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  43958. var data = this.getData();
  43959. var coordSys = this.coordinateSystem;
  43960. var indicatorAxes = coordSys.getIndicatorAxes();
  43961. var name = this.getData().getName(dataIndex);
  43962. var nameToDisplay = name === '' ? this.name : name;
  43963. var markerColor = retrieveVisualColorForTooltipMarker(this, dataIndex);
  43964. return createTooltipMarkup('section', {
  43965. header: nameToDisplay,
  43966. sortBlocks: true,
  43967. blocks: map(indicatorAxes, function (axis) {
  43968. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  43969. return createTooltipMarkup('nameValue', {
  43970. markerType: 'subItem',
  43971. markerColor: markerColor,
  43972. name: axis.name,
  43973. value: val,
  43974. sortParam: val
  43975. });
  43976. })
  43977. });
  43978. };
  43979. RadarSeriesModel.prototype.getTooltipPosition = function (dataIndex) {
  43980. if (dataIndex != null) {
  43981. var data_1 = this.getData();
  43982. var coordSys = this.coordinateSystem;
  43983. var values = data_1.getValues(map(coordSys.dimensions, function (dim) {
  43984. return data_1.mapDimension(dim);
  43985. }), dataIndex);
  43986. for (var i = 0, len = values.length; i < len; i++) {
  43987. if (!isNaN(values[i])) {
  43988. var indicatorAxes = coordSys.getIndicatorAxes();
  43989. return coordSys.coordToPoint(indicatorAxes[i].dataToCoord(values[i]), i);
  43990. }
  43991. }
  43992. }
  43993. };
  43994. RadarSeriesModel.type = 'series.radar';
  43995. RadarSeriesModel.dependencies = ['radar'];
  43996. RadarSeriesModel.defaultOption = {
  43997. // zlevel: 0,
  43998. z: 2,
  43999. colorBy: 'data',
  44000. coordinateSystem: 'radar',
  44001. legendHoverLink: true,
  44002. radarIndex: 0,
  44003. lineStyle: {
  44004. width: 2,
  44005. type: 'solid',
  44006. join: 'round'
  44007. },
  44008. label: {
  44009. position: 'top'
  44010. },
  44011. // areaStyle: {
  44012. // },
  44013. // itemStyle: {}
  44014. symbolSize: 8 // symbolRotate: null
  44015. };
  44016. return RadarSeriesModel;
  44017. }(SeriesModel);
  44018. var valueAxisDefault = axisDefault.value;
  44019. function defaultsShow(opt, show) {
  44020. return defaults({
  44021. show: show
  44022. }, opt);
  44023. }
  44024. var RadarModel =
  44025. /** @class */
  44026. function (_super) {
  44027. __extends(RadarModel, _super);
  44028. function RadarModel() {
  44029. var _this = _super !== null && _super.apply(this, arguments) || this;
  44030. _this.type = RadarModel.type;
  44031. return _this;
  44032. }
  44033. RadarModel.prototype.optionUpdated = function () {
  44034. var boundaryGap = this.get('boundaryGap');
  44035. var splitNumber = this.get('splitNumber');
  44036. var scale = this.get('scale');
  44037. var axisLine = this.get('axisLine');
  44038. var axisTick = this.get('axisTick'); // let axisType = this.get('axisType');
  44039. var axisLabel = this.get('axisLabel');
  44040. var nameTextStyle = this.get('axisName');
  44041. var showName = this.get(['axisName', 'show']);
  44042. var nameFormatter = this.get(['axisName', 'formatter']);
  44043. var nameGap = this.get('axisNameGap');
  44044. var triggerEvent = this.get('triggerEvent');
  44045. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  44046. // PENDING
  44047. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  44048. indicatorOpt.min = 0;
  44049. } else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  44050. indicatorOpt.max = 0;
  44051. }
  44052. var iNameTextStyle = nameTextStyle;
  44053. if (indicatorOpt.color != null) {
  44054. iNameTextStyle = defaults({
  44055. color: indicatorOpt.color
  44056. }, nameTextStyle);
  44057. } // Use same configuration
  44058. var innerIndicatorOpt = merge(clone(indicatorOpt), {
  44059. boundaryGap: boundaryGap,
  44060. splitNumber: splitNumber,
  44061. scale: scale,
  44062. axisLine: axisLine,
  44063. axisTick: axisTick,
  44064. // axisType: axisType,
  44065. axisLabel: axisLabel,
  44066. // Compatible with 2 and use text
  44067. name: indicatorOpt.text,
  44068. showName: showName,
  44069. nameLocation: 'end',
  44070. nameGap: nameGap,
  44071. // min: 0,
  44072. nameTextStyle: iNameTextStyle,
  44073. triggerEvent: triggerEvent
  44074. }, false);
  44075. if (isString(nameFormatter)) {
  44076. var indName = innerIndicatorOpt.name;
  44077. innerIndicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  44078. } else if (isFunction(nameFormatter)) {
  44079. innerIndicatorOpt.name = nameFormatter(innerIndicatorOpt.name, innerIndicatorOpt);
  44080. }
  44081. var model = new Model(innerIndicatorOpt, null, this.ecModel);
  44082. mixin(model, AxisModelCommonMixin.prototype); // For triggerEvent.
  44083. model.mainType = 'radar';
  44084. model.componentIndex = this.componentIndex;
  44085. return model;
  44086. }, this);
  44087. this._indicatorModels = indicatorModels;
  44088. };
  44089. RadarModel.prototype.getIndicatorModels = function () {
  44090. return this._indicatorModels;
  44091. };
  44092. RadarModel.type = 'radar';
  44093. RadarModel.defaultOption = {
  44094. // zlevel: 0,
  44095. z: 0,
  44096. center: ['50%', '50%'],
  44097. radius: '75%',
  44098. startAngle: 90,
  44099. axisName: {
  44100. show: true // formatter: null
  44101. // textStyle: {}
  44102. },
  44103. boundaryGap: [0, 0],
  44104. splitNumber: 5,
  44105. axisNameGap: 15,
  44106. scale: false,
  44107. // Polygon or circle
  44108. shape: 'polygon',
  44109. axisLine: merge({
  44110. lineStyle: {
  44111. color: '#bbb'
  44112. }
  44113. }, valueAxisDefault.axisLine),
  44114. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  44115. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  44116. // axisType: 'value',
  44117. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  44118. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  44119. // {text, min, max}
  44120. indicator: []
  44121. };
  44122. return RadarModel;
  44123. }(ComponentModel);
  44124. var axisBuilderAttrs$1 = ['axisLine', 'axisTickLabel', 'axisName'];
  44125. var RadarView$1 =
  44126. /** @class */
  44127. function (_super) {
  44128. __extends(RadarView, _super);
  44129. function RadarView() {
  44130. var _this = _super !== null && _super.apply(this, arguments) || this;
  44131. _this.type = RadarView.type;
  44132. return _this;
  44133. }
  44134. RadarView.prototype.render = function (radarModel, ecModel, api) {
  44135. var group = this.group;
  44136. group.removeAll();
  44137. this._buildAxes(radarModel);
  44138. this._buildSplitLineAndArea(radarModel);
  44139. };
  44140. RadarView.prototype._buildAxes = function (radarModel) {
  44141. var radar = radarModel.coordinateSystem;
  44142. var indicatorAxes = radar.getIndicatorAxes();
  44143. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  44144. var axisName = indicatorAxis.model.get('showName') ? indicatorAxis.name : ''; // hide name
  44145. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  44146. axisName: axisName,
  44147. position: [radar.cx, radar.cy],
  44148. rotation: indicatorAxis.angle,
  44149. labelDirection: -1,
  44150. tickDirection: -1,
  44151. nameDirection: 1
  44152. });
  44153. return axisBuilder;
  44154. });
  44155. each(axisBuilders, function (axisBuilder) {
  44156. each(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  44157. this.group.add(axisBuilder.getGroup());
  44158. }, this);
  44159. };
  44160. RadarView.prototype._buildSplitLineAndArea = function (radarModel) {
  44161. var radar = radarModel.coordinateSystem;
  44162. var indicatorAxes = radar.getIndicatorAxes();
  44163. if (!indicatorAxes.length) {
  44164. return;
  44165. }
  44166. var shape = radarModel.get('shape');
  44167. var splitLineModel = radarModel.getModel('splitLine');
  44168. var splitAreaModel = radarModel.getModel('splitArea');
  44169. var lineStyleModel = splitLineModel.getModel('lineStyle');
  44170. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  44171. var showSplitLine = splitLineModel.get('show');
  44172. var showSplitArea = splitAreaModel.get('show');
  44173. var splitLineColors = lineStyleModel.get('color');
  44174. var splitAreaColors = areaStyleModel.get('color');
  44175. var splitLineColorsArr = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  44176. var splitAreaColorsArr = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  44177. var splitLines = [];
  44178. var splitAreas = [];
  44179. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  44180. var colorIndex = idx % areaOrLineColorList.length;
  44181. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  44182. return colorIndex;
  44183. }
  44184. if (shape === 'circle') {
  44185. var ticksRadius = indicatorAxes[0].getTicksCoords();
  44186. var cx = radar.cx;
  44187. var cy = radar.cy;
  44188. for (var i = 0; i < ticksRadius.length; i++) {
  44189. if (showSplitLine) {
  44190. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  44191. splitLines[colorIndex].push(new Circle({
  44192. shape: {
  44193. cx: cx,
  44194. cy: cy,
  44195. r: ticksRadius[i].coord
  44196. }
  44197. }));
  44198. }
  44199. if (showSplitArea && i < ticksRadius.length - 1) {
  44200. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i);
  44201. splitAreas[colorIndex].push(new Ring({
  44202. shape: {
  44203. cx: cx,
  44204. cy: cy,
  44205. r0: ticksRadius[i].coord,
  44206. r: ticksRadius[i + 1].coord
  44207. }
  44208. }));
  44209. }
  44210. }
  44211. } // Polyyon
  44212. else {
  44213. var realSplitNumber_1;
  44214. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  44215. var ticksCoords = indicatorAxis.getTicksCoords();
  44216. realSplitNumber_1 = realSplitNumber_1 == null ? ticksCoords.length - 1 : Math.min(ticksCoords.length - 1, realSplitNumber_1);
  44217. return map(ticksCoords, function (tickCoord) {
  44218. return radar.coordToPoint(tickCoord.coord, idx);
  44219. });
  44220. });
  44221. var prevPoints = [];
  44222. for (var i = 0; i <= realSplitNumber_1; i++) {
  44223. var points = [];
  44224. for (var j = 0; j < indicatorAxes.length; j++) {
  44225. points.push(axesTicksPoints[j][i]);
  44226. } // Close
  44227. if (points[0]) {
  44228. points.push(points[0].slice());
  44229. } else {
  44230. if ("development" !== 'production') {
  44231. console.error('Can\'t draw value axis ' + i);
  44232. }
  44233. }
  44234. if (showSplitLine) {
  44235. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  44236. splitLines[colorIndex].push(new Polyline({
  44237. shape: {
  44238. points: points
  44239. }
  44240. }));
  44241. }
  44242. if (showSplitArea && prevPoints) {
  44243. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i - 1);
  44244. splitAreas[colorIndex].push(new Polygon({
  44245. shape: {
  44246. points: points.concat(prevPoints)
  44247. }
  44248. }));
  44249. }
  44250. prevPoints = points.slice().reverse();
  44251. }
  44252. }
  44253. var lineStyle = lineStyleModel.getLineStyle();
  44254. var areaStyle = areaStyleModel.getAreaStyle(); // Add splitArea before splitLine
  44255. each(splitAreas, function (splitAreas, idx) {
  44256. this.group.add(mergePath$1(splitAreas, {
  44257. style: defaults({
  44258. stroke: 'none',
  44259. fill: splitAreaColorsArr[idx % splitAreaColorsArr.length]
  44260. }, areaStyle),
  44261. silent: true
  44262. }));
  44263. }, this);
  44264. each(splitLines, function (splitLines, idx) {
  44265. this.group.add(mergePath$1(splitLines, {
  44266. style: defaults({
  44267. fill: 'none',
  44268. stroke: splitLineColorsArr[idx % splitLineColorsArr.length]
  44269. }, lineStyle),
  44270. silent: true
  44271. }));
  44272. }, this);
  44273. };
  44274. RadarView.type = 'radar';
  44275. return RadarView;
  44276. }(ComponentView);
  44277. var IndicatorAxis =
  44278. /** @class */
  44279. function (_super) {
  44280. __extends(IndicatorAxis, _super);
  44281. function IndicatorAxis(dim, scale, radiusExtent) {
  44282. var _this = _super.call(this, dim, scale, radiusExtent) || this;
  44283. _this.type = 'value';
  44284. _this.angle = 0;
  44285. _this.name = '';
  44286. return _this;
  44287. }
  44288. return IndicatorAxis;
  44289. }(Axis);
  44290. var Radar =
  44291. /** @class */
  44292. function () {
  44293. function Radar(radarModel, ecModel, api) {
  44294. /**
  44295. *
  44296. * Radar dimensions
  44297. */
  44298. this.dimensions = [];
  44299. this._model = radarModel;
  44300. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  44301. var dim = 'indicator_' + idx;
  44302. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale() // (indicatorModel.get('axisType') === 'log') ? new LogScale() : new IntervalScale()
  44303. );
  44304. indicatorAxis.name = indicatorModel.get('name'); // Inject model and axis
  44305. indicatorAxis.model = indicatorModel;
  44306. indicatorModel.axis = indicatorAxis;
  44307. this.dimensions.push(dim);
  44308. return indicatorAxis;
  44309. }, this);
  44310. this.resize(radarModel, api);
  44311. }
  44312. Radar.prototype.getIndicatorAxes = function () {
  44313. return this._indicatorAxes;
  44314. };
  44315. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  44316. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  44317. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  44318. }; // TODO: API should be coordToPoint([coord, indicatorIndex])
  44319. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  44320. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  44321. var angle = indicatorAxis.angle;
  44322. var x = this.cx + coord * Math.cos(angle);
  44323. var y = this.cy - coord * Math.sin(angle);
  44324. return [x, y];
  44325. };
  44326. Radar.prototype.pointToData = function (pt) {
  44327. var dx = pt[0] - this.cx;
  44328. var dy = pt[1] - this.cy;
  44329. var radius = Math.sqrt(dx * dx + dy * dy);
  44330. dx /= radius;
  44331. dy /= radius;
  44332. var radian = Math.atan2(-dy, dx); // Find the closest angle
  44333. // FIXME index can calculated directly
  44334. var minRadianDiff = Infinity;
  44335. var closestAxis;
  44336. var closestAxisIdx = -1;
  44337. for (var i = 0; i < this._indicatorAxes.length; i++) {
  44338. var indicatorAxis = this._indicatorAxes[i];
  44339. var diff = Math.abs(radian - indicatorAxis.angle);
  44340. if (diff < minRadianDiff) {
  44341. closestAxis = indicatorAxis;
  44342. closestAxisIdx = i;
  44343. minRadianDiff = diff;
  44344. }
  44345. }
  44346. return [closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius))];
  44347. };
  44348. Radar.prototype.resize = function (radarModel, api) {
  44349. var center = radarModel.get('center');
  44350. var viewWidth = api.getWidth();
  44351. var viewHeight = api.getHeight();
  44352. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  44353. this.cx = parsePercent$1(center[0], viewWidth);
  44354. this.cy = parsePercent$1(center[1], viewHeight);
  44355. this.startAngle = radarModel.get('startAngle') * Math.PI / 180; // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  44356. var radius = radarModel.get('radius');
  44357. if (isString(radius) || isNumber(radius)) {
  44358. radius = [0, radius];
  44359. }
  44360. this.r0 = parsePercent$1(radius[0], viewSize);
  44361. this.r = parsePercent$1(radius[1], viewSize);
  44362. each(this._indicatorAxes, function (indicatorAxis, idx) {
  44363. indicatorAxis.setExtent(this.r0, this.r);
  44364. var angle = this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length; // Normalize to [-PI, PI]
  44365. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  44366. indicatorAxis.angle = angle;
  44367. }, this);
  44368. };
  44369. Radar.prototype.update = function (ecModel, api) {
  44370. var indicatorAxes = this._indicatorAxes;
  44371. var radarModel = this._model;
  44372. each(indicatorAxes, function (indicatorAxis) {
  44373. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  44374. });
  44375. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  44376. if (radarSeries.get('coordinateSystem') !== 'radar' // @ts-ignore
  44377. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel) {
  44378. return;
  44379. }
  44380. var data = radarSeries.getData();
  44381. each(indicatorAxes, function (indicatorAxis) {
  44382. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  44383. });
  44384. }, this);
  44385. var splitNumber = radarModel.get('splitNumber');
  44386. var dummyScale = new IntervalScale();
  44387. dummyScale.setExtent(0, splitNumber);
  44388. dummyScale.setInterval(1); // Force all the axis fixing the maxSplitNumber.
  44389. each(indicatorAxes, function (indicatorAxis, idx) {
  44390. alignScaleTicks(indicatorAxis.scale, indicatorAxis.model, dummyScale);
  44391. });
  44392. };
  44393. Radar.prototype.convertToPixel = function (ecModel, finder, value) {
  44394. console.warn('Not implemented.');
  44395. return null;
  44396. };
  44397. Radar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  44398. console.warn('Not implemented.');
  44399. return null;
  44400. };
  44401. Radar.prototype.containPoint = function (point) {
  44402. console.warn('Not implemented.');
  44403. return false;
  44404. };
  44405. Radar.create = function (ecModel, api) {
  44406. var radarList = [];
  44407. ecModel.eachComponent('radar', function (radarModel) {
  44408. var radar = new Radar(radarModel, ecModel, api);
  44409. radarList.push(radar);
  44410. radarModel.coordinateSystem = radar;
  44411. });
  44412. ecModel.eachSeriesByType('radar', function (radarSeries) {
  44413. if (radarSeries.get('coordinateSystem') === 'radar') {
  44414. // Inject coordinate system
  44415. // @ts-ignore
  44416. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  44417. }
  44418. });
  44419. return radarList;
  44420. };
  44421. /**
  44422. * Radar dimensions is based on the data
  44423. */
  44424. Radar.dimensions = [];
  44425. return Radar;
  44426. }();
  44427. function install$7(registers) {
  44428. registers.registerCoordinateSystem('radar', Radar);
  44429. registers.registerComponentModel(RadarModel);
  44430. registers.registerComponentView(RadarView$1);
  44431. registers.registerVisual({
  44432. seriesType: 'radar',
  44433. reset: function (seriesModel) {
  44434. var data = seriesModel.getData(); // itemVisual symbol is for selected data
  44435. data.each(function (idx) {
  44436. data.setItemVisual(idx, 'legendIcon', 'roundRect');
  44437. }); // visual is for unselected data
  44438. data.setVisual('legendIcon', 'roundRect');
  44439. }
  44440. });
  44441. }
  44442. function install$8(registers) {
  44443. use(install$7);
  44444. registers.registerChartView(RadarView);
  44445. registers.registerSeriesModel(RadarSeriesModel);
  44446. registers.registerLayout(radarLayout);
  44447. registers.registerProcessor(dataFilter('radar'));
  44448. registers.registerPreprocessor(radarBackwardCompat);
  44449. }
  44450. var ATTR = '\0_ec_interaction_mutex';
  44451. function take(zr, resourceKey, userKey) {
  44452. var store = getStore(zr);
  44453. store[resourceKey] = userKey;
  44454. }
  44455. function release(zr, resourceKey, userKey) {
  44456. var store = getStore(zr);
  44457. var uKey = store[resourceKey];
  44458. if (uKey === userKey) {
  44459. store[resourceKey] = null;
  44460. }
  44461. }
  44462. function isTaken(zr, resourceKey) {
  44463. return !!getStore(zr)[resourceKey];
  44464. }
  44465. function getStore(zr) {
  44466. return zr[ATTR] || (zr[ATTR] = {});
  44467. }
  44468. /**
  44469. * payload: {
  44470. * type: 'takeGlobalCursor',
  44471. * key: 'dataZoomSelect', or 'brush', or ...,
  44472. * If no userKey, release global cursor.
  44473. * }
  44474. */
  44475. // TODO: SELF REGISTERED.
  44476. registerAction({
  44477. type: 'takeGlobalCursor',
  44478. event: 'globalCursorTaken',
  44479. update: 'update'
  44480. }, noop);
  44481. var RoamController =
  44482. /** @class */
  44483. function (_super) {
  44484. __extends(RoamController, _super);
  44485. function RoamController(zr) {
  44486. var _this = _super.call(this) || this;
  44487. _this._zr = zr; // Avoid two roamController bind the same handler
  44488. var mousedownHandler = bind(_this._mousedownHandler, _this);
  44489. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  44490. var mouseupHandler = bind(_this._mouseupHandler, _this);
  44491. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  44492. var pinchHandler = bind(_this._pinchHandler, _this);
  44493. /**
  44494. * Notice: only enable needed types. For example, if 'zoom'
  44495. * is not needed, 'zoom' should not be enabled, otherwise
  44496. * default mousewheel behaviour (scroll page) will be disabled.
  44497. */
  44498. _this.enable = function (controlType, opt) {
  44499. // Disable previous first
  44500. this.disable();
  44501. this._opt = defaults(clone(opt) || {}, {
  44502. zoomOnMouseWheel: true,
  44503. moveOnMouseMove: true,
  44504. // By default, wheel do not trigger move.
  44505. moveOnMouseWheel: false,
  44506. preventDefaultMouseMove: true
  44507. });
  44508. if (controlType == null) {
  44509. controlType = true;
  44510. }
  44511. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  44512. zr.on('mousedown', mousedownHandler);
  44513. zr.on('mousemove', mousemoveHandler);
  44514. zr.on('mouseup', mouseupHandler);
  44515. }
  44516. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  44517. zr.on('mousewheel', mousewheelHandler);
  44518. zr.on('pinch', pinchHandler);
  44519. }
  44520. };
  44521. _this.disable = function () {
  44522. zr.off('mousedown', mousedownHandler);
  44523. zr.off('mousemove', mousemoveHandler);
  44524. zr.off('mouseup', mouseupHandler);
  44525. zr.off('mousewheel', mousewheelHandler);
  44526. zr.off('pinch', pinchHandler);
  44527. };
  44528. return _this;
  44529. }
  44530. RoamController.prototype.isDragging = function () {
  44531. return this._dragging;
  44532. };
  44533. RoamController.prototype.isPinching = function () {
  44534. return this._pinching;
  44535. };
  44536. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  44537. this.pointerChecker = pointerChecker;
  44538. };
  44539. RoamController.prototype.dispose = function () {
  44540. this.disable();
  44541. };
  44542. RoamController.prototype._mousedownHandler = function (e) {
  44543. if (isMiddleOrRightButtonOnMouseUpDown(e)) {
  44544. return;
  44545. }
  44546. var el = e.target;
  44547. while (el) {
  44548. if (el.draggable) {
  44549. return;
  44550. } // check if host is draggable
  44551. el = el.__hostTarget || el.parent;
  44552. }
  44553. var x = e.offsetX;
  44554. var y = e.offsetY; // Only check on mosedown, but not mousemove.
  44555. // Mouse can be out of target when mouse moving.
  44556. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  44557. this._x = x;
  44558. this._y = y;
  44559. this._dragging = true;
  44560. }
  44561. };
  44562. RoamController.prototype._mousemoveHandler = function (e) {
  44563. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  44564. return;
  44565. }
  44566. var x = e.offsetX;
  44567. var y = e.offsetY;
  44568. var oldX = this._x;
  44569. var oldY = this._y;
  44570. var dx = x - oldX;
  44571. var dy = y - oldY;
  44572. this._x = x;
  44573. this._y = y;
  44574. this._opt.preventDefaultMouseMove && stop(e.event);
  44575. trigger(this, 'pan', 'moveOnMouseMove', e, {
  44576. dx: dx,
  44577. dy: dy,
  44578. oldX: oldX,
  44579. oldY: oldY,
  44580. newX: x,
  44581. newY: y,
  44582. isAvailableBehavior: null
  44583. });
  44584. };
  44585. RoamController.prototype._mouseupHandler = function (e) {
  44586. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  44587. this._dragging = false;
  44588. }
  44589. };
  44590. RoamController.prototype._mousewheelHandler = function (e) {
  44591. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  44592. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  44593. var wheelDelta = e.wheelDelta;
  44594. var absWheelDeltaDelta = Math.abs(wheelDelta);
  44595. var originX = e.offsetX;
  44596. var originY = e.offsetY; // wheelDelta maybe -0 in chrome mac.
  44597. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  44598. return;
  44599. } // If both `shouldZoom` and `shouldMove` is true, trigger
  44600. // their event both, and the final behavior is determined
  44601. // by event listener themselves.
  44602. if (shouldZoom) {
  44603. // Convenience:
  44604. // Mac and VM Windows on Mac: scroll up: zoom out.
  44605. // Windows: scroll up: zoom in.
  44606. // FIXME: Should do more test in different environment.
  44607. // wheelDelta is too complicated in difference nvironment
  44608. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  44609. // although it has been normallized by zrender.
  44610. // wheelDelta of mouse wheel is bigger than touch pad.
  44611. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  44612. var scale = wheelDelta > 0 ? factor : 1 / factor;
  44613. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  44614. scale: scale,
  44615. originX: originX,
  44616. originY: originY,
  44617. isAvailableBehavior: null
  44618. });
  44619. }
  44620. if (shouldMove) {
  44621. // FIXME: Should do more test in different environment.
  44622. var absDelta = Math.abs(wheelDelta); // wheelDelta of mouse wheel is bigger than touch pad.
  44623. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  44624. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  44625. scrollDelta: scrollDelta,
  44626. originX: originX,
  44627. originY: originY,
  44628. isAvailableBehavior: null
  44629. });
  44630. }
  44631. };
  44632. RoamController.prototype._pinchHandler = function (e) {
  44633. if (isTaken(this._zr, 'globalPan')) {
  44634. return;
  44635. }
  44636. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  44637. checkPointerAndTrigger(this, 'zoom', null, e, {
  44638. scale: scale,
  44639. originX: e.pinchX,
  44640. originY: e.pinchY,
  44641. isAvailableBehavior: null
  44642. });
  44643. };
  44644. return RoamController;
  44645. }(Eventful);
  44646. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  44647. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  44648. // When mouse is out of roamController rect,
  44649. // default befavoius should not be be disabled, otherwise
  44650. // page sliding is disabled, contrary to expectation.
  44651. stop(e.event);
  44652. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  44653. }
  44654. }
  44655. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  44656. // Also provide behavior checker for event listener, for some case that
  44657. // multiple components share one listener.
  44658. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e); // TODO should not have type issue.
  44659. controller.trigger(eventName, contollerEvent);
  44660. } // settings: {
  44661. // zoomOnMouseWheel
  44662. // moveOnMouseMove
  44663. // moveOnMouseWheel
  44664. // }
  44665. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  44666. function isAvailableBehavior(behaviorToCheck, e, settings) {
  44667. var setting = settings[behaviorToCheck];
  44668. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  44669. }
  44670. /*
  44671. * Licensed to the Apache Software Foundation (ASF) under one
  44672. * or more contributor license agreements. See the NOTICE file
  44673. * distributed with this work for additional information
  44674. * regarding copyright ownership. The ASF licenses this file
  44675. * to you under the Apache License, Version 2.0 (the
  44676. * "License"); you may not use this file except in compliance
  44677. * with the License. You may obtain a copy of the License at
  44678. *
  44679. * http://www.apache.org/licenses/LICENSE-2.0
  44680. *
  44681. * Unless required by applicable law or agreed to in writing,
  44682. * software distributed under the License is distributed on an
  44683. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44684. * KIND, either express or implied. See the License for the
  44685. * specific language governing permissions and limitations
  44686. * under the License.
  44687. */
  44688. /**
  44689. * AUTO-GENERATED FILE. DO NOT MODIFY.
  44690. */
  44691. /*
  44692. * Licensed to the Apache Software Foundation (ASF) under one
  44693. * or more contributor license agreements. See the NOTICE file
  44694. * distributed with this work for additional information
  44695. * regarding copyright ownership. The ASF licenses this file
  44696. * to you under the Apache License, Version 2.0 (the
  44697. * "License"); you may not use this file except in compliance
  44698. * with the License. You may obtain a copy of the License at
  44699. *
  44700. * http://www.apache.org/licenses/LICENSE-2.0
  44701. *
  44702. * Unless required by applicable law or agreed to in writing,
  44703. * software distributed under the License is distributed on an
  44704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44705. * KIND, either express or implied. See the License for the
  44706. * specific language governing permissions and limitations
  44707. * under the License.
  44708. */
  44709. /**
  44710. * For geo and graph.
  44711. */
  44712. function updateViewOnPan(controllerHost, dx, dy) {
  44713. var target = controllerHost.target;
  44714. target.x += dx;
  44715. target.y += dy;
  44716. target.dirty();
  44717. }
  44718. /**
  44719. * For geo and graph.
  44720. */
  44721. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  44722. var target = controllerHost.target;
  44723. var zoomLimit = controllerHost.zoomLimit;
  44724. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  44725. newZoom *= zoomDelta;
  44726. if (zoomLimit) {
  44727. var zoomMin = zoomLimit.min || 0;
  44728. var zoomMax = zoomLimit.max || Infinity;
  44729. newZoom = Math.max(Math.min(zoomMax, newZoom), zoomMin);
  44730. }
  44731. var zoomScale = newZoom / controllerHost.zoom;
  44732. controllerHost.zoom = newZoom; // Keep the mouse center when scaling
  44733. target.x -= (zoomX - target.x) * (zoomScale - 1);
  44734. target.y -= (zoomY - target.y) * (zoomScale - 1);
  44735. target.scaleX *= zoomScale;
  44736. target.scaleY *= zoomScale;
  44737. target.dirty();
  44738. }
  44739. /*
  44740. * Licensed to the Apache Software Foundation (ASF) under one
  44741. * or more contributor license agreements. See the NOTICE file
  44742. * distributed with this work for additional information
  44743. * regarding copyright ownership. The ASF licenses this file
  44744. * to you under the Apache License, Version 2.0 (the
  44745. * "License"); you may not use this file except in compliance
  44746. * with the License. You may obtain a copy of the License at
  44747. *
  44748. * http://www.apache.org/licenses/LICENSE-2.0
  44749. *
  44750. * Unless required by applicable law or agreed to in writing,
  44751. * software distributed under the License is distributed on an
  44752. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44753. * KIND, either express or implied. See the License for the
  44754. * specific language governing permissions and limitations
  44755. * under the License.
  44756. */
  44757. /**
  44758. * AUTO-GENERATED FILE. DO NOT MODIFY.
  44759. */
  44760. /*
  44761. * Licensed to the Apache Software Foundation (ASF) under one
  44762. * or more contributor license agreements. See the NOTICE file
  44763. * distributed with this work for additional information
  44764. * regarding copyright ownership. The ASF licenses this file
  44765. * to you under the Apache License, Version 2.0 (the
  44766. * "License"); you may not use this file except in compliance
  44767. * with the License. You may obtain a copy of the License at
  44768. *
  44769. * http://www.apache.org/licenses/LICENSE-2.0
  44770. *
  44771. * Unless required by applicable law or agreed to in writing,
  44772. * software distributed under the License is distributed on an
  44773. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44774. * KIND, either express or implied. See the License for the
  44775. * specific language governing permissions and limitations
  44776. * under the License.
  44777. */
  44778. var IRRELEVANT_EXCLUDES = {
  44779. 'axisPointer': 1,
  44780. 'tooltip': 1,
  44781. 'brush': 1
  44782. };
  44783. /**
  44784. * Avoid that: mouse click on a elements that is over geo or graph,
  44785. * but roam is triggered.
  44786. */
  44787. function onIrrelevantElement(e, api, targetCoordSysModel) {
  44788. var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.
  44789. var coordSys = model && model.coordinateSystem;
  44790. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  44791. }
  44792. function parseXML(svg) {
  44793. if (isString(svg)) {
  44794. var parser = new DOMParser();
  44795. svg = parser.parseFromString(svg, 'text/xml');
  44796. }
  44797. var svgNode = svg;
  44798. if (svgNode.nodeType === 9) {
  44799. svgNode = svgNode.firstChild;
  44800. }
  44801. while (svgNode.nodeName.toLowerCase() !== 'svg' || svgNode.nodeType !== 1) {
  44802. svgNode = svgNode.nextSibling;
  44803. }
  44804. return svgNode;
  44805. }
  44806. var nodeParsers;
  44807. var INHERITABLE_STYLE_ATTRIBUTES_MAP = {
  44808. 'fill': 'fill',
  44809. 'stroke': 'stroke',
  44810. 'stroke-width': 'lineWidth',
  44811. 'opacity': 'opacity',
  44812. 'fill-opacity': 'fillOpacity',
  44813. 'stroke-opacity': 'strokeOpacity',
  44814. 'stroke-dasharray': 'lineDash',
  44815. 'stroke-dashoffset': 'lineDashOffset',
  44816. 'stroke-linecap': 'lineCap',
  44817. 'stroke-linejoin': 'lineJoin',
  44818. 'stroke-miterlimit': 'miterLimit',
  44819. 'font-family': 'fontFamily',
  44820. 'font-size': 'fontSize',
  44821. 'font-style': 'fontStyle',
  44822. 'font-weight': 'fontWeight',
  44823. 'text-anchor': 'textAlign',
  44824. 'visibility': 'visibility',
  44825. 'display': 'display'
  44826. };
  44827. var INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS = keys(INHERITABLE_STYLE_ATTRIBUTES_MAP);
  44828. var SELF_STYLE_ATTRIBUTES_MAP = {
  44829. 'alignment-baseline': 'textBaseline',
  44830. 'stop-color': 'stopColor'
  44831. };
  44832. var SELF_STYLE_ATTRIBUTES_MAP_KEYS = keys(SELF_STYLE_ATTRIBUTES_MAP);
  44833. var SVGParser = (function () {
  44834. function SVGParser() {
  44835. this._defs = {};
  44836. this._root = null;
  44837. }
  44838. SVGParser.prototype.parse = function (xml, opt) {
  44839. opt = opt || {};
  44840. var svg = parseXML(xml);
  44841. if ("development" !== 'production') {
  44842. if (!svg) {
  44843. throw new Error('Illegal svg');
  44844. }
  44845. }
  44846. this._defsUsePending = [];
  44847. var root = new Group();
  44848. this._root = root;
  44849. var named = [];
  44850. var viewBox = svg.getAttribute('viewBox') || '';
  44851. var width = parseFloat((svg.getAttribute('width') || opt.width));
  44852. var height = parseFloat((svg.getAttribute('height') || opt.height));
  44853. isNaN(width) && (width = null);
  44854. isNaN(height) && (height = null);
  44855. parseAttributes(svg, root, null, true, false);
  44856. var child = svg.firstChild;
  44857. while (child) {
  44858. this._parseNode(child, root, named, null, false, false);
  44859. child = child.nextSibling;
  44860. }
  44861. applyDefs(this._defs, this._defsUsePending);
  44862. this._defsUsePending = [];
  44863. var viewBoxRect;
  44864. var viewBoxTransform;
  44865. if (viewBox) {
  44866. var viewBoxArr = splitNumberSequence(viewBox);
  44867. if (viewBoxArr.length >= 4) {
  44868. viewBoxRect = {
  44869. x: parseFloat((viewBoxArr[0] || 0)),
  44870. y: parseFloat((viewBoxArr[1] || 0)),
  44871. width: parseFloat(viewBoxArr[2]),
  44872. height: parseFloat(viewBoxArr[3])
  44873. };
  44874. }
  44875. }
  44876. if (viewBoxRect && width != null && height != null) {
  44877. viewBoxTransform = makeViewBoxTransform(viewBoxRect, { x: 0, y: 0, width: width, height: height });
  44878. if (!opt.ignoreViewBox) {
  44879. var elRoot = root;
  44880. root = new Group();
  44881. root.add(elRoot);
  44882. elRoot.scaleX = elRoot.scaleY = viewBoxTransform.scale;
  44883. elRoot.x = viewBoxTransform.x;
  44884. elRoot.y = viewBoxTransform.y;
  44885. }
  44886. }
  44887. if (!opt.ignoreRootClip && width != null && height != null) {
  44888. root.setClipPath(new Rect({
  44889. shape: { x: 0, y: 0, width: width, height: height }
  44890. }));
  44891. }
  44892. return {
  44893. root: root,
  44894. width: width,
  44895. height: height,
  44896. viewBoxRect: viewBoxRect,
  44897. viewBoxTransform: viewBoxTransform,
  44898. named: named
  44899. };
  44900. };
  44901. SVGParser.prototype._parseNode = function (xmlNode, parentGroup, named, namedFrom, isInDefs, isInText) {
  44902. var nodeName = xmlNode.nodeName.toLowerCase();
  44903. var el;
  44904. var namedFromForSub = namedFrom;
  44905. if (nodeName === 'defs') {
  44906. isInDefs = true;
  44907. }
  44908. if (nodeName === 'text') {
  44909. isInText = true;
  44910. }
  44911. if (nodeName === 'defs' || nodeName === 'switch') {
  44912. el = parentGroup;
  44913. }
  44914. else {
  44915. if (!isInDefs) {
  44916. var parser_1 = nodeParsers[nodeName];
  44917. if (parser_1 && hasOwn(nodeParsers, nodeName)) {
  44918. el = parser_1.call(this, xmlNode, parentGroup);
  44919. var nameAttr = xmlNode.getAttribute('name');
  44920. if (nameAttr) {
  44921. var newNamed = {
  44922. name: nameAttr,
  44923. namedFrom: null,
  44924. svgNodeTagLower: nodeName,
  44925. el: el
  44926. };
  44927. named.push(newNamed);
  44928. if (nodeName === 'g') {
  44929. namedFromForSub = newNamed;
  44930. }
  44931. }
  44932. else if (namedFrom) {
  44933. named.push({
  44934. name: namedFrom.name,
  44935. namedFrom: namedFrom,
  44936. svgNodeTagLower: nodeName,
  44937. el: el
  44938. });
  44939. }
  44940. parentGroup.add(el);
  44941. }
  44942. }
  44943. var parser = paintServerParsers[nodeName];
  44944. if (parser && hasOwn(paintServerParsers, nodeName)) {
  44945. var def = parser.call(this, xmlNode);
  44946. var id = xmlNode.getAttribute('id');
  44947. if (id) {
  44948. this._defs[id] = def;
  44949. }
  44950. }
  44951. }
  44952. if (el && el.isGroup) {
  44953. var child = xmlNode.firstChild;
  44954. while (child) {
  44955. if (child.nodeType === 1) {
  44956. this._parseNode(child, el, named, namedFromForSub, isInDefs, isInText);
  44957. }
  44958. else if (child.nodeType === 3 && isInText) {
  44959. this._parseText(child, el);
  44960. }
  44961. child = child.nextSibling;
  44962. }
  44963. }
  44964. };
  44965. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  44966. var text = new TSpan({
  44967. style: {
  44968. text: xmlNode.textContent
  44969. },
  44970. silent: true,
  44971. x: this._textX || 0,
  44972. y: this._textY || 0
  44973. });
  44974. inheritStyle(parentGroup, text);
  44975. parseAttributes(xmlNode, text, this._defsUsePending, false, false);
  44976. applyTextAlignment(text, parentGroup);
  44977. var textStyle = text.style;
  44978. var fontSize = textStyle.fontSize;
  44979. if (fontSize && fontSize < 9) {
  44980. textStyle.fontSize = 9;
  44981. text.scaleX *= fontSize / 9;
  44982. text.scaleY *= fontSize / 9;
  44983. }
  44984. var font = (textStyle.fontSize || textStyle.fontFamily) && [
  44985. textStyle.fontStyle,
  44986. textStyle.fontWeight,
  44987. (textStyle.fontSize || 12) + 'px',
  44988. textStyle.fontFamily || 'sans-serif'
  44989. ].join(' ');
  44990. textStyle.font = font;
  44991. var rect = text.getBoundingRect();
  44992. this._textX += rect.width;
  44993. parentGroup.add(text);
  44994. return text;
  44995. };
  44996. SVGParser.internalField = (function () {
  44997. nodeParsers = {
  44998. 'g': function (xmlNode, parentGroup) {
  44999. var g = new Group();
  45000. inheritStyle(parentGroup, g);
  45001. parseAttributes(xmlNode, g, this._defsUsePending, false, false);
  45002. return g;
  45003. },
  45004. 'rect': function (xmlNode, parentGroup) {
  45005. var rect = new Rect();
  45006. inheritStyle(parentGroup, rect);
  45007. parseAttributes(xmlNode, rect, this._defsUsePending, false, false);
  45008. rect.setShape({
  45009. x: parseFloat(xmlNode.getAttribute('x') || '0'),
  45010. y: parseFloat(xmlNode.getAttribute('y') || '0'),
  45011. width: parseFloat(xmlNode.getAttribute('width') || '0'),
  45012. height: parseFloat(xmlNode.getAttribute('height') || '0')
  45013. });
  45014. rect.silent = true;
  45015. return rect;
  45016. },
  45017. 'circle': function (xmlNode, parentGroup) {
  45018. var circle = new Circle();
  45019. inheritStyle(parentGroup, circle);
  45020. parseAttributes(xmlNode, circle, this._defsUsePending, false, false);
  45021. circle.setShape({
  45022. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  45023. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  45024. r: parseFloat(xmlNode.getAttribute('r') || '0')
  45025. });
  45026. circle.silent = true;
  45027. return circle;
  45028. },
  45029. 'line': function (xmlNode, parentGroup) {
  45030. var line = new Line();
  45031. inheritStyle(parentGroup, line);
  45032. parseAttributes(xmlNode, line, this._defsUsePending, false, false);
  45033. line.setShape({
  45034. x1: parseFloat(xmlNode.getAttribute('x1') || '0'),
  45035. y1: parseFloat(xmlNode.getAttribute('y1') || '0'),
  45036. x2: parseFloat(xmlNode.getAttribute('x2') || '0'),
  45037. y2: parseFloat(xmlNode.getAttribute('y2') || '0')
  45038. });
  45039. line.silent = true;
  45040. return line;
  45041. },
  45042. 'ellipse': function (xmlNode, parentGroup) {
  45043. var ellipse = new Ellipse();
  45044. inheritStyle(parentGroup, ellipse);
  45045. parseAttributes(xmlNode, ellipse, this._defsUsePending, false, false);
  45046. ellipse.setShape({
  45047. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  45048. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  45049. rx: parseFloat(xmlNode.getAttribute('rx') || '0'),
  45050. ry: parseFloat(xmlNode.getAttribute('ry') || '0')
  45051. });
  45052. ellipse.silent = true;
  45053. return ellipse;
  45054. },
  45055. 'polygon': function (xmlNode, parentGroup) {
  45056. var pointsStr = xmlNode.getAttribute('points');
  45057. var pointsArr;
  45058. if (pointsStr) {
  45059. pointsArr = parsePoints(pointsStr);
  45060. }
  45061. var polygon = new Polygon({
  45062. shape: {
  45063. points: pointsArr || []
  45064. },
  45065. silent: true
  45066. });
  45067. inheritStyle(parentGroup, polygon);
  45068. parseAttributes(xmlNode, polygon, this._defsUsePending, false, false);
  45069. return polygon;
  45070. },
  45071. 'polyline': function (xmlNode, parentGroup) {
  45072. var pointsStr = xmlNode.getAttribute('points');
  45073. var pointsArr;
  45074. if (pointsStr) {
  45075. pointsArr = parsePoints(pointsStr);
  45076. }
  45077. var polyline = new Polyline({
  45078. shape: {
  45079. points: pointsArr || []
  45080. },
  45081. silent: true
  45082. });
  45083. inheritStyle(parentGroup, polyline);
  45084. parseAttributes(xmlNode, polyline, this._defsUsePending, false, false);
  45085. return polyline;
  45086. },
  45087. 'image': function (xmlNode, parentGroup) {
  45088. var img = new ZRImage();
  45089. inheritStyle(parentGroup, img);
  45090. parseAttributes(xmlNode, img, this._defsUsePending, false, false);
  45091. img.setStyle({
  45092. image: xmlNode.getAttribute('xlink:href') || xmlNode.getAttribute('href'),
  45093. x: +xmlNode.getAttribute('x'),
  45094. y: +xmlNode.getAttribute('y'),
  45095. width: +xmlNode.getAttribute('width'),
  45096. height: +xmlNode.getAttribute('height')
  45097. });
  45098. img.silent = true;
  45099. return img;
  45100. },
  45101. 'text': function (xmlNode, parentGroup) {
  45102. var x = xmlNode.getAttribute('x') || '0';
  45103. var y = xmlNode.getAttribute('y') || '0';
  45104. var dx = xmlNode.getAttribute('dx') || '0';
  45105. var dy = xmlNode.getAttribute('dy') || '0';
  45106. this._textX = parseFloat(x) + parseFloat(dx);
  45107. this._textY = parseFloat(y) + parseFloat(dy);
  45108. var g = new Group();
  45109. inheritStyle(parentGroup, g);
  45110. parseAttributes(xmlNode, g, this._defsUsePending, false, true);
  45111. return g;
  45112. },
  45113. 'tspan': function (xmlNode, parentGroup) {
  45114. var x = xmlNode.getAttribute('x');
  45115. var y = xmlNode.getAttribute('y');
  45116. if (x != null) {
  45117. this._textX = parseFloat(x);
  45118. }
  45119. if (y != null) {
  45120. this._textY = parseFloat(y);
  45121. }
  45122. var dx = xmlNode.getAttribute('dx') || '0';
  45123. var dy = xmlNode.getAttribute('dy') || '0';
  45124. var g = new Group();
  45125. inheritStyle(parentGroup, g);
  45126. parseAttributes(xmlNode, g, this._defsUsePending, false, true);
  45127. this._textX += parseFloat(dx);
  45128. this._textY += parseFloat(dy);
  45129. return g;
  45130. },
  45131. 'path': function (xmlNode, parentGroup) {
  45132. var d = xmlNode.getAttribute('d') || '';
  45133. var path = createFromString(d);
  45134. inheritStyle(parentGroup, path);
  45135. parseAttributes(xmlNode, path, this._defsUsePending, false, false);
  45136. path.silent = true;
  45137. return path;
  45138. }
  45139. };
  45140. })();
  45141. return SVGParser;
  45142. }());
  45143. var paintServerParsers = {
  45144. 'lineargradient': function (xmlNode) {
  45145. var x1 = parseInt(xmlNode.getAttribute('x1') || '0', 10);
  45146. var y1 = parseInt(xmlNode.getAttribute('y1') || '0', 10);
  45147. var x2 = parseInt(xmlNode.getAttribute('x2') || '10', 10);
  45148. var y2 = parseInt(xmlNode.getAttribute('y2') || '0', 10);
  45149. var gradient = new LinearGradient(x1, y1, x2, y2);
  45150. parsePaintServerUnit(xmlNode, gradient);
  45151. parseGradientColorStops(xmlNode, gradient);
  45152. return gradient;
  45153. },
  45154. 'radialgradient': function (xmlNode) {
  45155. var cx = parseInt(xmlNode.getAttribute('cx') || '0', 10);
  45156. var cy = parseInt(xmlNode.getAttribute('cy') || '0', 10);
  45157. var r = parseInt(xmlNode.getAttribute('r') || '0', 10);
  45158. var gradient = new RadialGradient(cx, cy, r);
  45159. parsePaintServerUnit(xmlNode, gradient);
  45160. parseGradientColorStops(xmlNode, gradient);
  45161. return gradient;
  45162. }
  45163. };
  45164. function parsePaintServerUnit(xmlNode, gradient) {
  45165. var gradientUnits = xmlNode.getAttribute('gradientUnits');
  45166. if (gradientUnits === 'userSpaceOnUse') {
  45167. gradient.global = true;
  45168. }
  45169. }
  45170. function parseGradientColorStops(xmlNode, gradient) {
  45171. var stop = xmlNode.firstChild;
  45172. while (stop) {
  45173. if (stop.nodeType === 1
  45174. && stop.nodeName.toLocaleLowerCase() === 'stop') {
  45175. var offsetStr = stop.getAttribute('offset');
  45176. var offset = void 0;
  45177. if (offsetStr && offsetStr.indexOf('%') > 0) {
  45178. offset = parseInt(offsetStr, 10) / 100;
  45179. }
  45180. else if (offsetStr) {
  45181. offset = parseFloat(offsetStr);
  45182. }
  45183. else {
  45184. offset = 0;
  45185. }
  45186. var styleVals = {};
  45187. parseInlineStyle(stop, styleVals, styleVals);
  45188. var stopColor = styleVals.stopColor
  45189. || stop.getAttribute('stop-color')
  45190. || '#000000';
  45191. gradient.colorStops.push({
  45192. offset: offset,
  45193. color: stopColor
  45194. });
  45195. }
  45196. stop = stop.nextSibling;
  45197. }
  45198. }
  45199. function inheritStyle(parent, child) {
  45200. if (parent && parent.__inheritedStyle) {
  45201. if (!child.__inheritedStyle) {
  45202. child.__inheritedStyle = {};
  45203. }
  45204. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  45205. }
  45206. }
  45207. function parsePoints(pointsString) {
  45208. var list = splitNumberSequence(pointsString);
  45209. var points = [];
  45210. for (var i = 0; i < list.length; i += 2) {
  45211. var x = parseFloat(list[i]);
  45212. var y = parseFloat(list[i + 1]);
  45213. points.push([x, y]);
  45214. }
  45215. return points;
  45216. }
  45217. function parseAttributes(xmlNode, el, defsUsePending, onlyInlineStyle, isTextGroup) {
  45218. var disp = el;
  45219. var inheritedStyle = disp.__inheritedStyle = disp.__inheritedStyle || {};
  45220. var selfStyle = {};
  45221. if (xmlNode.nodeType === 1) {
  45222. parseTransformAttribute(xmlNode, el);
  45223. parseInlineStyle(xmlNode, inheritedStyle, selfStyle);
  45224. if (!onlyInlineStyle) {
  45225. parseAttributeStyle(xmlNode, inheritedStyle, selfStyle);
  45226. }
  45227. }
  45228. disp.style = disp.style || {};
  45229. if (inheritedStyle.fill != null) {
  45230. disp.style.fill = getFillStrokeStyle(disp, 'fill', inheritedStyle.fill, defsUsePending);
  45231. }
  45232. if (inheritedStyle.stroke != null) {
  45233. disp.style.stroke = getFillStrokeStyle(disp, 'stroke', inheritedStyle.stroke, defsUsePending);
  45234. }
  45235. each([
  45236. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  45237. ], function (propName) {
  45238. if (inheritedStyle[propName] != null) {
  45239. disp.style[propName] = parseFloat(inheritedStyle[propName]);
  45240. }
  45241. });
  45242. each([
  45243. 'lineDashOffset', 'lineCap', 'lineJoin', 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign'
  45244. ], function (propName) {
  45245. if (inheritedStyle[propName] != null) {
  45246. disp.style[propName] = inheritedStyle[propName];
  45247. }
  45248. });
  45249. if (isTextGroup) {
  45250. disp.__selfStyle = selfStyle;
  45251. }
  45252. if (inheritedStyle.lineDash) {
  45253. disp.style.lineDash = map(splitNumberSequence(inheritedStyle.lineDash), function (str) {
  45254. return parseFloat(str);
  45255. });
  45256. }
  45257. if (inheritedStyle.visibility === 'hidden' || inheritedStyle.visibility === 'collapse') {
  45258. disp.invisible = true;
  45259. }
  45260. if (inheritedStyle.display === 'none') {
  45261. disp.ignore = true;
  45262. }
  45263. }
  45264. function applyTextAlignment(text, parentGroup) {
  45265. var parentSelfStyle = parentGroup.__selfStyle;
  45266. if (parentSelfStyle) {
  45267. var textBaseline = parentSelfStyle.textBaseline;
  45268. var zrTextBaseline = textBaseline;
  45269. if (!textBaseline || textBaseline === 'auto') {
  45270. zrTextBaseline = 'alphabetic';
  45271. }
  45272. else if (textBaseline === 'baseline') {
  45273. zrTextBaseline = 'alphabetic';
  45274. }
  45275. else if (textBaseline === 'before-edge' || textBaseline === 'text-before-edge') {
  45276. zrTextBaseline = 'top';
  45277. }
  45278. else if (textBaseline === 'after-edge' || textBaseline === 'text-after-edge') {
  45279. zrTextBaseline = 'bottom';
  45280. }
  45281. else if (textBaseline === 'central' || textBaseline === 'mathematical') {
  45282. zrTextBaseline = 'middle';
  45283. }
  45284. text.style.textBaseline = zrTextBaseline;
  45285. }
  45286. var parentInheritedStyle = parentGroup.__inheritedStyle;
  45287. if (parentInheritedStyle) {
  45288. var textAlign = parentInheritedStyle.textAlign;
  45289. var zrTextAlign = textAlign;
  45290. if (textAlign) {
  45291. if (textAlign === 'middle') {
  45292. zrTextAlign = 'center';
  45293. }
  45294. text.style.textAlign = zrTextAlign;
  45295. }
  45296. }
  45297. }
  45298. var urlRegex = /^url\(\s*#(.*?)\)/;
  45299. function getFillStrokeStyle(el, method, str, defsUsePending) {
  45300. var urlMatch = str && str.match(urlRegex);
  45301. if (urlMatch) {
  45302. var url = trim(urlMatch[1]);
  45303. defsUsePending.push([el, method, url]);
  45304. return;
  45305. }
  45306. if (str === 'none') {
  45307. str = null;
  45308. }
  45309. return str;
  45310. }
  45311. function applyDefs(defs, defsUsePending) {
  45312. for (var i = 0; i < defsUsePending.length; i++) {
  45313. var item = defsUsePending[i];
  45314. item[0].style[item[1]] = defs[item[2]];
  45315. }
  45316. }
  45317. var numberReg$1 = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  45318. function splitNumberSequence(rawStr) {
  45319. return rawStr.match(numberReg$1) || [];
  45320. }
  45321. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.eE,]*)\)/g;
  45322. var DEGREE_TO_ANGLE = Math.PI / 180;
  45323. function parseTransformAttribute(xmlNode, node) {
  45324. var transform = xmlNode.getAttribute('transform');
  45325. if (transform) {
  45326. transform = transform.replace(/,/g, ' ');
  45327. var transformOps_1 = [];
  45328. var mt = null;
  45329. transform.replace(transformRegex, function (str, type, value) {
  45330. transformOps_1.push(type, value);
  45331. return '';
  45332. });
  45333. for (var i = transformOps_1.length - 1; i > 0; i -= 2) {
  45334. var value = transformOps_1[i];
  45335. var type = transformOps_1[i - 1];
  45336. var valueArr = splitNumberSequence(value);
  45337. mt = mt || create$1();
  45338. switch (type) {
  45339. case 'translate':
  45340. translate(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || '0')]);
  45341. break;
  45342. case 'scale':
  45343. scale$1(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || valueArr[0])]);
  45344. break;
  45345. case 'rotate':
  45346. rotate(mt, mt, -parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  45347. break;
  45348. case 'skewX':
  45349. var sx = Math.tan(parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  45350. mul$1(mt, [1, 0, sx, 1, 0, 0], mt);
  45351. break;
  45352. case 'skewY':
  45353. var sy = Math.tan(parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  45354. mul$1(mt, [1, sy, 0, 1, 0, 0], mt);
  45355. break;
  45356. case 'matrix':
  45357. mt[0] = parseFloat(valueArr[0]);
  45358. mt[1] = parseFloat(valueArr[1]);
  45359. mt[2] = parseFloat(valueArr[2]);
  45360. mt[3] = parseFloat(valueArr[3]);
  45361. mt[4] = parseFloat(valueArr[4]);
  45362. mt[5] = parseFloat(valueArr[5]);
  45363. break;
  45364. }
  45365. }
  45366. node.setLocalTransform(mt);
  45367. }
  45368. }
  45369. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  45370. function parseInlineStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
  45371. var style = xmlNode.getAttribute('style');
  45372. if (!style) {
  45373. return;
  45374. }
  45375. styleRegex.lastIndex = 0;
  45376. var styleRegResult;
  45377. while ((styleRegResult = styleRegex.exec(style)) != null) {
  45378. var svgStlAttr = styleRegResult[1];
  45379. var zrInheritableStlAttr = hasOwn(INHERITABLE_STYLE_ATTRIBUTES_MAP, svgStlAttr)
  45380. ? INHERITABLE_STYLE_ATTRIBUTES_MAP[svgStlAttr]
  45381. : null;
  45382. if (zrInheritableStlAttr) {
  45383. inheritableStyleResult[zrInheritableStlAttr] = styleRegResult[2];
  45384. }
  45385. var zrSelfStlAttr = hasOwn(SELF_STYLE_ATTRIBUTES_MAP, svgStlAttr)
  45386. ? SELF_STYLE_ATTRIBUTES_MAP[svgStlAttr]
  45387. : null;
  45388. if (zrSelfStlAttr) {
  45389. selfStyleResult[zrSelfStlAttr] = styleRegResult[2];
  45390. }
  45391. }
  45392. }
  45393. function parseAttributeStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
  45394. for (var i = 0; i < INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
  45395. var svgAttrName = INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS[i];
  45396. var attrValue = xmlNode.getAttribute(svgAttrName);
  45397. if (attrValue != null) {
  45398. inheritableStyleResult[INHERITABLE_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
  45399. }
  45400. }
  45401. for (var i = 0; i < SELF_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
  45402. var svgAttrName = SELF_STYLE_ATTRIBUTES_MAP_KEYS[i];
  45403. var attrValue = xmlNode.getAttribute(svgAttrName);
  45404. if (attrValue != null) {
  45405. selfStyleResult[SELF_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
  45406. }
  45407. }
  45408. }
  45409. function makeViewBoxTransform(viewBoxRect, boundingRect) {
  45410. var scaleX = boundingRect.width / viewBoxRect.width;
  45411. var scaleY = boundingRect.height / viewBoxRect.height;
  45412. var scale = Math.min(scaleX, scaleY);
  45413. return {
  45414. scale: scale,
  45415. x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + (boundingRect.x + boundingRect.width / 2),
  45416. y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + (boundingRect.y + boundingRect.height / 2)
  45417. };
  45418. }
  45419. function parseSVG(xml, opt) {
  45420. var parser = new SVGParser();
  45421. return parser.parse(xml, opt);
  45422. }
  45423. /**
  45424. * "region available" means that: enable users to set attribute `name="xxx"` on those tags
  45425. * to make it be a region.
  45426. * 1. region styles and its label styles can be defined in echarts opton:
  45427. * ```js
  45428. * geo: {
  45429. * regions: [{
  45430. * name: 'xxx',
  45431. * itemStyle: { ... },
  45432. * label: { ... }
  45433. * }, {
  45434. * ...
  45435. * },
  45436. * ...]
  45437. * };
  45438. * ```
  45439. * 2. name can be duplicated in different SVG tag. All of the tags with the same name share
  45440. * a region option. For exampel if there are two <path> representing two lung lobes. They have
  45441. * no common parents but both of them need to display label "lung" inside.
  45442. */
  45443. var REGION_AVAILABLE_SVG_TAG_MAP = createHashMap(['rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path', // <text> <tspan> are also enabled because some SVG might paint text itself,
  45444. // but still need to trigger events or tooltip.
  45445. 'text', 'tspan', // <g> is also enabled because this case: if multiple tags share one name
  45446. // and need label displayed, every tags will display the name, which is not
  45447. // expected. So we can put them into a <g name="xxx">. Thereby only one label
  45448. // displayed and located based on the bounding rect of the <g>.
  45449. 'g']);
  45450. var GeoSVGResource =
  45451. /** @class */
  45452. function () {
  45453. function GeoSVGResource(mapName, svg) {
  45454. this.type = 'geoSVG'; // All used graphics. key: hostKey, value: root
  45455. this._usedGraphicMap = createHashMap(); // All unused graphics.
  45456. this._freedGraphics = [];
  45457. this._mapName = mapName; // Only perform parse to XML object here, which might be time
  45458. // consiming for large SVG.
  45459. // Although convert XML to zrender element is also time consiming,
  45460. // if we do it here, the clone of zrender elements has to be
  45461. // required. So we do it once for each geo instance, util real
  45462. // performance issues call for optimizing it.
  45463. this._parsedXML = parseXML(svg);
  45464. }
  45465. GeoSVGResource.prototype.load = function ()
  45466. /* nameMap: NameMap */
  45467. {
  45468. // In the "load" stage, graphic need to be built to
  45469. // get boundingRect for geo coordinate system.
  45470. var firstGraphic = this._firstGraphic; // Create the return data structure only when first graphic created.
  45471. // Because they will be used in geo coordinate system update stage,
  45472. // and `regions` will be mounted at `geo` coordinate system,
  45473. // in which there is no "view" info, so that it should better not to
  45474. // make references to graphic elements.
  45475. if (!firstGraphic) {
  45476. firstGraphic = this._firstGraphic = this._buildGraphic(this._parsedXML);
  45477. this._freedGraphics.push(firstGraphic);
  45478. this._boundingRect = this._firstGraphic.boundingRect.clone(); // PENDING: `nameMap` will not be supported until some real requirement come.
  45479. // if (nameMap) {
  45480. // named = applyNameMap(named, nameMap);
  45481. // }
  45482. var _a = createRegions(firstGraphic.named),
  45483. regions = _a.regions,
  45484. regionsMap = _a.regionsMap;
  45485. this._regions = regions;
  45486. this._regionsMap = regionsMap;
  45487. }
  45488. return {
  45489. boundingRect: this._boundingRect,
  45490. regions: this._regions,
  45491. regionsMap: this._regionsMap
  45492. };
  45493. };
  45494. GeoSVGResource.prototype._buildGraphic = function (svgXML) {
  45495. var result;
  45496. var rootFromParse;
  45497. try {
  45498. result = svgXML && parseSVG(svgXML, {
  45499. ignoreViewBox: true,
  45500. ignoreRootClip: true
  45501. }) || {};
  45502. rootFromParse = result.root;
  45503. assert(rootFromParse != null);
  45504. } catch (e) {
  45505. throw new Error('Invalid svg format\n' + e.message);
  45506. } // Note: we keep the covenant that the root has no transform. So always add an extra root.
  45507. var root = new Group();
  45508. root.add(rootFromParse);
  45509. root.isGeoSVGGraphicRoot = true; // [THE_RULE_OF_VIEWPORT_AND_VIEWBOX]
  45510. //
  45511. // Consider: `<svg width="..." height="..." viewBox="...">`
  45512. // - the `width/height` we call it `svgWidth/svgHeight` for short.
  45513. // - `(0, 0, svgWidth, svgHeight)` defines the viewport of the SVG, or say,
  45514. // "viewport boundingRect", or `boundingRect` for short.
  45515. // - `viewBox` defines the transform from the real content ot the viewport.
  45516. // `viewBox` has the same unit as the content of SVG.
  45517. // If `viewBox` exists, a transform is defined, so the unit of `svgWidth/svgHeight` become
  45518. // different from the content of SVG. Otherwise, they are the same.
  45519. //
  45520. // If both `svgWidth/svgHeight/viewBox` are specified in a SVG file, the transform rule will be:
  45521. // 0. `boundingRect` is `(0, 0, svgWidth, svgHeight)`. Set it to Geo['_rect'] (View['_rect']).
  45522. // 1. Make a transform from `viewBox` to `boundingRect`.
  45523. // Note: only support `preserveAspectRatio 'xMidYMid'` here. That is, this transform will preserve
  45524. // the aspect ratio.
  45525. // 2. Make a transform from boundingRect to Geo['_viewRect'] (View['_viewRect'])
  45526. // (`Geo`/`View` will do this job).
  45527. // Note: this transform might not preserve aspect radio, which depending on how users specify
  45528. // viewRect in echarts option (e.g., `geo.left/top/width/height` will not preserve aspect ratio,
  45529. // but `geo.layoutCenter/layoutSize` will preserve aspect ratio).
  45530. //
  45531. // If `svgWidth/svgHeight` not specified, we use `viewBox` as the `boundingRect` to make the SVG
  45532. // layout look good.
  45533. //
  45534. // If neither `svgWidth/svgHeight` nor `viewBox` are not specified, we calculate the boundingRect
  45535. // of the SVG content and use them to make SVG layout look good.
  45536. var svgWidth = result.width;
  45537. var svgHeight = result.height;
  45538. var viewBoxRect = result.viewBoxRect;
  45539. var boundingRect = this._boundingRect;
  45540. if (!boundingRect) {
  45541. var bRectX = void 0;
  45542. var bRectY = void 0;
  45543. var bRectWidth = void 0;
  45544. var bRectHeight = void 0;
  45545. if (svgWidth != null) {
  45546. bRectX = 0;
  45547. bRectWidth = svgWidth;
  45548. } else if (viewBoxRect) {
  45549. bRectX = viewBoxRect.x;
  45550. bRectWidth = viewBoxRect.width;
  45551. }
  45552. if (svgHeight != null) {
  45553. bRectY = 0;
  45554. bRectHeight = svgHeight;
  45555. } else if (viewBoxRect) {
  45556. bRectY = viewBoxRect.y;
  45557. bRectHeight = viewBoxRect.height;
  45558. } // If both viewBox and svgWidth/svgHeight not specified,
  45559. // we have to determine how to layout those element to make them look good.
  45560. if (bRectX == null || bRectY == null) {
  45561. var calculatedBoundingRect = rootFromParse.getBoundingRect();
  45562. if (bRectX == null) {
  45563. bRectX = calculatedBoundingRect.x;
  45564. bRectWidth = calculatedBoundingRect.width;
  45565. }
  45566. if (bRectY == null) {
  45567. bRectY = calculatedBoundingRect.y;
  45568. bRectHeight = calculatedBoundingRect.height;
  45569. }
  45570. }
  45571. boundingRect = this._boundingRect = new BoundingRect(bRectX, bRectY, bRectWidth, bRectHeight);
  45572. }
  45573. if (viewBoxRect) {
  45574. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect); // Only support `preserveAspectRatio 'xMidYMid'`
  45575. rootFromParse.scaleX = rootFromParse.scaleY = viewBoxTransform.scale;
  45576. rootFromParse.x = viewBoxTransform.x;
  45577. rootFromParse.y = viewBoxTransform.y;
  45578. } // SVG needs to clip based on `viewBox`. And some SVG files really rely on this feature.
  45579. // They do not strictly confine all of the content inside a display rect, but deliberately
  45580. // use a `viewBox` to define a displayable rect.
  45581. // PENDING:
  45582. // The drawback of the `setClipPath` here is: the region label (genereted by echarts) near the
  45583. // edge might also be clipped, because region labels are put as `textContent` of the SVG path.
  45584. root.setClipPath(new Rect({
  45585. shape: boundingRect.plain()
  45586. }));
  45587. var named = [];
  45588. each(result.named, function (namedItem) {
  45589. if (REGION_AVAILABLE_SVG_TAG_MAP.get(namedItem.svgNodeTagLower) != null) {
  45590. named.push(namedItem);
  45591. setSilent(namedItem.el);
  45592. }
  45593. });
  45594. return {
  45595. root: root,
  45596. boundingRect: boundingRect,
  45597. named: named
  45598. };
  45599. };
  45600. /**
  45601. * Consider:
  45602. * (1) One graphic element can not be shared by different `geoView` running simultaneously.
  45603. * Notice, also need to consider multiple echarts instances share a `mapRecord`.
  45604. * (2) Converting SVG to graphic elements is time consuming.
  45605. * (3) In the current architecture, `load` should be called frequently to get boundingRect,
  45606. * and it is called without view info.
  45607. * So we maintain graphic elements in this module, and enables `view` to use/return these
  45608. * graphics from/to the pool with it's uid.
  45609. */
  45610. GeoSVGResource.prototype.useGraphic = function (hostKey
  45611. /* , nameMap: NameMap */
  45612. ) {
  45613. var usedRootMap = this._usedGraphicMap;
  45614. var svgGraphic = usedRootMap.get(hostKey);
  45615. if (svgGraphic) {
  45616. return svgGraphic;
  45617. }
  45618. svgGraphic = this._freedGraphics.pop() // use the first boundingRect to avoid duplicated boundingRect calculation.
  45619. || this._buildGraphic(this._parsedXML);
  45620. usedRootMap.set(hostKey, svgGraphic); // PENDING: `nameMap` will not be supported until some real requirement come.
  45621. // `nameMap` can only be obtained from echarts option.
  45622. // The original `named` must not be modified.
  45623. // if (nameMap) {
  45624. // svgGraphic = extend({}, svgGraphic);
  45625. // svgGraphic.named = applyNameMap(svgGraphic.named, nameMap);
  45626. // }
  45627. return svgGraphic;
  45628. };
  45629. GeoSVGResource.prototype.freeGraphic = function (hostKey) {
  45630. var usedRootMap = this._usedGraphicMap;
  45631. var svgGraphic = usedRootMap.get(hostKey);
  45632. if (svgGraphic) {
  45633. usedRootMap.removeKey(hostKey);
  45634. this._freedGraphics.push(svgGraphic);
  45635. }
  45636. };
  45637. return GeoSVGResource;
  45638. }();
  45639. function setSilent(el) {
  45640. // Only named element has silent: false, other elements should
  45641. // act as background and has no user interaction.
  45642. el.silent = false; // text|tspan will be converted to group.
  45643. if (el.isGroup) {
  45644. el.traverse(function (child) {
  45645. child.silent = false;
  45646. });
  45647. }
  45648. }
  45649. function createRegions(named) {
  45650. var regions = [];
  45651. var regionsMap = createHashMap(); // Create resions only for the first graphic.
  45652. each(named, function (namedItem) {
  45653. // Region has feature to calculate center for tooltip or other features.
  45654. // If there is a <g name="xxx">, the center should be the center of the
  45655. // bounding rect of the g.
  45656. if (namedItem.namedFrom != null) {
  45657. return;
  45658. }
  45659. var region = new GeoSVGRegion(namedItem.name, namedItem.el); // PENDING: if `nameMap` supported, this region can not be mounted on
  45660. // `this`, but can only be created each time `load()` called.
  45661. regions.push(region); // PENDING: if multiple tag named with the same name, only one will be
  45662. // found by `_regionsMap`. `_regionsMap` is used to find a coordinate
  45663. // by name. We use `region.getCenter()` as the coordinate.
  45664. regionsMap.set(namedItem.name, region);
  45665. });
  45666. return {
  45667. regions: regions,
  45668. regionsMap: regionsMap
  45669. };
  45670. } // PENDING: `nameMap` will not be supported until some real requirement come.
  45671. // /**
  45672. // * Use the alias in geoNameMap.
  45673. // * The input `named` must not be modified.
  45674. // */
  45675. // function applyNameMap(
  45676. // named: GeoSVGGraphicRecord['named'],
  45677. // nameMap: NameMap
  45678. // ): GeoSVGGraphicRecord['named'] {
  45679. // const result = [] as GeoSVGGraphicRecord['named'];
  45680. // for (let i = 0; i < named.length; i++) {
  45681. // let regionGraphic = named[i];
  45682. // const name = regionGraphic.name;
  45683. // if (nameMap && nameMap.hasOwnProperty(name)) {
  45684. // regionGraphic = extend({}, regionGraphic);
  45685. // regionGraphic.name = name;
  45686. // }
  45687. // result.push(regionGraphic);
  45688. // }
  45689. // return result;
  45690. // }
  45691. var geoCoord = [126, 25];
  45692. var nanhaiName = '南海诸岛';
  45693. var points$1 = [[[0, 3.5], [7, 11.2], [15, 11.9], [30, 7], [42, 0.7], [52, 0.7], [56, 7.7], [59, 0.7], [64, 0.7], [64, 0], [5, 0], [0, 3.5]], [[13, 16.1], [19, 14.7], [16, 21.7], [11, 23.1], [13, 16.1]], [[12, 32.2], [14, 38.5], [15, 38.5], [13, 32.2], [12, 32.2]], [[16, 47.6], [12, 53.2], [13, 53.2], [18, 47.6], [16, 47.6]], [[6, 64.4], [8, 70], [9, 70], [8, 64.4], [6, 64.4]], [[23, 82.6], [29, 79.8], [30, 79.8], [25, 82.6], [23, 82.6]], [[37, 70.7], [43, 62.3], [44, 62.3], [39, 70.7], [37, 70.7]], [[48, 51.1], [51, 45.5], [53, 45.5], [50, 51.1], [48, 51.1]], [[51, 35], [51, 28.7], [53, 28.7], [53, 35], [51, 35]], [[52, 22.4], [55, 17.5], [56, 17.5], [53, 22.4], [52, 22.4]], [[58, 12.6], [62, 7], [63, 7], [60, 12.6], [58, 12.6]], [[0, 3.5], [0, 93.1], [64, 93.1], [64, 0], [63, 0], [63, 92.4], [1, 92.4], [1, 3.5], [0, 3.5]]];
  45694. for (var i = 0; i < points$1.length; i++) {
  45695. for (var k = 0; k < points$1[i].length; k++) {
  45696. points$1[i][k][0] /= 10.5;
  45697. points$1[i][k][1] /= -10.5 / 0.75;
  45698. points$1[i][k][0] += geoCoord[0];
  45699. points$1[i][k][1] += geoCoord[1];
  45700. }
  45701. }
  45702. function fixNanhai(mapType, regions) {
  45703. if (mapType === 'china') {
  45704. for (var i = 0; i < regions.length; i++) {
  45705. // Already exists.
  45706. if (regions[i].name === nanhaiName) {
  45707. return;
  45708. }
  45709. }
  45710. regions.push(new GeoJSONRegion(nanhaiName, map(points$1, function (exterior) {
  45711. return {
  45712. type: 'polygon',
  45713. exterior: exterior
  45714. };
  45715. }), geoCoord));
  45716. }
  45717. }
  45718. /*
  45719. * Licensed to the Apache Software Foundation (ASF) under one
  45720. * or more contributor license agreements. See the NOTICE file
  45721. * distributed with this work for additional information
  45722. * regarding copyright ownership. The ASF licenses this file
  45723. * to you under the Apache License, Version 2.0 (the
  45724. * "License"); you may not use this file except in compliance
  45725. * with the License. You may obtain a copy of the License at
  45726. *
  45727. * http://www.apache.org/licenses/LICENSE-2.0
  45728. *
  45729. * Unless required by applicable law or agreed to in writing,
  45730. * software distributed under the License is distributed on an
  45731. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45732. * KIND, either express or implied. See the License for the
  45733. * specific language governing permissions and limitations
  45734. * under the License.
  45735. */
  45736. /**
  45737. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45738. */
  45739. /*
  45740. * Licensed to the Apache Software Foundation (ASF) under one
  45741. * or more contributor license agreements. See the NOTICE file
  45742. * distributed with this work for additional information
  45743. * regarding copyright ownership. The ASF licenses this file
  45744. * to you under the Apache License, Version 2.0 (the
  45745. * "License"); you may not use this file except in compliance
  45746. * with the License. You may obtain a copy of the License at
  45747. *
  45748. * http://www.apache.org/licenses/LICENSE-2.0
  45749. *
  45750. * Unless required by applicable law or agreed to in writing,
  45751. * software distributed under the License is distributed on an
  45752. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45753. * KIND, either express or implied. See the License for the
  45754. * specific language governing permissions and limitations
  45755. * under the License.
  45756. */
  45757. var coordsOffsetMap = {
  45758. '南海诸岛': [32, 80],
  45759. // 全国
  45760. '广东': [0, -10],
  45761. '香港': [10, 5],
  45762. '澳门': [-10, 10],
  45763. // '北京': [-10, 0],
  45764. '天津': [5, 5]
  45765. };
  45766. function fixTextCoords(mapType, region) {
  45767. if (mapType === 'china') {
  45768. var coordFix = coordsOffsetMap[region.name];
  45769. if (coordFix) {
  45770. var cp = region.getCenter();
  45771. cp[0] += coordFix[0] / 10.5;
  45772. cp[1] += -coordFix[1] / (10.5 / 0.75);
  45773. region.setCenter(cp);
  45774. }
  45775. }
  45776. }
  45777. /*
  45778. * Licensed to the Apache Software Foundation (ASF) under one
  45779. * or more contributor license agreements. See the NOTICE file
  45780. * distributed with this work for additional information
  45781. * regarding copyright ownership. The ASF licenses this file
  45782. * to you under the Apache License, Version 2.0 (the
  45783. * "License"); you may not use this file except in compliance
  45784. * with the License. You may obtain a copy of the License at
  45785. *
  45786. * http://www.apache.org/licenses/LICENSE-2.0
  45787. *
  45788. * Unless required by applicable law or agreed to in writing,
  45789. * software distributed under the License is distributed on an
  45790. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45791. * KIND, either express or implied. See the License for the
  45792. * specific language governing permissions and limitations
  45793. * under the License.
  45794. */
  45795. /**
  45796. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45797. */
  45798. /*
  45799. * Licensed to the Apache Software Foundation (ASF) under one
  45800. * or more contributor license agreements. See the NOTICE file
  45801. * distributed with this work for additional information
  45802. * regarding copyright ownership. The ASF licenses this file
  45803. * to you under the Apache License, Version 2.0 (the
  45804. * "License"); you may not use this file except in compliance
  45805. * with the License. You may obtain a copy of the License at
  45806. *
  45807. * http://www.apache.org/licenses/LICENSE-2.0
  45808. *
  45809. * Unless required by applicable law or agreed to in writing,
  45810. * software distributed under the License is distributed on an
  45811. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45812. * KIND, either express or implied. See the License for the
  45813. * specific language governing permissions and limitations
  45814. * under the License.
  45815. */
  45816. // Fix for 钓鱼岛
  45817. // let Region = require('../Region');
  45818. // let zrUtil = require('zrender/lib/core/util');
  45819. // let geoCoord = [126, 25];
  45820. var points$2 = [[[123.45165252685547, 25.73527164402261], [123.49731445312499, 25.73527164402261], [123.49731445312499, 25.750734064600884], [123.45165252685547, 25.750734064600884], [123.45165252685547, 25.73527164402261]]];
  45821. function fixDiaoyuIsland(mapType, region) {
  45822. if (mapType === 'china' && region.name === '台湾') {
  45823. region.geometries.push({
  45824. type: 'polygon',
  45825. exterior: points$2[0]
  45826. });
  45827. }
  45828. }
  45829. var DEFAULT_NAME_PROPERTY = 'name';
  45830. var GeoJSONResource =
  45831. /** @class */
  45832. function () {
  45833. function GeoJSONResource(mapName, geoJSON, specialAreas) {
  45834. this.type = 'geoJSON';
  45835. this._parsedMap = createHashMap();
  45836. this._mapName = mapName;
  45837. this._specialAreas = specialAreas; // PENDING: delay the parse to the first usage to rapid up the FMP?
  45838. this._geoJSON = parseInput(geoJSON);
  45839. }
  45840. /**
  45841. * @param nameMap can be null/undefined
  45842. * @param nameProperty can be null/undefined
  45843. */
  45844. GeoJSONResource.prototype.load = function (nameMap, nameProperty) {
  45845. nameProperty = nameProperty || DEFAULT_NAME_PROPERTY;
  45846. var parsed = this._parsedMap.get(nameProperty);
  45847. if (!parsed) {
  45848. var rawRegions = this._parseToRegions(nameProperty);
  45849. parsed = this._parsedMap.set(nameProperty, {
  45850. regions: rawRegions,
  45851. boundingRect: calculateBoundingRect(rawRegions)
  45852. });
  45853. }
  45854. var regionsMap = createHashMap();
  45855. var finalRegions = [];
  45856. each(parsed.regions, function (region) {
  45857. var regionName = region.name; // Try use the alias in geoNameMap
  45858. if (nameMap && hasOwn(nameMap, regionName)) {
  45859. region = region.cloneShallow(regionName = nameMap[regionName]);
  45860. }
  45861. finalRegions.push(region);
  45862. regionsMap.set(regionName, region);
  45863. });
  45864. return {
  45865. regions: finalRegions,
  45866. boundingRect: parsed.boundingRect || new BoundingRect(0, 0, 0, 0),
  45867. regionsMap: regionsMap
  45868. };
  45869. };
  45870. GeoJSONResource.prototype._parseToRegions = function (nameProperty) {
  45871. var mapName = this._mapName;
  45872. var geoJSON = this._geoJSON;
  45873. var rawRegions; // https://jsperf.com/try-catch-performance-overhead
  45874. try {
  45875. rawRegions = geoJSON ? parseGeoJSON(geoJSON, nameProperty) : [];
  45876. } catch (e) {
  45877. throw new Error('Invalid geoJson format\n' + e.message);
  45878. }
  45879. fixNanhai(mapName, rawRegions);
  45880. each(rawRegions, function (region) {
  45881. var regionName = region.name;
  45882. fixTextCoords(mapName, region);
  45883. fixDiaoyuIsland(mapName, region); // Some area like Alaska in USA map needs to be tansformed
  45884. // to look better
  45885. var specialArea = this._specialAreas && this._specialAreas[regionName];
  45886. if (specialArea) {
  45887. region.transformTo(specialArea.left, specialArea.top, specialArea.width, specialArea.height);
  45888. }
  45889. }, this);
  45890. return rawRegions;
  45891. };
  45892. /**
  45893. * Only for exporting to users.
  45894. * **MUST NOT** used internally.
  45895. */
  45896. GeoJSONResource.prototype.getMapForUser = function () {
  45897. return {
  45898. // For backward compatibility, use geoJson
  45899. // PENDING: it has been returning them without clone.
  45900. // do we need to avoid outsite modification?
  45901. geoJson: this._geoJSON,
  45902. geoJSON: this._geoJSON,
  45903. specialAreas: this._specialAreas
  45904. };
  45905. };
  45906. return GeoJSONResource;
  45907. }();
  45908. function calculateBoundingRect(regions) {
  45909. var rect;
  45910. for (var i = 0; i < regions.length; i++) {
  45911. var regionRect = regions[i].getBoundingRect();
  45912. rect = rect || regionRect.clone();
  45913. rect.union(regionRect);
  45914. }
  45915. return rect;
  45916. }
  45917. function parseInput(source) {
  45918. return !isString(source) ? source : typeof JSON !== 'undefined' && JSON.parse ? JSON.parse(source) : new Function('return (' + source + ');')();
  45919. }
  45920. var storage = createHashMap();
  45921. var geoSourceManager = {
  45922. /**
  45923. * Compatible with previous `echarts.registerMap`.
  45924. *
  45925. * @usage
  45926. * ```js
  45927. *
  45928. * echarts.registerMap('USA', geoJson, specialAreas);
  45929. *
  45930. * echarts.registerMap('USA', {
  45931. * geoJson: geoJson,
  45932. * specialAreas: {...}
  45933. * });
  45934. * echarts.registerMap('USA', {
  45935. * geoJSON: geoJson,
  45936. * specialAreas: {...}
  45937. * });
  45938. *
  45939. * echarts.registerMap('airport', {
  45940. * svg: svg
  45941. * }
  45942. * ```
  45943. *
  45944. * Note:
  45945. * Do not support that register multiple geoJSON or SVG
  45946. * one map name. Because different geoJSON and SVG have
  45947. * different unit. It's not easy to make sure how those
  45948. * units are mapping/normalize.
  45949. * If intending to use multiple geoJSON or SVG, we can
  45950. * use multiple geo coordinate system.
  45951. */
  45952. registerMap: function (mapName, rawDef, rawSpecialAreas) {
  45953. if (rawDef.svg) {
  45954. var resource = new GeoSVGResource(mapName, rawDef.svg);
  45955. storage.set(mapName, resource);
  45956. } else {
  45957. // Recommend:
  45958. // echarts.registerMap('eu', { geoJSON: xxx, specialAreas: xxx });
  45959. // Backward compatibility:
  45960. // echarts.registerMap('eu', geoJSON, specialAreas);
  45961. // echarts.registerMap('eu', { geoJson: xxx, specialAreas: xxx });
  45962. var geoJSON = rawDef.geoJson || rawDef.geoJSON;
  45963. if (geoJSON && !rawDef.features) {
  45964. rawSpecialAreas = rawDef.specialAreas;
  45965. } else {
  45966. geoJSON = rawDef;
  45967. }
  45968. var resource = new GeoJSONResource(mapName, geoJSON, rawSpecialAreas);
  45969. storage.set(mapName, resource);
  45970. }
  45971. },
  45972. getGeoResource: function (mapName) {
  45973. return storage.get(mapName);
  45974. },
  45975. /**
  45976. * Only for exporting to users.
  45977. * **MUST NOT** used internally.
  45978. */
  45979. getMapForUser: function (mapName) {
  45980. var resource = storage.get(mapName); // Do not support return SVG until some real requirement come.
  45981. return resource && resource.type === 'geoJSON' && resource.getMapForUser();
  45982. },
  45983. load: function (mapName, nameMap, nameProperty) {
  45984. var resource = storage.get(mapName);
  45985. if (!resource) {
  45986. if ("development" !== 'production') {
  45987. console.error('Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.');
  45988. }
  45989. return;
  45990. }
  45991. return resource.load(nameMap, nameProperty);
  45992. }
  45993. };
  45994. /**
  45995. * Only these tags enable use `itemStyle` if they are named in SVG.
  45996. * Other tags like <text> <tspan> <image> might not suitable for `itemStyle`.
  45997. * They will not be considered to be styled until some requirements come.
  45998. */
  45999. var OPTION_STYLE_ENABLED_TAGS = ['rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path'];
  46000. var OPTION_STYLE_ENABLED_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS);
  46001. var STATE_TRIGGER_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat(['g']));
  46002. var LABEL_HOST_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat(['g']));
  46003. var mapLabelRaw = makeInner();
  46004. function getFixedItemStyle(model) {
  46005. var itemStyle = model.getItemStyle();
  46006. var areaColor = model.get('areaColor'); // If user want the color not to be changed when hover,
  46007. // they should both set areaColor and color to be null.
  46008. if (areaColor != null) {
  46009. itemStyle.fill = areaColor;
  46010. }
  46011. return itemStyle;
  46012. } // Only stroke can be used for line.
  46013. // Using fill in style if stroke not exits.
  46014. // TODO Not sure yet. Perhaps a separate `lineStyle`?
  46015. function fixLineStyle(styleHost) {
  46016. var style = styleHost.style;
  46017. if (style) {
  46018. style.stroke = style.stroke || style.fill;
  46019. style.fill = null;
  46020. }
  46021. }
  46022. var MapDraw =
  46023. /** @class */
  46024. function () {
  46025. function MapDraw(api) {
  46026. var group = new Group();
  46027. this.uid = getUID('ec_map_draw');
  46028. this._controller = new RoamController(api.getZr());
  46029. this._controllerHost = {
  46030. target: group
  46031. };
  46032. this.group = group;
  46033. group.add(this._regionsGroup = new Group());
  46034. group.add(this._svgGroup = new Group());
  46035. }
  46036. MapDraw.prototype.draw = function (mapOrGeoModel, ecModel, api, fromView, payload) {
  46037. var isGeo = mapOrGeoModel.mainType === 'geo'; // Map series has data. GEO model that controlled by map series
  46038. // will be assigned with map data. Other GEO model has no data.
  46039. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  46040. isGeo && ecModel.eachComponent({
  46041. mainType: 'series',
  46042. subType: 'map'
  46043. }, function (mapSeries) {
  46044. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  46045. data = mapSeries.getData();
  46046. }
  46047. });
  46048. var geo = mapOrGeoModel.coordinateSystem;
  46049. var regionsGroup = this._regionsGroup;
  46050. var group = this.group;
  46051. var transformInfo = geo.getTransformInfo();
  46052. var transformInfoRaw = transformInfo.raw;
  46053. var transformInfoRoam = transformInfo.roam; // No animation when first draw or in action
  46054. var isFirstDraw = !regionsGroup.childAt(0) || payload;
  46055. if (isFirstDraw) {
  46056. group.x = transformInfoRoam.x;
  46057. group.y = transformInfoRoam.y;
  46058. group.scaleX = transformInfoRoam.scaleX;
  46059. group.scaleY = transformInfoRoam.scaleY;
  46060. group.dirty();
  46061. } else {
  46062. updateProps(group, transformInfoRoam, mapOrGeoModel);
  46063. }
  46064. var isVisualEncodedByVisualMap = data && data.getVisual('visualMeta') && data.getVisual('visualMeta').length > 0;
  46065. var viewBuildCtx = {
  46066. api: api,
  46067. geo: geo,
  46068. mapOrGeoModel: mapOrGeoModel,
  46069. data: data,
  46070. isVisualEncodedByVisualMap: isVisualEncodedByVisualMap,
  46071. isGeo: isGeo,
  46072. transformInfoRaw: transformInfoRaw
  46073. };
  46074. if (geo.resourceType === 'geoJSON') {
  46075. this._buildGeoJSON(viewBuildCtx);
  46076. } else if (geo.resourceType === 'geoSVG') {
  46077. this._buildSVG(viewBuildCtx);
  46078. }
  46079. this._updateController(mapOrGeoModel, ecModel, api);
  46080. this._updateMapSelectHandler(mapOrGeoModel, regionsGroup, api, fromView);
  46081. };
  46082. MapDraw.prototype._buildGeoJSON = function (viewBuildCtx) {
  46083. var regionsGroupByName = this._regionsGroupByName = createHashMap();
  46084. var regionsInfoByName = createHashMap();
  46085. var regionsGroup = this._regionsGroup;
  46086. var transformInfoRaw = viewBuildCtx.transformInfoRaw;
  46087. var mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
  46088. var data = viewBuildCtx.data;
  46089. var projection = viewBuildCtx.geo.projection;
  46090. var projectionStream = projection && projection.stream;
  46091. function transformPoint(point, project) {
  46092. if (project) {
  46093. // projection may return null point.
  46094. point = project(point);
  46095. }
  46096. return point && [point[0] * transformInfoRaw.scaleX + transformInfoRaw.x, point[1] * transformInfoRaw.scaleY + transformInfoRaw.y];
  46097. }
  46098. function transformPolygonPoints(inPoints) {
  46099. var outPoints = []; // If projectionStream is provided. Use it instead of single point project.
  46100. var project = !projectionStream && projection && projection.project;
  46101. for (var i = 0; i < inPoints.length; ++i) {
  46102. var newPt = transformPoint(inPoints[i], project);
  46103. newPt && outPoints.push(newPt);
  46104. }
  46105. return outPoints;
  46106. }
  46107. function getPolyShape(points) {
  46108. return {
  46109. shape: {
  46110. points: transformPolygonPoints(points)
  46111. }
  46112. };
  46113. }
  46114. regionsGroup.removeAll(); // Only when the resource is GeoJSON, there is `geo.regions`.
  46115. each(viewBuildCtx.geo.regions, function (region) {
  46116. var regionName = region.name; // Consider in GeoJson properties.name may be duplicated, for example,
  46117. // there is multiple region named "United Kindom" or "France" (so many
  46118. // colonies). And it is not appropriate to merge them in geo, which
  46119. // will make them share the same label and bring trouble in label
  46120. // location calculation.
  46121. var regionGroup = regionsGroupByName.get(regionName);
  46122. var _a = regionsInfoByName.get(regionName) || {},
  46123. dataIdx = _a.dataIdx,
  46124. regionModel = _a.regionModel;
  46125. if (!regionGroup) {
  46126. regionGroup = regionsGroupByName.set(regionName, new Group());
  46127. regionsGroup.add(regionGroup);
  46128. dataIdx = data ? data.indexOfName(regionName) : null;
  46129. regionModel = viewBuildCtx.isGeo ? mapOrGeoModel.getRegionModel(regionName) : data ? data.getItemModel(dataIdx) : null;
  46130. regionsInfoByName.set(regionName, {
  46131. dataIdx: dataIdx,
  46132. regionModel: regionModel
  46133. });
  46134. }
  46135. var polygonSubpaths = [];
  46136. var polylineSubpaths = [];
  46137. each(region.geometries, function (geometry) {
  46138. // Polygon and MultiPolygon
  46139. if (geometry.type === 'polygon') {
  46140. var polys = [geometry.exterior].concat(geometry.interiors || []);
  46141. if (projectionStream) {
  46142. polys = projectPolys(polys, projectionStream);
  46143. }
  46144. each(polys, function (poly) {
  46145. polygonSubpaths.push(new Polygon(getPolyShape(poly)));
  46146. });
  46147. } // LineString and MultiLineString
  46148. else {
  46149. var points = geometry.points;
  46150. if (projectionStream) {
  46151. points = projectPolys(points, projectionStream, true);
  46152. }
  46153. each(points, function (points) {
  46154. polylineSubpaths.push(new Polyline(getPolyShape(points)));
  46155. });
  46156. }
  46157. });
  46158. var centerPt = transformPoint(region.getCenter(), projection && projection.project);
  46159. function createCompoundPath(subpaths, isLine) {
  46160. if (!subpaths.length) {
  46161. return;
  46162. }
  46163. var compoundPath = new CompoundPath({
  46164. culling: true,
  46165. segmentIgnoreThreshold: 1,
  46166. shape: {
  46167. paths: subpaths
  46168. }
  46169. });
  46170. regionGroup.add(compoundPath);
  46171. applyOptionStyleForRegion(viewBuildCtx, compoundPath, dataIdx, regionModel);
  46172. resetLabelForRegion(viewBuildCtx, compoundPath, regionName, regionModel, mapOrGeoModel, dataIdx, centerPt);
  46173. if (isLine) {
  46174. fixLineStyle(compoundPath);
  46175. each(compoundPath.states, fixLineStyle);
  46176. }
  46177. }
  46178. createCompoundPath(polygonSubpaths);
  46179. createCompoundPath(polylineSubpaths, true);
  46180. }); // Ensure children have been added to `regionGroup` before calling them.
  46181. regionsGroupByName.each(function (regionGroup, regionName) {
  46182. var _a = regionsInfoByName.get(regionName),
  46183. dataIdx = _a.dataIdx,
  46184. regionModel = _a.regionModel;
  46185. resetEventTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel, dataIdx);
  46186. resetTooltipForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel);
  46187. resetStateTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel);
  46188. }, this);
  46189. };
  46190. MapDraw.prototype._buildSVG = function (viewBuildCtx) {
  46191. var mapName = viewBuildCtx.geo.map;
  46192. var transformInfoRaw = viewBuildCtx.transformInfoRaw;
  46193. this._svgGroup.x = transformInfoRaw.x;
  46194. this._svgGroup.y = transformInfoRaw.y;
  46195. this._svgGroup.scaleX = transformInfoRaw.scaleX;
  46196. this._svgGroup.scaleY = transformInfoRaw.scaleY;
  46197. if (this._svgResourceChanged(mapName)) {
  46198. this._freeSVG();
  46199. this._useSVG(mapName);
  46200. }
  46201. var svgDispatcherMap = this._svgDispatcherMap = createHashMap();
  46202. var focusSelf = false;
  46203. each(this._svgGraphicRecord.named, function (namedItem) {
  46204. // Note that we also allow different elements have the same name.
  46205. // For example, a glyph of a city and the label of the city have
  46206. // the same name and their tooltip info can be defined in a single
  46207. // region option.
  46208. var regionName = namedItem.name;
  46209. var mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
  46210. var data = viewBuildCtx.data;
  46211. var svgNodeTagLower = namedItem.svgNodeTagLower;
  46212. var el = namedItem.el;
  46213. var dataIdx = data ? data.indexOfName(regionName) : null;
  46214. var regionModel = mapOrGeoModel.getRegionModel(regionName);
  46215. if (OPTION_STYLE_ENABLED_TAG_MAP.get(svgNodeTagLower) != null && el instanceof Displayable) {
  46216. applyOptionStyleForRegion(viewBuildCtx, el, dataIdx, regionModel);
  46217. }
  46218. if (el instanceof Displayable) {
  46219. el.culling = true;
  46220. } // We do not know how the SVG like so we'd better not to change z2.
  46221. // Otherwise it might bring some unexpected result. For example,
  46222. // an area hovered that make some inner city can not be clicked.
  46223. el.z2EmphasisLift = 0; // If self named:
  46224. if (!namedItem.namedFrom) {
  46225. // label should batter to be displayed based on the center of <g>
  46226. // if it is named rather than displayed on each child.
  46227. if (LABEL_HOST_MAP.get(svgNodeTagLower) != null) {
  46228. resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx, null);
  46229. }
  46230. resetEventTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx);
  46231. resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel);
  46232. if (STATE_TRIGGER_TAG_MAP.get(svgNodeTagLower) != null) {
  46233. var focus_1 = resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel);
  46234. if (focus_1 === 'self') {
  46235. focusSelf = true;
  46236. }
  46237. var els = svgDispatcherMap.get(regionName) || svgDispatcherMap.set(regionName, []);
  46238. els.push(el);
  46239. }
  46240. }
  46241. }, this);
  46242. this._enableBlurEntireSVG(focusSelf, viewBuildCtx);
  46243. };
  46244. MapDraw.prototype._enableBlurEntireSVG = function (focusSelf, viewBuildCtx) {
  46245. // It's a little complicated to support blurring the entire geoSVG in series-map.
  46246. // So do not support it until some requirements come.
  46247. // At present, in series-map, only regions can be blurred.
  46248. if (focusSelf && viewBuildCtx.isGeo) {
  46249. var blurStyle = viewBuildCtx.mapOrGeoModel.getModel(['blur', 'itemStyle']).getItemStyle(); // Only support `opacity` here. Because not sure that other props are suitable for
  46250. // all of the elements generated by SVG (especially for Text/TSpan/Image/... ).
  46251. var opacity_1 = blurStyle.opacity;
  46252. this._svgGraphicRecord.root.traverse(function (el) {
  46253. if (!el.isGroup) {
  46254. // PENDING: clear those settings to SVG elements when `_freeSVG`.
  46255. // (Currently it happen not to be needed.)
  46256. setDefaultStateProxy(el);
  46257. var style = el.ensureState('blur').style || {}; // Do not overwrite the region style that already set from region option.
  46258. if (style.opacity == null && opacity_1 != null) {
  46259. style.opacity = opacity_1;
  46260. } // If `ensureState('blur').style = {}`, there will be default opacity.
  46261. // Enable `stateTransition` (animation).
  46262. el.ensureState('emphasis');
  46263. }
  46264. });
  46265. }
  46266. };
  46267. MapDraw.prototype.remove = function () {
  46268. this._regionsGroup.removeAll();
  46269. this._regionsGroupByName = null;
  46270. this._svgGroup.removeAll();
  46271. this._freeSVG();
  46272. this._controller.dispose();
  46273. this._controllerHost = null;
  46274. };
  46275. MapDraw.prototype.findHighDownDispatchers = function (name, geoModel) {
  46276. if (name == null) {
  46277. return [];
  46278. }
  46279. var geo = geoModel.coordinateSystem;
  46280. if (geo.resourceType === 'geoJSON') {
  46281. var regionsGroupByName = this._regionsGroupByName;
  46282. if (regionsGroupByName) {
  46283. var regionGroup = regionsGroupByName.get(name);
  46284. return regionGroup ? [regionGroup] : [];
  46285. }
  46286. } else if (geo.resourceType === 'geoSVG') {
  46287. return this._svgDispatcherMap && this._svgDispatcherMap.get(name) || [];
  46288. }
  46289. };
  46290. MapDraw.prototype._svgResourceChanged = function (mapName) {
  46291. return this._svgMapName !== mapName;
  46292. };
  46293. MapDraw.prototype._useSVG = function (mapName) {
  46294. var resource = geoSourceManager.getGeoResource(mapName);
  46295. if (resource && resource.type === 'geoSVG') {
  46296. var svgGraphic = resource.useGraphic(this.uid);
  46297. this._svgGroup.add(svgGraphic.root);
  46298. this._svgGraphicRecord = svgGraphic;
  46299. this._svgMapName = mapName;
  46300. }
  46301. };
  46302. MapDraw.prototype._freeSVG = function () {
  46303. var mapName = this._svgMapName;
  46304. if (mapName == null) {
  46305. return;
  46306. }
  46307. var resource = geoSourceManager.getGeoResource(mapName);
  46308. if (resource && resource.type === 'geoSVG') {
  46309. resource.freeGraphic(this.uid);
  46310. }
  46311. this._svgGraphicRecord = null;
  46312. this._svgDispatcherMap = null;
  46313. this._svgGroup.removeAll();
  46314. this._svgMapName = null;
  46315. };
  46316. MapDraw.prototype._updateController = function (mapOrGeoModel, ecModel, api) {
  46317. var geo = mapOrGeoModel.coordinateSystem;
  46318. var controller = this._controller;
  46319. var controllerHost = this._controllerHost; // @ts-ignore FIXME:TS
  46320. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  46321. controllerHost.zoom = geo.getZoom(); // roamType is will be set default true if it is null
  46322. // @ts-ignore FIXME:TS
  46323. controller.enable(mapOrGeoModel.get('roam') || false);
  46324. var mainType = mapOrGeoModel.mainType;
  46325. function makeActionBase() {
  46326. var action = {
  46327. type: 'geoRoam',
  46328. componentType: mainType
  46329. };
  46330. action[mainType + 'Id'] = mapOrGeoModel.id;
  46331. return action;
  46332. }
  46333. controller.off('pan').on('pan', function (e) {
  46334. this._mouseDownFlag = false;
  46335. updateViewOnPan(controllerHost, e.dx, e.dy);
  46336. api.dispatchAction(extend(makeActionBase(), {
  46337. dx: e.dx,
  46338. dy: e.dy,
  46339. animation: {
  46340. duration: 0
  46341. }
  46342. }));
  46343. }, this);
  46344. controller.off('zoom').on('zoom', function (e) {
  46345. this._mouseDownFlag = false;
  46346. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  46347. api.dispatchAction(extend(makeActionBase(), {
  46348. zoom: e.scale,
  46349. originX: e.originX,
  46350. originY: e.originY,
  46351. animation: {
  46352. duration: 0
  46353. }
  46354. }));
  46355. }, this);
  46356. controller.setPointerChecker(function (e, x, y) {
  46357. return geo.containPoint([x, y]) && !onIrrelevantElement(e, api, mapOrGeoModel);
  46358. });
  46359. };
  46360. /**
  46361. * FIXME: this is a temporarily workaround.
  46362. * When `geoRoam` the elements need to be reset in `MapView['render']`, because the props like
  46363. * `ignore` might have been modified by `LabelManager`, and `LabelManager#addLabelsOfSeries`
  46364. * will subsequently cache `defaultAttr` like `ignore`. If do not do this reset, the modified
  46365. * props will have no chance to be restored.
  46366. * Note: This reset should be after `clearStates` in `renderSeries` because `useStates` in
  46367. * `renderSeries` will cache the modified `ignore` to `el._normalState`.
  46368. * TODO:
  46369. * Use clone/immutable in `LabelManager`?
  46370. */
  46371. MapDraw.prototype.resetForLabelLayout = function () {
  46372. this.group.traverse(function (el) {
  46373. var label = el.getTextContent();
  46374. if (label) {
  46375. label.ignore = mapLabelRaw(label).ignore;
  46376. }
  46377. });
  46378. };
  46379. MapDraw.prototype._updateMapSelectHandler = function (mapOrGeoModel, regionsGroup, api, fromView) {
  46380. var mapDraw = this;
  46381. regionsGroup.off('mousedown');
  46382. regionsGroup.off('click'); // @ts-ignore FIXME:TS resolve type conflict
  46383. if (mapOrGeoModel.get('selectedMode')) {
  46384. regionsGroup.on('mousedown', function () {
  46385. mapDraw._mouseDownFlag = true;
  46386. });
  46387. regionsGroup.on('click', function (e) {
  46388. if (!mapDraw._mouseDownFlag) {
  46389. return;
  46390. }
  46391. mapDraw._mouseDownFlag = false;
  46392. });
  46393. }
  46394. };
  46395. return MapDraw;
  46396. }();
  46397. function applyOptionStyleForRegion(viewBuildCtx, el, dataIndex, regionModel) {
  46398. // All of the path are using `itemStyle`, because
  46399. // (1) Some SVG also use fill on polyline (The different between
  46400. // polyline and polygon is "open" or "close" but not fill or not).
  46401. // (2) For the common props like opacity, if some use itemStyle
  46402. // and some use `lineStyle`, it might confuse users.
  46403. // (3) Most SVG use <path>, where can not detect whether to draw a "line"
  46404. // or a filled shape, so use `itemStyle` for <path>.
  46405. var normalStyleModel = regionModel.getModel('itemStyle');
  46406. var emphasisStyleModel = regionModel.getModel(['emphasis', 'itemStyle']);
  46407. var blurStyleModel = regionModel.getModel(['blur', 'itemStyle']);
  46408. var selectStyleModel = regionModel.getModel(['select', 'itemStyle']); // NOTE: DON'T use 'style' in visual when drawing map.
  46409. // This component is used for drawing underlying map for both geo component and map series.
  46410. var normalStyle = getFixedItemStyle(normalStyleModel);
  46411. var emphasisStyle = getFixedItemStyle(emphasisStyleModel);
  46412. var selectStyle = getFixedItemStyle(selectStyleModel);
  46413. var blurStyle = getFixedItemStyle(blurStyleModel); // Update the itemStyle if has data visual
  46414. var data = viewBuildCtx.data;
  46415. if (data) {
  46416. // Only visual color of each item will be used. It can be encoded by visualMap
  46417. // But visual color of series is used in symbol drawing
  46418. // Visual color for each series is for the symbol draw
  46419. var style = data.getItemVisual(dataIndex, 'style');
  46420. var decal = data.getItemVisual(dataIndex, 'decal');
  46421. if (viewBuildCtx.isVisualEncodedByVisualMap && style.fill) {
  46422. normalStyle.fill = style.fill;
  46423. }
  46424. if (decal) {
  46425. normalStyle.decal = createOrUpdatePatternFromDecal(decal, viewBuildCtx.api);
  46426. }
  46427. } // SVG text, tspan and image can be named but not supporeted
  46428. // to be styled by region option yet.
  46429. el.setStyle(normalStyle);
  46430. el.style.strokeNoScale = true;
  46431. el.ensureState('emphasis').style = emphasisStyle;
  46432. el.ensureState('select').style = selectStyle;
  46433. el.ensureState('blur').style = blurStyle; // Enable blur
  46434. setDefaultStateProxy(el);
  46435. }
  46436. function resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, // Exist only if `viewBuildCtx.data` exists.
  46437. dataIdx, // If labelXY not provided, use `textConfig.position: 'inside'`
  46438. labelXY) {
  46439. var data = viewBuildCtx.data;
  46440. var isGeo = viewBuildCtx.isGeo;
  46441. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  46442. var itemLayout = data && data.getItemLayout(dataIdx); // In the following cases label will be drawn
  46443. // 1. In map series and data value is NaN
  46444. // 2. In geo component
  46445. // 3. Region has no series legendIcon, which will be add a showLabel flag in mapSymbolLayout
  46446. if (isGeo || isDataNaN || itemLayout && itemLayout.showLabel) {
  46447. var query = !isGeo ? dataIdx : regionName;
  46448. var labelFetcher = void 0; // Consider dataIdx not found.
  46449. if (!data || dataIdx >= 0) {
  46450. labelFetcher = mapOrGeoModel;
  46451. }
  46452. var specifiedTextOpt = labelXY ? {
  46453. normal: {
  46454. align: 'center',
  46455. verticalAlign: 'middle'
  46456. }
  46457. } : null; // Caveat: must be called after `setDefaultStateProxy(el);` called.
  46458. // because textContent will be assign with `el.stateProxy` inside.
  46459. setLabelStyle(el, getLabelStatesModels(regionModel), {
  46460. labelFetcher: labelFetcher,
  46461. labelDataIndex: query,
  46462. defaultText: regionName
  46463. }, specifiedTextOpt);
  46464. var textEl = el.getTextContent();
  46465. if (textEl) {
  46466. mapLabelRaw(textEl).ignore = textEl.ignore;
  46467. if (el.textConfig && labelXY) {
  46468. // Compute a relative offset based on the el bounding rect.
  46469. var rect = el.getBoundingRect().clone(); // Need to make sure the percent position base on the same rect in normal and
  46470. // emphasis state. Otherwise if using boundingRect of el, but the emphasis state
  46471. // has borderWidth (even 0.5px), the text position will be changed obviously
  46472. // if the position is very big like ['1234%', '1345%'].
  46473. el.textConfig.layoutRect = rect;
  46474. el.textConfig.position = [(labelXY[0] - rect.x) / rect.width * 100 + '%', (labelXY[1] - rect.y) / rect.height * 100 + '%'];
  46475. }
  46476. } // PENDING:
  46477. // If labelLayout is enabled (test/label-layout.html), el.dataIndex should be specified.
  46478. // But el.dataIndex is also used to determine whether user event should be triggered,
  46479. // where el.seriesIndex or el.dataModel must be specified. At present for a single el
  46480. // there is not case that "only label layout enabled but user event disabled", so here
  46481. // we depends `resetEventTriggerForRegion` to do the job of setting `el.dataIndex`.
  46482. el.disableLabelAnimation = true;
  46483. } else {
  46484. el.removeTextContent();
  46485. el.removeTextConfig();
  46486. el.disableLabelAnimation = null;
  46487. }
  46488. }
  46489. function resetEventTriggerForRegion(viewBuildCtx, eventTrigger, regionName, regionModel, mapOrGeoModel, // Exist only if `viewBuildCtx.data` exists.
  46490. dataIdx) {
  46491. // setItemGraphicEl, setHoverStyle after all polygons and labels
  46492. // are added to the regionGroup
  46493. if (viewBuildCtx.data) {
  46494. // FIXME: when series-map use a SVG map, and there are duplicated name specified
  46495. // on different SVG elements, after `data.setItemGraphicEl(...)`:
  46496. // (1) all of them will be mounted with `dataIndex`, `seriesIndex`, so that tooltip
  46497. // can be triggered only mouse hover. That's correct.
  46498. // (2) only the last element will be kept in `data`, so that if trigger tooltip
  46499. // by `dispatchAction`, only the last one can be found and triggered. That might be
  46500. // not correct. We will fix it in future if anyone demanding that.
  46501. viewBuildCtx.data.setItemGraphicEl(dataIdx, eventTrigger);
  46502. } // series-map will not trigger "geoselectchange" no matter it is
  46503. // based on a declared geo component. Because series-map will
  46504. // trigger "selectchange". If it trigger both the two events,
  46505. // If users call `chart.dispatchAction({type: 'toggleSelect'})`,
  46506. // it not easy to also fire event "geoselectchanged".
  46507. else {
  46508. // Package custom mouse event for geo component
  46509. getECData(eventTrigger).eventData = {
  46510. componentType: 'geo',
  46511. componentIndex: mapOrGeoModel.componentIndex,
  46512. geoIndex: mapOrGeoModel.componentIndex,
  46513. name: regionName,
  46514. region: regionModel && regionModel.option || {}
  46515. };
  46516. }
  46517. }
  46518. function resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) {
  46519. if (!viewBuildCtx.data) {
  46520. setTooltipConfig({
  46521. el: el,
  46522. componentModel: mapOrGeoModel,
  46523. itemName: regionName,
  46524. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46525. itemTooltipOption: regionModel.get('tooltip')
  46526. });
  46527. }
  46528. }
  46529. function resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) {
  46530. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46531. el.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode'); // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46532. var emphasisModel = regionModel.getModel('emphasis');
  46533. var focus = emphasisModel.get('focus');
  46534. toggleHoverEmphasis(el, focus, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  46535. if (viewBuildCtx.isGeo) {
  46536. enableComponentHighDownFeatures(el, mapOrGeoModel, regionName);
  46537. }
  46538. return focus;
  46539. }
  46540. function projectPolys(rings, // Polygons include exterior and interiors. Or polylines.
  46541. createStream, isLine) {
  46542. var polygons = [];
  46543. var curPoly;
  46544. function startPolygon() {
  46545. curPoly = [];
  46546. }
  46547. function endPolygon() {
  46548. if (curPoly.length) {
  46549. polygons.push(curPoly);
  46550. curPoly = [];
  46551. }
  46552. }
  46553. var stream = createStream({
  46554. polygonStart: startPolygon,
  46555. polygonEnd: endPolygon,
  46556. lineStart: startPolygon,
  46557. lineEnd: endPolygon,
  46558. point: function (x, y) {
  46559. // May have NaN values from stream.
  46560. if (isFinite(x) && isFinite(y)) {
  46561. curPoly.push([x, y]);
  46562. }
  46563. },
  46564. sphere: function () {}
  46565. });
  46566. !isLine && stream.polygonStart();
  46567. each(rings, function (ring) {
  46568. stream.lineStart();
  46569. for (var i = 0; i < ring.length; i++) {
  46570. stream.point(ring[i][0], ring[i][1]);
  46571. }
  46572. stream.lineEnd();
  46573. });
  46574. !isLine && stream.polygonEnd();
  46575. return polygons;
  46576. }
  46577. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46578. var MapView =
  46579. /** @class */
  46580. function (_super) {
  46581. __extends(MapView, _super);
  46582. function MapView() {
  46583. var _this = _super !== null && _super.apply(this, arguments) || this;
  46584. _this.type = MapView.type;
  46585. return _this;
  46586. }
  46587. MapView.prototype.render = function (mapModel, ecModel, api, payload) {
  46588. // Not render if it is an toggleSelect action from self
  46589. if (payload && payload.type === 'mapToggleSelect' && payload.from === this.uid) {
  46590. return;
  46591. }
  46592. var group = this.group;
  46593. group.removeAll();
  46594. if (mapModel.getHostGeoModel()) {
  46595. return;
  46596. }
  46597. if (this._mapDraw && payload && payload.type === 'geoRoam') {
  46598. this._mapDraw.resetForLabelLayout();
  46599. } // Not update map if it is an roam action from self
  46600. if (!(payload && payload.type === 'geoRoam' && payload.componentType === 'series' && payload.seriesId === mapModel.id)) {
  46601. if (mapModel.needsDrawMap) {
  46602. var mapDraw = this._mapDraw || new MapDraw(api);
  46603. group.add(mapDraw.group);
  46604. mapDraw.draw(mapModel, ecModel, api, this, payload);
  46605. this._mapDraw = mapDraw;
  46606. } else {
  46607. // Remove drawn map
  46608. this._mapDraw && this._mapDraw.remove();
  46609. this._mapDraw = null;
  46610. }
  46611. } else {
  46612. var mapDraw = this._mapDraw;
  46613. mapDraw && group.add(mapDraw.group);
  46614. }
  46615. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend') && this._renderSymbols(mapModel, ecModel, api);
  46616. };
  46617. MapView.prototype.remove = function () {
  46618. this._mapDraw && this._mapDraw.remove();
  46619. this._mapDraw = null;
  46620. this.group.removeAll();
  46621. };
  46622. MapView.prototype.dispose = function () {
  46623. this._mapDraw && this._mapDraw.remove();
  46624. this._mapDraw = null;
  46625. };
  46626. MapView.prototype._renderSymbols = function (mapModel, ecModel, api) {
  46627. var originalData = mapModel.originalData;
  46628. var group = this.group;
  46629. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  46630. if (isNaN(value)) {
  46631. return;
  46632. }
  46633. var layout = originalData.getItemLayout(originalDataIndex);
  46634. if (!layout || !layout.point) {
  46635. // Not exists in map
  46636. return;
  46637. }
  46638. var point = layout.point;
  46639. var offset = layout.offset;
  46640. var circle = new Circle({
  46641. style: {
  46642. // Because the special of map draw.
  46643. // Which needs statistic of multiple series and draw on one map.
  46644. // And each series also need a symbol with legend color
  46645. //
  46646. // Layout and visual are put one the different data
  46647. // TODO
  46648. fill: mapModel.getData().getVisual('style').fill
  46649. },
  46650. shape: {
  46651. cx: point[0] + offset * 9,
  46652. cy: point[1],
  46653. r: 3
  46654. },
  46655. silent: true,
  46656. // Do not overlap the first series, on which labels are displayed.
  46657. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  46658. }); // Only the series that has the first value on the same region is in charge of rendering the label.
  46659. // But consider the case:
  46660. // series: [
  46661. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  46662. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  46663. // ]
  46664. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  46665. // For backward compatibility, we follow the rule that render label `A` by the
  46666. // settings on series `X` but render label `C` by the settings on series `Y`.
  46667. if (!offset) {
  46668. var fullData = mapModel.mainSeries.getData();
  46669. var name_1 = originalData.getName(originalDataIndex);
  46670. var fullIndex_1 = fullData.indexOfName(name_1);
  46671. var itemModel = originalData.getItemModel(originalDataIndex);
  46672. var labelModel = itemModel.getModel('label');
  46673. var regionGroup = fullData.getItemGraphicEl(fullIndex_1); // `getFormattedLabel` needs to use `getData` inside. Here
  46674. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  46675. // FIXME
  46676. // If this is not the `mainSeries`, the item model (like label formatter)
  46677. // set on original data item will never get. But it has been working
  46678. // like that from the beginning, and this scenario is rarely encountered.
  46679. // So it won't be fixed until we have to.
  46680. setLabelStyle(circle, getLabelStatesModels(itemModel), {
  46681. labelFetcher: {
  46682. getFormattedLabel: function (idx, state) {
  46683. return mapModel.getFormattedLabel(fullIndex_1, state);
  46684. }
  46685. },
  46686. defaultText: name_1
  46687. });
  46688. circle.disableLabelAnimation = true;
  46689. if (!labelModel.get('position')) {
  46690. circle.setTextConfig({
  46691. position: 'bottom'
  46692. });
  46693. }
  46694. regionGroup.onHoverStateChange = function (toState) {
  46695. setStatesFlag(circle, toState);
  46696. };
  46697. }
  46698. group.add(circle);
  46699. });
  46700. };
  46701. MapView.type = 'map';
  46702. return MapView;
  46703. }(ChartView);
  46704. var MapSeries =
  46705. /** @class */
  46706. function (_super) {
  46707. __extends(MapSeries, _super);
  46708. function MapSeries() {
  46709. var _this = _super !== null && _super.apply(this, arguments) || this;
  46710. _this.type = MapSeries.type; // Only first map series of same mapType will drawMap.
  46711. _this.needsDrawMap = false; // Group of all map series with same mapType
  46712. _this.seriesGroup = [];
  46713. _this.getTooltipPosition = function (dataIndex) {
  46714. if (dataIndex != null) {
  46715. var name_1 = this.getData().getName(dataIndex);
  46716. var geo = this.coordinateSystem;
  46717. var region = geo.getRegion(name_1);
  46718. return region && geo.dataToPoint(region.getCenter());
  46719. }
  46720. };
  46721. return _this;
  46722. }
  46723. MapSeries.prototype.getInitialData = function (option) {
  46724. var data = createSeriesDataSimply(this, {
  46725. coordDimensions: ['value'],
  46726. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  46727. });
  46728. var dataNameMap = createHashMap();
  46729. var toAppendNames = [];
  46730. for (var i = 0, len = data.count(); i < len; i++) {
  46731. var name_2 = data.getName(i);
  46732. dataNameMap.set(name_2, true);
  46733. }
  46734. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap, this.option.nameProperty);
  46735. each(geoSource.regions, function (region) {
  46736. var name = region.name;
  46737. if (!dataNameMap.get(name)) {
  46738. toAppendNames.push(name);
  46739. }
  46740. }); // Complete data with missing regions. The consequent processes (like visual
  46741. // map and render) can not be performed without a "full data". For example,
  46742. // find `dataIndex` by name.
  46743. data.appendValues([], toAppendNames);
  46744. return data;
  46745. };
  46746. /**
  46747. * If no host geo model, return null, which means using a
  46748. * inner exclusive geo model.
  46749. */
  46750. MapSeries.prototype.getHostGeoModel = function () {
  46751. var geoIndex = this.option.geoIndex;
  46752. return geoIndex != null ? this.ecModel.getComponent('geo', geoIndex) : null;
  46753. };
  46754. MapSeries.prototype.getMapType = function () {
  46755. return (this.getHostGeoModel() || this).option.map;
  46756. }; // _fillOption(option, mapName) {
  46757. // Shallow clone
  46758. // option = zrUtil.extend({}, option);
  46759. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  46760. // return option;
  46761. // }
  46762. MapSeries.prototype.getRawValue = function (dataIndex) {
  46763. // Use value stored in data instead because it is calculated from multiple series
  46764. // FIXME Provide all value of multiple series ?
  46765. var data = this.getData();
  46766. return data.get(data.mapDimension('value'), dataIndex);
  46767. };
  46768. /**
  46769. * Get model of region
  46770. */
  46771. MapSeries.prototype.getRegionModel = function (regionName) {
  46772. var data = this.getData();
  46773. return data.getItemModel(data.indexOfName(regionName));
  46774. };
  46775. /**
  46776. * Map tooltip formatter
  46777. */
  46778. MapSeries.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  46779. // FIXME orignalData and data is a bit confusing
  46780. var data = this.getData();
  46781. var value = this.getRawValue(dataIndex);
  46782. var name = data.getName(dataIndex);
  46783. var seriesGroup = this.seriesGroup;
  46784. var seriesNames = [];
  46785. for (var i = 0; i < seriesGroup.length; i++) {
  46786. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  46787. var valueDim = data.mapDimension('value');
  46788. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  46789. seriesNames.push(seriesGroup[i].name);
  46790. }
  46791. }
  46792. return createTooltipMarkup('section', {
  46793. header: seriesNames.join(', '),
  46794. noHeader: !seriesNames.length,
  46795. blocks: [createTooltipMarkup('nameValue', {
  46796. name: name,
  46797. value: value
  46798. })]
  46799. });
  46800. };
  46801. MapSeries.prototype.setZoom = function (zoom) {
  46802. this.option.zoom = zoom;
  46803. };
  46804. MapSeries.prototype.setCenter = function (center) {
  46805. this.option.center = center;
  46806. };
  46807. MapSeries.prototype.getLegendIcon = function (opt) {
  46808. var iconType = opt.icon || 'roundRect';
  46809. var icon = createSymbol(iconType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill);
  46810. icon.setStyle(opt.itemStyle); // Map do not use itemStyle.borderWidth as border width
  46811. icon.style.stroke = 'none'; // No rotation because no series visual symbol for map
  46812. if (iconType.indexOf('empty') > -1) {
  46813. icon.style.stroke = icon.style.fill;
  46814. icon.style.fill = '#fff';
  46815. icon.style.lineWidth = 2;
  46816. }
  46817. return icon;
  46818. };
  46819. MapSeries.type = 'series.map';
  46820. MapSeries.dependencies = ['geo'];
  46821. MapSeries.layoutMode = 'box';
  46822. MapSeries.defaultOption = {
  46823. // 一级层叠
  46824. // zlevel: 0,
  46825. // 二级层叠
  46826. z: 2,
  46827. coordinateSystem: 'geo',
  46828. // map should be explicitly specified since ec3.
  46829. map: '',
  46830. // If `geoIndex` is not specified, a exclusive geo will be
  46831. // created. Otherwise use the specified geo component, and
  46832. // `map` and `mapType` are ignored.
  46833. // geoIndex: 0,
  46834. // 'center' | 'left' | 'right' | 'x%' | {number}
  46835. left: 'center',
  46836. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  46837. top: 'center',
  46838. // right
  46839. // bottom
  46840. // width:
  46841. // height
  46842. // Aspect is width / height. Inited to be geoJson bbox aspect
  46843. // This parameter is used for scale this aspect
  46844. // Default value:
  46845. // for geoSVG source: 1,
  46846. // for geoJSON source: 0.75.
  46847. aspectScale: null,
  46848. // Layout with center and size
  46849. // If you want to put map in a fixed size box with right aspect ratio
  46850. // This two properties may be more convenient.
  46851. // layoutCenter: [50%, 50%]
  46852. // layoutSize: 100
  46853. showLegendSymbol: true,
  46854. // Define left-top, right-bottom coords to control view
  46855. // For example, [ [180, 90], [-180, -90] ],
  46856. // higher priority than center and zoom
  46857. boundingCoords: null,
  46858. // Default on center of map
  46859. center: null,
  46860. zoom: 1,
  46861. scaleLimit: null,
  46862. selectedMode: true,
  46863. label: {
  46864. show: false,
  46865. color: '#000'
  46866. },
  46867. // scaleLimit: null,
  46868. itemStyle: {
  46869. borderWidth: 0.5,
  46870. borderColor: '#444',
  46871. areaColor: '#eee'
  46872. },
  46873. emphasis: {
  46874. label: {
  46875. show: true,
  46876. color: 'rgb(100,0,0)'
  46877. },
  46878. itemStyle: {
  46879. areaColor: 'rgba(255,215,0,0.8)'
  46880. }
  46881. },
  46882. select: {
  46883. label: {
  46884. show: true,
  46885. color: 'rgb(100,0,0)'
  46886. },
  46887. itemStyle: {
  46888. color: 'rgba(255,215,0,0.8)'
  46889. }
  46890. },
  46891. nameProperty: 'name'
  46892. };
  46893. return MapSeries;
  46894. }(SeriesModel);
  46895. function dataStatistics(datas, statisticType) {
  46896. var dataNameMap = {};
  46897. each(datas, function (data) {
  46898. data.each(data.mapDimension('value'), function (value, idx) {
  46899. // Add prefix to avoid conflict with Object.prototype.
  46900. var mapKey = 'ec-' + data.getName(idx);
  46901. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  46902. if (!isNaN(value)) {
  46903. dataNameMap[mapKey].push(value);
  46904. }
  46905. });
  46906. });
  46907. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  46908. var mapKey = 'ec-' + datas[0].getName(idx);
  46909. var sum = 0;
  46910. var min = Infinity;
  46911. var max = -Infinity;
  46912. var len = dataNameMap[mapKey].length;
  46913. for (var i = 0; i < len; i++) {
  46914. min = Math.min(min, dataNameMap[mapKey][i]);
  46915. max = Math.max(max, dataNameMap[mapKey][i]);
  46916. sum += dataNameMap[mapKey][i];
  46917. }
  46918. var result;
  46919. if (statisticType === 'min') {
  46920. result = min;
  46921. } else if (statisticType === 'max') {
  46922. result = max;
  46923. } else if (statisticType === 'average') {
  46924. result = sum / len;
  46925. } else {
  46926. result = sum;
  46927. }
  46928. return len === 0 ? NaN : result;
  46929. });
  46930. }
  46931. function mapDataStatistic(ecModel) {
  46932. var seriesGroups = {};
  46933. ecModel.eachSeriesByType('map', function (seriesModel) {
  46934. var hostGeoModel = seriesModel.getHostGeoModel();
  46935. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  46936. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  46937. });
  46938. each(seriesGroups, function (seriesList, key) {
  46939. var data = dataStatistics(map(seriesList, function (seriesModel) {
  46940. return seriesModel.getData();
  46941. }), seriesList[0].get('mapValueCalculation'));
  46942. for (var i = 0; i < seriesList.length; i++) {
  46943. seriesList[i].originalData = seriesList[i].getData();
  46944. } // FIXME Put where?
  46945. for (var i = 0; i < seriesList.length; i++) {
  46946. seriesList[i].seriesGroup = seriesList;
  46947. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  46948. seriesList[i].setData(data.cloneShallow());
  46949. seriesList[i].mainSeries = seriesList[0];
  46950. }
  46951. });
  46952. }
  46953. function mapSymbolLayout(ecModel) {
  46954. var processedMapType = {};
  46955. ecModel.eachSeriesByType('map', function (mapSeries) {
  46956. var mapType = mapSeries.getMapType();
  46957. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  46958. return;
  46959. }
  46960. var mapSymbolOffsets = {};
  46961. each(mapSeries.seriesGroup, function (subMapSeries) {
  46962. var geo = subMapSeries.coordinateSystem;
  46963. var data = subMapSeries.originalData;
  46964. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  46965. data.each(data.mapDimension('value'), function (value, idx) {
  46966. var name = data.getName(idx);
  46967. var region = geo.getRegion(name); // If input series.data is [11, 22, '-'/null/undefined, 44],
  46968. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  46969. // not be drawn. So here must validate if value is NaN.
  46970. if (!region || isNaN(value)) {
  46971. return;
  46972. }
  46973. var offset = mapSymbolOffsets[name] || 0;
  46974. var point = geo.dataToPoint(region.getCenter());
  46975. mapSymbolOffsets[name] = offset + 1;
  46976. data.setItemLayout(idx, {
  46977. point: point,
  46978. offset: offset
  46979. });
  46980. });
  46981. }
  46982. }); // Show label of those region not has legendIcon (which is offset 0)
  46983. var data = mapSeries.getData();
  46984. data.each(function (idx) {
  46985. var name = data.getName(idx);
  46986. var layout = data.getItemLayout(idx) || {};
  46987. layout.showLabel = !mapSymbolOffsets[name];
  46988. data.setItemLayout(idx, layout);
  46989. });
  46990. processedMapType[mapType] = true;
  46991. });
  46992. }
  46993. var v2ApplyTransform = applyTransform;
  46994. var View =
  46995. /** @class */
  46996. function (_super) {
  46997. __extends(View, _super);
  46998. function View(name) {
  46999. var _this = _super.call(this) || this;
  47000. _this.type = 'view';
  47001. _this.dimensions = ['x', 'y'];
  47002. /**
  47003. * Represents the transform brought by roam/zoom.
  47004. * If `View['_viewRect']` applies roam transform,
  47005. * we can get the final displayed rect.
  47006. */
  47007. _this._roamTransformable = new Transformable();
  47008. /**
  47009. * Represents the transform from `View['_rect']` to `View['_viewRect']`.
  47010. */
  47011. _this._rawTransformable = new Transformable();
  47012. _this.name = name;
  47013. return _this;
  47014. }
  47015. View.prototype.setBoundingRect = function (x, y, width, height) {
  47016. this._rect = new BoundingRect(x, y, width, height);
  47017. return this._rect;
  47018. };
  47019. /**
  47020. * @return {module:zrender/core/BoundingRect}
  47021. */
  47022. View.prototype.getBoundingRect = function () {
  47023. return this._rect;
  47024. };
  47025. View.prototype.setViewRect = function (x, y, width, height) {
  47026. this._transformTo(x, y, width, height);
  47027. this._viewRect = new BoundingRect(x, y, width, height);
  47028. };
  47029. /**
  47030. * Transformed to particular position and size
  47031. */
  47032. View.prototype._transformTo = function (x, y, width, height) {
  47033. var rect = this.getBoundingRect();
  47034. var rawTransform = this._rawTransformable;
  47035. rawTransform.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  47036. var rawParent = rawTransform.parent;
  47037. rawTransform.parent = null;
  47038. rawTransform.decomposeTransform();
  47039. rawTransform.parent = rawParent;
  47040. this._updateTransform();
  47041. };
  47042. /**
  47043. * Set center of view
  47044. */
  47045. View.prototype.setCenter = function (centerCoord, api) {
  47046. if (!centerCoord) {
  47047. return;
  47048. }
  47049. this._center = [parsePercent$1(centerCoord[0], api.getWidth()), parsePercent$1(centerCoord[1], api.getHeight())];
  47050. this._updateCenterAndZoom();
  47051. };
  47052. View.prototype.setZoom = function (zoom) {
  47053. zoom = zoom || 1;
  47054. var zoomLimit = this.zoomLimit;
  47055. if (zoomLimit) {
  47056. if (zoomLimit.max != null) {
  47057. zoom = Math.min(zoomLimit.max, zoom);
  47058. }
  47059. if (zoomLimit.min != null) {
  47060. zoom = Math.max(zoomLimit.min, zoom);
  47061. }
  47062. }
  47063. this._zoom = zoom;
  47064. this._updateCenterAndZoom();
  47065. };
  47066. /**
  47067. * Get default center without roam
  47068. */
  47069. View.prototype.getDefaultCenter = function () {
  47070. // Rect before any transform
  47071. var rawRect = this.getBoundingRect();
  47072. var cx = rawRect.x + rawRect.width / 2;
  47073. var cy = rawRect.y + rawRect.height / 2;
  47074. return [cx, cy];
  47075. };
  47076. View.prototype.getCenter = function () {
  47077. return this._center || this.getDefaultCenter();
  47078. };
  47079. View.prototype.getZoom = function () {
  47080. return this._zoom || 1;
  47081. };
  47082. View.prototype.getRoamTransform = function () {
  47083. return this._roamTransformable.getLocalTransform();
  47084. };
  47085. /**
  47086. * Remove roam
  47087. */
  47088. View.prototype._updateCenterAndZoom = function () {
  47089. // Must update after view transform updated
  47090. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  47091. var roamTransform = this._roamTransformable;
  47092. var defaultCenter = this.getDefaultCenter();
  47093. var center = this.getCenter();
  47094. var zoom = this.getZoom();
  47095. center = applyTransform([], center, rawTransformMatrix);
  47096. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  47097. roamTransform.originX = center[0];
  47098. roamTransform.originY = center[1];
  47099. roamTransform.x = defaultCenter[0] - center[0];
  47100. roamTransform.y = defaultCenter[1] - center[1];
  47101. roamTransform.scaleX = roamTransform.scaleY = zoom;
  47102. this._updateTransform();
  47103. };
  47104. /**
  47105. * Update transform props on `this` based on the current
  47106. * `this._roamTransformable` and `this._rawTransformable`.
  47107. */
  47108. View.prototype._updateTransform = function () {
  47109. var roamTransformable = this._roamTransformable;
  47110. var rawTransformable = this._rawTransformable;
  47111. rawTransformable.parent = roamTransformable;
  47112. roamTransformable.updateTransform();
  47113. rawTransformable.updateTransform();
  47114. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  47115. this._rawTransform = rawTransformable.getLocalTransform();
  47116. this.invTransform = this.invTransform || [];
  47117. invert(this.invTransform, this.transform);
  47118. this.decomposeTransform();
  47119. };
  47120. View.prototype.getTransformInfo = function () {
  47121. var rawTransformable = this._rawTransformable;
  47122. var roamTransformable = this._roamTransformable; // Because roamTransformabel has `originX/originY` modified,
  47123. // but the caller of `getTransformInfo` can not handle `originX/originY`,
  47124. // so need to recalculate them.
  47125. var dummyTransformable = new Transformable();
  47126. dummyTransformable.transform = roamTransformable.transform;
  47127. dummyTransformable.decomposeTransform();
  47128. return {
  47129. roam: {
  47130. x: dummyTransformable.x,
  47131. y: dummyTransformable.y,
  47132. scaleX: dummyTransformable.scaleX,
  47133. scaleY: dummyTransformable.scaleY
  47134. },
  47135. raw: {
  47136. x: rawTransformable.x,
  47137. y: rawTransformable.y,
  47138. scaleX: rawTransformable.scaleX,
  47139. scaleY: rawTransformable.scaleY
  47140. }
  47141. };
  47142. };
  47143. View.prototype.getViewRect = function () {
  47144. return this._viewRect;
  47145. };
  47146. /**
  47147. * Get view rect after roam transform
  47148. */
  47149. View.prototype.getViewRectAfterRoam = function () {
  47150. var rect = this.getBoundingRect().clone();
  47151. rect.applyTransform(this.transform);
  47152. return rect;
  47153. };
  47154. /**
  47155. * Convert a single (lon, lat) data item to (x, y) point.
  47156. */
  47157. View.prototype.dataToPoint = function (data, noRoam, out) {
  47158. var transform = noRoam ? this._rawTransform : this.transform;
  47159. out = out || [];
  47160. return transform ? v2ApplyTransform(out, data, transform) : copy(out, data);
  47161. };
  47162. /**
  47163. * Convert a (x, y) point to (lon, lat) data
  47164. */
  47165. View.prototype.pointToData = function (point) {
  47166. var invTransform = this.invTransform;
  47167. return invTransform ? v2ApplyTransform([], point, invTransform) : [point[0], point[1]];
  47168. };
  47169. View.prototype.convertToPixel = function (ecModel, finder, value) {
  47170. var coordSys = getCoordSys(finder);
  47171. return coordSys === this ? coordSys.dataToPoint(value) : null;
  47172. };
  47173. View.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  47174. var coordSys = getCoordSys(finder);
  47175. return coordSys === this ? coordSys.pointToData(pixel) : null;
  47176. };
  47177. /**
  47178. * @implements
  47179. */
  47180. View.prototype.containPoint = function (point) {
  47181. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  47182. };
  47183. View.dimensions = ['x', 'y'];
  47184. return View;
  47185. }(Transformable);
  47186. function getCoordSys(finder) {
  47187. var seriesModel = finder.seriesModel;
  47188. return seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  47189. }
  47190. var GEO_DEFAULT_PARAMS = {
  47191. 'geoJSON': {
  47192. aspectScale: 0.75,
  47193. invertLongitute: true
  47194. },
  47195. 'geoSVG': {
  47196. aspectScale: 1,
  47197. invertLongitute: false
  47198. }
  47199. };
  47200. var geo2DDimensions = ['lng', 'lat'];
  47201. var Geo =
  47202. /** @class */
  47203. function (_super) {
  47204. __extends(Geo, _super);
  47205. function Geo(name, map, opt) {
  47206. var _this = _super.call(this, name) || this;
  47207. _this.dimensions = geo2DDimensions;
  47208. _this.type = 'geo'; // Only store specified name coord via `addGeoCoord`.
  47209. _this._nameCoordMap = createHashMap();
  47210. _this.map = map;
  47211. var projection = opt.projection;
  47212. var source = geoSourceManager.load(map, opt.nameMap, opt.nameProperty);
  47213. var resource = geoSourceManager.getGeoResource(map);
  47214. var resourceType = _this.resourceType = resource ? resource.type : null;
  47215. var regions = _this.regions = source.regions;
  47216. var defaultParams = GEO_DEFAULT_PARAMS[resource.type];
  47217. _this._regionsMap = source.regionsMap;
  47218. _this.regions = source.regions;
  47219. if ("development" !== 'production' && projection) {
  47220. // Do some check
  47221. if (resourceType === 'geoSVG') {
  47222. if ("development" !== 'production') {
  47223. warn("Map " + map + " with SVG source can't use projection. Only GeoJSON source supports projection.");
  47224. }
  47225. projection = null;
  47226. }
  47227. if (!(projection.project && projection.unproject)) {
  47228. if ("development" !== 'production') {
  47229. warn('project and unproject must be both provided in the projeciton.');
  47230. }
  47231. projection = null;
  47232. }
  47233. }
  47234. _this.projection = projection;
  47235. var boundingRect;
  47236. if (projection) {
  47237. // Can't reuse the raw bounding rect
  47238. for (var i = 0; i < regions.length; i++) {
  47239. var regionRect = regions[i].getBoundingRect(projection);
  47240. boundingRect = boundingRect || regionRect.clone();
  47241. boundingRect.union(regionRect);
  47242. }
  47243. } else {
  47244. boundingRect = source.boundingRect;
  47245. }
  47246. _this.setBoundingRect(boundingRect.x, boundingRect.y, boundingRect.width, boundingRect.height); // aspectScale and invertLongitute actually is the parameters default raw projection.
  47247. // So we ignore them if projection is given.
  47248. // Ignore default aspect scale if projection exits.
  47249. _this.aspectScale = projection ? 1 : retrieve2(opt.aspectScale, defaultParams.aspectScale); // Not invert longitude if projection exits.
  47250. _this._invertLongitute = projection ? false : defaultParams.invertLongitute;
  47251. return _this;
  47252. }
  47253. Geo.prototype._transformTo = function (x, y, width, height) {
  47254. var rect = this.getBoundingRect();
  47255. var invertLongitute = this._invertLongitute;
  47256. rect = rect.clone();
  47257. if (invertLongitute) {
  47258. // Longitude is inverted.
  47259. rect.y = -rect.y - rect.height;
  47260. }
  47261. var rawTransformable = this._rawTransformable;
  47262. rawTransformable.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  47263. var rawParent = rawTransformable.parent;
  47264. rawTransformable.parent = null;
  47265. rawTransformable.decomposeTransform();
  47266. rawTransformable.parent = rawParent;
  47267. if (invertLongitute) {
  47268. rawTransformable.scaleY = -rawTransformable.scaleY;
  47269. }
  47270. this._updateTransform();
  47271. };
  47272. Geo.prototype.getRegion = function (name) {
  47273. return this._regionsMap.get(name);
  47274. };
  47275. Geo.prototype.getRegionByCoord = function (coord) {
  47276. var regions = this.regions;
  47277. for (var i = 0; i < regions.length; i++) {
  47278. var region = regions[i];
  47279. if (region.type === 'geoJSON' && region.contain(coord)) {
  47280. return regions[i];
  47281. }
  47282. }
  47283. };
  47284. /**
  47285. * Add geoCoord for indexing by name
  47286. */
  47287. Geo.prototype.addGeoCoord = function (name, geoCoord) {
  47288. this._nameCoordMap.set(name, geoCoord);
  47289. };
  47290. /**
  47291. * Get geoCoord by name
  47292. */
  47293. Geo.prototype.getGeoCoord = function (name) {
  47294. var region = this._regionsMap.get(name); // Calculate center only on demand.
  47295. return this._nameCoordMap.get(name) || region && region.getCenter();
  47296. };
  47297. Geo.prototype.dataToPoint = function (data, noRoam, out) {
  47298. if (isString(data)) {
  47299. // Map area name to geoCoord
  47300. data = this.getGeoCoord(data);
  47301. }
  47302. if (data) {
  47303. var projection = this.projection;
  47304. if (projection) {
  47305. // projection may return null point.
  47306. data = projection.project(data);
  47307. }
  47308. return data && this.projectedToPoint(data, noRoam, out);
  47309. }
  47310. };
  47311. Geo.prototype.pointToData = function (point) {
  47312. var projection = this.projection;
  47313. if (projection) {
  47314. // projection may return null point.
  47315. point = projection.unproject(point);
  47316. }
  47317. return point && this.pointToProjected(point);
  47318. };
  47319. /**
  47320. * Point to projected data. Same with pointToData when projection is used.
  47321. */
  47322. Geo.prototype.pointToProjected = function (point) {
  47323. return _super.prototype.pointToData.call(this, point);
  47324. };
  47325. Geo.prototype.projectedToPoint = function (projected, noRoam, out) {
  47326. return _super.prototype.dataToPoint.call(this, projected, noRoam, out);
  47327. };
  47328. Geo.prototype.convertToPixel = function (ecModel, finder, value) {
  47329. var coordSys = getCoordSys$1(finder);
  47330. return coordSys === this ? coordSys.dataToPoint(value) : null;
  47331. };
  47332. Geo.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  47333. var coordSys = getCoordSys$1(finder);
  47334. return coordSys === this ? coordSys.pointToData(pixel) : null;
  47335. };
  47336. return Geo;
  47337. }(View);
  47338. mixin(Geo, View);
  47339. function getCoordSys$1(finder) {
  47340. var geoModel = finder.geoModel;
  47341. var seriesModel = finder.seriesModel;
  47342. return geoModel ? geoModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem // For map series.
  47343. || (seriesModel.getReferringComponents('geo', SINGLE_REFERRING).models[0] || {}).coordinateSystem : null;
  47344. }
  47345. /**
  47346. * Resize method bound to the geo
  47347. */
  47348. function resizeGeo(geoModel, api) {
  47349. var boundingCoords = geoModel.get('boundingCoords');
  47350. if (boundingCoords != null) {
  47351. var leftTop_1 = boundingCoords[0];
  47352. var rightBottom_1 = boundingCoords[1];
  47353. if (!(isFinite(leftTop_1[0]) && isFinite(leftTop_1[1]) && isFinite(rightBottom_1[0]) && isFinite(rightBottom_1[1]))) {
  47354. if ("development" !== 'production') {
  47355. console.error('Invalid boundingCoords');
  47356. }
  47357. } else {
  47358. // Sample around the lng/lat rect and use projection to calculate actual bounding rect.
  47359. var projection_1 = this.projection;
  47360. if (projection_1) {
  47361. var xMin = leftTop_1[0];
  47362. var yMin = leftTop_1[1];
  47363. var xMax = rightBottom_1[0];
  47364. var yMax = rightBottom_1[1];
  47365. leftTop_1 = [Infinity, Infinity];
  47366. rightBottom_1 = [-Infinity, -Infinity]; // TODO better way?
  47367. var sampleLine = function (x0, y0, x1, y1) {
  47368. var dx = x1 - x0;
  47369. var dy = y1 - y0;
  47370. for (var i = 0; i <= 100; i++) {
  47371. var p = i / 100;
  47372. var pt = projection_1.project([x0 + dx * p, y0 + dy * p]);
  47373. min(leftTop_1, leftTop_1, pt);
  47374. max(rightBottom_1, rightBottom_1, pt);
  47375. }
  47376. }; // Top
  47377. sampleLine(xMin, yMin, xMax, yMin); // Right
  47378. sampleLine(xMax, yMin, xMax, yMax); // Bottom
  47379. sampleLine(xMax, yMax, xMin, yMax); // Left
  47380. sampleLine(xMin, yMax, xMax, yMin);
  47381. }
  47382. this.setBoundingRect(leftTop_1[0], leftTop_1[1], rightBottom_1[0] - leftTop_1[0], rightBottom_1[1] - leftTop_1[1]);
  47383. }
  47384. }
  47385. var rect = this.getBoundingRect();
  47386. var centerOption = geoModel.get('layoutCenter');
  47387. var sizeOption = geoModel.get('layoutSize');
  47388. var viewWidth = api.getWidth();
  47389. var viewHeight = api.getHeight();
  47390. var aspect = rect.width / rect.height * this.aspectScale;
  47391. var useCenterAndSize = false;
  47392. var center;
  47393. var size;
  47394. if (centerOption && sizeOption) {
  47395. center = [parsePercent$1(centerOption[0], viewWidth), parsePercent$1(centerOption[1], viewHeight)];
  47396. size = parsePercent$1(sizeOption, Math.min(viewWidth, viewHeight));
  47397. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  47398. useCenterAndSize = true;
  47399. } else {
  47400. if ("development" !== 'production') {
  47401. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  47402. }
  47403. }
  47404. }
  47405. var viewRect;
  47406. if (useCenterAndSize) {
  47407. viewRect = {};
  47408. if (aspect > 1) {
  47409. // Width is same with size
  47410. viewRect.width = size;
  47411. viewRect.height = size / aspect;
  47412. } else {
  47413. viewRect.height = size;
  47414. viewRect.width = size * aspect;
  47415. }
  47416. viewRect.y = center[1] - viewRect.height / 2;
  47417. viewRect.x = center[0] - viewRect.width / 2;
  47418. } else {
  47419. // Use left/top/width/height
  47420. var boxLayoutOption = geoModel.getBoxLayoutParams();
  47421. boxLayoutOption.aspect = aspect;
  47422. viewRect = getLayoutRect(boxLayoutOption, {
  47423. width: viewWidth,
  47424. height: viewHeight
  47425. });
  47426. }
  47427. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  47428. this.setCenter(geoModel.get('center'), api);
  47429. this.setZoom(geoModel.get('zoom'));
  47430. } // Back compat for ECharts2, where the coord map is set on map series:
  47431. // {type: 'map', geoCoord: {'cityA': [116.46,39.92], 'cityA': [119.12,24.61]}},
  47432. function setGeoCoords(geo, model) {
  47433. each(model.get('geoCoord'), function (geoCoord, name) {
  47434. geo.addGeoCoord(name, geoCoord);
  47435. });
  47436. }
  47437. var GeoCreator =
  47438. /** @class */
  47439. function () {
  47440. function GeoCreator() {
  47441. // For deciding which dimensions to use when creating list data
  47442. this.dimensions = geo2DDimensions;
  47443. }
  47444. GeoCreator.prototype.create = function (ecModel, api) {
  47445. var geoList = [];
  47446. function getCommonGeoProperties(model) {
  47447. return {
  47448. nameProperty: model.get('nameProperty'),
  47449. aspectScale: model.get('aspectScale'),
  47450. projection: model.get('projection')
  47451. };
  47452. } // FIXME Create each time may be slow
  47453. ecModel.eachComponent('geo', function (geoModel, idx) {
  47454. var mapName = geoModel.get('map');
  47455. var geo = new Geo(mapName + idx, mapName, extend({
  47456. nameMap: geoModel.get('nameMap')
  47457. }, getCommonGeoProperties(geoModel)));
  47458. geo.zoomLimit = geoModel.get('scaleLimit');
  47459. geoList.push(geo); // setGeoCoords(geo, geoModel);
  47460. geoModel.coordinateSystem = geo;
  47461. geo.model = geoModel; // Inject resize method
  47462. geo.resize = resizeGeo;
  47463. geo.resize(geoModel, api);
  47464. });
  47465. ecModel.eachSeries(function (seriesModel) {
  47466. var coordSys = seriesModel.get('coordinateSystem');
  47467. if (coordSys === 'geo') {
  47468. var geoIndex = seriesModel.get('geoIndex') || 0;
  47469. seriesModel.coordinateSystem = geoList[geoIndex];
  47470. }
  47471. }); // If has map series
  47472. var mapModelGroupBySeries = {};
  47473. ecModel.eachSeriesByType('map', function (seriesModel) {
  47474. if (!seriesModel.getHostGeoModel()) {
  47475. var mapType = seriesModel.getMapType();
  47476. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  47477. mapModelGroupBySeries[mapType].push(seriesModel);
  47478. }
  47479. });
  47480. each(mapModelGroupBySeries, function (mapSeries, mapType) {
  47481. var nameMapList = map(mapSeries, function (singleMapSeries) {
  47482. return singleMapSeries.get('nameMap');
  47483. });
  47484. var geo = new Geo(mapType, mapType, extend({
  47485. nameMap: mergeAll(nameMapList)
  47486. }, getCommonGeoProperties(mapSeries[0])));
  47487. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  47488. return singleMapSeries.get('scaleLimit');
  47489. }));
  47490. geoList.push(geo); // Inject resize method
  47491. geo.resize = resizeGeo;
  47492. geo.resize(mapSeries[0], api);
  47493. each(mapSeries, function (singleMapSeries) {
  47494. singleMapSeries.coordinateSystem = geo;
  47495. setGeoCoords(geo, singleMapSeries);
  47496. });
  47497. });
  47498. return geoList;
  47499. };
  47500. /**
  47501. * Fill given regions array
  47502. */
  47503. GeoCreator.prototype.getFilledRegions = function (originRegionArr, mapName, nameMap, nameProperty) {
  47504. // Not use the original
  47505. var regionsArr = (originRegionArr || []).slice();
  47506. var dataNameMap = createHashMap();
  47507. for (var i = 0; i < regionsArr.length; i++) {
  47508. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  47509. }
  47510. var source = geoSourceManager.load(mapName, nameMap, nameProperty);
  47511. each(source.regions, function (region) {
  47512. var name = region.name;
  47513. !dataNameMap.get(name) && regionsArr.push({
  47514. name: name
  47515. });
  47516. });
  47517. return regionsArr;
  47518. };
  47519. return GeoCreator;
  47520. }();
  47521. var geoCreator = new GeoCreator();
  47522. var GeoModel =
  47523. /** @class */
  47524. function (_super) {
  47525. __extends(GeoModel, _super);
  47526. function GeoModel() {
  47527. var _this = _super !== null && _super.apply(this, arguments) || this;
  47528. _this.type = GeoModel.type;
  47529. return _this;
  47530. }
  47531. GeoModel.prototype.init = function (option, parentModel, ecModel) {
  47532. var source = geoSourceManager.getGeoResource(option.map);
  47533. if (source && source.type === 'geoJSON') {
  47534. var itemStyle = option.itemStyle = option.itemStyle || {};
  47535. if (!('color' in itemStyle)) {
  47536. itemStyle.color = '#eee';
  47537. }
  47538. }
  47539. this.mergeDefaultAndTheme(option, ecModel); // Default label emphasis `show`
  47540. defaultEmphasis(option, 'label', ['show']);
  47541. };
  47542. GeoModel.prototype.optionUpdated = function () {
  47543. var _this = this;
  47544. var option = this.option;
  47545. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap, option.nameProperty);
  47546. var selectedMap = {};
  47547. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  47548. var regionName = regionOpt.name;
  47549. if (regionName) {
  47550. optionModelMap.set(regionName, new Model(regionOpt, _this, _this.ecModel));
  47551. if (regionOpt.selected) {
  47552. selectedMap[regionName] = true;
  47553. }
  47554. }
  47555. return optionModelMap;
  47556. }, createHashMap());
  47557. if (!option.selectedMap) {
  47558. option.selectedMap = selectedMap;
  47559. }
  47560. };
  47561. /**
  47562. * Get model of region.
  47563. */
  47564. GeoModel.prototype.getRegionModel = function (name) {
  47565. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  47566. };
  47567. /**
  47568. * Format label
  47569. * @param name Region name
  47570. */
  47571. GeoModel.prototype.getFormattedLabel = function (name, status) {
  47572. var regionModel = this.getRegionModel(name);
  47573. var formatter = status === 'normal' ? regionModel.get(['label', 'formatter']) : regionModel.get(['emphasis', 'label', 'formatter']);
  47574. var params = {
  47575. name: name
  47576. };
  47577. if (isFunction(formatter)) {
  47578. params.status = status;
  47579. return formatter(params);
  47580. } else if (isString(formatter)) {
  47581. return formatter.replace('{a}', name != null ? name : '');
  47582. }
  47583. };
  47584. GeoModel.prototype.setZoom = function (zoom) {
  47585. this.option.zoom = zoom;
  47586. };
  47587. GeoModel.prototype.setCenter = function (center) {
  47588. this.option.center = center;
  47589. }; // PENGING If selectedMode is null ?
  47590. GeoModel.prototype.select = function (name) {
  47591. var option = this.option;
  47592. var selectedMode = option.selectedMode;
  47593. if (!selectedMode) {
  47594. return;
  47595. }
  47596. if (selectedMode !== 'multiple') {
  47597. option.selectedMap = null;
  47598. }
  47599. var selectedMap = option.selectedMap || (option.selectedMap = {});
  47600. selectedMap[name] = true;
  47601. };
  47602. GeoModel.prototype.unSelect = function (name) {
  47603. var selectedMap = this.option.selectedMap;
  47604. if (selectedMap) {
  47605. selectedMap[name] = false;
  47606. }
  47607. };
  47608. GeoModel.prototype.toggleSelected = function (name) {
  47609. this[this.isSelected(name) ? 'unSelect' : 'select'](name);
  47610. };
  47611. GeoModel.prototype.isSelected = function (name) {
  47612. var selectedMap = this.option.selectedMap;
  47613. return !!(selectedMap && selectedMap[name]);
  47614. };
  47615. GeoModel.type = 'geo';
  47616. GeoModel.layoutMode = 'box';
  47617. GeoModel.defaultOption = {
  47618. // zlevel: 0,
  47619. z: 0,
  47620. show: true,
  47621. left: 'center',
  47622. top: 'center',
  47623. // Default value:
  47624. // for geoSVG source: 1,
  47625. // for geoJSON source: 0.75.
  47626. aspectScale: null,
  47627. // /// Layout with center and size
  47628. // If you want to put map in a fixed size box with right aspect ratio
  47629. // This two properties may be more convenient
  47630. // layoutCenter: [50%, 50%]
  47631. // layoutSize: 100
  47632. silent: false,
  47633. // Map type
  47634. map: '',
  47635. // Define left-top, right-bottom coords to control view
  47636. // For example, [ [180, 90], [-180, -90] ]
  47637. boundingCoords: null,
  47638. // Default on center of map
  47639. center: null,
  47640. zoom: 1,
  47641. scaleLimit: null,
  47642. // selectedMode: false
  47643. label: {
  47644. show: false,
  47645. color: '#000'
  47646. },
  47647. itemStyle: {
  47648. borderWidth: 0.5,
  47649. borderColor: '#444' // Default color:
  47650. // + geoJSON: #eee
  47651. // + geoSVG: null (use SVG original `fill`)
  47652. // color: '#eee'
  47653. },
  47654. emphasis: {
  47655. label: {
  47656. show: true,
  47657. color: 'rgb(100,0,0)'
  47658. },
  47659. itemStyle: {
  47660. color: 'rgba(255,215,0,0.8)'
  47661. }
  47662. },
  47663. select: {
  47664. label: {
  47665. show: true,
  47666. color: 'rgb(100,0,0)'
  47667. },
  47668. itemStyle: {
  47669. color: 'rgba(255,215,0,0.8)'
  47670. }
  47671. },
  47672. regions: [] // tooltip: {
  47673. // show: false
  47674. // }
  47675. };
  47676. return GeoModel;
  47677. }(ComponentModel);
  47678. /*
  47679. * Licensed to the Apache Software Foundation (ASF) under one
  47680. * or more contributor license agreements. See the NOTICE file
  47681. * distributed with this work for additional information
  47682. * regarding copyright ownership. The ASF licenses this file
  47683. * to you under the Apache License, Version 2.0 (the
  47684. * "License"); you may not use this file except in compliance
  47685. * with the License. You may obtain a copy of the License at
  47686. *
  47687. * http://www.apache.org/licenses/LICENSE-2.0
  47688. *
  47689. * Unless required by applicable law or agreed to in writing,
  47690. * software distributed under the License is distributed on an
  47691. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47692. * KIND, either express or implied. See the License for the
  47693. * specific language governing permissions and limitations
  47694. * under the License.
  47695. */
  47696. /**
  47697. * AUTO-GENERATED FILE. DO NOT MODIFY.
  47698. */
  47699. /*
  47700. * Licensed to the Apache Software Foundation (ASF) under one
  47701. * or more contributor license agreements. See the NOTICE file
  47702. * distributed with this work for additional information
  47703. * regarding copyright ownership. The ASF licenses this file
  47704. * to you under the Apache License, Version 2.0 (the
  47705. * "License"); you may not use this file except in compliance
  47706. * with the License. You may obtain a copy of the License at
  47707. *
  47708. * http://www.apache.org/licenses/LICENSE-2.0
  47709. *
  47710. * Unless required by applicable law or agreed to in writing,
  47711. * software distributed under the License is distributed on an
  47712. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47713. * KIND, either express or implied. See the License for the
  47714. * specific language governing permissions and limitations
  47715. * under the License.
  47716. */
  47717. function getCenterCoord(view, point) {
  47718. // Use projected coord as center because it's linear.
  47719. return view.pointToProjected ? view.pointToProjected(point) : view.pointToData(point);
  47720. }
  47721. function updateCenterAndZoom(view, payload, zoomLimit, api) {
  47722. var previousZoom = view.getZoom();
  47723. var center = view.getCenter();
  47724. var zoom = payload.zoom;
  47725. var point = view.projectedToPoint ? view.projectedToPoint(center) : view.dataToPoint(center);
  47726. if (payload.dx != null && payload.dy != null) {
  47727. point[0] -= payload.dx;
  47728. point[1] -= payload.dy;
  47729. view.setCenter(getCenterCoord(view, point), api);
  47730. }
  47731. if (zoom != null) {
  47732. if (zoomLimit) {
  47733. var zoomMin = zoomLimit.min || 0;
  47734. var zoomMax = zoomLimit.max || Infinity;
  47735. zoom = Math.max(Math.min(previousZoom * zoom, zoomMax), zoomMin) / previousZoom;
  47736. } // Zoom on given point(originX, originY)
  47737. view.scaleX *= zoom;
  47738. view.scaleY *= zoom;
  47739. var fixX = (payload.originX - view.x) * (zoom - 1);
  47740. var fixY = (payload.originY - view.y) * (zoom - 1);
  47741. view.x -= fixX;
  47742. view.y -= fixY;
  47743. view.updateTransform(); // Get the new center
  47744. view.setCenter(getCenterCoord(view, point), api);
  47745. view.setZoom(zoom * previousZoom);
  47746. }
  47747. return {
  47748. center: view.getCenter(),
  47749. zoom: view.getZoom()
  47750. };
  47751. }
  47752. var GeoView =
  47753. /** @class */
  47754. function (_super) {
  47755. __extends(GeoView, _super);
  47756. function GeoView() {
  47757. var _this = _super !== null && _super.apply(this, arguments) || this;
  47758. _this.type = GeoView.type;
  47759. _this.focusBlurEnabled = true;
  47760. return _this;
  47761. }
  47762. GeoView.prototype.init = function (ecModel, api) {
  47763. this._api = api;
  47764. };
  47765. GeoView.prototype.render = function (geoModel, ecModel, api, payload) {
  47766. this._model = geoModel;
  47767. if (!geoModel.get('show')) {
  47768. this._mapDraw && this._mapDraw.remove();
  47769. this._mapDraw = null;
  47770. return;
  47771. }
  47772. if (!this._mapDraw) {
  47773. this._mapDraw = new MapDraw(api);
  47774. }
  47775. var mapDraw = this._mapDraw;
  47776. mapDraw.draw(geoModel, ecModel, api, this, payload);
  47777. mapDraw.group.on('click', this._handleRegionClick, this);
  47778. mapDraw.group.silent = geoModel.get('silent');
  47779. this.group.add(mapDraw.group);
  47780. this.updateSelectStatus(geoModel, ecModel, api);
  47781. };
  47782. GeoView.prototype._handleRegionClick = function (e) {
  47783. var eventData;
  47784. findEventDispatcher(e.target, function (current) {
  47785. return (eventData = getECData(current).eventData) != null;
  47786. }, true);
  47787. if (eventData) {
  47788. this._api.dispatchAction({
  47789. type: 'geoToggleSelect',
  47790. geoId: this._model.id,
  47791. name: eventData.name
  47792. });
  47793. }
  47794. };
  47795. GeoView.prototype.updateSelectStatus = function (model, ecModel, api) {
  47796. var _this = this;
  47797. this._mapDraw.group.traverse(function (node) {
  47798. var eventData = getECData(node).eventData;
  47799. if (eventData) {
  47800. _this._model.isSelected(eventData.name) ? api.enterSelect(node) : api.leaveSelect(node); // No need to traverse children.
  47801. return true;
  47802. }
  47803. });
  47804. };
  47805. GeoView.prototype.findHighDownDispatchers = function (name) {
  47806. return this._mapDraw && this._mapDraw.findHighDownDispatchers(name, this._model);
  47807. };
  47808. GeoView.prototype.dispose = function () {
  47809. this._mapDraw && this._mapDraw.remove();
  47810. };
  47811. GeoView.type = 'geo';
  47812. return GeoView;
  47813. }(ComponentView);
  47814. function registerMap$1(mapName, geoJson, specialAreas) {
  47815. geoSourceManager.registerMap(mapName, geoJson, specialAreas);
  47816. }
  47817. function install$9(registers) {
  47818. registers.registerCoordinateSystem('geo', geoCreator);
  47819. registers.registerComponentModel(GeoModel);
  47820. registers.registerComponentView(GeoView);
  47821. registers.registerImpl('registerMap', registerMap$1);
  47822. registers.registerImpl('getMap', function (mapName) {
  47823. return geoSourceManager.getMapForUser(mapName);
  47824. });
  47825. function makeAction(method, actionInfo) {
  47826. actionInfo.update = 'geo:updateSelectStatus';
  47827. registers.registerAction(actionInfo, function (payload, ecModel) {
  47828. var selected = {};
  47829. var allSelected = [];
  47830. ecModel.eachComponent({
  47831. mainType: 'geo',
  47832. query: payload
  47833. }, function (geoModel) {
  47834. geoModel[method](payload.name);
  47835. var geo = geoModel.coordinateSystem;
  47836. each(geo.regions, function (region) {
  47837. selected[region.name] = geoModel.isSelected(region.name) || false;
  47838. }); // Notice: there might be duplicated name in different regions.
  47839. var names = [];
  47840. each(selected, function (v, name) {
  47841. selected[name] && names.push(name);
  47842. });
  47843. allSelected.push({
  47844. geoIndex: geoModel.componentIndex,
  47845. // Use singular, the same naming convention as the event `selectchanged`.
  47846. name: names
  47847. });
  47848. });
  47849. return {
  47850. selected: selected,
  47851. allSelected: allSelected,
  47852. name: payload.name
  47853. };
  47854. });
  47855. }
  47856. makeAction('toggleSelected', {
  47857. type: 'geoToggleSelect',
  47858. event: 'geoselectchanged'
  47859. });
  47860. makeAction('select', {
  47861. type: 'geoSelect',
  47862. event: 'geoselected'
  47863. });
  47864. makeAction('unSelect', {
  47865. type: 'geoUnSelect',
  47866. event: 'geounselected'
  47867. });
  47868. /**
  47869. * @payload
  47870. * @property {string} [componentType=series]
  47871. * @property {number} [dx]
  47872. * @property {number} [dy]
  47873. * @property {number} [zoom]
  47874. * @property {number} [originX]
  47875. * @property {number} [originY]
  47876. */
  47877. registers.registerAction({
  47878. type: 'geoRoam',
  47879. event: 'geoRoam',
  47880. update: 'updateTransform'
  47881. }, function (payload, ecModel, api) {
  47882. var componentType = payload.componentType || 'series';
  47883. ecModel.eachComponent({
  47884. mainType: componentType,
  47885. query: payload
  47886. }, function (componentModel) {
  47887. var geo = componentModel.coordinateSystem;
  47888. if (geo.type !== 'geo') {
  47889. return;
  47890. }
  47891. var res = updateCenterAndZoom(geo, payload, componentModel.get('scaleLimit'), api);
  47892. componentModel.setCenter && componentModel.setCenter(res.center);
  47893. componentModel.setZoom && componentModel.setZoom(res.zoom); // All map series with same `map` use the same geo coordinate system
  47894. // So the center and zoom must be in sync. Include the series not selected by legend
  47895. if (componentType === 'series') {
  47896. each(componentModel.seriesGroup, function (seriesModel) {
  47897. seriesModel.setCenter(res.center);
  47898. seriesModel.setZoom(res.zoom);
  47899. });
  47900. }
  47901. });
  47902. });
  47903. }
  47904. function install$a(registers) {
  47905. use(install$9);
  47906. registers.registerChartView(MapView);
  47907. registers.registerSeriesModel(MapSeries);
  47908. registers.registerLayout(mapSymbolLayout);
  47909. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  47910. createLegacyDataSelectAction('map', registers.registerAction);
  47911. }
  47912. /**
  47913. * Initialize all computational message for following algorithm.
  47914. */
  47915. function init$2(inRoot) {
  47916. var root = inRoot;
  47917. root.hierNode = {
  47918. defaultAncestor: null,
  47919. ancestor: root,
  47920. prelim: 0,
  47921. modifier: 0,
  47922. change: 0,
  47923. shift: 0,
  47924. i: 0,
  47925. thread: null
  47926. };
  47927. var nodes = [root];
  47928. var node;
  47929. var children;
  47930. while (node = nodes.pop()) {
  47931. // jshint ignore:line
  47932. children = node.children;
  47933. if (node.isExpand && children.length) {
  47934. var n = children.length;
  47935. for (var i = n - 1; i >= 0; i--) {
  47936. var child = children[i];
  47937. child.hierNode = {
  47938. defaultAncestor: null,
  47939. ancestor: child,
  47940. prelim: 0,
  47941. modifier: 0,
  47942. change: 0,
  47943. shift: 0,
  47944. i: i,
  47945. thread: null
  47946. };
  47947. nodes.push(child);
  47948. }
  47949. }
  47950. }
  47951. }
  47952. /**
  47953. * The implementation of this function was originally copied from "d3.js"
  47954. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  47955. * with some modifications made for this program.
  47956. * See the license statement at the head of this file.
  47957. *
  47958. * Computes a preliminary x coordinate for node. Before that, this function is
  47959. * applied recursively to the children of node, as well as the function
  47960. * apportion(). After spacing out the children by calling executeShifts(), the
  47961. * node is placed to the midpoint of its outermost children.
  47962. */
  47963. function firstWalk(node, separation) {
  47964. var children = node.isExpand ? node.children : [];
  47965. var siblings = node.parentNode.children;
  47966. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  47967. if (children.length) {
  47968. executeShifts(node);
  47969. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  47970. if (subtreeW) {
  47971. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  47972. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  47973. } else {
  47974. node.hierNode.prelim = midPoint;
  47975. }
  47976. } else if (subtreeW) {
  47977. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  47978. }
  47979. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  47980. }
  47981. /**
  47982. * The implementation of this function was originally copied from "d3.js"
  47983. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  47984. * with some modifications made for this program.
  47985. * See the license statement at the head of this file.
  47986. *
  47987. * Computes all real x-coordinates by summing up the modifiers recursively.
  47988. */
  47989. function secondWalk(node) {
  47990. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  47991. node.setLayout({
  47992. x: nodeX
  47993. }, true);
  47994. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  47995. }
  47996. function separation(cb) {
  47997. return arguments.length ? cb : defaultSeparation;
  47998. }
  47999. /**
  48000. * Transform the common coordinate to radial coordinate.
  48001. */
  48002. function radialCoordinate(rad, r) {
  48003. rad -= Math.PI / 2;
  48004. return {
  48005. x: r * Math.cos(rad),
  48006. y: r * Math.sin(rad)
  48007. };
  48008. }
  48009. /**
  48010. * Get the layout position of the whole view.
  48011. */
  48012. function getViewRect$1(seriesModel, api) {
  48013. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  48014. width: api.getWidth(),
  48015. height: api.getHeight()
  48016. });
  48017. }
  48018. /**
  48019. * All other shifts, applied to the smaller subtrees between w- and w+, are
  48020. * performed by this function.
  48021. *
  48022. * The implementation of this function was originally copied from "d3.js"
  48023. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48024. * with some modifications made for this program.
  48025. * See the license statement at the head of this file.
  48026. */
  48027. function executeShifts(node) {
  48028. var children = node.children;
  48029. var n = children.length;
  48030. var shift = 0;
  48031. var change = 0;
  48032. while (--n >= 0) {
  48033. var child = children[n];
  48034. child.hierNode.prelim += shift;
  48035. child.hierNode.modifier += shift;
  48036. change += child.hierNode.change;
  48037. shift += child.hierNode.shift + change;
  48038. }
  48039. }
  48040. /**
  48041. * The implementation of this function was originally copied from "d3.js"
  48042. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48043. * with some modifications made for this program.
  48044. * See the license statement at the head of this file.
  48045. *
  48046. * The core of the algorithm. Here, a new subtree is combined with the
  48047. * previous subtrees. Threads are used to traverse the inside and outside
  48048. * contours of the left and right subtree up to the highest common level.
  48049. * Whenever two nodes of the inside contours conflict, we compute the left
  48050. * one of the greatest uncommon ancestors using the function nextAncestor()
  48051. * and call moveSubtree() to shift the subtree and prepare the shifts of
  48052. * smaller subtrees. Finally, we add a new thread (if necessary).
  48053. */
  48054. function apportion(subtreeV, subtreeW, ancestor, separation) {
  48055. if (subtreeW) {
  48056. var nodeOutRight = subtreeV;
  48057. var nodeInRight = subtreeV;
  48058. var nodeOutLeft = nodeInRight.parentNode.children[0];
  48059. var nodeInLeft = subtreeW;
  48060. var sumOutRight = nodeOutRight.hierNode.modifier;
  48061. var sumInRight = nodeInRight.hierNode.modifier;
  48062. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  48063. var sumInLeft = nodeInLeft.hierNode.modifier;
  48064. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  48065. nodeOutRight = nextRight(nodeOutRight);
  48066. nodeOutLeft = nextLeft(nodeOutLeft);
  48067. nodeOutRight.hierNode.ancestor = subtreeV;
  48068. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim - sumInRight + separation(nodeInLeft, nodeInRight);
  48069. if (shift > 0) {
  48070. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  48071. sumInRight += shift;
  48072. sumOutRight += shift;
  48073. }
  48074. sumInLeft += nodeInLeft.hierNode.modifier;
  48075. sumInRight += nodeInRight.hierNode.modifier;
  48076. sumOutRight += nodeOutRight.hierNode.modifier;
  48077. sumOutLeft += nodeOutLeft.hierNode.modifier;
  48078. }
  48079. if (nodeInLeft && !nextRight(nodeOutRight)) {
  48080. nodeOutRight.hierNode.thread = nodeInLeft;
  48081. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  48082. }
  48083. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  48084. nodeOutLeft.hierNode.thread = nodeInRight;
  48085. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  48086. ancestor = subtreeV;
  48087. }
  48088. }
  48089. return ancestor;
  48090. }
  48091. /**
  48092. * This function is used to traverse the right contour of a subtree.
  48093. * It returns the rightmost child of node or the thread of node. The function
  48094. * returns null if and only if node is on the highest depth of its subtree.
  48095. */
  48096. function nextRight(node) {
  48097. var children = node.children;
  48098. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  48099. }
  48100. /**
  48101. * This function is used to traverse the left contour of a subtree (or a subforest).
  48102. * It returns the leftmost child of node or the thread of node. The function
  48103. * returns null if and only if node is on the highest depth of its subtree.
  48104. */
  48105. function nextLeft(node) {
  48106. var children = node.children;
  48107. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  48108. }
  48109. /**
  48110. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  48111. * Otherwise, returns the specified ancestor.
  48112. */
  48113. function nextAncestor(nodeInLeft, node, ancestor) {
  48114. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode ? nodeInLeft.hierNode.ancestor : ancestor;
  48115. }
  48116. /**
  48117. * The implementation of this function was originally copied from "d3.js"
  48118. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48119. * with some modifications made for this program.
  48120. * See the license statement at the head of this file.
  48121. *
  48122. * Shifts the current subtree rooted at wr.
  48123. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  48124. */
  48125. function moveSubtree(wl, wr, shift) {
  48126. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  48127. wr.hierNode.change -= change;
  48128. wr.hierNode.shift += shift;
  48129. wr.hierNode.modifier += shift;
  48130. wr.hierNode.prelim += shift;
  48131. wl.hierNode.change += change;
  48132. }
  48133. /**
  48134. * The implementation of this function was originally copied from "d3.js"
  48135. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48136. * with some modifications made for this program.
  48137. * See the license statement at the head of this file.
  48138. */
  48139. function defaultSeparation(node1, node2) {
  48140. return node1.parentNode === node2.parentNode ? 1 : 2;
  48141. }
  48142. var TreeEdgeShape =
  48143. /** @class */
  48144. function () {
  48145. function TreeEdgeShape() {
  48146. this.parentPoint = [];
  48147. this.childPoints = [];
  48148. }
  48149. return TreeEdgeShape;
  48150. }();
  48151. var TreePath =
  48152. /** @class */
  48153. function (_super) {
  48154. __extends(TreePath, _super);
  48155. function TreePath(opts) {
  48156. return _super.call(this, opts) || this;
  48157. }
  48158. TreePath.prototype.getDefaultStyle = function () {
  48159. return {
  48160. stroke: '#000',
  48161. fill: null
  48162. };
  48163. };
  48164. TreePath.prototype.getDefaultShape = function () {
  48165. return new TreeEdgeShape();
  48166. };
  48167. TreePath.prototype.buildPath = function (ctx, shape) {
  48168. var childPoints = shape.childPoints;
  48169. var childLen = childPoints.length;
  48170. var parentPoint = shape.parentPoint;
  48171. var firstChildPos = childPoints[0];
  48172. var lastChildPos = childPoints[childLen - 1];
  48173. if (childLen === 1) {
  48174. ctx.moveTo(parentPoint[0], parentPoint[1]);
  48175. ctx.lineTo(firstChildPos[0], firstChildPos[1]);
  48176. return;
  48177. }
  48178. var orient = shape.orient;
  48179. var forkDim = orient === 'TB' || orient === 'BT' ? 0 : 1;
  48180. var otherDim = 1 - forkDim;
  48181. var forkPosition = parsePercent$1(shape.forkPosition, 1);
  48182. var tmpPoint = [];
  48183. tmpPoint[forkDim] = parentPoint[forkDim];
  48184. tmpPoint[otherDim] = parentPoint[otherDim] + (lastChildPos[otherDim] - parentPoint[otherDim]) * forkPosition;
  48185. ctx.moveTo(parentPoint[0], parentPoint[1]);
  48186. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48187. ctx.moveTo(firstChildPos[0], firstChildPos[1]);
  48188. tmpPoint[forkDim] = firstChildPos[forkDim];
  48189. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48190. tmpPoint[forkDim] = lastChildPos[forkDim];
  48191. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48192. ctx.lineTo(lastChildPos[0], lastChildPos[1]);
  48193. for (var i = 1; i < childLen - 1; i++) {
  48194. var point = childPoints[i];
  48195. ctx.moveTo(point[0], point[1]);
  48196. tmpPoint[forkDim] = point[forkDim];
  48197. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48198. }
  48199. };
  48200. return TreePath;
  48201. }(Path);
  48202. var TreeView =
  48203. /** @class */
  48204. function (_super) {
  48205. __extends(TreeView, _super);
  48206. function TreeView() {
  48207. var _this = _super !== null && _super.apply(this, arguments) || this;
  48208. _this.type = TreeView.type;
  48209. _this._mainGroup = new Group();
  48210. return _this;
  48211. }
  48212. TreeView.prototype.init = function (ecModel, api) {
  48213. this._controller = new RoamController(api.getZr());
  48214. this._controllerHost = {
  48215. target: this.group
  48216. };
  48217. this.group.add(this._mainGroup);
  48218. };
  48219. TreeView.prototype.render = function (seriesModel, ecModel, api) {
  48220. var data = seriesModel.getData();
  48221. var layoutInfo = seriesModel.layoutInfo;
  48222. var group = this._mainGroup;
  48223. var layout = seriesModel.get('layout');
  48224. if (layout === 'radial') {
  48225. group.x = layoutInfo.x + layoutInfo.width / 2;
  48226. group.y = layoutInfo.y + layoutInfo.height / 2;
  48227. } else {
  48228. group.x = layoutInfo.x;
  48229. group.y = layoutInfo.y;
  48230. }
  48231. this._updateViewCoordSys(seriesModel, api);
  48232. this._updateController(seriesModel, ecModel, api);
  48233. var oldData = this._data;
  48234. data.diff(oldData).add(function (newIdx) {
  48235. if (symbolNeedsDraw$1(data, newIdx)) {
  48236. // Create node and edge
  48237. updateNode(data, newIdx, null, group, seriesModel);
  48238. }
  48239. }).update(function (newIdx, oldIdx) {
  48240. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  48241. if (!symbolNeedsDraw$1(data, newIdx)) {
  48242. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  48243. return;
  48244. } // Update node and edge
  48245. updateNode(data, newIdx, symbolEl, group, seriesModel);
  48246. }).remove(function (oldIdx) {
  48247. var symbolEl = oldData.getItemGraphicEl(oldIdx); // When remove a collapsed node of subtree, since the collapsed
  48248. // node haven't been initialized with a symbol element,
  48249. // you can't found it's symbol element through index.
  48250. // so if we want to remove the symbol element we should insure
  48251. // that the symbol element is not null.
  48252. if (symbolEl) {
  48253. removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  48254. }
  48255. }).execute();
  48256. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  48257. this._updateNodeAndLinkScale(seriesModel);
  48258. if (seriesModel.get('expandAndCollapse') === true) {
  48259. data.eachItemGraphicEl(function (el, dataIndex) {
  48260. el.off('click').on('click', function () {
  48261. api.dispatchAction({
  48262. type: 'treeExpandAndCollapse',
  48263. seriesId: seriesModel.id,
  48264. dataIndex: dataIndex
  48265. });
  48266. });
  48267. });
  48268. }
  48269. this._data = data;
  48270. };
  48271. TreeView.prototype._updateViewCoordSys = function (seriesModel, api) {
  48272. var data = seriesModel.getData();
  48273. var points = [];
  48274. data.each(function (idx) {
  48275. var layout = data.getItemLayout(idx);
  48276. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  48277. points.push([+layout.x, +layout.y]);
  48278. }
  48279. });
  48280. var min = [];
  48281. var max = [];
  48282. fromPoints(points, min, max); // If don't Store min max when collapse the root node after roam,
  48283. // the root node will disappear.
  48284. var oldMin = this._min;
  48285. var oldMax = this._max; // If width or height is 0
  48286. if (max[0] - min[0] === 0) {
  48287. min[0] = oldMin ? oldMin[0] : min[0] - 1;
  48288. max[0] = oldMax ? oldMax[0] : max[0] + 1;
  48289. }
  48290. if (max[1] - min[1] === 0) {
  48291. min[1] = oldMin ? oldMin[1] : min[1] - 1;
  48292. max[1] = oldMax ? oldMax[1] : max[1] + 1;
  48293. }
  48294. var viewCoordSys = seriesModel.coordinateSystem = new View();
  48295. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  48296. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  48297. viewCoordSys.setCenter(seriesModel.get('center'), api);
  48298. viewCoordSys.setZoom(seriesModel.get('zoom')); // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  48299. this.group.attr({
  48300. x: viewCoordSys.x,
  48301. y: viewCoordSys.y,
  48302. scaleX: viewCoordSys.scaleX,
  48303. scaleY: viewCoordSys.scaleY
  48304. });
  48305. this._min = min;
  48306. this._max = max;
  48307. };
  48308. TreeView.prototype._updateController = function (seriesModel, ecModel, api) {
  48309. var _this = this;
  48310. var controller = this._controller;
  48311. var controllerHost = this._controllerHost;
  48312. var group = this.group;
  48313. controller.setPointerChecker(function (e, x, y) {
  48314. var rect = group.getBoundingRect();
  48315. rect.applyTransform(group.transform);
  48316. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  48317. });
  48318. controller.enable(seriesModel.get('roam'));
  48319. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  48320. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  48321. controller.off('pan').off('zoom').on('pan', function (e) {
  48322. updateViewOnPan(controllerHost, e.dx, e.dy);
  48323. api.dispatchAction({
  48324. seriesId: seriesModel.id,
  48325. type: 'treeRoam',
  48326. dx: e.dx,
  48327. dy: e.dy
  48328. });
  48329. }).on('zoom', function (e) {
  48330. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  48331. api.dispatchAction({
  48332. seriesId: seriesModel.id,
  48333. type: 'treeRoam',
  48334. zoom: e.scale,
  48335. originX: e.originX,
  48336. originY: e.originY
  48337. });
  48338. _this._updateNodeAndLinkScale(seriesModel); // Only update label layout on zoom
  48339. api.updateLabelLayout();
  48340. });
  48341. };
  48342. TreeView.prototype._updateNodeAndLinkScale = function (seriesModel) {
  48343. var data = seriesModel.getData();
  48344. var nodeScale = this._getNodeGlobalScale(seriesModel);
  48345. data.eachItemGraphicEl(function (el, idx) {
  48346. el.setSymbolScale(nodeScale);
  48347. });
  48348. };
  48349. TreeView.prototype._getNodeGlobalScale = function (seriesModel) {
  48350. var coordSys = seriesModel.coordinateSystem;
  48351. if (coordSys.type !== 'view') {
  48352. return 1;
  48353. }
  48354. var nodeScaleRatio = this._nodeScaleRatio;
  48355. var groupZoom = coordSys.scaleX || 1; // Scale node when zoom changes
  48356. var roamZoom = coordSys.getZoom();
  48357. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  48358. return nodeScale / groupZoom;
  48359. };
  48360. TreeView.prototype.dispose = function () {
  48361. this._controller && this._controller.dispose();
  48362. this._controllerHost = null;
  48363. };
  48364. TreeView.prototype.remove = function () {
  48365. this._mainGroup.removeAll();
  48366. this._data = null;
  48367. };
  48368. TreeView.type = 'tree';
  48369. return TreeView;
  48370. }(ChartView);
  48371. function symbolNeedsDraw$1(data, dataIndex) {
  48372. var layout = data.getItemLayout(dataIndex);
  48373. return layout && !isNaN(layout.x) && !isNaN(layout.y);
  48374. }
  48375. function updateNode(data, dataIndex, symbolEl, group, seriesModel) {
  48376. var isInit = !symbolEl;
  48377. var node = data.tree.getNodeByDataIndex(dataIndex);
  48378. var itemModel = node.getModel();
  48379. var visualColor = node.getVisual('style').fill;
  48380. var symbolInnerColor = node.isExpand === false && node.children.length !== 0 ? visualColor : '#fff';
  48381. var virtualRoot = data.tree.root;
  48382. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  48383. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  48384. var sourceLayout = source.getLayout();
  48385. var sourceOldLayout = sourceSymbolEl ? {
  48386. x: sourceSymbolEl.__oldX,
  48387. y: sourceSymbolEl.__oldY,
  48388. rawX: sourceSymbolEl.__radialOldRawX,
  48389. rawY: sourceSymbolEl.__radialOldRawY
  48390. } : sourceLayout;
  48391. var targetLayout = node.getLayout();
  48392. if (isInit) {
  48393. symbolEl = new Symbol(data, dataIndex, null, {
  48394. symbolInnerColor: symbolInnerColor,
  48395. useNameLabel: true
  48396. });
  48397. symbolEl.x = sourceOldLayout.x;
  48398. symbolEl.y = sourceOldLayout.y;
  48399. } else {
  48400. symbolEl.updateData(data, dataIndex, null, {
  48401. symbolInnerColor: symbolInnerColor,
  48402. useNameLabel: true
  48403. });
  48404. }
  48405. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  48406. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  48407. symbolEl.__radialRawX = targetLayout.rawX;
  48408. symbolEl.__radialRawY = targetLayout.rawY;
  48409. group.add(symbolEl);
  48410. data.setItemGraphicEl(dataIndex, symbolEl);
  48411. symbolEl.__oldX = symbolEl.x;
  48412. symbolEl.__oldY = symbolEl.y;
  48413. updateProps(symbolEl, {
  48414. x: targetLayout.x,
  48415. y: targetLayout.y
  48416. }, seriesModel);
  48417. var symbolPath = symbolEl.getSymbolPath();
  48418. if (seriesModel.get('layout') === 'radial') {
  48419. var realRoot = virtualRoot.children[0];
  48420. var rootLayout = realRoot.getLayout();
  48421. var length_1 = realRoot.children.length;
  48422. var rad = void 0;
  48423. var isLeft = void 0;
  48424. if (targetLayout.x === rootLayout.x && node.isExpand === true && realRoot.children.length) {
  48425. var center = {
  48426. x: (realRoot.children[0].getLayout().x + realRoot.children[length_1 - 1].getLayout().x) / 2,
  48427. y: (realRoot.children[0].getLayout().y + realRoot.children[length_1 - 1].getLayout().y) / 2
  48428. };
  48429. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  48430. if (rad < 0) {
  48431. rad = Math.PI * 2 + rad;
  48432. }
  48433. isLeft = center.x < rootLayout.x;
  48434. if (isLeft) {
  48435. rad = rad - Math.PI;
  48436. }
  48437. } else {
  48438. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  48439. if (rad < 0) {
  48440. rad = Math.PI * 2 + rad;
  48441. }
  48442. if (node.children.length === 0 || node.children.length !== 0 && node.isExpand === false) {
  48443. isLeft = targetLayout.x < rootLayout.x;
  48444. if (isLeft) {
  48445. rad = rad - Math.PI;
  48446. }
  48447. } else {
  48448. isLeft = targetLayout.x > rootLayout.x;
  48449. if (!isLeft) {
  48450. rad = rad - Math.PI;
  48451. }
  48452. }
  48453. }
  48454. var textPosition = isLeft ? 'left' : 'right';
  48455. var normalLabelModel = itemModel.getModel('label');
  48456. var rotate = normalLabelModel.get('rotate');
  48457. var labelRotateRadian = rotate * (Math.PI / 180);
  48458. var textContent = symbolPath.getTextContent();
  48459. if (textContent) {
  48460. symbolPath.setTextConfig({
  48461. position: normalLabelModel.get('position') || textPosition,
  48462. rotation: rotate == null ? -rad : labelRotateRadian,
  48463. origin: 'center'
  48464. });
  48465. textContent.setStyle('verticalAlign', 'middle');
  48466. }
  48467. } // Handle status
  48468. var focus = itemModel.get(['emphasis', 'focus']);
  48469. var focusDataIndices = focus === 'relative' ? concatArray(node.getAncestorsIndices(), node.getDescendantIndices()) : focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : null;
  48470. if (focusDataIndices) {
  48471. // Modify the focus to data indices.
  48472. getECData(symbolEl).focus = focusDataIndices;
  48473. }
  48474. drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group);
  48475. if (symbolEl.__edge) {
  48476. symbolEl.onHoverStateChange = function (toState) {
  48477. if (toState !== 'blur') {
  48478. // NOTE: Ensure the parent elements will been blurred firstly.
  48479. // According to the return of getAncestorsIndices and getDescendantIndices
  48480. // TODO: A bit tricky.
  48481. var parentEl = node.parentNode && data.getItemGraphicEl(node.parentNode.dataIndex);
  48482. if (!(parentEl && parentEl.hoverState === HOVER_STATE_BLUR)) {
  48483. setStatesFlag(symbolEl.__edge, toState);
  48484. }
  48485. }
  48486. };
  48487. }
  48488. }
  48489. function drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group) {
  48490. var itemModel = node.getModel();
  48491. var edgeShape = seriesModel.get('edgeShape');
  48492. var layout = seriesModel.get('layout');
  48493. var orient = seriesModel.getOrient();
  48494. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  48495. var edgeForkPosition = seriesModel.get('edgeForkPosition');
  48496. var lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  48497. var edge = symbolEl.__edge; // curve edge from node -> parent
  48498. // polyline edge from node -> children
  48499. if (edgeShape === 'curve') {
  48500. if (node.parentNode && node.parentNode !== virtualRoot) {
  48501. if (!edge) {
  48502. edge = symbolEl.__edge = new BezierCurve({
  48503. shape: getEdgeShape(layout, orient, curvature, sourceOldLayout, sourceOldLayout)
  48504. });
  48505. }
  48506. updateProps(edge, {
  48507. shape: getEdgeShape(layout, orient, curvature, sourceLayout, targetLayout)
  48508. }, seriesModel);
  48509. }
  48510. } else if (edgeShape === 'polyline') {
  48511. if (layout === 'orthogonal') {
  48512. if (node !== virtualRoot && node.children && node.children.length !== 0 && node.isExpand === true) {
  48513. var children = node.children;
  48514. var childPoints = [];
  48515. for (var i = 0; i < children.length; i++) {
  48516. var childLayout = children[i].getLayout();
  48517. childPoints.push([childLayout.x, childLayout.y]);
  48518. }
  48519. if (!edge) {
  48520. edge = symbolEl.__edge = new TreePath({
  48521. shape: {
  48522. parentPoint: [targetLayout.x, targetLayout.y],
  48523. childPoints: [[targetLayout.x, targetLayout.y]],
  48524. orient: orient,
  48525. forkPosition: edgeForkPosition
  48526. }
  48527. });
  48528. }
  48529. updateProps(edge, {
  48530. shape: {
  48531. parentPoint: [targetLayout.x, targetLayout.y],
  48532. childPoints: childPoints
  48533. }
  48534. }, seriesModel);
  48535. }
  48536. } else {
  48537. if ("development" !== 'production') {
  48538. throw new Error('The polyline edgeShape can only be used in orthogonal layout');
  48539. }
  48540. }
  48541. } // show all edge when edgeShape is 'curve', filter node `isExpand` is false when edgeShape is 'polyline'
  48542. if (edge && !(edgeShape === 'polyline' && !node.isExpand)) {
  48543. edge.useStyle(defaults({
  48544. strokeNoScale: true,
  48545. fill: null
  48546. }, lineStyle));
  48547. setStatesStylesFromModel(edge, itemModel, 'lineStyle');
  48548. setDefaultStateProxy(edge);
  48549. group.add(edge);
  48550. }
  48551. }
  48552. function removeNodeEdge(node, data, group, seriesModel, removeAnimationOpt) {
  48553. var virtualRoot = data.tree.root;
  48554. var _a = getSourceNode(virtualRoot, node),
  48555. source = _a.source,
  48556. sourceLayout = _a.sourceLayout;
  48557. var symbolEl = data.getItemGraphicEl(node.dataIndex);
  48558. if (!symbolEl) {
  48559. return;
  48560. }
  48561. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  48562. var sourceEdge = sourceSymbolEl.__edge; // 1. when expand the sub tree, delete the children node should delete the edge of
  48563. // the source at the same time. because the polyline edge shape is only owned by the source.
  48564. // 2.when the node is the only children of the source, delete the node should delete the edge of
  48565. // the source at the same time. the same reason as above.
  48566. var edge = symbolEl.__edge || (source.isExpand === false || source.children.length === 1 ? sourceEdge : undefined);
  48567. var edgeShape = seriesModel.get('edgeShape');
  48568. var layoutOpt = seriesModel.get('layout');
  48569. var orient = seriesModel.get('orient');
  48570. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  48571. if (edge) {
  48572. if (edgeShape === 'curve') {
  48573. removeElement(edge, {
  48574. shape: getEdgeShape(layoutOpt, orient, curvature, sourceLayout, sourceLayout),
  48575. style: {
  48576. opacity: 0
  48577. }
  48578. }, seriesModel, {
  48579. cb: function () {
  48580. group.remove(edge);
  48581. },
  48582. removeOpt: removeAnimationOpt
  48583. });
  48584. } else if (edgeShape === 'polyline' && seriesModel.get('layout') === 'orthogonal') {
  48585. removeElement(edge, {
  48586. shape: {
  48587. parentPoint: [sourceLayout.x, sourceLayout.y],
  48588. childPoints: [[sourceLayout.x, sourceLayout.y]]
  48589. },
  48590. style: {
  48591. opacity: 0
  48592. }
  48593. }, seriesModel, {
  48594. cb: function () {
  48595. group.remove(edge);
  48596. },
  48597. removeOpt: removeAnimationOpt
  48598. });
  48599. }
  48600. }
  48601. }
  48602. function getSourceNode(virtualRoot, node) {
  48603. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  48604. var sourceLayout;
  48605. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  48606. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  48607. }
  48608. return {
  48609. source: source,
  48610. sourceLayout: sourceLayout
  48611. };
  48612. }
  48613. function removeNode(data, dataIndex, symbolEl, group, seriesModel) {
  48614. var node = data.tree.getNodeByDataIndex(dataIndex);
  48615. var virtualRoot = data.tree.root;
  48616. var sourceLayout = getSourceNode(virtualRoot, node).sourceLayout; // Use same duration and easing with update to have more consistent animation.
  48617. var removeAnimationOpt = {
  48618. duration: seriesModel.get('animationDurationUpdate'),
  48619. easing: seriesModel.get('animationEasingUpdate')
  48620. };
  48621. removeElement(symbolEl, {
  48622. x: sourceLayout.x + 1,
  48623. y: sourceLayout.y + 1
  48624. }, seriesModel, {
  48625. cb: function () {
  48626. group.remove(symbolEl);
  48627. data.setItemGraphicEl(dataIndex, null);
  48628. },
  48629. removeOpt: removeAnimationOpt
  48630. });
  48631. symbolEl.fadeOut(null, data.hostModel, {
  48632. fadeLabel: true,
  48633. animation: removeAnimationOpt
  48634. }); // remove edge as parent node
  48635. node.children.forEach(function (childNode) {
  48636. removeNodeEdge(childNode, data, group, seriesModel, removeAnimationOpt);
  48637. }); // remove edge as child node
  48638. removeNodeEdge(node, data, group, seriesModel, removeAnimationOpt);
  48639. }
  48640. function getEdgeShape(layoutOpt, orient, curvature, sourceLayout, targetLayout) {
  48641. var cpx1;
  48642. var cpy1;
  48643. var cpx2;
  48644. var cpy2;
  48645. var x1;
  48646. var x2;
  48647. var y1;
  48648. var y2;
  48649. if (layoutOpt === 'radial') {
  48650. x1 = sourceLayout.rawX;
  48651. y1 = sourceLayout.rawY;
  48652. x2 = targetLayout.rawX;
  48653. y2 = targetLayout.rawY;
  48654. var radialCoor1 = radialCoordinate(x1, y1);
  48655. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * curvature);
  48656. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * curvature);
  48657. var radialCoor4 = radialCoordinate(x2, y2);
  48658. return {
  48659. x1: radialCoor1.x || 0,
  48660. y1: radialCoor1.y || 0,
  48661. x2: radialCoor4.x || 0,
  48662. y2: radialCoor4.y || 0,
  48663. cpx1: radialCoor2.x || 0,
  48664. cpy1: radialCoor2.y || 0,
  48665. cpx2: radialCoor3.x || 0,
  48666. cpy2: radialCoor3.y || 0
  48667. };
  48668. } else {
  48669. x1 = sourceLayout.x;
  48670. y1 = sourceLayout.y;
  48671. x2 = targetLayout.x;
  48672. y2 = targetLayout.y;
  48673. if (orient === 'LR' || orient === 'RL') {
  48674. cpx1 = x1 + (x2 - x1) * curvature;
  48675. cpy1 = y1;
  48676. cpx2 = x2 + (x1 - x2) * curvature;
  48677. cpy2 = y2;
  48678. }
  48679. if (orient === 'TB' || orient === 'BT') {
  48680. cpx1 = x1;
  48681. cpy1 = y1 + (y2 - y1) * curvature;
  48682. cpx2 = x2;
  48683. cpy2 = y2 + (y1 - y2) * curvature;
  48684. }
  48685. }
  48686. return {
  48687. x1: x1,
  48688. y1: y1,
  48689. x2: x2,
  48690. y2: y2,
  48691. cpx1: cpx1,
  48692. cpy1: cpy1,
  48693. cpx2: cpx2,
  48694. cpy2: cpy2
  48695. };
  48696. }
  48697. var inner$7 = makeInner();
  48698. function linkSeriesData(opt) {
  48699. var mainData = opt.mainData;
  48700. var datas = opt.datas;
  48701. if (!datas) {
  48702. datas = {
  48703. main: mainData
  48704. };
  48705. opt.datasAttr = {
  48706. main: 'data'
  48707. };
  48708. }
  48709. opt.datas = opt.mainData = null;
  48710. linkAll(mainData, datas, opt); // Porxy data original methods.
  48711. each(datas, function (data) {
  48712. each(mainData.TRANSFERABLE_METHODS, function (methodName) {
  48713. data.wrapMethod(methodName, curry(transferInjection, opt));
  48714. });
  48715. }); // Beyond transfer, additional features should be added to `cloneShallow`.
  48716. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt)); // Only mainData trigger change, because struct.update may trigger
  48717. // another changable methods, which may bring about dead lock.
  48718. each(mainData.CHANGABLE_METHODS, function (methodName) {
  48719. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  48720. }); // Make sure datas contains mainData.
  48721. assert(datas[mainData.dataType] === mainData);
  48722. }
  48723. function transferInjection(opt, res) {
  48724. if (isMainData(this)) {
  48725. // Transfer datas to new main data.
  48726. var datas = extend({}, inner$7(this).datas);
  48727. datas[this.dataType] = res;
  48728. linkAll(res, datas, opt);
  48729. } else {
  48730. // Modify the reference in main data to point newData.
  48731. linkSingle(res, this.dataType, inner$7(this).mainData, opt);
  48732. }
  48733. return res;
  48734. }
  48735. function changeInjection(opt, res) {
  48736. opt.struct && opt.struct.update();
  48737. return res;
  48738. }
  48739. function cloneShallowInjection(opt, res) {
  48740. // cloneShallow, which brings about some fragilities, may be inappropriate
  48741. // to be exposed as an API. So for implementation simplicity we can make
  48742. // the restriction that cloneShallow of not-mainData should not be invoked
  48743. // outside, but only be invoked here.
  48744. each(inner$7(res).datas, function (data, dataType) {
  48745. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  48746. });
  48747. return res;
  48748. }
  48749. /**
  48750. * Supplement method to List.
  48751. *
  48752. * @public
  48753. * @param [dataType] If not specified, return mainData.
  48754. */
  48755. function getLinkedData(dataType) {
  48756. var mainData = inner$7(this).mainData;
  48757. return dataType == null || mainData == null ? mainData : inner$7(mainData).datas[dataType];
  48758. }
  48759. /**
  48760. * Get list of all linked data
  48761. */
  48762. function getLinkedDataAll() {
  48763. var mainData = inner$7(this).mainData;
  48764. return mainData == null ? [{
  48765. data: mainData
  48766. }] : map(keys(inner$7(mainData).datas), function (type) {
  48767. return {
  48768. type: type,
  48769. data: inner$7(mainData).datas[type]
  48770. };
  48771. });
  48772. }
  48773. function isMainData(data) {
  48774. return inner$7(data).mainData === data;
  48775. }
  48776. function linkAll(mainData, datas, opt) {
  48777. inner$7(mainData).datas = {};
  48778. each(datas, function (data, dataType) {
  48779. linkSingle(data, dataType, mainData, opt);
  48780. });
  48781. }
  48782. function linkSingle(data, dataType, mainData, opt) {
  48783. inner$7(mainData).datas[dataType] = data;
  48784. inner$7(data).mainData = mainData;
  48785. data.dataType = dataType;
  48786. if (opt.struct) {
  48787. data[opt.structAttr] = opt.struct;
  48788. opt.struct[opt.datasAttr[dataType]] = data;
  48789. } // Supplement method.
  48790. data.getLinkedData = getLinkedData;
  48791. data.getLinkedDataAll = getLinkedDataAll;
  48792. }
  48793. var TreeNode =
  48794. /** @class */
  48795. function () {
  48796. function TreeNode(name, hostTree) {
  48797. this.depth = 0;
  48798. this.height = 0;
  48799. /**
  48800. * Reference to list item.
  48801. * Do not persistent dataIndex outside,
  48802. * besause it may be changed by list.
  48803. * If dataIndex -1,
  48804. * this node is logical deleted (filtered) in list.
  48805. */
  48806. this.dataIndex = -1;
  48807. this.children = [];
  48808. this.viewChildren = [];
  48809. this.isExpand = false;
  48810. this.name = name || '';
  48811. this.hostTree = hostTree;
  48812. }
  48813. /**
  48814. * The node is removed.
  48815. */
  48816. TreeNode.prototype.isRemoved = function () {
  48817. return this.dataIndex < 0;
  48818. };
  48819. TreeNode.prototype.eachNode = function (options, cb, context) {
  48820. if (isFunction(options)) {
  48821. context = cb;
  48822. cb = options;
  48823. options = null;
  48824. }
  48825. options = options || {};
  48826. if (isString(options)) {
  48827. options = {
  48828. order: options
  48829. };
  48830. }
  48831. var order = options.order || 'preorder';
  48832. var children = this[options.attr || 'children'];
  48833. var suppressVisitSub;
  48834. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  48835. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  48836. children[i].eachNode(options, cb, context);
  48837. }
  48838. order === 'postorder' && cb.call(context, this);
  48839. };
  48840. /**
  48841. * Update depth and height of this subtree.
  48842. */
  48843. TreeNode.prototype.updateDepthAndHeight = function (depth) {
  48844. var height = 0;
  48845. this.depth = depth;
  48846. for (var i = 0; i < this.children.length; i++) {
  48847. var child = this.children[i];
  48848. child.updateDepthAndHeight(depth + 1);
  48849. if (child.height > height) {
  48850. height = child.height;
  48851. }
  48852. }
  48853. this.height = height + 1;
  48854. };
  48855. TreeNode.prototype.getNodeById = function (id) {
  48856. if (this.getId() === id) {
  48857. return this;
  48858. }
  48859. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  48860. var res = children[i].getNodeById(id);
  48861. if (res) {
  48862. return res;
  48863. }
  48864. }
  48865. };
  48866. TreeNode.prototype.contains = function (node) {
  48867. if (node === this) {
  48868. return true;
  48869. }
  48870. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  48871. var res = children[i].contains(node);
  48872. if (res) {
  48873. return res;
  48874. }
  48875. }
  48876. };
  48877. /**
  48878. * @param includeSelf Default false.
  48879. * @return order: [root, child, grandchild, ...]
  48880. */
  48881. TreeNode.prototype.getAncestors = function (includeSelf) {
  48882. var ancestors = [];
  48883. var node = includeSelf ? this : this.parentNode;
  48884. while (node) {
  48885. ancestors.push(node);
  48886. node = node.parentNode;
  48887. }
  48888. ancestors.reverse();
  48889. return ancestors;
  48890. };
  48891. TreeNode.prototype.getAncestorsIndices = function () {
  48892. var indices = [];
  48893. var currNode = this;
  48894. while (currNode) {
  48895. indices.push(currNode.dataIndex);
  48896. currNode = currNode.parentNode;
  48897. }
  48898. indices.reverse();
  48899. return indices;
  48900. };
  48901. TreeNode.prototype.getDescendantIndices = function () {
  48902. var indices = [];
  48903. this.eachNode(function (childNode) {
  48904. indices.push(childNode.dataIndex);
  48905. });
  48906. return indices;
  48907. };
  48908. TreeNode.prototype.getValue = function (dimension) {
  48909. var data = this.hostTree.data;
  48910. return data.getStore().get(data.getDimensionIndex(dimension || 'value'), this.dataIndex);
  48911. };
  48912. TreeNode.prototype.setLayout = function (layout, merge) {
  48913. this.dataIndex >= 0 && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge);
  48914. };
  48915. /**
  48916. * @return {Object} layout
  48917. */
  48918. TreeNode.prototype.getLayout = function () {
  48919. return this.hostTree.data.getItemLayout(this.dataIndex);
  48920. }; // @depcrecated
  48921. // getModel<T = unknown, S extends keyof T = keyof T>(path: S): Model<T[S]>
  48922. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  48923. TreeNode.prototype.getModel = function (path) {
  48924. if (this.dataIndex < 0) {
  48925. return;
  48926. }
  48927. var hostTree = this.hostTree;
  48928. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  48929. return itemModel.getModel(path);
  48930. }; // TODO: TYPE More specific model
  48931. TreeNode.prototype.getLevelModel = function () {
  48932. return (this.hostTree.levelModels || [])[this.depth];
  48933. };
  48934. TreeNode.prototype.setVisual = function (key, value) {
  48935. this.dataIndex >= 0 && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  48936. };
  48937. /**
  48938. * Get item visual
  48939. * FIXME: make return type better
  48940. */
  48941. TreeNode.prototype.getVisual = function (key) {
  48942. return this.hostTree.data.getItemVisual(this.dataIndex, key);
  48943. };
  48944. TreeNode.prototype.getRawIndex = function () {
  48945. return this.hostTree.data.getRawIndex(this.dataIndex);
  48946. };
  48947. TreeNode.prototype.getId = function () {
  48948. return this.hostTree.data.getId(this.dataIndex);
  48949. };
  48950. /**
  48951. * index in parent's children
  48952. */
  48953. TreeNode.prototype.getChildIndex = function () {
  48954. if (this.parentNode) {
  48955. var children = this.parentNode.children;
  48956. for (var i = 0; i < children.length; ++i) {
  48957. if (children[i] === this) {
  48958. return i;
  48959. }
  48960. }
  48961. return -1;
  48962. }
  48963. return -1;
  48964. };
  48965. /**
  48966. * if this is an ancestor of another node
  48967. *
  48968. * @param node another node
  48969. * @return if is ancestor
  48970. */
  48971. TreeNode.prototype.isAncestorOf = function (node) {
  48972. var parent = node.parentNode;
  48973. while (parent) {
  48974. if (parent === this) {
  48975. return true;
  48976. }
  48977. parent = parent.parentNode;
  48978. }
  48979. return false;
  48980. };
  48981. /**
  48982. * if this is an descendant of another node
  48983. *
  48984. * @param node another node
  48985. * @return if is descendant
  48986. */
  48987. TreeNode.prototype.isDescendantOf = function (node) {
  48988. return node !== this && node.isAncestorOf(this);
  48989. };
  48990. return TreeNode;
  48991. }();
  48992. var Tree =
  48993. /** @class */
  48994. function () {
  48995. function Tree(hostModel) {
  48996. this.type = 'tree';
  48997. this._nodes = [];
  48998. this.hostModel = hostModel;
  48999. }
  49000. Tree.prototype.eachNode = function (options, cb, context) {
  49001. this.root.eachNode(options, cb, context);
  49002. };
  49003. Tree.prototype.getNodeByDataIndex = function (dataIndex) {
  49004. var rawIndex = this.data.getRawIndex(dataIndex);
  49005. return this._nodes[rawIndex];
  49006. };
  49007. Tree.prototype.getNodeById = function (name) {
  49008. return this.root.getNodeById(name);
  49009. };
  49010. /**
  49011. * Update item available by list,
  49012. * when list has been performed options like 'filterSelf' or 'map'.
  49013. */
  49014. Tree.prototype.update = function () {
  49015. var data = this.data;
  49016. var nodes = this._nodes;
  49017. for (var i = 0, len = nodes.length; i < len; i++) {
  49018. nodes[i].dataIndex = -1;
  49019. }
  49020. for (var i = 0, len = data.count(); i < len; i++) {
  49021. nodes[data.getRawIndex(i)].dataIndex = i;
  49022. }
  49023. };
  49024. /**
  49025. * Clear all layouts
  49026. */
  49027. Tree.prototype.clearLayouts = function () {
  49028. this.data.clearItemLayouts();
  49029. };
  49030. /**
  49031. * data node format:
  49032. * {
  49033. * name: ...
  49034. * value: ...
  49035. * children: [
  49036. * {
  49037. * name: ...
  49038. * value: ...
  49039. * children: ...
  49040. * },
  49041. * ...
  49042. * ]
  49043. * }
  49044. */
  49045. Tree.createTree = function (dataRoot, hostModel, beforeLink) {
  49046. var tree = new Tree(hostModel);
  49047. var listData = [];
  49048. var dimMax = 1;
  49049. buildHierarchy(dataRoot);
  49050. function buildHierarchy(dataNode, parentNode) {
  49051. var value = dataNode.value;
  49052. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  49053. listData.push(dataNode);
  49054. var node = new TreeNode(convertOptionIdName(dataNode.name, ''), tree);
  49055. parentNode ? addChild(node, parentNode) : tree.root = node;
  49056. tree._nodes.push(node);
  49057. var children = dataNode.children;
  49058. if (children) {
  49059. for (var i = 0; i < children.length; i++) {
  49060. buildHierarchy(children[i], node);
  49061. }
  49062. }
  49063. }
  49064. tree.root.updateDepthAndHeight(0);
  49065. var dimensions = prepareSeriesDataSchema(listData, {
  49066. coordDimensions: ['value'],
  49067. dimensionsCount: dimMax
  49068. }).dimensions;
  49069. var list = new SeriesData(dimensions, hostModel);
  49070. list.initData(listData);
  49071. beforeLink && beforeLink(list);
  49072. linkSeriesData({
  49073. mainData: list,
  49074. struct: tree,
  49075. structAttr: 'tree'
  49076. });
  49077. tree.update();
  49078. return tree;
  49079. };
  49080. return Tree;
  49081. }();
  49082. /**
  49083. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  49084. * so this function is not ready and not necessary to be public.
  49085. */
  49086. function addChild(child, node) {
  49087. var children = node.children;
  49088. if (child.parentNode === node) {
  49089. return;
  49090. }
  49091. children.push(child);
  49092. child.parentNode = node;
  49093. }
  49094. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  49095. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  49096. var root = seriesModel.getData().tree.root;
  49097. var targetNode = payload.targetNode;
  49098. if (isString(targetNode)) {
  49099. targetNode = root.getNodeById(targetNode);
  49100. }
  49101. if (targetNode && root.contains(targetNode)) {
  49102. return {
  49103. node: targetNode
  49104. };
  49105. }
  49106. var targetNodeId = payload.targetNodeId;
  49107. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  49108. return {
  49109. node: targetNode
  49110. };
  49111. }
  49112. }
  49113. } // Not includes the given node at the last item.
  49114. function getPathToRoot(node) {
  49115. var path = [];
  49116. while (node) {
  49117. node = node.parentNode;
  49118. node && path.push(node);
  49119. }
  49120. return path.reverse();
  49121. }
  49122. function aboveViewRoot(viewRoot, node) {
  49123. var viewPath = getPathToRoot(viewRoot);
  49124. return indexOf(viewPath, node) >= 0;
  49125. } // From root to the input node (the input node will be included).
  49126. function wrapTreePathInfo(node, seriesModel) {
  49127. var treePathInfo = [];
  49128. while (node) {
  49129. var nodeDataIndex = node.dataIndex;
  49130. treePathInfo.push({
  49131. name: node.name,
  49132. dataIndex: nodeDataIndex,
  49133. value: seriesModel.getRawValue(nodeDataIndex)
  49134. });
  49135. node = node.parentNode;
  49136. }
  49137. treePathInfo.reverse();
  49138. return treePathInfo;
  49139. }
  49140. var TreeSeriesModel =
  49141. /** @class */
  49142. function (_super) {
  49143. __extends(TreeSeriesModel, _super);
  49144. function TreeSeriesModel() {
  49145. var _this = _super !== null && _super.apply(this, arguments) || this;
  49146. _this.hasSymbolVisual = true; // Do it self.
  49147. _this.ignoreStyleOnData = true;
  49148. return _this;
  49149. }
  49150. /**
  49151. * Init a tree data structure from data in option series
  49152. */
  49153. TreeSeriesModel.prototype.getInitialData = function (option) {
  49154. // create a virtual root
  49155. var root = {
  49156. name: option.name,
  49157. children: option.data
  49158. };
  49159. var leaves = option.leaves || {};
  49160. var leavesModel = new Model(leaves, this, this.ecModel);
  49161. var tree = Tree.createTree(root, this, beforeLink);
  49162. function beforeLink(nodeData) {
  49163. nodeData.wrapMethod('getItemModel', function (model, idx) {
  49164. var node = tree.getNodeByDataIndex(idx);
  49165. if (!(node && node.children.length && node.isExpand)) {
  49166. model.parentModel = leavesModel;
  49167. }
  49168. return model;
  49169. });
  49170. }
  49171. var treeDepth = 0;
  49172. tree.eachNode('preorder', function (node) {
  49173. if (node.depth > treeDepth) {
  49174. treeDepth = node.depth;
  49175. }
  49176. });
  49177. var expandAndCollapse = option.expandAndCollapse;
  49178. var expandTreeDepth = expandAndCollapse && option.initialTreeDepth >= 0 ? option.initialTreeDepth : treeDepth;
  49179. tree.root.eachNode('preorder', function (node) {
  49180. var item = node.hostTree.data.getRawDataItem(node.dataIndex); // Add item.collapsed != null, because users can collapse node original in the series.data.
  49181. node.isExpand = item && item.collapsed != null ? !item.collapsed : node.depth <= expandTreeDepth;
  49182. });
  49183. return tree.data;
  49184. };
  49185. /**
  49186. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  49187. * @returns {string} orient
  49188. */
  49189. TreeSeriesModel.prototype.getOrient = function () {
  49190. var orient = this.get('orient');
  49191. if (orient === 'horizontal') {
  49192. orient = 'LR';
  49193. } else if (orient === 'vertical') {
  49194. orient = 'TB';
  49195. }
  49196. return orient;
  49197. };
  49198. TreeSeriesModel.prototype.setZoom = function (zoom) {
  49199. this.option.zoom = zoom;
  49200. };
  49201. TreeSeriesModel.prototype.setCenter = function (center) {
  49202. this.option.center = center;
  49203. };
  49204. TreeSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  49205. var tree = this.getData().tree;
  49206. var realRoot = tree.root.children[0];
  49207. var node = tree.getNodeByDataIndex(dataIndex);
  49208. var value = node.getValue();
  49209. var name = node.name;
  49210. while (node && node !== realRoot) {
  49211. name = node.parentNode.name + '.' + name;
  49212. node = node.parentNode;
  49213. }
  49214. return createTooltipMarkup('nameValue', {
  49215. name: name,
  49216. value: value,
  49217. noValue: isNaN(value) || value == null
  49218. });
  49219. }; // Add tree path to tooltip param
  49220. TreeSeriesModel.prototype.getDataParams = function (dataIndex) {
  49221. var params = _super.prototype.getDataParams.apply(this, arguments);
  49222. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  49223. params.treeAncestors = wrapTreePathInfo(node, this);
  49224. params.collapsed = !node.isExpand;
  49225. return params;
  49226. };
  49227. TreeSeriesModel.type = 'series.tree'; // can support the position parameters 'left', 'top','right','bottom', 'width',
  49228. // 'height' in the setOption() with 'merge' mode normal.
  49229. TreeSeriesModel.layoutMode = 'box';
  49230. TreeSeriesModel.defaultOption = {
  49231. // zlevel: 0,
  49232. z: 2,
  49233. coordinateSystem: 'view',
  49234. // the position of the whole view
  49235. left: '12%',
  49236. top: '12%',
  49237. right: '12%',
  49238. bottom: '12%',
  49239. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  49240. layout: 'orthogonal',
  49241. // value can be 'polyline'
  49242. edgeShape: 'curve',
  49243. edgeForkPosition: '50%',
  49244. // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  49245. roam: false,
  49246. // Symbol size scale ratio in roam
  49247. nodeScaleRatio: 0.4,
  49248. // Default on center of graph
  49249. center: null,
  49250. zoom: 1,
  49251. orient: 'LR',
  49252. symbol: 'emptyCircle',
  49253. symbolSize: 7,
  49254. expandAndCollapse: true,
  49255. initialTreeDepth: 2,
  49256. lineStyle: {
  49257. color: '#ccc',
  49258. width: 1.5,
  49259. curveness: 0.5
  49260. },
  49261. itemStyle: {
  49262. color: 'lightsteelblue',
  49263. // borderColor: '#c23531',
  49264. borderWidth: 1.5
  49265. },
  49266. label: {
  49267. show: true
  49268. },
  49269. animationEasing: 'linear',
  49270. animationDuration: 700,
  49271. animationDurationUpdate: 500
  49272. };
  49273. return TreeSeriesModel;
  49274. }(SeriesModel);
  49275. /*
  49276. * Licensed to the Apache Software Foundation (ASF) under one
  49277. * or more contributor license agreements. See the NOTICE file
  49278. * distributed with this work for additional information
  49279. * regarding copyright ownership. The ASF licenses this file
  49280. * to you under the Apache License, Version 2.0 (the
  49281. * "License"); you may not use this file except in compliance
  49282. * with the License. You may obtain a copy of the License at
  49283. *
  49284. * http://www.apache.org/licenses/LICENSE-2.0
  49285. *
  49286. * Unless required by applicable law or agreed to in writing,
  49287. * software distributed under the License is distributed on an
  49288. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49289. * KIND, either express or implied. See the License for the
  49290. * specific language governing permissions and limitations
  49291. * under the License.
  49292. */
  49293. /**
  49294. * AUTO-GENERATED FILE. DO NOT MODIFY.
  49295. */
  49296. /*
  49297. * Licensed to the Apache Software Foundation (ASF) under one
  49298. * or more contributor license agreements. See the NOTICE file
  49299. * distributed with this work for additional information
  49300. * regarding copyright ownership. The ASF licenses this file
  49301. * to you under the Apache License, Version 2.0 (the
  49302. * "License"); you may not use this file except in compliance
  49303. * with the License. You may obtain a copy of the License at
  49304. *
  49305. * http://www.apache.org/licenses/LICENSE-2.0
  49306. *
  49307. * Unless required by applicable law or agreed to in writing,
  49308. * software distributed under the License is distributed on an
  49309. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49310. * KIND, either express or implied. See the License for the
  49311. * specific language governing permissions and limitations
  49312. * under the License.
  49313. */
  49314. /**
  49315. * Traverse the tree from bottom to top and do something
  49316. */
  49317. function eachAfter(root, callback, separation) {
  49318. var nodes = [root];
  49319. var next = [];
  49320. var node;
  49321. while (node = nodes.pop()) {
  49322. // jshint ignore:line
  49323. next.push(node);
  49324. if (node.isExpand) {
  49325. var children = node.children;
  49326. if (children.length) {
  49327. for (var i = 0; i < children.length; i++) {
  49328. nodes.push(children[i]);
  49329. }
  49330. }
  49331. }
  49332. }
  49333. while (node = next.pop()) {
  49334. // jshint ignore:line
  49335. callback(node, separation);
  49336. }
  49337. }
  49338. /**
  49339. * Traverse the tree from top to bottom and do something
  49340. */
  49341. function eachBefore(root, callback) {
  49342. var nodes = [root];
  49343. var node;
  49344. while (node = nodes.pop()) {
  49345. // jshint ignore:line
  49346. callback(node);
  49347. if (node.isExpand) {
  49348. var children = node.children;
  49349. if (children.length) {
  49350. for (var i = children.length - 1; i >= 0; i--) {
  49351. nodes.push(children[i]);
  49352. }
  49353. }
  49354. }
  49355. }
  49356. }
  49357. function treeLayout(ecModel, api) {
  49358. ecModel.eachSeriesByType('tree', function (seriesModel) {
  49359. commonLayout(seriesModel, api);
  49360. });
  49361. }
  49362. function commonLayout(seriesModel, api) {
  49363. var layoutInfo = getViewRect$1(seriesModel, api);
  49364. seriesModel.layoutInfo = layoutInfo;
  49365. var layout = seriesModel.get('layout');
  49366. var width = 0;
  49367. var height = 0;
  49368. var separation$1 = null;
  49369. if (layout === 'radial') {
  49370. width = 2 * Math.PI;
  49371. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  49372. separation$1 = separation(function (node1, node2) {
  49373. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  49374. });
  49375. } else {
  49376. width = layoutInfo.width;
  49377. height = layoutInfo.height;
  49378. separation$1 = separation();
  49379. }
  49380. var virtualRoot = seriesModel.getData().tree.root;
  49381. var realRoot = virtualRoot.children[0];
  49382. if (realRoot) {
  49383. init$2(virtualRoot);
  49384. eachAfter(realRoot, firstWalk, separation$1);
  49385. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  49386. eachBefore(realRoot, secondWalk);
  49387. var left_1 = realRoot;
  49388. var right_1 = realRoot;
  49389. var bottom_1 = realRoot;
  49390. eachBefore(realRoot, function (node) {
  49391. var x = node.getLayout().x;
  49392. if (x < left_1.getLayout().x) {
  49393. left_1 = node;
  49394. }
  49395. if (x > right_1.getLayout().x) {
  49396. right_1 = node;
  49397. }
  49398. if (node.depth > bottom_1.depth) {
  49399. bottom_1 = node;
  49400. }
  49401. });
  49402. var delta = left_1 === right_1 ? 1 : separation$1(left_1, right_1) / 2;
  49403. var tx_1 = delta - left_1.getLayout().x;
  49404. var kx_1 = 0;
  49405. var ky_1 = 0;
  49406. var coorX_1 = 0;
  49407. var coorY_1 = 0;
  49408. if (layout === 'radial') {
  49409. kx_1 = width / (right_1.getLayout().x + delta + tx_1); // here we use (node.depth - 1), bucause the real root's depth is 1
  49410. ky_1 = height / (bottom_1.depth - 1 || 1);
  49411. eachBefore(realRoot, function (node) {
  49412. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  49413. coorY_1 = (node.depth - 1) * ky_1;
  49414. var finalCoor = radialCoordinate(coorX_1, coorY_1);
  49415. node.setLayout({
  49416. x: finalCoor.x,
  49417. y: finalCoor.y,
  49418. rawX: coorX_1,
  49419. rawY: coorY_1
  49420. }, true);
  49421. });
  49422. } else {
  49423. var orient_1 = seriesModel.getOrient();
  49424. if (orient_1 === 'RL' || orient_1 === 'LR') {
  49425. ky_1 = height / (right_1.getLayout().x + delta + tx_1);
  49426. kx_1 = width / (bottom_1.depth - 1 || 1);
  49427. eachBefore(realRoot, function (node) {
  49428. coorY_1 = (node.getLayout().x + tx_1) * ky_1;
  49429. coorX_1 = orient_1 === 'LR' ? (node.depth - 1) * kx_1 : width - (node.depth - 1) * kx_1;
  49430. node.setLayout({
  49431. x: coorX_1,
  49432. y: coorY_1
  49433. }, true);
  49434. });
  49435. } else if (orient_1 === 'TB' || orient_1 === 'BT') {
  49436. kx_1 = width / (right_1.getLayout().x + delta + tx_1);
  49437. ky_1 = height / (bottom_1.depth - 1 || 1);
  49438. eachBefore(realRoot, function (node) {
  49439. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  49440. coorY_1 = orient_1 === 'TB' ? (node.depth - 1) * ky_1 : height - (node.depth - 1) * ky_1;
  49441. node.setLayout({
  49442. x: coorX_1,
  49443. y: coorY_1
  49444. }, true);
  49445. });
  49446. }
  49447. }
  49448. }
  49449. }
  49450. function treeVisual(ecModel) {
  49451. ecModel.eachSeriesByType('tree', function (seriesModel) {
  49452. var data = seriesModel.getData();
  49453. var tree = data.tree;
  49454. tree.eachNode(function (node) {
  49455. var model = node.getModel(); // TODO Optimize
  49456. var style = model.getModel('itemStyle').getItemStyle();
  49457. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  49458. extend(existsStyle, style);
  49459. });
  49460. });
  49461. }
  49462. function installTreeAction(registers) {
  49463. registers.registerAction({
  49464. type: 'treeExpandAndCollapse',
  49465. event: 'treeExpandAndCollapse',
  49466. update: 'update'
  49467. }, function (payload, ecModel) {
  49468. ecModel.eachComponent({
  49469. mainType: 'series',
  49470. subType: 'tree',
  49471. query: payload
  49472. }, function (seriesModel) {
  49473. var dataIndex = payload.dataIndex;
  49474. var tree = seriesModel.getData().tree;
  49475. var node = tree.getNodeByDataIndex(dataIndex);
  49476. node.isExpand = !node.isExpand;
  49477. });
  49478. });
  49479. registers.registerAction({
  49480. type: 'treeRoam',
  49481. event: 'treeRoam',
  49482. // Here we set 'none' instead of 'update', because roam action
  49483. // just need to update the transform matrix without having to recalculate
  49484. // the layout. So don't need to go through the whole update process, such
  49485. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  49486. update: 'none'
  49487. }, function (payload, ecModel, api) {
  49488. ecModel.eachComponent({
  49489. mainType: 'series',
  49490. subType: 'tree',
  49491. query: payload
  49492. }, function (seriesModel) {
  49493. var coordSys = seriesModel.coordinateSystem;
  49494. var res = updateCenterAndZoom(coordSys, payload, undefined, api);
  49495. seriesModel.setCenter && seriesModel.setCenter(res.center);
  49496. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  49497. });
  49498. });
  49499. }
  49500. function install$b(registers) {
  49501. registers.registerChartView(TreeView);
  49502. registers.registerSeriesModel(TreeSeriesModel);
  49503. registers.registerLayout(treeLayout);
  49504. registers.registerVisual(treeVisual);
  49505. installTreeAction(registers);
  49506. }
  49507. var actionTypes = ['treemapZoomToNode', 'treemapRender', 'treemapMove'];
  49508. function installTreemapAction(registers) {
  49509. for (var i = 0; i < actionTypes.length; i++) {
  49510. registers.registerAction({
  49511. type: actionTypes[i],
  49512. update: 'updateView'
  49513. }, noop);
  49514. }
  49515. registers.registerAction({
  49516. type: 'treemapRootToNode',
  49517. update: 'updateView'
  49518. }, function (payload, ecModel) {
  49519. ecModel.eachComponent({
  49520. mainType: 'series',
  49521. subType: 'treemap',
  49522. query: payload
  49523. }, handleRootToNode);
  49524. function handleRootToNode(model, index) {
  49525. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  49526. var targetInfo = retrieveTargetInfo(payload, types, model);
  49527. if (targetInfo) {
  49528. var originViewRoot = model.getViewRoot();
  49529. if (originViewRoot) {
  49530. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  49531. }
  49532. model.resetViewRoot(targetInfo.node);
  49533. }
  49534. }
  49535. });
  49536. }
  49537. function enableAriaDecalForTree(seriesModel) {
  49538. var data = seriesModel.getData();
  49539. var tree = data.tree;
  49540. var decalPaletteScope = {};
  49541. tree.eachNode(function (node) {
  49542. // Use decal of level 1 node
  49543. var current = node;
  49544. while (current && current.depth > 1) {
  49545. current = current.parentNode;
  49546. }
  49547. var decal = getDecalFromPalette(seriesModel.ecModel, current.name || current.dataIndex + '', decalPaletteScope);
  49548. node.setVisual('decal', decal);
  49549. });
  49550. }
  49551. var TreemapSeriesModel =
  49552. /** @class */
  49553. function (_super) {
  49554. __extends(TreemapSeriesModel, _super);
  49555. function TreemapSeriesModel() {
  49556. var _this = _super !== null && _super.apply(this, arguments) || this;
  49557. _this.type = TreemapSeriesModel.type;
  49558. _this.preventUsingHoverLayer = true;
  49559. return _this;
  49560. }
  49561. /**
  49562. * @override
  49563. */
  49564. TreemapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  49565. // Create a virtual root.
  49566. var root = {
  49567. name: option.name,
  49568. children: option.data
  49569. };
  49570. completeTreeValue(root);
  49571. var levels = option.levels || []; // Used in "visual priority" in `treemapVisual.js`.
  49572. // This way is a little tricky, must satisfy the precondition:
  49573. // 1. There is no `treeNode.getModel('itemStyle.xxx')` used.
  49574. // 2. The `Model.prototype.getModel()` will not use any clone-like way.
  49575. var designatedVisualItemStyle = this.designatedVisualItemStyle = {};
  49576. var designatedVisualModel = new Model({
  49577. itemStyle: designatedVisualItemStyle
  49578. }, this, ecModel);
  49579. levels = option.levels = setDefault(levels, ecModel);
  49580. var levelModels = map(levels || [], function (levelDefine) {
  49581. return new Model(levelDefine, designatedVisualModel, ecModel);
  49582. }, this); // Make sure always a new tree is created when setOption,
  49583. // in TreemapView, we check whether oldTree === newTree
  49584. // to choose mappings approach among old shapes and new shapes.
  49585. var tree = Tree.createTree(root, this, beforeLink);
  49586. function beforeLink(nodeData) {
  49587. nodeData.wrapMethod('getItemModel', function (model, idx) {
  49588. var node = tree.getNodeByDataIndex(idx);
  49589. var levelModel = node ? levelModels[node.depth] : null; // If no levelModel, we also need `designatedVisualModel`.
  49590. model.parentModel = levelModel || designatedVisualModel;
  49591. return model;
  49592. });
  49593. }
  49594. return tree.data;
  49595. };
  49596. TreemapSeriesModel.prototype.optionUpdated = function () {
  49597. this.resetViewRoot();
  49598. };
  49599. /**
  49600. * @override
  49601. * @param {number} dataIndex
  49602. * @param {boolean} [mutipleSeries=false]
  49603. */
  49604. TreemapSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  49605. var data = this.getData();
  49606. var value = this.getRawValue(dataIndex);
  49607. var name = data.getName(dataIndex);
  49608. return createTooltipMarkup('nameValue', {
  49609. name: name,
  49610. value: value
  49611. });
  49612. };
  49613. /**
  49614. * Add tree path to tooltip param
  49615. *
  49616. * @override
  49617. * @param {number} dataIndex
  49618. * @return {Object}
  49619. */
  49620. TreemapSeriesModel.prototype.getDataParams = function (dataIndex) {
  49621. var params = _super.prototype.getDataParams.apply(this, arguments);
  49622. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  49623. params.treeAncestors = wrapTreePathInfo(node, this); // compatitable the previous code.
  49624. params.treePathInfo = params.treeAncestors;
  49625. return params;
  49626. };
  49627. /**
  49628. * @public
  49629. * @param {Object} layoutInfo {
  49630. * x: containerGroup x
  49631. * y: containerGroup y
  49632. * width: containerGroup width
  49633. * height: containerGroup height
  49634. * }
  49635. */
  49636. TreemapSeriesModel.prototype.setLayoutInfo = function (layoutInfo) {
  49637. /**
  49638. * @readOnly
  49639. * @type {Object}
  49640. */
  49641. this.layoutInfo = this.layoutInfo || {};
  49642. extend(this.layoutInfo, layoutInfo);
  49643. };
  49644. /**
  49645. * @param {string} id
  49646. * @return {number} index
  49647. */
  49648. TreemapSeriesModel.prototype.mapIdToIndex = function (id) {
  49649. // A feature is implemented:
  49650. // index is monotone increasing with the sequence of
  49651. // input id at the first time.
  49652. // This feature can make sure that each data item and its
  49653. // mapped color have the same index between data list and
  49654. // color list at the beginning, which is useful for user
  49655. // to adjust data-color mapping.
  49656. /**
  49657. * @private
  49658. * @type {Object}
  49659. */
  49660. var idIndexMap = this._idIndexMap;
  49661. if (!idIndexMap) {
  49662. idIndexMap = this._idIndexMap = createHashMap();
  49663. /**
  49664. * @private
  49665. * @type {number}
  49666. */
  49667. this._idIndexMapCount = 0;
  49668. }
  49669. var index = idIndexMap.get(id);
  49670. if (index == null) {
  49671. idIndexMap.set(id, index = this._idIndexMapCount++);
  49672. }
  49673. return index;
  49674. };
  49675. TreemapSeriesModel.prototype.getViewRoot = function () {
  49676. return this._viewRoot;
  49677. };
  49678. TreemapSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  49679. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  49680. var root = this.getRawData().tree.root;
  49681. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  49682. this._viewRoot = root;
  49683. }
  49684. };
  49685. TreemapSeriesModel.prototype.enableAriaDecal = function () {
  49686. enableAriaDecalForTree(this);
  49687. };
  49688. TreemapSeriesModel.type = 'series.treemap';
  49689. TreemapSeriesModel.layoutMode = 'box';
  49690. TreemapSeriesModel.defaultOption = {
  49691. // Disable progressive rendering
  49692. progressive: 0,
  49693. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  49694. left: 'center',
  49695. top: 'middle',
  49696. width: '80%',
  49697. height: '80%',
  49698. sort: true,
  49699. clipWindow: 'origin',
  49700. squareRatio: 0.5 * (1 + Math.sqrt(5)),
  49701. leafDepth: null,
  49702. drillDownIcon: '▶',
  49703. // to align specialized icon. ▷▶❒❐▼✚
  49704. zoomToNodeRatio: 0.32 * 0.32,
  49705. roam: true,
  49706. nodeClick: 'zoomToNode',
  49707. animation: true,
  49708. animationDurationUpdate: 900,
  49709. animationEasing: 'quinticInOut',
  49710. breadcrumb: {
  49711. show: true,
  49712. height: 22,
  49713. left: 'center',
  49714. top: 'bottom',
  49715. // right
  49716. // bottom
  49717. emptyItemWidth: 25,
  49718. itemStyle: {
  49719. color: 'rgba(0,0,0,0.7)',
  49720. textStyle: {
  49721. color: '#fff'
  49722. }
  49723. },
  49724. emphasis: {
  49725. itemStyle: {
  49726. color: 'rgba(0,0,0,0.9)' // '#5793f3',
  49727. }
  49728. }
  49729. },
  49730. label: {
  49731. show: true,
  49732. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  49733. distance: 0,
  49734. padding: 5,
  49735. position: 'inside',
  49736. // formatter: null,
  49737. color: '#fff',
  49738. overflow: 'truncate' // align
  49739. // verticalAlign
  49740. },
  49741. upperLabel: {
  49742. show: false,
  49743. position: [0, '50%'],
  49744. height: 20,
  49745. // formatter: null,
  49746. // color: '#fff',
  49747. overflow: 'truncate',
  49748. // align: null,
  49749. verticalAlign: 'middle'
  49750. },
  49751. itemStyle: {
  49752. color: null,
  49753. colorAlpha: null,
  49754. colorSaturation: null,
  49755. borderWidth: 0,
  49756. gapWidth: 0,
  49757. borderColor: '#fff',
  49758. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  49759. // border color is evaluated by color of current node and
  49760. // borderColorSaturation.
  49761. },
  49762. emphasis: {
  49763. upperLabel: {
  49764. show: true,
  49765. position: [0, '50%'],
  49766. overflow: 'truncate',
  49767. verticalAlign: 'middle'
  49768. }
  49769. },
  49770. visualDimension: 0,
  49771. visualMin: null,
  49772. visualMax: null,
  49773. color: [],
  49774. // level[n].color (if necessary).
  49775. // + Specify color list of each level. level[0].color would be global
  49776. // color list if not specified. (see method `setDefault`).
  49777. // + But set as a empty array to forbid fetch color from global palette
  49778. // when using nodeModel.get('color'), otherwise nodes on deep level
  49779. // will always has color palette set and are not able to inherit color
  49780. // from parent node.
  49781. // + TreemapSeries.color can not be set as 'none', otherwise effect
  49782. // legend color fetching (see seriesColor.js).
  49783. colorAlpha: null,
  49784. colorSaturation: null,
  49785. colorMappingBy: 'index',
  49786. visibleMin: 10,
  49787. // be rendered. Only works when sort is 'asc' or 'desc'.
  49788. childrenVisibleMin: null,
  49789. // grandchildren will not show.
  49790. // Why grandchildren? If not grandchildren but children,
  49791. // some siblings show children and some not,
  49792. // the appearance may be mess and not consistent,
  49793. levels: [] // Each item: {
  49794. // visibleMin, itemStyle, visualDimension, label
  49795. // }
  49796. };
  49797. return TreemapSeriesModel;
  49798. }(SeriesModel);
  49799. /**
  49800. * @param {Object} dataNode
  49801. */
  49802. function completeTreeValue(dataNode) {
  49803. // Postorder travel tree.
  49804. // If value of none-leaf node is not set,
  49805. // calculate it by suming up the value of all children.
  49806. var sum = 0;
  49807. each(dataNode.children, function (child) {
  49808. completeTreeValue(child);
  49809. var childValue = child.value;
  49810. isArray(childValue) && (childValue = childValue[0]);
  49811. sum += childValue;
  49812. });
  49813. var thisValue = dataNode.value;
  49814. if (isArray(thisValue)) {
  49815. thisValue = thisValue[0];
  49816. }
  49817. if (thisValue == null || isNaN(thisValue)) {
  49818. thisValue = sum;
  49819. } // Value should not less than 0.
  49820. if (thisValue < 0) {
  49821. thisValue = 0;
  49822. }
  49823. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  49824. }
  49825. /**
  49826. * set default to level configuration
  49827. */
  49828. function setDefault(levels, ecModel) {
  49829. var globalColorList = normalizeToArray(ecModel.get('color'));
  49830. var globalDecalList = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  49831. if (!globalColorList) {
  49832. return;
  49833. }
  49834. levels = levels || [];
  49835. var hasColorDefine;
  49836. var hasDecalDefine;
  49837. each(levels, function (levelDefine) {
  49838. var model = new Model(levelDefine);
  49839. var modelColor = model.get('color');
  49840. var modelDecal = model.get('decal');
  49841. if (model.get(['itemStyle', 'color']) || modelColor && modelColor !== 'none') {
  49842. hasColorDefine = true;
  49843. }
  49844. if (model.get(['itemStyle', 'decal']) || modelDecal && modelDecal !== 'none') {
  49845. hasDecalDefine = true;
  49846. }
  49847. });
  49848. var level0 = levels[0] || (levels[0] = {});
  49849. if (!hasColorDefine) {
  49850. level0.color = globalColorList.slice();
  49851. }
  49852. if (!hasDecalDefine && globalDecalList) {
  49853. level0.decal = globalDecalList.slice();
  49854. }
  49855. return levels;
  49856. }
  49857. var TEXT_PADDING = 8;
  49858. var ITEM_GAP = 8;
  49859. var ARRAY_LENGTH = 5;
  49860. var Breadcrumb =
  49861. /** @class */
  49862. function () {
  49863. function Breadcrumb(containerGroup) {
  49864. this.group = new Group();
  49865. containerGroup.add(this.group);
  49866. }
  49867. Breadcrumb.prototype.render = function (seriesModel, api, targetNode, onSelect) {
  49868. var model = seriesModel.getModel('breadcrumb');
  49869. var thisGroup = this.group;
  49870. thisGroup.removeAll();
  49871. if (!model.get('show') || !targetNode) {
  49872. return;
  49873. }
  49874. var normalStyleModel = model.getModel('itemStyle');
  49875. var emphasisModel = model.getModel('emphasis');
  49876. var textStyleModel = normalStyleModel.getModel('textStyle');
  49877. var emphasisTextStyleModel = emphasisModel.getModel(['itemStyle', 'textStyle']);
  49878. var layoutParam = {
  49879. pos: {
  49880. left: model.get('left'),
  49881. right: model.get('right'),
  49882. top: model.get('top'),
  49883. bottom: model.get('bottom')
  49884. },
  49885. box: {
  49886. width: api.getWidth(),
  49887. height: api.getHeight()
  49888. },
  49889. emptyItemWidth: model.get('emptyItemWidth'),
  49890. totalWidth: 0,
  49891. renderList: []
  49892. };
  49893. this._prepare(targetNode, layoutParam, textStyleModel);
  49894. this._renderContent(seriesModel, layoutParam, normalStyleModel, emphasisModel, textStyleModel, emphasisTextStyleModel, onSelect);
  49895. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  49896. };
  49897. /**
  49898. * Prepare render list and total width
  49899. * @private
  49900. */
  49901. Breadcrumb.prototype._prepare = function (targetNode, layoutParam, textStyleModel) {
  49902. for (var node = targetNode; node; node = node.parentNode) {
  49903. var text = convertOptionIdName(node.getModel().get('name'), '');
  49904. var textRect = textStyleModel.getTextRect(text);
  49905. var itemWidth = Math.max(textRect.width + TEXT_PADDING * 2, layoutParam.emptyItemWidth);
  49906. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  49907. layoutParam.renderList.push({
  49908. node: node,
  49909. text: text,
  49910. width: itemWidth
  49911. });
  49912. }
  49913. };
  49914. /**
  49915. * @private
  49916. */
  49917. Breadcrumb.prototype._renderContent = function (seriesModel, layoutParam, normalStyleModel, emphasisModel, textStyleModel, emphasisTextStyleModel, onSelect) {
  49918. // Start rendering.
  49919. var lastX = 0;
  49920. var emptyItemWidth = layoutParam.emptyItemWidth;
  49921. var height = seriesModel.get(['breadcrumb', 'height']);
  49922. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  49923. var totalWidth = layoutParam.totalWidth;
  49924. var renderList = layoutParam.renderList;
  49925. var emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  49926. for (var i = renderList.length - 1; i >= 0; i--) {
  49927. var item = renderList[i];
  49928. var itemNode = item.node;
  49929. var itemWidth = item.width;
  49930. var text = item.text; // Hdie text and shorten width if necessary.
  49931. if (totalWidth > availableSize.width) {
  49932. totalWidth -= itemWidth - emptyItemWidth;
  49933. itemWidth = emptyItemWidth;
  49934. text = null;
  49935. }
  49936. var el = new Polygon({
  49937. shape: {
  49938. points: makeItemPoints(lastX, 0, itemWidth, height, i === renderList.length - 1, i === 0)
  49939. },
  49940. style: defaults(normalStyleModel.getItemStyle(), {
  49941. lineJoin: 'bevel'
  49942. }),
  49943. textContent: new ZRText({
  49944. style: createTextStyle(textStyleModel, {
  49945. text: text
  49946. })
  49947. }),
  49948. textConfig: {
  49949. position: 'inside'
  49950. },
  49951. z2: Z2_EMPHASIS_LIFT * 1e4,
  49952. onclick: curry(onSelect, itemNode)
  49953. });
  49954. el.disableLabelAnimation = true;
  49955. el.getTextContent().ensureState('emphasis').style = createTextStyle(emphasisTextStyleModel, {
  49956. text: text
  49957. });
  49958. el.ensureState('emphasis').style = emphasisItemStyle;
  49959. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  49960. this.group.add(el);
  49961. packEventData(el, seriesModel, itemNode);
  49962. lastX += itemWidth + ITEM_GAP;
  49963. }
  49964. };
  49965. Breadcrumb.prototype.remove = function () {
  49966. this.group.removeAll();
  49967. };
  49968. return Breadcrumb;
  49969. }();
  49970. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  49971. var points = [[head ? x : x - ARRAY_LENGTH, y], [x + itemWidth, y], [x + itemWidth, y + itemHeight], [head ? x : x - ARRAY_LENGTH, y + itemHeight]];
  49972. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  49973. !head && points.push([x, y + itemHeight / 2]);
  49974. return points;
  49975. } // Package custom mouse event.
  49976. function packEventData(el, seriesModel, itemNode) {
  49977. getECData(el).eventData = {
  49978. componentType: 'series',
  49979. componentSubType: 'treemap',
  49980. componentIndex: seriesModel.componentIndex,
  49981. seriesIndex: seriesModel.seriesIndex,
  49982. seriesName: seriesModel.name,
  49983. seriesType: 'treemap',
  49984. selfType: 'breadcrumb',
  49985. nodeData: {
  49986. dataIndex: itemNode && itemNode.dataIndex,
  49987. name: itemNode && itemNode.name
  49988. },
  49989. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  49990. };
  49991. }
  49992. /*
  49993. * Licensed to the Apache Software Foundation (ASF) under one
  49994. * or more contributor license agreements. See the NOTICE file
  49995. * distributed with this work for additional information
  49996. * regarding copyright ownership. The ASF licenses this file
  49997. * to you under the Apache License, Version 2.0 (the
  49998. * "License"); you may not use this file except in compliance
  49999. * with the License. You may obtain a copy of the License at
  50000. *
  50001. * http://www.apache.org/licenses/LICENSE-2.0
  50002. *
  50003. * Unless required by applicable law or agreed to in writing,
  50004. * software distributed under the License is distributed on an
  50005. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50006. * KIND, either express or implied. See the License for the
  50007. * specific language governing permissions and limitations
  50008. * under the License.
  50009. */
  50010. /**
  50011. * AUTO-GENERATED FILE. DO NOT MODIFY.
  50012. */
  50013. /*
  50014. * Licensed to the Apache Software Foundation (ASF) under one
  50015. * or more contributor license agreements. See the NOTICE file
  50016. * distributed with this work for additional information
  50017. * regarding copyright ownership. The ASF licenses this file
  50018. * to you under the Apache License, Version 2.0 (the
  50019. * "License"); you may not use this file except in compliance
  50020. * with the License. You may obtain a copy of the License at
  50021. *
  50022. * http://www.apache.org/licenses/LICENSE-2.0
  50023. *
  50024. * Unless required by applicable law or agreed to in writing,
  50025. * software distributed under the License is distributed on an
  50026. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50027. * KIND, either express or implied. See the License for the
  50028. * specific language governing permissions and limitations
  50029. * under the License.
  50030. */
  50031. /**
  50032. * Animate multiple elements with a single done-callback.
  50033. *
  50034. * @example
  50035. * animation
  50036. * .createWrap()
  50037. * .add(el1, {x: 10, y: 10})
  50038. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  50039. * .done(function () { // done })
  50040. * .start('cubicOut');
  50041. */
  50042. var AnimationWrap =
  50043. /** @class */
  50044. function () {
  50045. function AnimationWrap() {
  50046. this._storage = [];
  50047. this._elExistsMap = {};
  50048. }
  50049. /**
  50050. * Caution: a el can only be added once, otherwise 'done'
  50051. * might not be called. This method checks this (by el.id),
  50052. * suppresses adding and returns false when existing el found.
  50053. *
  50054. * @return Whether adding succeeded.
  50055. */
  50056. AnimationWrap.prototype.add = function (el, target, duration, delay, easing) {
  50057. if (this._elExistsMap[el.id]) {
  50058. return false;
  50059. }
  50060. this._elExistsMap[el.id] = true;
  50061. this._storage.push({
  50062. el: el,
  50063. target: target,
  50064. duration: duration,
  50065. delay: delay,
  50066. easing: easing
  50067. });
  50068. return true;
  50069. };
  50070. /**
  50071. * Only execute when animation done/aborted.
  50072. */
  50073. AnimationWrap.prototype.finished = function (callback) {
  50074. this._finishedCallback = callback;
  50075. return this;
  50076. };
  50077. /**
  50078. * Will stop exist animation firstly.
  50079. */
  50080. AnimationWrap.prototype.start = function () {
  50081. var _this = this;
  50082. var count = this._storage.length;
  50083. var checkTerminate = function () {
  50084. count--;
  50085. if (count <= 0) {
  50086. // Guard.
  50087. _this._storage.length = 0;
  50088. _this._elExistsMap = {};
  50089. _this._finishedCallback && _this._finishedCallback();
  50090. }
  50091. };
  50092. for (var i = 0, len = this._storage.length; i < len; i++) {
  50093. var item = this._storage[i];
  50094. item.el.animateTo(item.target, {
  50095. duration: item.duration,
  50096. delay: item.delay,
  50097. easing: item.easing,
  50098. setToFinal: true,
  50099. done: checkTerminate,
  50100. aborted: checkTerminate
  50101. });
  50102. }
  50103. return this;
  50104. };
  50105. return AnimationWrap;
  50106. }();
  50107. function createWrap() {
  50108. return new AnimationWrap();
  50109. }
  50110. var Group$1 = Group;
  50111. var Rect$1 = Rect;
  50112. var DRAG_THRESHOLD = 3;
  50113. var PATH_LABEL_NOAMAL = 'label';
  50114. var PATH_UPPERLABEL_NORMAL = 'upperLabel'; // Should larger than emphasis states lift z
  50115. var Z2_BASE = Z2_EMPHASIS_LIFT * 10; // Should bigger than every z2.
  50116. var Z2_BG = Z2_EMPHASIS_LIFT * 2;
  50117. var Z2_CONTENT = Z2_EMPHASIS_LIFT * 3;
  50118. var getStateItemStyle = makeStyleMapper([['fill', 'color'], // `borderColor` and `borderWidth` has been occupied,
  50119. // so use `stroke` to indicate the stroke of the rect.
  50120. ['stroke', 'strokeColor'], ['lineWidth', 'strokeWidth'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  50121. // So do not transfer decal directly.
  50122. ]);
  50123. var getItemStyleNormal = function (model) {
  50124. // Normal style props should include emphasis style props.
  50125. var itemStyle = getStateItemStyle(model); // Clear styles set by emphasis.
  50126. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  50127. return itemStyle;
  50128. };
  50129. var inner$8 = makeInner();
  50130. var TreemapView =
  50131. /** @class */
  50132. function (_super) {
  50133. __extends(TreemapView, _super);
  50134. function TreemapView() {
  50135. var _this = _super !== null && _super.apply(this, arguments) || this;
  50136. _this.type = TreemapView.type;
  50137. _this._state = 'ready';
  50138. _this._storage = createStorage();
  50139. return _this;
  50140. }
  50141. /**
  50142. * @override
  50143. */
  50144. TreemapView.prototype.render = function (seriesModel, ecModel, api, payload) {
  50145. var models = ecModel.findComponents({
  50146. mainType: 'series',
  50147. subType: 'treemap',
  50148. query: payload
  50149. });
  50150. if (indexOf(models, seriesModel) < 0) {
  50151. return;
  50152. }
  50153. this.seriesModel = seriesModel;
  50154. this.api = api;
  50155. this.ecModel = ecModel;
  50156. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  50157. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  50158. var payloadType = payload && payload.type;
  50159. var layoutInfo = seriesModel.layoutInfo;
  50160. var isInit = !this._oldTree;
  50161. var thisStorage = this._storage; // Mark new root when action is treemapRootToNode.
  50162. var reRoot = payloadType === 'treemapRootToNode' && targetInfo && thisStorage ? {
  50163. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  50164. direction: payload.direction
  50165. } : null;
  50166. var containerGroup = this._giveContainerGroup(layoutInfo);
  50167. var hasAnimation = seriesModel.get('animation');
  50168. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  50169. hasAnimation && !isInit && (!payloadType || payloadType === 'treemapZoomToNode' || payloadType === 'treemapRootToNode') ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot) : renderResult.renderFinally();
  50170. this._resetController(api);
  50171. this._renderBreadcrumb(seriesModel, api, targetInfo);
  50172. };
  50173. TreemapView.prototype._giveContainerGroup = function (layoutInfo) {
  50174. var containerGroup = this._containerGroup;
  50175. if (!containerGroup) {
  50176. // FIXME
  50177. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  50178. containerGroup = this._containerGroup = new Group$1();
  50179. this._initEvents(containerGroup);
  50180. this.group.add(containerGroup);
  50181. }
  50182. containerGroup.x = layoutInfo.x;
  50183. containerGroup.y = layoutInfo.y;
  50184. return containerGroup;
  50185. };
  50186. TreemapView.prototype._doRender = function (containerGroup, seriesModel, reRoot) {
  50187. var thisTree = seriesModel.getData().tree;
  50188. var oldTree = this._oldTree; // Clear last shape records.
  50189. var lastsForAnimation = createStorage();
  50190. var thisStorage = createStorage();
  50191. var oldStorage = this._storage;
  50192. var willInvisibleEls = [];
  50193. function doRenderNode(thisNode, oldNode, parentGroup, depth) {
  50194. return renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth);
  50195. } // Notice: When thisTree and oldTree are the same tree (see list.cloneShallow),
  50196. // the oldTree is actually losted, so we cannot find all of the old graphic
  50197. // elements from tree. So we use this strategy: make element storage, move
  50198. // from old storage to new storage, clear old storage.
  50199. dualTravel(thisTree.root ? [thisTree.root] : [], oldTree && oldTree.root ? [oldTree.root] : [], containerGroup, thisTree === oldTree || !oldTree, 0); // Process all removing.
  50200. var willDeleteEls = clearStorage(oldStorage);
  50201. this._oldTree = thisTree;
  50202. this._storage = thisStorage;
  50203. return {
  50204. lastsForAnimation: lastsForAnimation,
  50205. willDeleteEls: willDeleteEls,
  50206. renderFinally: renderFinally
  50207. };
  50208. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  50209. // When 'render' is triggered by action,
  50210. // 'this' and 'old' may be the same tree,
  50211. // we use rawIndex in that case.
  50212. if (sameTree) {
  50213. oldViewChildren = thisViewChildren;
  50214. each(thisViewChildren, function (child, index) {
  50215. !child.isRemoved() && processNode(index, index);
  50216. });
  50217. } // Diff hierarchically (diff only in each subtree, but not whole).
  50218. // because, consistency of view is important.
  50219. else {
  50220. new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  50221. }
  50222. function getKey(node) {
  50223. // Identify by name or raw index.
  50224. return node.getId();
  50225. }
  50226. function processNode(newIndex, oldIndex) {
  50227. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  50228. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  50229. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  50230. group && dualTravel(thisNode && thisNode.viewChildren || [], oldNode && oldNode.viewChildren || [], group, sameTree, depth + 1);
  50231. }
  50232. }
  50233. function clearStorage(storage) {
  50234. var willDeleteEls = createStorage();
  50235. storage && each(storage, function (store, storageName) {
  50236. var delEls = willDeleteEls[storageName];
  50237. each(store, function (el) {
  50238. el && (delEls.push(el), inner$8(el).willDelete = true);
  50239. });
  50240. });
  50241. return willDeleteEls;
  50242. }
  50243. function renderFinally() {
  50244. each(willDeleteEls, function (els) {
  50245. each(els, function (el) {
  50246. el.parent && el.parent.remove(el);
  50247. });
  50248. });
  50249. each(willInvisibleEls, function (el) {
  50250. el.invisible = true; // Setting invisible is for optimizing, so no need to set dirty,
  50251. // just mark as invisible.
  50252. el.dirty();
  50253. });
  50254. }
  50255. };
  50256. TreemapView.prototype._doAnimation = function (containerGroup, renderResult, seriesModel, reRoot) {
  50257. var durationOption = seriesModel.get('animationDurationUpdate');
  50258. var easingOption = seriesModel.get('animationEasing'); // TODO: do not support function until necessary.
  50259. var duration = (isFunction(durationOption) ? 0 : durationOption) || 0;
  50260. var easing = (isFunction(easingOption) ? null : easingOption) || 'cubicOut';
  50261. var animationWrap = createWrap(); // Make delete animations.
  50262. each(renderResult.willDeleteEls, function (store, storageName) {
  50263. each(store, function (el, rawIndex) {
  50264. if (el.invisible) {
  50265. return;
  50266. }
  50267. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  50268. var target;
  50269. var innerStore = inner$8(parent);
  50270. if (reRoot && reRoot.direction === 'drillDown') {
  50271. target = parent === reRoot.rootNodeGroup // This is the content element of view root.
  50272. // Only `content` will enter this branch, because
  50273. // `background` and `nodeGroup` will not be deleted.
  50274. ? {
  50275. shape: {
  50276. x: 0,
  50277. y: 0,
  50278. width: innerStore.nodeWidth,
  50279. height: innerStore.nodeHeight
  50280. },
  50281. style: {
  50282. opacity: 0
  50283. }
  50284. } // Others.
  50285. : {
  50286. style: {
  50287. opacity: 0
  50288. }
  50289. };
  50290. } else {
  50291. var targetX = 0;
  50292. var targetY = 0;
  50293. if (!innerStore.willDelete) {
  50294. // Let node animate to right-bottom corner, cooperating with fadeout,
  50295. // which is appropriate for user understanding.
  50296. // Divided by 2 for reRoot rolling up effect.
  50297. targetX = innerStore.nodeWidth / 2;
  50298. targetY = innerStore.nodeHeight / 2;
  50299. }
  50300. target = storageName === 'nodeGroup' ? {
  50301. x: targetX,
  50302. y: targetY,
  50303. style: {
  50304. opacity: 0
  50305. }
  50306. } : {
  50307. shape: {
  50308. x: targetX,
  50309. y: targetY,
  50310. width: 0,
  50311. height: 0
  50312. },
  50313. style: {
  50314. opacity: 0
  50315. }
  50316. };
  50317. } // TODO: do not support delay until necessary.
  50318. target && animationWrap.add(el, target, duration, 0, easing);
  50319. });
  50320. }); // Make other animations
  50321. each(this._storage, function (store, storageName) {
  50322. each(store, function (el, rawIndex) {
  50323. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  50324. var target = {};
  50325. if (!last) {
  50326. return;
  50327. }
  50328. if (el instanceof Group) {
  50329. if (last.oldX != null) {
  50330. target.x = el.x;
  50331. target.y = el.y;
  50332. el.x = last.oldX;
  50333. el.y = last.oldY;
  50334. }
  50335. } else {
  50336. if (last.oldShape) {
  50337. target.shape = extend({}, el.shape);
  50338. el.setShape(last.oldShape);
  50339. }
  50340. if (last.fadein) {
  50341. el.setStyle('opacity', 0);
  50342. target.style = {
  50343. opacity: 1
  50344. };
  50345. } // When animation is stopped for succedent animation starting,
  50346. // el.style.opacity might not be 1
  50347. else if (el.style.opacity !== 1) {
  50348. target.style = {
  50349. opacity: 1
  50350. };
  50351. }
  50352. }
  50353. animationWrap.add(el, target, duration, 0, easing);
  50354. });
  50355. }, this);
  50356. this._state = 'animating';
  50357. animationWrap.finished(bind(function () {
  50358. this._state = 'ready';
  50359. renderResult.renderFinally();
  50360. }, this)).start();
  50361. };
  50362. TreemapView.prototype._resetController = function (api) {
  50363. var controller = this._controller; // Init controller.
  50364. if (!controller) {
  50365. controller = this._controller = new RoamController(api.getZr());
  50366. controller.enable(this.seriesModel.get('roam'));
  50367. controller.on('pan', bind(this._onPan, this));
  50368. controller.on('zoom', bind(this._onZoom, this));
  50369. }
  50370. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  50371. controller.setPointerChecker(function (e, x, y) {
  50372. return rect.contain(x, y);
  50373. });
  50374. };
  50375. TreemapView.prototype._clearController = function () {
  50376. var controller = this._controller;
  50377. if (controller) {
  50378. controller.dispose();
  50379. controller = null;
  50380. }
  50381. };
  50382. TreemapView.prototype._onPan = function (e) {
  50383. if (this._state !== 'animating' && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)) {
  50384. // These param must not be cached.
  50385. var root = this.seriesModel.getData().tree.root;
  50386. if (!root) {
  50387. return;
  50388. }
  50389. var rootLayout = root.getLayout();
  50390. if (!rootLayout) {
  50391. return;
  50392. }
  50393. this.api.dispatchAction({
  50394. type: 'treemapMove',
  50395. from: this.uid,
  50396. seriesId: this.seriesModel.id,
  50397. rootRect: {
  50398. x: rootLayout.x + e.dx,
  50399. y: rootLayout.y + e.dy,
  50400. width: rootLayout.width,
  50401. height: rootLayout.height
  50402. }
  50403. });
  50404. }
  50405. };
  50406. TreemapView.prototype._onZoom = function (e) {
  50407. var mouseX = e.originX;
  50408. var mouseY = e.originY;
  50409. if (this._state !== 'animating') {
  50410. // These param must not be cached.
  50411. var root = this.seriesModel.getData().tree.root;
  50412. if (!root) {
  50413. return;
  50414. }
  50415. var rootLayout = root.getLayout();
  50416. if (!rootLayout) {
  50417. return;
  50418. }
  50419. var rect = new BoundingRect(rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height);
  50420. var layoutInfo = this.seriesModel.layoutInfo; // Transform mouse coord from global to containerGroup.
  50421. mouseX -= layoutInfo.x;
  50422. mouseY -= layoutInfo.y; // Scale root bounding rect.
  50423. var m = create$1();
  50424. translate(m, m, [-mouseX, -mouseY]);
  50425. scale$1(m, m, [e.scale, e.scale]);
  50426. translate(m, m, [mouseX, mouseY]);
  50427. rect.applyTransform(m);
  50428. this.api.dispatchAction({
  50429. type: 'treemapRender',
  50430. from: this.uid,
  50431. seriesId: this.seriesModel.id,
  50432. rootRect: {
  50433. x: rect.x,
  50434. y: rect.y,
  50435. width: rect.width,
  50436. height: rect.height
  50437. }
  50438. });
  50439. }
  50440. };
  50441. TreemapView.prototype._initEvents = function (containerGroup) {
  50442. var _this = this;
  50443. containerGroup.on('click', function (e) {
  50444. if (_this._state !== 'ready') {
  50445. return;
  50446. }
  50447. var nodeClick = _this.seriesModel.get('nodeClick', true);
  50448. if (!nodeClick) {
  50449. return;
  50450. }
  50451. var targetInfo = _this.findTarget(e.offsetX, e.offsetY);
  50452. if (!targetInfo) {
  50453. return;
  50454. }
  50455. var node = targetInfo.node;
  50456. if (node.getLayout().isLeafRoot) {
  50457. _this._rootToNode(targetInfo);
  50458. } else {
  50459. if (nodeClick === 'zoomToNode') {
  50460. _this._zoomToNode(targetInfo);
  50461. } else if (nodeClick === 'link') {
  50462. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  50463. var link = itemModel.get('link', true);
  50464. var linkTarget = itemModel.get('target', true) || 'blank';
  50465. link && windowOpen(link, linkTarget);
  50466. }
  50467. }
  50468. }, this);
  50469. };
  50470. TreemapView.prototype._renderBreadcrumb = function (seriesModel, api, targetInfo) {
  50471. var _this = this;
  50472. if (!targetInfo) {
  50473. targetInfo = seriesModel.get('leafDepth', true) != null ? {
  50474. node: seriesModel.getViewRoot()
  50475. } // FIXME
  50476. // better way?
  50477. // Find breadcrumb tail on center of containerGroup.
  50478. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  50479. if (!targetInfo) {
  50480. targetInfo = {
  50481. node: seriesModel.getData().tree.root
  50482. };
  50483. }
  50484. }
  50485. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group))).render(seriesModel, api, targetInfo.node, function (node) {
  50486. if (_this._state !== 'animating') {
  50487. aboveViewRoot(seriesModel.getViewRoot(), node) ? _this._rootToNode({
  50488. node: node
  50489. }) : _this._zoomToNode({
  50490. node: node
  50491. });
  50492. }
  50493. });
  50494. };
  50495. /**
  50496. * @override
  50497. */
  50498. TreemapView.prototype.remove = function () {
  50499. this._clearController();
  50500. this._containerGroup && this._containerGroup.removeAll();
  50501. this._storage = createStorage();
  50502. this._state = 'ready';
  50503. this._breadcrumb && this._breadcrumb.remove();
  50504. };
  50505. TreemapView.prototype.dispose = function () {
  50506. this._clearController();
  50507. };
  50508. TreemapView.prototype._zoomToNode = function (targetInfo) {
  50509. this.api.dispatchAction({
  50510. type: 'treemapZoomToNode',
  50511. from: this.uid,
  50512. seriesId: this.seriesModel.id,
  50513. targetNode: targetInfo.node
  50514. });
  50515. };
  50516. TreemapView.prototype._rootToNode = function (targetInfo) {
  50517. this.api.dispatchAction({
  50518. type: 'treemapRootToNode',
  50519. from: this.uid,
  50520. seriesId: this.seriesModel.id,
  50521. targetNode: targetInfo.node
  50522. });
  50523. };
  50524. /**
  50525. * @public
  50526. * @param {number} x Global coord x.
  50527. * @param {number} y Global coord y.
  50528. * @return {Object} info If not found, return undefined;
  50529. * @return {number} info.node Target node.
  50530. * @return {number} info.offsetX x refer to target node.
  50531. * @return {number} info.offsetY y refer to target node.
  50532. */
  50533. TreemapView.prototype.findTarget = function (x, y) {
  50534. var targetInfo;
  50535. var viewRoot = this.seriesModel.getViewRoot();
  50536. viewRoot.eachNode({
  50537. attr: 'viewChildren',
  50538. order: 'preorder'
  50539. }, function (node) {
  50540. var bgEl = this._storage.background[node.getRawIndex()]; // If invisible, there might be no element.
  50541. if (bgEl) {
  50542. var point = bgEl.transformCoordToLocal(x, y);
  50543. var shape = bgEl.shape; // For performance consideration, don't use 'getBoundingRect'.
  50544. if (shape.x <= point[0] && point[0] <= shape.x + shape.width && shape.y <= point[1] && point[1] <= shape.y + shape.height) {
  50545. targetInfo = {
  50546. node: node,
  50547. offsetX: point[0],
  50548. offsetY: point[1]
  50549. };
  50550. } else {
  50551. return false; // Suppress visit subtree.
  50552. }
  50553. }
  50554. }, this);
  50555. return targetInfo;
  50556. };
  50557. TreemapView.type = 'treemap';
  50558. return TreemapView;
  50559. }(ChartView);
  50560. /**
  50561. * @inner
  50562. */
  50563. function createStorage() {
  50564. return {
  50565. nodeGroup: [],
  50566. background: [],
  50567. content: []
  50568. };
  50569. }
  50570. /**
  50571. * @inner
  50572. * @return Return undefined means do not travel further.
  50573. */
  50574. function renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth) {
  50575. // Whether under viewRoot.
  50576. if (!thisNode) {
  50577. // Deleting nodes will be performed finally. This method just find
  50578. // element from old storage, or create new element, set them to new
  50579. // storage, and set styles.
  50580. return;
  50581. } // -------------------------------------------------------------------
  50582. // Start of closure variables available in "Procedures in renderNode".
  50583. var thisLayout = thisNode.getLayout();
  50584. var data = seriesModel.getData();
  50585. var nodeModel = thisNode.getModel(); // Only for enabling highlight/downplay. Clear firstly.
  50586. // Because some node will not be rendered.
  50587. data.setItemGraphicEl(thisNode.dataIndex, null);
  50588. if (!thisLayout || !thisLayout.isInView) {
  50589. return;
  50590. }
  50591. var thisWidth = thisLayout.width;
  50592. var thisHeight = thisLayout.height;
  50593. var borderWidth = thisLayout.borderWidth;
  50594. var thisInvisible = thisLayout.invisible;
  50595. var thisRawIndex = thisNode.getRawIndex();
  50596. var oldRawIndex = oldNode && oldNode.getRawIndex();
  50597. var thisViewChildren = thisNode.viewChildren;
  50598. var upperHeight = thisLayout.upperHeight;
  50599. var isParent = thisViewChildren && thisViewChildren.length;
  50600. var itemStyleNormalModel = nodeModel.getModel('itemStyle');
  50601. var itemStyleEmphasisModel = nodeModel.getModel(['emphasis', 'itemStyle']);
  50602. var itemStyleBlurModel = nodeModel.getModel(['blur', 'itemStyle']);
  50603. var itemStyleSelectModel = nodeModel.getModel(['select', 'itemStyle']);
  50604. var borderRadius = itemStyleNormalModel.get('borderRadius') || 0; // End of closure ariables available in "Procedures in renderNode".
  50605. // -----------------------------------------------------------------
  50606. // Node group
  50607. var group = giveGraphic('nodeGroup', Group$1);
  50608. if (!group) {
  50609. return;
  50610. }
  50611. parentGroup.add(group); // x,y are not set when el is above view root.
  50612. group.x = thisLayout.x || 0;
  50613. group.y = thisLayout.y || 0;
  50614. group.markRedraw();
  50615. inner$8(group).nodeWidth = thisWidth;
  50616. inner$8(group).nodeHeight = thisHeight;
  50617. if (thisLayout.isAboveViewRoot) {
  50618. return group;
  50619. } // Background
  50620. var bg = giveGraphic('background', Rect$1, depth, Z2_BG);
  50621. bg && renderBackground(group, bg, isParent && thisLayout.upperLabelHeight);
  50622. var emphasisModel = nodeModel.getModel('emphasis');
  50623. var focus = emphasisModel.get('focus');
  50624. var blurScope = emphasisModel.get('blurScope');
  50625. var isDisabled = emphasisModel.get('disabled');
  50626. var focusOrIndices = focus === 'ancestor' ? thisNode.getAncestorsIndices() : focus === 'descendant' ? thisNode.getDescendantIndices() : focus; // No children, render content.
  50627. if (isParent) {
  50628. // Because of the implementation about "traverse" in graphic hover style, we
  50629. // can not set hover listener on the "group" of non-leaf node. Otherwise the
  50630. // hover event from the descendents will be listenered.
  50631. if (isHighDownDispatcher(group)) {
  50632. setAsHighDownDispatcher(group, false);
  50633. }
  50634. if (bg) {
  50635. setAsHighDownDispatcher(bg, !isDisabled); // Only for enabling highlight/downplay.
  50636. data.setItemGraphicEl(thisNode.dataIndex, bg);
  50637. enableHoverFocus(bg, focusOrIndices, blurScope);
  50638. }
  50639. } else {
  50640. var content = giveGraphic('content', Rect$1, depth, Z2_CONTENT);
  50641. content && renderContent(group, content);
  50642. bg.disableMorphing = true;
  50643. if (bg && isHighDownDispatcher(bg)) {
  50644. setAsHighDownDispatcher(bg, false);
  50645. }
  50646. setAsHighDownDispatcher(group, !isDisabled); // Only for enabling highlight/downplay.
  50647. data.setItemGraphicEl(thisNode.dataIndex, group);
  50648. enableHoverFocus(group, focusOrIndices, blurScope);
  50649. }
  50650. return group; // ----------------------------
  50651. // | Procedures in renderNode |
  50652. // ----------------------------
  50653. function renderBackground(group, bg, useUpperLabel) {
  50654. var ecData = getECData(bg); // For tooltip.
  50655. ecData.dataIndex = thisNode.dataIndex;
  50656. ecData.seriesIndex = seriesModel.seriesIndex;
  50657. bg.setShape({
  50658. x: 0,
  50659. y: 0,
  50660. width: thisWidth,
  50661. height: thisHeight,
  50662. r: borderRadius
  50663. });
  50664. if (thisInvisible) {
  50665. // If invisible, do not set visual, otherwise the element will
  50666. // change immediately before animation. We think it is OK to
  50667. // remain its origin color when moving out of the view window.
  50668. processInvisible(bg);
  50669. } else {
  50670. bg.invisible = false;
  50671. var style = thisNode.getVisual('style');
  50672. var visualBorderColor = style.stroke;
  50673. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  50674. normalStyle.fill = visualBorderColor;
  50675. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  50676. emphasisStyle.fill = itemStyleEmphasisModel.get('borderColor');
  50677. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  50678. blurStyle.fill = itemStyleBlurModel.get('borderColor');
  50679. var selectStyle = getStateItemStyle(itemStyleSelectModel);
  50680. selectStyle.fill = itemStyleSelectModel.get('borderColor');
  50681. if (useUpperLabel) {
  50682. var upperLabelWidth = thisWidth - 2 * borderWidth;
  50683. prepareText( // PENDING: convert ZRColor to ColorString for text.
  50684. bg, visualBorderColor, style.opacity, {
  50685. x: borderWidth,
  50686. y: 0,
  50687. width: upperLabelWidth,
  50688. height: upperHeight
  50689. });
  50690. } // For old bg.
  50691. else {
  50692. bg.removeTextContent();
  50693. }
  50694. bg.setStyle(normalStyle);
  50695. bg.ensureState('emphasis').style = emphasisStyle;
  50696. bg.ensureState('blur').style = blurStyle;
  50697. bg.ensureState('select').style = selectStyle;
  50698. setDefaultStateProxy(bg);
  50699. }
  50700. group.add(bg);
  50701. }
  50702. function renderContent(group, content) {
  50703. var ecData = getECData(content); // For tooltip.
  50704. ecData.dataIndex = thisNode.dataIndex;
  50705. ecData.seriesIndex = seriesModel.seriesIndex;
  50706. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  50707. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  50708. content.culling = true;
  50709. content.setShape({
  50710. x: borderWidth,
  50711. y: borderWidth,
  50712. width: contentWidth,
  50713. height: contentHeight,
  50714. r: borderRadius
  50715. });
  50716. if (thisInvisible) {
  50717. // If invisible, do not set visual, otherwise the element will
  50718. // change immediately before animation. We think it is OK to
  50719. // remain its origin color when moving out of the view window.
  50720. processInvisible(content);
  50721. } else {
  50722. content.invisible = false;
  50723. var nodeStyle = thisNode.getVisual('style');
  50724. var visualColor = nodeStyle.fill;
  50725. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  50726. normalStyle.fill = visualColor;
  50727. normalStyle.decal = nodeStyle.decal;
  50728. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  50729. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  50730. var selectStyle = getStateItemStyle(itemStyleSelectModel); // PENDING: convert ZRColor to ColorString for text.
  50731. prepareText(content, visualColor, nodeStyle.opacity, null);
  50732. content.setStyle(normalStyle);
  50733. content.ensureState('emphasis').style = emphasisStyle;
  50734. content.ensureState('blur').style = blurStyle;
  50735. content.ensureState('select').style = selectStyle;
  50736. setDefaultStateProxy(content);
  50737. }
  50738. group.add(content);
  50739. }
  50740. function processInvisible(element) {
  50741. // Delay invisible setting utill animation finished,
  50742. // avoid element vanish suddenly before animation.
  50743. !element.invisible && willInvisibleEls.push(element);
  50744. }
  50745. function prepareText(rectEl, visualColor, visualOpacity, // Can be null/undefined
  50746. upperLabelRect) {
  50747. var normalLabelModel = nodeModel.getModel(upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL);
  50748. var defaultText = convertOptionIdName(nodeModel.get('name'), null);
  50749. var isShow = normalLabelModel.getShallow('show');
  50750. setLabelStyle(rectEl, getLabelStatesModels(nodeModel, upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL), {
  50751. defaultText: isShow ? defaultText : null,
  50752. inheritColor: visualColor,
  50753. defaultOpacity: visualOpacity,
  50754. labelFetcher: seriesModel,
  50755. labelDataIndex: thisNode.dataIndex
  50756. });
  50757. var textEl = rectEl.getTextContent();
  50758. if (!textEl) {
  50759. return;
  50760. }
  50761. var textStyle = textEl.style;
  50762. var textPadding = normalizeCssArray(textStyle.padding || 0);
  50763. if (upperLabelRect) {
  50764. rectEl.setTextConfig({
  50765. layoutRect: upperLabelRect
  50766. });
  50767. textEl.disableLabelLayout = true;
  50768. }
  50769. textEl.beforeUpdate = function () {
  50770. var width = Math.max((upperLabelRect ? upperLabelRect.width : rectEl.shape.width) - textPadding[1] - textPadding[3], 0);
  50771. var height = Math.max((upperLabelRect ? upperLabelRect.height : rectEl.shape.height) - textPadding[0] - textPadding[2], 0);
  50772. if (textStyle.width !== width || textStyle.height !== height) {
  50773. textEl.setStyle({
  50774. width: width,
  50775. height: height
  50776. });
  50777. }
  50778. };
  50779. textStyle.truncateMinChar = 2;
  50780. textStyle.lineOverflow = 'truncate';
  50781. addDrillDownIcon(textStyle, upperLabelRect, thisLayout);
  50782. var textEmphasisState = textEl.getState('emphasis');
  50783. addDrillDownIcon(textEmphasisState ? textEmphasisState.style : null, upperLabelRect, thisLayout);
  50784. }
  50785. function addDrillDownIcon(style, upperLabelRect, thisLayout) {
  50786. var text = style ? style.text : null;
  50787. if (!upperLabelRect && thisLayout.isLeafRoot && text != null) {
  50788. var iconChar = seriesModel.get('drillDownIcon', true);
  50789. style.text = iconChar ? iconChar + ' ' + text : text;
  50790. }
  50791. }
  50792. function giveGraphic(storageName, Ctor, depth, z) {
  50793. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  50794. var lasts = lastsForAnimation[storageName];
  50795. if (element) {
  50796. // Remove from oldStorage
  50797. oldStorage[storageName][oldRawIndex] = null;
  50798. prepareAnimationWhenHasOld(lasts, element);
  50799. } // If invisible and no old element, do not create new element (for optimizing).
  50800. else if (!thisInvisible) {
  50801. element = new Ctor();
  50802. if (element instanceof Displayable) {
  50803. element.z2 = calculateZ2(depth, z);
  50804. }
  50805. prepareAnimationWhenNoOld(lasts, element);
  50806. } // Set to thisStorage
  50807. return thisStorage[storageName][thisRawIndex] = element;
  50808. }
  50809. function prepareAnimationWhenHasOld(lasts, element) {
  50810. var lastCfg = lasts[thisRawIndex] = {};
  50811. if (element instanceof Group$1) {
  50812. lastCfg.oldX = element.x;
  50813. lastCfg.oldY = element.y;
  50814. } else {
  50815. lastCfg.oldShape = extend({}, element.shape);
  50816. }
  50817. } // If a element is new, we need to find the animation start point carefully,
  50818. // otherwise it will looks strange when 'zoomToNode'.
  50819. function prepareAnimationWhenNoOld(lasts, element) {
  50820. var lastCfg = lasts[thisRawIndex] = {};
  50821. var parentNode = thisNode.parentNode;
  50822. var isGroup = element instanceof Group;
  50823. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  50824. var parentOldX = 0;
  50825. var parentOldY = 0; // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  50826. // For convenience, get old bounding rect from background.
  50827. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  50828. if (!reRoot && parentOldBg && parentOldBg.oldShape) {
  50829. parentOldX = parentOldBg.oldShape.width;
  50830. parentOldY = parentOldBg.oldShape.height;
  50831. } // When no parent old shape found, its parent is new too,
  50832. // so we can just use {x:0, y:0}.
  50833. if (isGroup) {
  50834. lastCfg.oldX = 0;
  50835. lastCfg.oldY = parentOldY;
  50836. } else {
  50837. lastCfg.oldShape = {
  50838. x: parentOldX,
  50839. y: parentOldY,
  50840. width: 0,
  50841. height: 0
  50842. };
  50843. }
  50844. } // Fade in, user can be aware that these nodes are new.
  50845. lastCfg.fadein = !isGroup;
  50846. }
  50847. } // We cannot set all background with the same z, because the behaviour of
  50848. // drill down and roll up differ background creation sequence from tree
  50849. // hierarchy sequence, which cause lower background elements to overlap
  50850. // upper ones. So we calculate z based on depth.
  50851. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  50852. // treemap with large z overlaps other components.
  50853. function calculateZ2(depth, z2InLevel) {
  50854. return depth * Z2_BASE + z2InLevel;
  50855. }
  50856. var each$3 = each;
  50857. var isObject$3 = isObject;
  50858. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  50859. var VisualMapping =
  50860. /** @class */
  50861. function () {
  50862. function VisualMapping(option) {
  50863. var mappingMethod = option.mappingMethod;
  50864. var visualType = option.type;
  50865. var thisOption = this.option = clone(option);
  50866. this.type = visualType;
  50867. this.mappingMethod = mappingMethod;
  50868. this._normalizeData = normalizers[mappingMethod];
  50869. var visualHandler = VisualMapping.visualHandlers[visualType];
  50870. this.applyVisual = visualHandler.applyVisual;
  50871. this.getColorMapper = visualHandler.getColorMapper;
  50872. this._normalizedToVisual = visualHandler._normalizedToVisual[mappingMethod];
  50873. if (mappingMethod === 'piecewise') {
  50874. normalizeVisualRange(thisOption);
  50875. preprocessForPiecewise(thisOption);
  50876. } else if (mappingMethod === 'category') {
  50877. thisOption.categories ? preprocessForSpecifiedCategory(thisOption) // categories is ordinal when thisOption.categories not specified,
  50878. // which need no more preprocess except normalize visual.
  50879. : normalizeVisualRange(thisOption, true);
  50880. } else {
  50881. // mappingMethod === 'linear' or 'fixed'
  50882. assert(mappingMethod !== 'linear' || thisOption.dataExtent);
  50883. normalizeVisualRange(thisOption);
  50884. }
  50885. }
  50886. VisualMapping.prototype.mapValueToVisual = function (value) {
  50887. var normalized = this._normalizeData(value);
  50888. return this._normalizedToVisual(normalized, value);
  50889. };
  50890. VisualMapping.prototype.getNormalizer = function () {
  50891. return bind(this._normalizeData, this);
  50892. };
  50893. /**
  50894. * List available visual types.
  50895. *
  50896. * @public
  50897. * @return {Array.<string>}
  50898. */
  50899. VisualMapping.listVisualTypes = function () {
  50900. return keys(VisualMapping.visualHandlers);
  50901. }; // /**
  50902. // * @public
  50903. // */
  50904. // static addVisualHandler(name, handler) {
  50905. // visualHandlers[name] = handler;
  50906. // }
  50907. /**
  50908. * @public
  50909. */
  50910. VisualMapping.isValidType = function (visualType) {
  50911. return VisualMapping.visualHandlers.hasOwnProperty(visualType);
  50912. };
  50913. /**
  50914. * Convenient method.
  50915. * Visual can be Object or Array or primary type.
  50916. */
  50917. VisualMapping.eachVisual = function (visual, callback, context) {
  50918. if (isObject(visual)) {
  50919. each(visual, callback, context);
  50920. } else {
  50921. callback.call(context, visual);
  50922. }
  50923. };
  50924. VisualMapping.mapVisual = function (visual, callback, context) {
  50925. var isPrimary;
  50926. var newVisual = isArray(visual) ? [] : isObject(visual) ? {} : (isPrimary = true, null);
  50927. VisualMapping.eachVisual(visual, function (v, key) {
  50928. var newVal = callback.call(context, v, key);
  50929. isPrimary ? newVisual = newVal : newVisual[key] = newVal;
  50930. });
  50931. return newVisual;
  50932. };
  50933. /**
  50934. * Retrieve visual properties from given object.
  50935. */
  50936. VisualMapping.retrieveVisuals = function (obj) {
  50937. var ret = {};
  50938. var hasVisual;
  50939. obj && each$3(VisualMapping.visualHandlers, function (h, visualType) {
  50940. if (obj.hasOwnProperty(visualType)) {
  50941. ret[visualType] = obj[visualType];
  50942. hasVisual = true;
  50943. }
  50944. });
  50945. return hasVisual ? ret : null;
  50946. };
  50947. /**
  50948. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  50949. *
  50950. * @public
  50951. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  50952. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  50953. * @return {Array.<string>} Sorted visual types.
  50954. */
  50955. VisualMapping.prepareVisualTypes = function (visualTypes) {
  50956. if (isArray(visualTypes)) {
  50957. visualTypes = visualTypes.slice();
  50958. } else if (isObject$3(visualTypes)) {
  50959. var types_1 = [];
  50960. each$3(visualTypes, function (item, type) {
  50961. types_1.push(type);
  50962. });
  50963. visualTypes = types_1;
  50964. } else {
  50965. return [];
  50966. }
  50967. visualTypes.sort(function (type1, type2) {
  50968. // color should be front of colorSaturation, colorAlpha, ...
  50969. // symbol and symbolSize do not matter.
  50970. return type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0 ? 1 : -1;
  50971. });
  50972. return visualTypes;
  50973. };
  50974. /**
  50975. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  50976. * Other visuals are only depends on themself.
  50977. */
  50978. VisualMapping.dependsOn = function (visualType1, visualType2) {
  50979. return visualType2 === 'color' ? !!(visualType1 && visualType1.indexOf(visualType2) === 0) : visualType1 === visualType2;
  50980. };
  50981. /**
  50982. * @param value
  50983. * @param pieceList [{value: ..., interval: [min, max]}, ...]
  50984. * Always from small to big.
  50985. * @param findClosestWhenOutside Default to be false
  50986. * @return index
  50987. */
  50988. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  50989. var possibleI;
  50990. var abs = Infinity; // value has the higher priority.
  50991. for (var i = 0, len = pieceList.length; i < len; i++) {
  50992. var pieceValue = pieceList[i].value;
  50993. if (pieceValue != null) {
  50994. if (pieceValue === value // FIXME
  50995. // It is supposed to compare value according to value type of dimension,
  50996. // but currently value type can exactly be string or number.
  50997. // Compromise for numeric-like string (like '12'), especially
  50998. // in the case that visualMap.categories is ['22', '33'].
  50999. || isString(pieceValue) && pieceValue === value + '') {
  51000. return i;
  51001. }
  51002. findClosestWhenOutside && updatePossible(pieceValue, i);
  51003. }
  51004. }
  51005. for (var i = 0, len = pieceList.length; i < len; i++) {
  51006. var piece = pieceList[i];
  51007. var interval = piece.interval;
  51008. var close_1 = piece.close;
  51009. if (interval) {
  51010. if (interval[0] === -Infinity) {
  51011. if (littleThan(close_1[1], value, interval[1])) {
  51012. return i;
  51013. }
  51014. } else if (interval[1] === Infinity) {
  51015. if (littleThan(close_1[0], interval[0], value)) {
  51016. return i;
  51017. }
  51018. } else if (littleThan(close_1[0], interval[0], value) && littleThan(close_1[1], value, interval[1])) {
  51019. return i;
  51020. }
  51021. findClosestWhenOutside && updatePossible(interval[0], i);
  51022. findClosestWhenOutside && updatePossible(interval[1], i);
  51023. }
  51024. }
  51025. if (findClosestWhenOutside) {
  51026. return value === Infinity ? pieceList.length - 1 : value === -Infinity ? 0 : possibleI;
  51027. }
  51028. function updatePossible(val, index) {
  51029. var newAbs = Math.abs(val - value);
  51030. if (newAbs < abs) {
  51031. abs = newAbs;
  51032. possibleI = index;
  51033. }
  51034. }
  51035. };
  51036. VisualMapping.visualHandlers = {
  51037. color: {
  51038. applyVisual: makeApplyVisual('color'),
  51039. getColorMapper: function () {
  51040. var thisOption = this.option;
  51041. return bind(thisOption.mappingMethod === 'category' ? function (value, isNormalized) {
  51042. !isNormalized && (value = this._normalizeData(value));
  51043. return doMapCategory.call(this, value);
  51044. } : function (value, isNormalized, out) {
  51045. // If output rgb array
  51046. // which will be much faster and useful in pixel manipulation
  51047. var returnRGBArray = !!out;
  51048. !isNormalized && (value = this._normalizeData(value));
  51049. out = fastLerp(value, thisOption.parsedVisual, out);
  51050. return returnRGBArray ? out : stringify(out, 'rgba');
  51051. }, this);
  51052. },
  51053. _normalizedToVisual: {
  51054. linear: function (normalized) {
  51055. return stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  51056. },
  51057. category: doMapCategory,
  51058. piecewise: function (normalized, value) {
  51059. var result = getSpecifiedVisual.call(this, value);
  51060. if (result == null) {
  51061. result = stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  51062. }
  51063. return result;
  51064. },
  51065. fixed: doMapFixed
  51066. }
  51067. },
  51068. colorHue: makePartialColorVisualHandler(function (color$1, value) {
  51069. return modifyHSL(color$1, value);
  51070. }),
  51071. colorSaturation: makePartialColorVisualHandler(function (color$1, value) {
  51072. return modifyHSL(color$1, null, value);
  51073. }),
  51074. colorLightness: makePartialColorVisualHandler(function (color$1, value) {
  51075. return modifyHSL(color$1, null, null, value);
  51076. }),
  51077. colorAlpha: makePartialColorVisualHandler(function (color$1, value) {
  51078. return modifyAlpha(color$1, value);
  51079. }),
  51080. decal: {
  51081. applyVisual: makeApplyVisual('decal'),
  51082. _normalizedToVisual: {
  51083. linear: null,
  51084. category: doMapCategory,
  51085. piecewise: null,
  51086. fixed: null
  51087. }
  51088. },
  51089. opacity: {
  51090. applyVisual: makeApplyVisual('opacity'),
  51091. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  51092. },
  51093. liftZ: {
  51094. applyVisual: makeApplyVisual('liftZ'),
  51095. _normalizedToVisual: {
  51096. linear: doMapFixed,
  51097. category: doMapFixed,
  51098. piecewise: doMapFixed,
  51099. fixed: doMapFixed
  51100. }
  51101. },
  51102. symbol: {
  51103. applyVisual: function (value, getter, setter) {
  51104. var symbolCfg = this.mapValueToVisual(value);
  51105. setter('symbol', symbolCfg);
  51106. },
  51107. _normalizedToVisual: {
  51108. linear: doMapToArray,
  51109. category: doMapCategory,
  51110. piecewise: function (normalized, value) {
  51111. var result = getSpecifiedVisual.call(this, value);
  51112. if (result == null) {
  51113. result = doMapToArray.call(this, normalized);
  51114. }
  51115. return result;
  51116. },
  51117. fixed: doMapFixed
  51118. }
  51119. },
  51120. symbolSize: {
  51121. applyVisual: makeApplyVisual('symbolSize'),
  51122. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  51123. }
  51124. };
  51125. return VisualMapping;
  51126. }();
  51127. function preprocessForPiecewise(thisOption) {
  51128. var pieceList = thisOption.pieceList;
  51129. thisOption.hasSpecialVisual = false;
  51130. each(pieceList, function (piece, index) {
  51131. piece.originIndex = index; // piece.visual is "result visual value" but not
  51132. // a visual range, so it does not need to be normalized.
  51133. if (piece.visual != null) {
  51134. thisOption.hasSpecialVisual = true;
  51135. }
  51136. });
  51137. }
  51138. function preprocessForSpecifiedCategory(thisOption) {
  51139. // Hash categories.
  51140. var categories = thisOption.categories;
  51141. var categoryMap = thisOption.categoryMap = {};
  51142. var visual = thisOption.visual;
  51143. each$3(categories, function (cate, index) {
  51144. categoryMap[cate] = index;
  51145. }); // Process visual map input.
  51146. if (!isArray(visual)) {
  51147. var visualArr_1 = [];
  51148. if (isObject(visual)) {
  51149. each$3(visual, function (v, cate) {
  51150. var index = categoryMap[cate];
  51151. visualArr_1[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  51152. });
  51153. } else {
  51154. // Is primary type, represents default visual.
  51155. visualArr_1[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  51156. }
  51157. visual = setVisualToOption(thisOption, visualArr_1);
  51158. } // Remove categories that has no visual,
  51159. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  51160. for (var i = categories.length - 1; i >= 0; i--) {
  51161. if (visual[i] == null) {
  51162. delete categoryMap[categories[i]];
  51163. categories.pop();
  51164. }
  51165. }
  51166. }
  51167. function normalizeVisualRange(thisOption, isCategory) {
  51168. var visual = thisOption.visual;
  51169. var visualArr = [];
  51170. if (isObject(visual)) {
  51171. each$3(visual, function (v) {
  51172. visualArr.push(v);
  51173. });
  51174. } else if (visual != null) {
  51175. visualArr.push(visual);
  51176. }
  51177. var doNotNeedPair = {
  51178. color: 1,
  51179. symbol: 1
  51180. };
  51181. if (!isCategory && visualArr.length === 1 && !doNotNeedPair.hasOwnProperty(thisOption.type)) {
  51182. // Do not care visualArr.length === 0, which is illegal.
  51183. visualArr[1] = visualArr[0];
  51184. }
  51185. setVisualToOption(thisOption, visualArr);
  51186. }
  51187. function makePartialColorVisualHandler(applyValue) {
  51188. return {
  51189. applyVisual: function (value, getter, setter) {
  51190. // Only used in HSL
  51191. var colorChannel = this.mapValueToVisual(value); // Must not be array value
  51192. setter('color', applyValue(getter('color'), colorChannel));
  51193. },
  51194. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  51195. };
  51196. }
  51197. function doMapToArray(normalized) {
  51198. var visual = this.option.visual;
  51199. return visual[Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))] || {}; // TODO {}?
  51200. }
  51201. function makeApplyVisual(visualType) {
  51202. return function (value, getter, setter) {
  51203. setter(visualType, this.mapValueToVisual(value));
  51204. };
  51205. }
  51206. function doMapCategory(normalized) {
  51207. var visual = this.option.visual;
  51208. return visual[this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX ? normalized % visual.length : normalized];
  51209. }
  51210. function doMapFixed() {
  51211. // visual will be convert to array.
  51212. return this.option.visual[0];
  51213. }
  51214. /**
  51215. * Create mapped to numeric visual
  51216. */
  51217. function createNormalizedToNumericVisual(sourceExtent) {
  51218. return {
  51219. linear: function (normalized) {
  51220. return linearMap(normalized, sourceExtent, this.option.visual, true);
  51221. },
  51222. category: doMapCategory,
  51223. piecewise: function (normalized, value) {
  51224. var result = getSpecifiedVisual.call(this, value);
  51225. if (result == null) {
  51226. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  51227. }
  51228. return result;
  51229. },
  51230. fixed: doMapFixed
  51231. };
  51232. }
  51233. function getSpecifiedVisual(value) {
  51234. var thisOption = this.option;
  51235. var pieceList = thisOption.pieceList;
  51236. if (thisOption.hasSpecialVisual) {
  51237. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  51238. var piece = pieceList[pieceIndex];
  51239. if (piece && piece.visual) {
  51240. return piece.visual[this.type];
  51241. }
  51242. }
  51243. }
  51244. function setVisualToOption(thisOption, visualArr) {
  51245. thisOption.visual = visualArr;
  51246. if (thisOption.type === 'color') {
  51247. thisOption.parsedVisual = map(visualArr, function (item) {
  51248. var color$1 = parse(item);
  51249. if (!color$1 && "development" !== 'production') {
  51250. warn("'" + item + "' is an illegal color, fallback to '#000000'", true);
  51251. }
  51252. return color$1 || [0, 0, 0, 1];
  51253. });
  51254. }
  51255. return visualArr;
  51256. }
  51257. /**
  51258. * Normalizers by mapping methods.
  51259. */
  51260. var normalizers = {
  51261. linear: function (value) {
  51262. return linearMap(value, this.option.dataExtent, [0, 1], true);
  51263. },
  51264. piecewise: function (value) {
  51265. var pieceList = this.option.pieceList;
  51266. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  51267. if (pieceIndex != null) {
  51268. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  51269. }
  51270. },
  51271. category: function (value) {
  51272. var index = this.option.categories ? this.option.categoryMap[value] : value; // ordinal value
  51273. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  51274. },
  51275. fixed: noop
  51276. };
  51277. function littleThan(close, a, b) {
  51278. return close ? a <= b : a < b;
  51279. }
  51280. var ITEM_STYLE_NORMAL = 'itemStyle';
  51281. var inner$9 = makeInner();
  51282. var treemapVisual = {
  51283. seriesType: 'treemap',
  51284. reset: function (seriesModel) {
  51285. var tree = seriesModel.getData().tree;
  51286. var root = tree.root;
  51287. if (root.isRemoved()) {
  51288. return;
  51289. }
  51290. travelTree(root, // Visual should calculate from tree root but not view root.
  51291. {}, seriesModel.getViewRoot().getAncestors(), seriesModel);
  51292. }
  51293. };
  51294. function travelTree(node, designatedVisual, viewRootAncestors, seriesModel) {
  51295. var nodeModel = node.getModel();
  51296. var nodeLayout = node.getLayout();
  51297. var data = node.hostTree.data; // Optimize
  51298. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  51299. return;
  51300. }
  51301. var nodeItemStyleModel = nodeModel.getModel(ITEM_STYLE_NORMAL);
  51302. var visuals = buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel);
  51303. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style'); // calculate border color
  51304. var borderColor = nodeItemStyleModel.get('borderColor');
  51305. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  51306. var thisNodeColor;
  51307. if (borderColorSaturation != null) {
  51308. // For performance, do not always execute 'calculateColor'.
  51309. thisNodeColor = calculateColor(visuals);
  51310. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  51311. }
  51312. existsStyle.stroke = borderColor;
  51313. var viewChildren = node.viewChildren;
  51314. if (!viewChildren || !viewChildren.length) {
  51315. thisNodeColor = calculateColor(visuals); // Apply visual to this node.
  51316. existsStyle.fill = thisNodeColor;
  51317. } else {
  51318. var mapping_1 = buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren); // Designate visual to children.
  51319. each(viewChildren, function (child, index) {
  51320. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  51321. if (child.depth >= viewRootAncestors.length || child === viewRootAncestors[child.depth]) {
  51322. var childVisual = mapVisual(nodeModel, visuals, child, index, mapping_1, seriesModel);
  51323. travelTree(child, childVisual, viewRootAncestors, seriesModel);
  51324. }
  51325. });
  51326. }
  51327. }
  51328. function buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel) {
  51329. var visuals = extend({}, designatedVisual);
  51330. var designatedVisualItemStyle = seriesModel.designatedVisualItemStyle;
  51331. each(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  51332. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  51333. designatedVisualItemStyle[visualName] = designatedVisual[visualName];
  51334. var val = nodeItemStyleModel.get(visualName);
  51335. designatedVisualItemStyle[visualName] = null;
  51336. val != null && (visuals[visualName] = val);
  51337. });
  51338. return visuals;
  51339. }
  51340. function calculateColor(visuals) {
  51341. var color = getValueVisualDefine(visuals, 'color');
  51342. if (color) {
  51343. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  51344. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  51345. if (colorSaturation) {
  51346. color = modifyHSL(color, null, null, colorSaturation);
  51347. }
  51348. if (colorAlpha) {
  51349. color = modifyAlpha(color, colorAlpha);
  51350. }
  51351. return color;
  51352. }
  51353. }
  51354. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  51355. return thisNodeColor != null // Can only be string
  51356. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation) : null;
  51357. }
  51358. function getValueVisualDefine(visuals, name) {
  51359. var value = visuals[name];
  51360. if (value != null && value !== 'none') {
  51361. return value;
  51362. }
  51363. }
  51364. function buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren) {
  51365. if (!viewChildren || !viewChildren.length) {
  51366. return;
  51367. }
  51368. var rangeVisual = getRangeVisual(nodeModel, 'color') || visuals.color != null && visuals.color !== 'none' && (getRangeVisual(nodeModel, 'colorAlpha') || getRangeVisual(nodeModel, 'colorSaturation'));
  51369. if (!rangeVisual) {
  51370. return;
  51371. }
  51372. var visualMin = nodeModel.get('visualMin');
  51373. var visualMax = nodeModel.get('visualMax');
  51374. var dataExtent = nodeLayout.dataExtent.slice();
  51375. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  51376. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  51377. var colorMappingBy = nodeModel.get('colorMappingBy');
  51378. var opt = {
  51379. type: rangeVisual.name,
  51380. dataExtent: dataExtent,
  51381. visual: rangeVisual.range
  51382. };
  51383. if (opt.type === 'color' && (colorMappingBy === 'index' || colorMappingBy === 'id')) {
  51384. opt.mappingMethod = 'category';
  51385. opt.loop = true; // categories is ordinal, so do not set opt.categories.
  51386. } else {
  51387. opt.mappingMethod = 'linear';
  51388. }
  51389. var mapping = new VisualMapping(opt);
  51390. inner$9(mapping).drColorMappingBy = colorMappingBy;
  51391. return mapping;
  51392. } // Notice: If we don't have the attribute 'colorRange', but only use
  51393. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  51394. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  51395. // this problem will be encountered:
  51396. // If a level-1 node doesn't have children, and its siblings have children,
  51397. // and colorRange is set on level-1, then the node cannot be colored.
  51398. // So we separate 'colorRange' and 'color' to different attributes.
  51399. function getRangeVisual(nodeModel, name) {
  51400. // 'colorRange', 'colorARange', 'colorSRange'.
  51401. // If not exists on this node, fetch from levels and series.
  51402. var range = nodeModel.get(name);
  51403. return isArray(range) && range.length ? {
  51404. name: name,
  51405. range: range
  51406. } : null;
  51407. }
  51408. function mapVisual(nodeModel, visuals, child, index, mapping, seriesModel) {
  51409. var childVisuals = extend({}, visuals);
  51410. if (mapping) {
  51411. // Only support color, colorAlpha, colorSaturation.
  51412. var mappingType = mapping.type;
  51413. var colorMappingBy = mappingType === 'color' && inner$9(mapping).drColorMappingBy;
  51414. var value = colorMappingBy === 'index' ? index : colorMappingBy === 'id' ? seriesModel.mapIdToIndex(child.getId()) : child.getValue(nodeModel.get('visualDimension'));
  51415. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  51416. }
  51417. return childVisuals;
  51418. }
  51419. var mathMax$7 = Math.max;
  51420. var mathMin$7 = Math.min;
  51421. var retrieveValue = retrieve;
  51422. var each$4 = each;
  51423. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  51424. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  51425. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  51426. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  51427. /**
  51428. * @public
  51429. */
  51430. var treemapLayout = {
  51431. seriesType: 'treemap',
  51432. reset: function (seriesModel, ecModel, api, payload) {
  51433. // Layout result in each node:
  51434. // {x, y, width, height, area, borderWidth}
  51435. var ecWidth = api.getWidth();
  51436. var ecHeight = api.getHeight();
  51437. var seriesOption = seriesModel.option;
  51438. var layoutInfo = getLayoutRect(seriesModel.getBoxLayoutParams(), {
  51439. width: api.getWidth(),
  51440. height: api.getHeight()
  51441. });
  51442. var size = seriesOption.size || []; // Compatible with ec2.
  51443. var containerWidth = parsePercent$1(retrieveValue(layoutInfo.width, size[0]), ecWidth);
  51444. var containerHeight = parsePercent$1(retrieveValue(layoutInfo.height, size[1]), ecHeight); // Fetch payload info.
  51445. var payloadType = payload && payload.type;
  51446. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  51447. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  51448. var rootRect = payloadType === 'treemapRender' || payloadType === 'treemapMove' ? payload.rootRect : null;
  51449. var viewRoot = seriesModel.getViewRoot();
  51450. var viewAbovePath = getPathToRoot(viewRoot);
  51451. if (payloadType !== 'treemapMove') {
  51452. var rootSize = payloadType === 'treemapZoomToNode' ? estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) : rootRect ? [rootRect.width, rootRect.height] : [containerWidth, containerHeight];
  51453. var sort_1 = seriesOption.sort;
  51454. if (sort_1 && sort_1 !== 'asc' && sort_1 !== 'desc') {
  51455. // Default to be desc order.
  51456. sort_1 = 'desc';
  51457. }
  51458. var options = {
  51459. squareRatio: seriesOption.squareRatio,
  51460. sort: sort_1,
  51461. leafDepth: seriesOption.leafDepth
  51462. }; // layout should be cleared because using updateView but not update.
  51463. viewRoot.hostTree.clearLayouts(); // TODO
  51464. // optimize: if out of view clip, do not layout.
  51465. // But take care that if do not render node out of view clip,
  51466. // how to calculate start po
  51467. var viewRootLayout_1 = {
  51468. x: 0,
  51469. y: 0,
  51470. width: rootSize[0],
  51471. height: rootSize[1],
  51472. area: rootSize[0] * rootSize[1]
  51473. };
  51474. viewRoot.setLayout(viewRootLayout_1);
  51475. squarify(viewRoot, options, false, 0); // Supplement layout.
  51476. viewRootLayout_1 = viewRoot.getLayout();
  51477. each$4(viewAbovePath, function (node, index) {
  51478. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  51479. node.setLayout(extend({
  51480. dataExtent: [childValue, childValue],
  51481. borderWidth: 0,
  51482. upperHeight: 0
  51483. }, viewRootLayout_1));
  51484. });
  51485. }
  51486. var treeRoot = seriesModel.getData().tree.root;
  51487. treeRoot.setLayout(calculateRootPosition(layoutInfo, rootRect, targetInfo), true);
  51488. seriesModel.setLayoutInfo(layoutInfo); // FIXME
  51489. // 现在没有clip功能,暂时取ec高宽。
  51490. prunning(treeRoot, // Transform to base element coordinate system.
  51491. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight), viewAbovePath, viewRoot, 0);
  51492. }
  51493. };
  51494. /**
  51495. * Layout treemap with squarify algorithm.
  51496. * The original presentation of this algorithm
  51497. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  51498. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  51499. * The implementation of this algorithm was originally copied from "d3.js"
  51500. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  51501. * with some modifications made for this program.
  51502. * See the license statement at the head of this file.
  51503. *
  51504. * @protected
  51505. * @param {module:echarts/data/Tree~TreeNode} node
  51506. * @param {Object} options
  51507. * @param {string} options.sort 'asc' or 'desc'
  51508. * @param {number} options.squareRatio
  51509. * @param {boolean} hideChildren
  51510. * @param {number} depth
  51511. */
  51512. function squarify(node, options, hideChildren, depth) {
  51513. var width;
  51514. var height;
  51515. if (node.isRemoved()) {
  51516. return;
  51517. }
  51518. var thisLayout = node.getLayout();
  51519. width = thisLayout.width;
  51520. height = thisLayout.height; // Considering border and gap
  51521. var nodeModel = node.getModel();
  51522. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  51523. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  51524. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  51525. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  51526. var layoutOffset = borderWidth - halfGapWidth;
  51527. var layoutOffsetUpper = upperHeight - halfGapWidth;
  51528. node.setLayout({
  51529. borderWidth: borderWidth,
  51530. upperHeight: upperHeight,
  51531. upperLabelHeight: upperLabelHeight
  51532. }, true);
  51533. width = mathMax$7(width - 2 * layoutOffset, 0);
  51534. height = mathMax$7(height - layoutOffset - layoutOffsetUpper, 0);
  51535. var totalArea = width * height;
  51536. var viewChildren = initChildren(node, nodeModel, totalArea, options, hideChildren, depth);
  51537. if (!viewChildren.length) {
  51538. return;
  51539. }
  51540. var rect = {
  51541. x: layoutOffset,
  51542. y: layoutOffsetUpper,
  51543. width: width,
  51544. height: height
  51545. };
  51546. var rowFixedLength = mathMin$7(width, height);
  51547. var best = Infinity; // the best row score so far
  51548. var row = [];
  51549. row.area = 0;
  51550. for (var i = 0, len = viewChildren.length; i < len;) {
  51551. var child = viewChildren[i];
  51552. row.push(child);
  51553. row.area += child.getLayout().area;
  51554. var score = worst(row, rowFixedLength, options.squareRatio); // continue with this orientation
  51555. if (score <= best) {
  51556. i++;
  51557. best = score;
  51558. } // abort, and try a different orientation
  51559. else {
  51560. row.area -= row.pop().getLayout().area;
  51561. position(row, rowFixedLength, rect, halfGapWidth, false);
  51562. rowFixedLength = mathMin$7(rect.width, rect.height);
  51563. row.length = row.area = 0;
  51564. best = Infinity;
  51565. }
  51566. }
  51567. if (row.length) {
  51568. position(row, rowFixedLength, rect, halfGapWidth, true);
  51569. }
  51570. if (!hideChildren) {
  51571. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  51572. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  51573. hideChildren = true;
  51574. }
  51575. }
  51576. for (var i = 0, len = viewChildren.length; i < len; i++) {
  51577. squarify(viewChildren[i], options, hideChildren, depth + 1);
  51578. }
  51579. }
  51580. /**
  51581. * Set area to each child, and calculate data extent for visual coding.
  51582. */
  51583. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  51584. var viewChildren = node.children || [];
  51585. var orderBy = options.sort;
  51586. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  51587. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth; // leafDepth has higher priority.
  51588. if (hideChildren && !overLeafDepth) {
  51589. return node.viewChildren = [];
  51590. } // Sort children, order by desc.
  51591. viewChildren = filter(viewChildren, function (child) {
  51592. return !child.isRemoved();
  51593. });
  51594. sort$1(viewChildren, orderBy);
  51595. var info = statistic(nodeModel, viewChildren, orderBy);
  51596. if (info.sum === 0) {
  51597. return node.viewChildren = [];
  51598. }
  51599. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  51600. if (info.sum === 0) {
  51601. return node.viewChildren = [];
  51602. } // Set area to each child.
  51603. for (var i = 0, len = viewChildren.length; i < len; i++) {
  51604. var area = viewChildren[i].getValue() / info.sum * totalArea; // Do not use setLayout({...}, true), because it is needed to clear last layout.
  51605. viewChildren[i].setLayout({
  51606. area: area
  51607. });
  51608. }
  51609. if (overLeafDepth) {
  51610. viewChildren.length && node.setLayout({
  51611. isLeafRoot: true
  51612. }, true);
  51613. viewChildren.length = 0;
  51614. }
  51615. node.viewChildren = viewChildren;
  51616. node.setLayout({
  51617. dataExtent: info.dataExtent
  51618. }, true);
  51619. return viewChildren;
  51620. }
  51621. /**
  51622. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  51623. */
  51624. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  51625. // visibleMin is not supported yet when no option.sort.
  51626. if (!orderBy) {
  51627. return sum;
  51628. }
  51629. var visibleMin = nodeModel.get('visibleMin');
  51630. var len = orderedChildren.length;
  51631. var deletePoint = len; // Always travel from little value to big value.
  51632. for (var i = len - 1; i >= 0; i--) {
  51633. var value = orderedChildren[orderBy === 'asc' ? len - i - 1 : i].getValue();
  51634. if (value / sum * totalArea < visibleMin) {
  51635. deletePoint = i;
  51636. sum -= value;
  51637. }
  51638. }
  51639. orderBy === 'asc' ? orderedChildren.splice(0, len - deletePoint) : orderedChildren.splice(deletePoint, len - deletePoint);
  51640. return sum;
  51641. }
  51642. /**
  51643. * Sort
  51644. */
  51645. function sort$1(viewChildren, orderBy) {
  51646. if (orderBy) {
  51647. viewChildren.sort(function (a, b) {
  51648. var diff = orderBy === 'asc' ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  51649. return diff === 0 ? orderBy === 'asc' ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex : diff;
  51650. });
  51651. }
  51652. return viewChildren;
  51653. }
  51654. /**
  51655. * Statistic
  51656. */
  51657. function statistic(nodeModel, children, orderBy) {
  51658. // Calculate sum.
  51659. var sum = 0;
  51660. for (var i = 0, len = children.length; i < len; i++) {
  51661. sum += children[i].getValue();
  51662. } // Statistic data extent for latter visual coding.
  51663. // Notice: data extent should be calculate based on raw children
  51664. // but not filtered view children, otherwise visual mapping will not
  51665. // be stable when zoom (where children is filtered by visibleMin).
  51666. var dimension = nodeModel.get('visualDimension');
  51667. var dataExtent; // The same as area dimension.
  51668. if (!children || !children.length) {
  51669. dataExtent = [NaN, NaN];
  51670. } else if (dimension === 'value' && orderBy) {
  51671. dataExtent = [children[children.length - 1].getValue(), children[0].getValue()];
  51672. orderBy === 'asc' && dataExtent.reverse();
  51673. } // Other dimension.
  51674. else {
  51675. dataExtent = [Infinity, -Infinity];
  51676. each$4(children, function (child) {
  51677. var value = child.getValue(dimension);
  51678. value < dataExtent[0] && (dataExtent[0] = value);
  51679. value > dataExtent[1] && (dataExtent[1] = value);
  51680. });
  51681. }
  51682. return {
  51683. sum: sum,
  51684. dataExtent: dataExtent
  51685. };
  51686. }
  51687. /**
  51688. * Computes the score for the specified row,
  51689. * as the worst aspect ratio.
  51690. */
  51691. function worst(row, rowFixedLength, ratio) {
  51692. var areaMax = 0;
  51693. var areaMin = Infinity;
  51694. for (var i = 0, area = void 0, len = row.length; i < len; i++) {
  51695. area = row[i].getLayout().area;
  51696. if (area) {
  51697. area < areaMin && (areaMin = area);
  51698. area > areaMax && (areaMax = area);
  51699. }
  51700. }
  51701. var squareArea = row.area * row.area;
  51702. var f = rowFixedLength * rowFixedLength * ratio;
  51703. return squareArea ? mathMax$7(f * areaMax / squareArea, squareArea / (f * areaMin)) : Infinity;
  51704. }
  51705. /**
  51706. * Positions the specified row of nodes. Modifies `rect`.
  51707. */
  51708. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  51709. // When rowFixedLength === rect.width,
  51710. // it is horizontal subdivision,
  51711. // rowFixedLength is the width of the subdivision,
  51712. // rowOtherLength is the height of the subdivision,
  51713. // and nodes will be positioned from left to right.
  51714. // wh[idx0WhenH] means: when horizontal,
  51715. // wh[idx0WhenH] => wh[0] => 'width'.
  51716. // xy[idx1WhenH] => xy[1] => 'y'.
  51717. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  51718. var idx1WhenH = 1 - idx0WhenH;
  51719. var xy = ['x', 'y'];
  51720. var wh = ['width', 'height'];
  51721. var last = rect[xy[idx0WhenH]];
  51722. var rowOtherLength = rowFixedLength ? row.area / rowFixedLength : 0;
  51723. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  51724. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  51725. }
  51726. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  51727. var node = row[i];
  51728. var nodeLayout = {};
  51729. var step = rowOtherLength ? node.getLayout().area / rowOtherLength : 0;
  51730. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$7(rowOtherLength - 2 * halfGapWidth, 0); // We use Math.max/min to avoid negative width/height when considering gap width.
  51731. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  51732. var modWH = i === rowLen - 1 || remain < step ? remain : step;
  51733. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$7(modWH - 2 * halfGapWidth, 0);
  51734. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$7(halfGapWidth, wh1 / 2);
  51735. nodeLayout[xy[idx0WhenH]] = last + mathMin$7(halfGapWidth, wh0 / 2);
  51736. last += modWH;
  51737. node.setLayout(nodeLayout, true);
  51738. }
  51739. rect[xy[idx1WhenH]] += rowOtherLength;
  51740. rect[wh[idx1WhenH]] -= rowOtherLength;
  51741. } // Return [containerWidth, containerHeight] as default.
  51742. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  51743. // If targetInfo.node exists, we zoom to the node,
  51744. // so estimate whole width and height by target node.
  51745. var currNode = (targetInfo || {}).node;
  51746. var defaultSize = [containerWidth, containerHeight];
  51747. if (!currNode || currNode === viewRoot) {
  51748. return defaultSize;
  51749. }
  51750. var parent;
  51751. var viewArea = containerWidth * containerHeight;
  51752. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  51753. while (parent = currNode.parentNode) {
  51754. // jshint ignore:line
  51755. var sum = 0;
  51756. var siblings = parent.children;
  51757. for (var i = 0, len = siblings.length; i < len; i++) {
  51758. sum += siblings[i].getValue();
  51759. }
  51760. var currNodeValue = currNode.getValue();
  51761. if (currNodeValue === 0) {
  51762. return defaultSize;
  51763. }
  51764. area *= sum / currNodeValue; // Considering border, suppose aspect ratio is 1.
  51765. var parentModel = parent.getModel();
  51766. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  51767. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel));
  51768. area += 4 * borderWidth * borderWidth + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  51769. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  51770. currNode = parent;
  51771. }
  51772. area < viewArea && (area = viewArea);
  51773. var scale = Math.pow(area / viewArea, 0.5);
  51774. return [containerWidth * scale, containerHeight * scale];
  51775. } // Root position based on coord of containerGroup
  51776. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  51777. if (rootRect) {
  51778. return {
  51779. x: rootRect.x,
  51780. y: rootRect.y
  51781. };
  51782. }
  51783. var defaultPosition = {
  51784. x: 0,
  51785. y: 0
  51786. };
  51787. if (!targetInfo) {
  51788. return defaultPosition;
  51789. } // If targetInfo is fetched by 'retrieveTargetInfo',
  51790. // old tree and new tree are the same tree,
  51791. // so the node still exists and we can visit it.
  51792. var targetNode = targetInfo.node;
  51793. var layout = targetNode.getLayout();
  51794. if (!layout) {
  51795. return defaultPosition;
  51796. } // Transform coord from local to container.
  51797. var targetCenter = [layout.width / 2, layout.height / 2];
  51798. var node = targetNode;
  51799. while (node) {
  51800. var nodeLayout = node.getLayout();
  51801. targetCenter[0] += nodeLayout.x;
  51802. targetCenter[1] += nodeLayout.y;
  51803. node = node.parentNode;
  51804. }
  51805. return {
  51806. x: layoutInfo.width / 2 - targetCenter[0],
  51807. y: layoutInfo.height / 2 - targetCenter[1]
  51808. };
  51809. } // Mark nodes visible for prunning when visual coding and rendering.
  51810. // Prunning depends on layout and root position, so we have to do it after layout.
  51811. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  51812. var nodeLayout = node.getLayout();
  51813. var nodeInViewAbovePath = viewAbovePath[depth];
  51814. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  51815. if (nodeInViewAbovePath && !isAboveViewRoot || depth === viewAbovePath.length && node !== viewRoot) {
  51816. return;
  51817. }
  51818. node.setLayout({
  51819. // isInView means: viewRoot sub tree + viewAbovePath
  51820. isInView: true,
  51821. // invisible only means: outside view clip so that the node can not
  51822. // see but still layout for animation preparation but not render.
  51823. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  51824. isAboveViewRoot: isAboveViewRoot
  51825. }, true); // Transform to child coordinate.
  51826. var childClipRect = new BoundingRect(clipRect.x - nodeLayout.x, clipRect.y - nodeLayout.y, clipRect.width, clipRect.height);
  51827. each$4(node.viewChildren || [], function (child) {
  51828. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  51829. });
  51830. }
  51831. function getUpperLabelHeight(model) {
  51832. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  51833. }
  51834. function install$c(registers) {
  51835. registers.registerSeriesModel(TreemapSeriesModel);
  51836. registers.registerChartView(TreemapView);
  51837. registers.registerVisual(treemapVisual);
  51838. registers.registerLayout(treemapLayout);
  51839. installTreemapAction(registers);
  51840. }
  51841. function categoryFilter(ecModel) {
  51842. var legendModels = ecModel.findComponents({
  51843. mainType: 'legend'
  51844. });
  51845. if (!legendModels || !legendModels.length) {
  51846. return;
  51847. }
  51848. ecModel.eachSeriesByType('graph', function (graphSeries) {
  51849. var categoriesData = graphSeries.getCategoriesData();
  51850. var graph = graphSeries.getGraph();
  51851. var data = graph.data;
  51852. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  51853. data.filterSelf(function (idx) {
  51854. var model = data.getItemModel(idx);
  51855. var category = model.getShallow('category');
  51856. if (category != null) {
  51857. if (isNumber(category)) {
  51858. category = categoryNames[category];
  51859. } // If in any legend component the status is not selected.
  51860. for (var i = 0; i < legendModels.length; i++) {
  51861. if (!legendModels[i].isSelected(category)) {
  51862. return false;
  51863. }
  51864. }
  51865. }
  51866. return true;
  51867. });
  51868. });
  51869. }
  51870. function categoryVisual(ecModel) {
  51871. var paletteScope = {};
  51872. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51873. var categoriesData = seriesModel.getCategoriesData();
  51874. var data = seriesModel.getData();
  51875. var categoryNameIdxMap = {};
  51876. categoriesData.each(function (idx) {
  51877. var name = categoriesData.getName(idx); // Add prefix to avoid conflict with Object.prototype.
  51878. categoryNameIdxMap['ec-' + name] = idx;
  51879. var itemModel = categoriesData.getItemModel(idx);
  51880. var style = itemModel.getModel('itemStyle').getItemStyle();
  51881. if (!style.fill) {
  51882. // Get color from palette.
  51883. style.fill = seriesModel.getColorFromPalette(name, paletteScope);
  51884. }
  51885. categoriesData.setItemVisual(idx, 'style', style);
  51886. var symbolVisualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  51887. for (var i = 0; i < symbolVisualList.length; i++) {
  51888. var symbolVisual = itemModel.getShallow(symbolVisualList[i], true);
  51889. if (symbolVisual != null) {
  51890. categoriesData.setItemVisual(idx, symbolVisualList[i], symbolVisual);
  51891. }
  51892. }
  51893. }); // Assign category color to visual
  51894. if (categoriesData.count()) {
  51895. data.each(function (idx) {
  51896. var model = data.getItemModel(idx);
  51897. var categoryIdx = model.getShallow('category');
  51898. if (categoryIdx != null) {
  51899. if (isString(categoryIdx)) {
  51900. categoryIdx = categoryNameIdxMap['ec-' + categoryIdx];
  51901. }
  51902. var categoryStyle = categoriesData.getItemVisual(categoryIdx, 'style');
  51903. var style = data.ensureUniqueItemVisual(idx, 'style');
  51904. extend(style, categoryStyle);
  51905. var visualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  51906. for (var i = 0; i < visualList.length; i++) {
  51907. data.setItemVisual(idx, visualList[i], categoriesData.getItemVisual(categoryIdx, visualList[i]));
  51908. }
  51909. }
  51910. });
  51911. }
  51912. });
  51913. }
  51914. function normalize$2(a) {
  51915. if (!(a instanceof Array)) {
  51916. a = [a, a];
  51917. }
  51918. return a;
  51919. }
  51920. function graphEdgeVisual(ecModel) {
  51921. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51922. var graph = seriesModel.getGraph();
  51923. var edgeData = seriesModel.getEdgeData();
  51924. var symbolType = normalize$2(seriesModel.get('edgeSymbol'));
  51925. var symbolSize = normalize$2(seriesModel.get('edgeSymbolSize')); // const colorQuery = ['lineStyle', 'color'] as const;
  51926. // const opacityQuery = ['lineStyle', 'opacity'] as const;
  51927. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  51928. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  51929. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  51930. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  51931. edgeData.setVisual('style', seriesModel.getModel('lineStyle').getLineStyle());
  51932. edgeData.each(function (idx) {
  51933. var itemModel = edgeData.getItemModel(idx);
  51934. var edge = graph.getEdgeByIndex(idx);
  51935. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  51936. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true)); // Edge visual must after node visual
  51937. var style = itemModel.getModel('lineStyle').getLineStyle();
  51938. var existsStyle = edgeData.ensureUniqueItemVisual(idx, 'style');
  51939. extend(existsStyle, style);
  51940. switch (existsStyle.stroke) {
  51941. case 'source':
  51942. {
  51943. var nodeStyle = edge.node1.getVisual('style');
  51944. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  51945. break;
  51946. }
  51947. case 'target':
  51948. {
  51949. var nodeStyle = edge.node2.getVisual('style');
  51950. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  51951. break;
  51952. }
  51953. }
  51954. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  51955. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  51956. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  51957. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  51958. });
  51959. });
  51960. }
  51961. var KEY_DELIMITER = '-->';
  51962. /**
  51963. * params handler
  51964. * @param {module:echarts/model/SeriesModel} seriesModel
  51965. * @returns {*}
  51966. */
  51967. var getAutoCurvenessParams = function (seriesModel) {
  51968. return seriesModel.get('autoCurveness') || null;
  51969. };
  51970. /**
  51971. * Generate a list of edge curvatures, 20 is the default
  51972. * @param {module:echarts/model/SeriesModel} seriesModel
  51973. * @param {number} appendLength
  51974. * @return 20 => [0, -0.2, 0.2, -0.4, 0.4, -0.6, 0.6, -0.8, 0.8, -1, 1, -1.2, 1.2, -1.4, 1.4, -1.6, 1.6, -1.8, 1.8, -2]
  51975. */
  51976. var createCurveness = function (seriesModel, appendLength) {
  51977. var autoCurvenessParmas = getAutoCurvenessParams(seriesModel);
  51978. var length = 20;
  51979. var curvenessList = []; // handler the function set
  51980. if (isNumber(autoCurvenessParmas)) {
  51981. length = autoCurvenessParmas;
  51982. } else if (isArray(autoCurvenessParmas)) {
  51983. seriesModel.__curvenessList = autoCurvenessParmas;
  51984. return;
  51985. } // append length
  51986. if (appendLength > length) {
  51987. length = appendLength;
  51988. } // make sure the length is even
  51989. var len = length % 2 ? length + 2 : length + 3;
  51990. curvenessList = [];
  51991. for (var i = 0; i < len; i++) {
  51992. curvenessList.push((i % 2 ? i + 1 : i) / 10 * (i % 2 ? -1 : 1));
  51993. }
  51994. seriesModel.__curvenessList = curvenessList;
  51995. };
  51996. /**
  51997. * Create different cache key data in the positive and negative directions, in order to set the curvature later
  51998. * @param {number|string|module:echarts/data/Graph.Node} n1
  51999. * @param {number|string|module:echarts/data/Graph.Node} n2
  52000. * @param {module:echarts/model/SeriesModel} seriesModel
  52001. * @returns {string} key
  52002. */
  52003. var getKeyOfEdges = function (n1, n2, seriesModel) {
  52004. var source = [n1.id, n1.dataIndex].join('.');
  52005. var target = [n2.id, n2.dataIndex].join('.');
  52006. return [seriesModel.uid, source, target].join(KEY_DELIMITER);
  52007. };
  52008. /**
  52009. * get opposite key
  52010. * @param {string} key
  52011. * @returns {string}
  52012. */
  52013. var getOppositeKey = function (key) {
  52014. var keys = key.split(KEY_DELIMITER);
  52015. return [keys[0], keys[2], keys[1]].join(KEY_DELIMITER);
  52016. };
  52017. /**
  52018. * get edgeMap with key
  52019. * @param edge
  52020. * @param {module:echarts/model/SeriesModel} seriesModel
  52021. */
  52022. var getEdgeFromMap = function (edge, seriesModel) {
  52023. var key = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  52024. return seriesModel.__edgeMap[key];
  52025. };
  52026. /**
  52027. * calculate all cases total length
  52028. * @param edge
  52029. * @param seriesModel
  52030. * @returns {number}
  52031. */
  52032. var getTotalLengthBetweenNodes = function (edge, seriesModel) {
  52033. var len = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node1, edge.node2, seriesModel), seriesModel);
  52034. var lenV = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node2, edge.node1, seriesModel), seriesModel);
  52035. return len + lenV;
  52036. };
  52037. /**
  52038. *
  52039. * @param key
  52040. */
  52041. var getEdgeMapLengthWithKey = function (key, seriesModel) {
  52042. var edgeMap = seriesModel.__edgeMap;
  52043. return edgeMap[key] ? edgeMap[key].length : 0;
  52044. };
  52045. /**
  52046. * Count the number of edges between the same two points, used to obtain the curvature table and the parity of the edge
  52047. * @see /graph/GraphSeries.js@getInitialData
  52048. * @param {module:echarts/model/SeriesModel} seriesModel
  52049. */
  52050. function initCurvenessList(seriesModel) {
  52051. if (!getAutoCurvenessParams(seriesModel)) {
  52052. return;
  52053. }
  52054. seriesModel.__curvenessList = [];
  52055. seriesModel.__edgeMap = {}; // calc the array of curveness List
  52056. createCurveness(seriesModel);
  52057. }
  52058. /**
  52059. * set edgeMap with key
  52060. * @param {number|string|module:echarts/data/Graph.Node} n1
  52061. * @param {number|string|module:echarts/data/Graph.Node} n2
  52062. * @param {module:echarts/model/SeriesModel} seriesModel
  52063. * @param {number} index
  52064. */
  52065. function createEdgeMapForCurveness(n1, n2, seriesModel, index) {
  52066. if (!getAutoCurvenessParams(seriesModel)) {
  52067. return;
  52068. }
  52069. var key = getKeyOfEdges(n1, n2, seriesModel);
  52070. var edgeMap = seriesModel.__edgeMap;
  52071. var oppositeEdges = edgeMap[getOppositeKey(key)]; // set direction
  52072. if (edgeMap[key] && !oppositeEdges) {
  52073. edgeMap[key].isForward = true;
  52074. } else if (oppositeEdges && edgeMap[key]) {
  52075. oppositeEdges.isForward = true;
  52076. edgeMap[key].isForward = false;
  52077. }
  52078. edgeMap[key] = edgeMap[key] || [];
  52079. edgeMap[key].push(index);
  52080. }
  52081. /**
  52082. * get curvature for edge
  52083. * @param edge
  52084. * @param {module:echarts/model/SeriesModel} seriesModel
  52085. * @param index
  52086. */
  52087. function getCurvenessForEdge(edge, seriesModel, index, needReverse) {
  52088. var autoCurvenessParams = getAutoCurvenessParams(seriesModel);
  52089. var isArrayParam = isArray(autoCurvenessParams);
  52090. if (!autoCurvenessParams) {
  52091. return null;
  52092. }
  52093. var edgeArray = getEdgeFromMap(edge, seriesModel);
  52094. if (!edgeArray) {
  52095. return null;
  52096. }
  52097. var edgeIndex = -1;
  52098. for (var i = 0; i < edgeArray.length; i++) {
  52099. if (edgeArray[i] === index) {
  52100. edgeIndex = i;
  52101. break;
  52102. }
  52103. } // if totalLen is Longer createCurveness
  52104. var totalLen = getTotalLengthBetweenNodes(edge, seriesModel);
  52105. createCurveness(seriesModel, totalLen);
  52106. edge.lineStyle = edge.lineStyle || {}; // if is opposite edge, must set curvenss to opposite number
  52107. var curKey = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  52108. var curvenessList = seriesModel.__curvenessList; // if pass array no need parity
  52109. var parityCorrection = isArrayParam ? 0 : totalLen % 2 ? 0 : 1;
  52110. if (!edgeArray.isForward) {
  52111. // the opposite edge show outside
  52112. var oppositeKey = getOppositeKey(curKey);
  52113. var len = getEdgeMapLengthWithKey(oppositeKey, seriesModel);
  52114. var resValue = curvenessList[edgeIndex + len + parityCorrection]; // isNeedReverse, simple, force type need reverse the curveness in the junction of the forword and the opposite
  52115. if (needReverse) {
  52116. // set as array may make the parity handle with the len of opposite
  52117. if (isArrayParam) {
  52118. if (autoCurvenessParams && autoCurvenessParams[0] === 0) {
  52119. return (len + parityCorrection) % 2 ? resValue : -resValue;
  52120. } else {
  52121. return ((len % 2 ? 0 : 1) + parityCorrection) % 2 ? resValue : -resValue;
  52122. }
  52123. } else {
  52124. return (len + parityCorrection) % 2 ? resValue : -resValue;
  52125. }
  52126. } else {
  52127. return curvenessList[edgeIndex + len + parityCorrection];
  52128. }
  52129. } else {
  52130. return curvenessList[parityCorrection + edgeIndex];
  52131. }
  52132. }
  52133. function simpleLayout(seriesModel) {
  52134. var coordSys = seriesModel.coordinateSystem;
  52135. if (coordSys && coordSys.type !== 'view') {
  52136. return;
  52137. }
  52138. var graph = seriesModel.getGraph();
  52139. graph.eachNode(function (node) {
  52140. var model = node.getModel();
  52141. node.setLayout([+model.get('x'), +model.get('y')]);
  52142. });
  52143. simpleLayoutEdge(graph, seriesModel);
  52144. }
  52145. function simpleLayoutEdge(graph, seriesModel) {
  52146. graph.eachEdge(function (edge, index) {
  52147. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, seriesModel, index, true), 0);
  52148. var p1 = clone$1(edge.node1.getLayout());
  52149. var p2 = clone$1(edge.node2.getLayout());
  52150. var points = [p1, p2];
  52151. if (+curveness) {
  52152. points.push([(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness]);
  52153. }
  52154. edge.setLayout(points);
  52155. });
  52156. }
  52157. function graphSimpleLayout(ecModel, api) {
  52158. ecModel.eachSeriesByType('graph', function (seriesModel) {
  52159. var layout = seriesModel.get('layout');
  52160. var coordSys = seriesModel.coordinateSystem;
  52161. if (coordSys && coordSys.type !== 'view') {
  52162. var data_1 = seriesModel.getData();
  52163. var dimensions_1 = [];
  52164. each(coordSys.dimensions, function (coordDim) {
  52165. dimensions_1 = dimensions_1.concat(data_1.mapDimensionsAll(coordDim));
  52166. });
  52167. for (var dataIndex = 0; dataIndex < data_1.count(); dataIndex++) {
  52168. var value = [];
  52169. var hasValue = false;
  52170. for (var i = 0; i < dimensions_1.length; i++) {
  52171. var val = data_1.get(dimensions_1[i], dataIndex);
  52172. if (!isNaN(val)) {
  52173. hasValue = true;
  52174. }
  52175. value.push(val);
  52176. }
  52177. if (hasValue) {
  52178. data_1.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  52179. } else {
  52180. // Also {Array.<number>}, not undefined to avoid if...else... statement
  52181. data_1.setItemLayout(dataIndex, [NaN, NaN]);
  52182. }
  52183. }
  52184. simpleLayoutEdge(data_1.graph, seriesModel);
  52185. } else if (!layout || layout === 'none') {
  52186. simpleLayout(seriesModel);
  52187. }
  52188. });
  52189. }
  52190. /*
  52191. * Licensed to the Apache Software Foundation (ASF) under one
  52192. * or more contributor license agreements. See the NOTICE file
  52193. * distributed with this work for additional information
  52194. * regarding copyright ownership. The ASF licenses this file
  52195. * to you under the Apache License, Version 2.0 (the
  52196. * "License"); you may not use this file except in compliance
  52197. * with the License. You may obtain a copy of the License at
  52198. *
  52199. * http://www.apache.org/licenses/LICENSE-2.0
  52200. *
  52201. * Unless required by applicable law or agreed to in writing,
  52202. * software distributed under the License is distributed on an
  52203. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52204. * KIND, either express or implied. See the License for the
  52205. * specific language governing permissions and limitations
  52206. * under the License.
  52207. */
  52208. /**
  52209. * AUTO-GENERATED FILE. DO NOT MODIFY.
  52210. */
  52211. /*
  52212. * Licensed to the Apache Software Foundation (ASF) under one
  52213. * or more contributor license agreements. See the NOTICE file
  52214. * distributed with this work for additional information
  52215. * regarding copyright ownership. The ASF licenses this file
  52216. * to you under the Apache License, Version 2.0 (the
  52217. * "License"); you may not use this file except in compliance
  52218. * with the License. You may obtain a copy of the License at
  52219. *
  52220. * http://www.apache.org/licenses/LICENSE-2.0
  52221. *
  52222. * Unless required by applicable law or agreed to in writing,
  52223. * software distributed under the License is distributed on an
  52224. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52225. * KIND, either express or implied. See the License for the
  52226. * specific language governing permissions and limitations
  52227. * under the License.
  52228. */
  52229. function getNodeGlobalScale(seriesModel) {
  52230. var coordSys = seriesModel.coordinateSystem;
  52231. if (coordSys.type !== 'view') {
  52232. return 1;
  52233. }
  52234. var nodeScaleRatio = seriesModel.option.nodeScaleRatio;
  52235. var groupZoom = coordSys.scaleX; // Scale node when zoom changes
  52236. var roamZoom = coordSys.getZoom();
  52237. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  52238. return nodeScale / groupZoom;
  52239. }
  52240. function getSymbolSize(node) {
  52241. var symbolSize = node.getVisual('symbolSize');
  52242. if (symbolSize instanceof Array) {
  52243. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  52244. }
  52245. return +symbolSize;
  52246. }
  52247. var PI$6 = Math.PI;
  52248. var _symbolRadiansHalf = [];
  52249. /**
  52250. * `basedOn` can be:
  52251. * 'value':
  52252. * This layout is not accurate and have same bad case. For example,
  52253. * if the min value is very smaller than the max value, the nodes
  52254. * with the min value probably overlap even though there is enough
  52255. * space to layout them. So we only use this approach in the as the
  52256. * init layout of the force layout.
  52257. * FIXME
  52258. * Probably we do not need this method any more but use
  52259. * `basedOn: 'symbolSize'` in force layout if
  52260. * delay its init operations to GraphView.
  52261. * 'symbolSize':
  52262. * This approach work only if all of the symbol size calculated.
  52263. * That is, the progressive rendering is not applied to graph.
  52264. * FIXME
  52265. * If progressive rendering is applied to graph some day,
  52266. * probably we have to use `basedOn: 'value'`.
  52267. */
  52268. function circularLayout(seriesModel, basedOn, draggingNode, pointer) {
  52269. var coordSys = seriesModel.coordinateSystem;
  52270. if (coordSys && coordSys.type !== 'view') {
  52271. return;
  52272. }
  52273. var rect = coordSys.getBoundingRect();
  52274. var nodeData = seriesModel.getData();
  52275. var graph = nodeData.graph;
  52276. var cx = rect.width / 2 + rect.x;
  52277. var cy = rect.height / 2 + rect.y;
  52278. var r = Math.min(rect.width, rect.height) / 2;
  52279. var count = nodeData.count();
  52280. nodeData.setLayout({
  52281. cx: cx,
  52282. cy: cy
  52283. });
  52284. if (!count) {
  52285. return;
  52286. }
  52287. if (draggingNode) {
  52288. var _a = coordSys.pointToData(pointer),
  52289. tempX = _a[0],
  52290. tempY = _a[1];
  52291. var v = [tempX - cx, tempY - cy];
  52292. normalize(v, v);
  52293. scale(v, v, r);
  52294. draggingNode.setLayout([cx + v[0], cy + v[1]], true);
  52295. var circularRotateLabel = seriesModel.get(['circular', 'rotateLabel']);
  52296. rotateNodeLabel(draggingNode, circularRotateLabel, cx, cy);
  52297. }
  52298. _layoutNodesBasedOn[basedOn](seriesModel, graph, nodeData, r, cx, cy, count);
  52299. graph.eachEdge(function (edge, index) {
  52300. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), getCurvenessForEdge(edge, seriesModel, index), 0);
  52301. var p1 = clone$1(edge.node1.getLayout());
  52302. var p2 = clone$1(edge.node2.getLayout());
  52303. var cp1;
  52304. var x12 = (p1[0] + p2[0]) / 2;
  52305. var y12 = (p1[1] + p2[1]) / 2;
  52306. if (+curveness) {
  52307. curveness *= 3;
  52308. cp1 = [cx * curveness + x12 * (1 - curveness), cy * curveness + y12 * (1 - curveness)];
  52309. }
  52310. edge.setLayout([p1, p2, cp1]);
  52311. });
  52312. }
  52313. var _layoutNodesBasedOn = {
  52314. value: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  52315. var angle = 0;
  52316. var sum = nodeData.getSum('value');
  52317. var unitAngle = Math.PI * 2 / (sum || count);
  52318. graph.eachNode(function (node) {
  52319. var value = node.getValue('value');
  52320. var radianHalf = unitAngle * (sum ? value : 1) / 2;
  52321. angle += radianHalf;
  52322. node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  52323. angle += radianHalf;
  52324. });
  52325. },
  52326. symbolSize: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  52327. var sumRadian = 0;
  52328. _symbolRadiansHalf.length = count;
  52329. var nodeScale = getNodeGlobalScale(seriesModel);
  52330. graph.eachNode(function (node) {
  52331. var symbolSize = getSymbolSize(node); // Normally this case will not happen, but we still add
  52332. // some the defensive code (2px is an arbitrary value).
  52333. isNaN(symbolSize) && (symbolSize = 2);
  52334. symbolSize < 0 && (symbolSize = 0);
  52335. symbolSize *= nodeScale;
  52336. var symbolRadianHalf = Math.asin(symbolSize / 2 / r); // when `symbolSize / 2` is bigger than `r`.
  52337. isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$6 / 2);
  52338. _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf;
  52339. sumRadian += symbolRadianHalf * 2;
  52340. });
  52341. var halfRemainRadian = (2 * PI$6 - sumRadian) / count / 2;
  52342. var angle = 0;
  52343. graph.eachNode(function (node) {
  52344. var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex];
  52345. angle += radianHalf; // init circular layout for
  52346. // 1. layout undefined node
  52347. // 2. not fixed node
  52348. (!node.getLayout() || !node.getLayout().fixed) && node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  52349. angle += radianHalf;
  52350. });
  52351. }
  52352. };
  52353. function rotateNodeLabel(node, circularRotateLabel, cx, cy) {
  52354. var el = node.getGraphicEl(); // need to check if el exists. '-' value may not create node element.
  52355. if (!el) {
  52356. return;
  52357. }
  52358. var nodeModel = node.getModel();
  52359. var labelRotate = nodeModel.get(['label', 'rotate']) || 0;
  52360. var symbolPath = el.getSymbolPath();
  52361. if (circularRotateLabel) {
  52362. var pos = node.getLayout();
  52363. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  52364. if (rad < 0) {
  52365. rad = Math.PI * 2 + rad;
  52366. }
  52367. var isLeft = pos[0] < cx;
  52368. if (isLeft) {
  52369. rad = rad - Math.PI;
  52370. }
  52371. var textPosition = isLeft ? 'left' : 'right';
  52372. symbolPath.setTextConfig({
  52373. rotation: -rad,
  52374. position: textPosition,
  52375. origin: 'center'
  52376. });
  52377. var emphasisState = symbolPath.ensureState('emphasis');
  52378. extend(emphasisState.textConfig || (emphasisState.textConfig = {}), {
  52379. position: textPosition
  52380. });
  52381. } else {
  52382. symbolPath.setTextConfig({
  52383. rotation: labelRotate *= Math.PI / 180
  52384. });
  52385. }
  52386. }
  52387. function graphCircularLayout(ecModel) {
  52388. ecModel.eachSeriesByType('graph', function (seriesModel) {
  52389. if (seriesModel.get('layout') === 'circular') {
  52390. circularLayout(seriesModel, 'symbolSize');
  52391. }
  52392. });
  52393. }
  52394. var scaleAndAdd$1 = scaleAndAdd; // function adjacentNode(n, e) {
  52395. // return e.n1 === n ? e.n2 : e.n1;
  52396. // }
  52397. function forceLayout(inNodes, inEdges, opts) {
  52398. var nodes = inNodes;
  52399. var edges = inEdges;
  52400. var rect = opts.rect;
  52401. var width = rect.width;
  52402. var height = rect.height;
  52403. var center = [rect.x + width / 2, rect.y + height / 2]; // let scale = opts.scale || 1;
  52404. var gravity = opts.gravity == null ? 0.1 : opts.gravity; // for (let i = 0; i < edges.length; i++) {
  52405. // let e = edges[i];
  52406. // let n1 = e.n1;
  52407. // let n2 = e.n2;
  52408. // n1.edges = n1.edges || [];
  52409. // n2.edges = n2.edges || [];
  52410. // n1.edges.push(e);
  52411. // n2.edges.push(e);
  52412. // }
  52413. // Init position
  52414. for (var i = 0; i < nodes.length; i++) {
  52415. var n = nodes[i];
  52416. if (!n.p) {
  52417. n.p = create(width * (Math.random() - 0.5) + center[0], height * (Math.random() - 0.5) + center[1]);
  52418. }
  52419. n.pp = clone$1(n.p);
  52420. n.edges = null;
  52421. } // Formula in 'Graph Drawing by Force-directed Placement'
  52422. // let k = scale * Math.sqrt(width * height / nodes.length);
  52423. // let k2 = k * k;
  52424. var initialFriction = opts.friction == null ? 0.6 : opts.friction;
  52425. var friction = initialFriction;
  52426. var beforeStepCallback;
  52427. var afterStepCallback;
  52428. return {
  52429. warmUp: function () {
  52430. friction = initialFriction * 0.8;
  52431. },
  52432. setFixed: function (idx) {
  52433. nodes[idx].fixed = true;
  52434. },
  52435. setUnfixed: function (idx) {
  52436. nodes[idx].fixed = false;
  52437. },
  52438. /**
  52439. * Before step hook
  52440. */
  52441. beforeStep: function (cb) {
  52442. beforeStepCallback = cb;
  52443. },
  52444. /**
  52445. * After step hook
  52446. */
  52447. afterStep: function (cb) {
  52448. afterStepCallback = cb;
  52449. },
  52450. /**
  52451. * Some formulas were originally copied from "d3.js"
  52452. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  52453. * with some modifications made for this project.
  52454. * See the license statement at the head of this file.
  52455. */
  52456. step: function (cb) {
  52457. beforeStepCallback && beforeStepCallback(nodes, edges);
  52458. var v12 = [];
  52459. var nLen = nodes.length;
  52460. for (var i = 0; i < edges.length; i++) {
  52461. var e = edges[i];
  52462. if (e.ignoreForceLayout) {
  52463. continue;
  52464. }
  52465. var n1 = e.n1;
  52466. var n2 = e.n2;
  52467. sub(v12, n2.p, n1.p);
  52468. var d = len(v12) - e.d;
  52469. var w = n2.w / (n1.w + n2.w);
  52470. if (isNaN(w)) {
  52471. w = 0;
  52472. }
  52473. normalize(v12, v12);
  52474. !n1.fixed && scaleAndAdd$1(n1.p, n1.p, v12, w * d * friction);
  52475. !n2.fixed && scaleAndAdd$1(n2.p, n2.p, v12, -(1 - w) * d * friction);
  52476. } // Gravity
  52477. for (var i = 0; i < nLen; i++) {
  52478. var n = nodes[i];
  52479. if (!n.fixed) {
  52480. sub(v12, center, n.p); // let d = vec2.len(v12);
  52481. // vec2.scale(v12, v12, 1 / d);
  52482. // let gravityFactor = gravity;
  52483. scaleAndAdd$1(n.p, n.p, v12, gravity * friction);
  52484. }
  52485. } // Repulsive
  52486. // PENDING
  52487. for (var i = 0; i < nLen; i++) {
  52488. var n1 = nodes[i];
  52489. for (var j = i + 1; j < nLen; j++) {
  52490. var n2 = nodes[j];
  52491. sub(v12, n2.p, n1.p);
  52492. var d = len(v12);
  52493. if (d === 0) {
  52494. // Random repulse
  52495. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  52496. d = 1;
  52497. }
  52498. var repFact = (n1.rep + n2.rep) / d / d;
  52499. !n1.fixed && scaleAndAdd$1(n1.pp, n1.pp, v12, repFact);
  52500. !n2.fixed && scaleAndAdd$1(n2.pp, n2.pp, v12, -repFact);
  52501. }
  52502. }
  52503. var v = [];
  52504. for (var i = 0; i < nLen; i++) {
  52505. var n = nodes[i];
  52506. if (!n.fixed) {
  52507. sub(v, n.p, n.pp);
  52508. scaleAndAdd$1(n.p, n.p, v, friction);
  52509. copy(n.pp, n.p);
  52510. }
  52511. }
  52512. friction = friction * 0.992;
  52513. var finished = friction < 0.01;
  52514. afterStepCallback && afterStepCallback(nodes, edges, finished);
  52515. cb && cb(finished);
  52516. }
  52517. };
  52518. }
  52519. function graphForceLayout(ecModel) {
  52520. ecModel.eachSeriesByType('graph', function (graphSeries) {
  52521. var coordSys = graphSeries.coordinateSystem;
  52522. if (coordSys && coordSys.type !== 'view') {
  52523. return;
  52524. }
  52525. if (graphSeries.get('layout') === 'force') {
  52526. var preservedPoints_1 = graphSeries.preservedPoints || {};
  52527. var graph_1 = graphSeries.getGraph();
  52528. var nodeData_1 = graph_1.data;
  52529. var edgeData = graph_1.edgeData;
  52530. var forceModel = graphSeries.getModel('force');
  52531. var initLayout = forceModel.get('initLayout');
  52532. if (graphSeries.preservedPoints) {
  52533. nodeData_1.each(function (idx) {
  52534. var id = nodeData_1.getId(idx);
  52535. nodeData_1.setItemLayout(idx, preservedPoints_1[id] || [NaN, NaN]);
  52536. });
  52537. } else if (!initLayout || initLayout === 'none') {
  52538. simpleLayout(graphSeries);
  52539. } else if (initLayout === 'circular') {
  52540. circularLayout(graphSeries, 'value');
  52541. }
  52542. var nodeDataExtent_1 = nodeData_1.getDataExtent('value');
  52543. var edgeDataExtent_1 = edgeData.getDataExtent('value'); // let edgeDataExtent = edgeData.getDataExtent('value');
  52544. var repulsion = forceModel.get('repulsion');
  52545. var edgeLength = forceModel.get('edgeLength');
  52546. var repulsionArr_1 = isArray(repulsion) ? repulsion : [repulsion, repulsion];
  52547. var edgeLengthArr_1 = isArray(edgeLength) ? edgeLength : [edgeLength, edgeLength]; // Larger value has smaller length
  52548. edgeLengthArr_1 = [edgeLengthArr_1[1], edgeLengthArr_1[0]];
  52549. var nodes_1 = nodeData_1.mapArray('value', function (value, idx) {
  52550. var point = nodeData_1.getItemLayout(idx);
  52551. var rep = linearMap(value, nodeDataExtent_1, repulsionArr_1);
  52552. if (isNaN(rep)) {
  52553. rep = (repulsionArr_1[0] + repulsionArr_1[1]) / 2;
  52554. }
  52555. return {
  52556. w: rep,
  52557. rep: rep,
  52558. fixed: nodeData_1.getItemModel(idx).get('fixed'),
  52559. p: !point || isNaN(point[0]) || isNaN(point[1]) ? null : point
  52560. };
  52561. });
  52562. var edges = edgeData.mapArray('value', function (value, idx) {
  52563. var edge = graph_1.getEdgeByIndex(idx);
  52564. var d = linearMap(value, edgeDataExtent_1, edgeLengthArr_1);
  52565. if (isNaN(d)) {
  52566. d = (edgeLengthArr_1[0] + edgeLengthArr_1[1]) / 2;
  52567. }
  52568. var edgeModel = edge.getModel();
  52569. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, graphSeries, idx, true), 0);
  52570. return {
  52571. n1: nodes_1[edge.node1.dataIndex],
  52572. n2: nodes_1[edge.node2.dataIndex],
  52573. d: d,
  52574. curveness: curveness,
  52575. ignoreForceLayout: edgeModel.get('ignoreForceLayout')
  52576. };
  52577. }); // let coordSys = graphSeries.coordinateSystem;
  52578. var rect = coordSys.getBoundingRect();
  52579. var forceInstance = forceLayout(nodes_1, edges, {
  52580. rect: rect,
  52581. gravity: forceModel.get('gravity'),
  52582. friction: forceModel.get('friction')
  52583. });
  52584. forceInstance.beforeStep(function (nodes, edges) {
  52585. for (var i = 0, l = nodes.length; i < l; i++) {
  52586. if (nodes[i].fixed) {
  52587. // Write back to layout instance
  52588. copy(nodes[i].p, graph_1.getNodeByIndex(i).getLayout());
  52589. }
  52590. }
  52591. });
  52592. forceInstance.afterStep(function (nodes, edges, stopped) {
  52593. for (var i = 0, l = nodes.length; i < l; i++) {
  52594. if (!nodes[i].fixed) {
  52595. graph_1.getNodeByIndex(i).setLayout(nodes[i].p);
  52596. }
  52597. preservedPoints_1[nodeData_1.getId(i)] = nodes[i].p;
  52598. }
  52599. for (var i = 0, l = edges.length; i < l; i++) {
  52600. var e = edges[i];
  52601. var edge = graph_1.getEdgeByIndex(i);
  52602. var p1 = e.n1.p;
  52603. var p2 = e.n2.p;
  52604. var points = edge.getLayout();
  52605. points = points ? points.slice() : [];
  52606. points[0] = points[0] || [];
  52607. points[1] = points[1] || [];
  52608. copy(points[0], p1);
  52609. copy(points[1], p2);
  52610. if (+e.curveness) {
  52611. points[2] = [(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness];
  52612. }
  52613. edge.setLayout(points);
  52614. }
  52615. });
  52616. graphSeries.forceLayout = forceInstance;
  52617. graphSeries.preservedPoints = preservedPoints_1; // Step to get the layout
  52618. forceInstance.step();
  52619. } else {
  52620. // Remove prev injected forceLayout instance
  52621. graphSeries.forceLayout = null;
  52622. }
  52623. });
  52624. }
  52625. function getViewRect$2(seriesModel, api, aspect) {
  52626. var option = extend(seriesModel.getBoxLayoutParams(), {
  52627. aspect: aspect
  52628. });
  52629. return getLayoutRect(option, {
  52630. width: api.getWidth(),
  52631. height: api.getHeight()
  52632. });
  52633. }
  52634. function createViewCoordSys(ecModel, api) {
  52635. var viewList = [];
  52636. ecModel.eachSeriesByType('graph', function (seriesModel) {
  52637. var coordSysType = seriesModel.get('coordinateSystem');
  52638. if (!coordSysType || coordSysType === 'view') {
  52639. var data_1 = seriesModel.getData();
  52640. var positions = data_1.mapArray(function (idx) {
  52641. var itemModel = data_1.getItemModel(idx);
  52642. return [+itemModel.get('x'), +itemModel.get('y')];
  52643. });
  52644. var min = [];
  52645. var max = [];
  52646. fromPoints(positions, min, max); // If width or height is 0
  52647. if (max[0] - min[0] === 0) {
  52648. max[0] += 1;
  52649. min[0] -= 1;
  52650. }
  52651. if (max[1] - min[1] === 0) {
  52652. max[1] += 1;
  52653. min[1] -= 1;
  52654. }
  52655. var aspect = (max[0] - min[0]) / (max[1] - min[1]); // FIXME If get view rect after data processed?
  52656. var viewRect = getViewRect$2(seriesModel, api, aspect); // Position may be NaN, use view rect instead
  52657. if (isNaN(aspect)) {
  52658. min = [viewRect.x, viewRect.y];
  52659. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  52660. }
  52661. var bbWidth = max[0] - min[0];
  52662. var bbHeight = max[1] - min[1];
  52663. var viewWidth = viewRect.width;
  52664. var viewHeight = viewRect.height;
  52665. var viewCoordSys = seriesModel.coordinateSystem = new View();
  52666. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  52667. viewCoordSys.setBoundingRect(min[0], min[1], bbWidth, bbHeight);
  52668. viewCoordSys.setViewRect(viewRect.x, viewRect.y, viewWidth, viewHeight); // Update roam info
  52669. viewCoordSys.setCenter(seriesModel.get('center'), api);
  52670. viewCoordSys.setZoom(seriesModel.get('zoom'));
  52671. viewList.push(viewCoordSys);
  52672. }
  52673. });
  52674. return viewList;
  52675. }
  52676. var straightLineProto = Line.prototype;
  52677. var bezierCurveProto = BezierCurve.prototype;
  52678. var StraightLineShape =
  52679. /** @class */
  52680. function () {
  52681. function StraightLineShape() {
  52682. // Start point
  52683. this.x1 = 0;
  52684. this.y1 = 0; // End point
  52685. this.x2 = 0;
  52686. this.y2 = 0;
  52687. this.percent = 1;
  52688. }
  52689. return StraightLineShape;
  52690. }();
  52691. var CurveShape =
  52692. /** @class */
  52693. function (_super) {
  52694. __extends(CurveShape, _super);
  52695. function CurveShape() {
  52696. return _super !== null && _super.apply(this, arguments) || this;
  52697. }
  52698. return CurveShape;
  52699. }(StraightLineShape);
  52700. function isStraightLine(shape) {
  52701. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  52702. }
  52703. var ECLinePath =
  52704. /** @class */
  52705. function (_super) {
  52706. __extends(ECLinePath, _super);
  52707. function ECLinePath(opts) {
  52708. var _this = _super.call(this, opts) || this;
  52709. _this.type = 'ec-line';
  52710. return _this;
  52711. }
  52712. ECLinePath.prototype.getDefaultStyle = function () {
  52713. return {
  52714. stroke: '#000',
  52715. fill: null
  52716. };
  52717. };
  52718. ECLinePath.prototype.getDefaultShape = function () {
  52719. return new StraightLineShape();
  52720. };
  52721. ECLinePath.prototype.buildPath = function (ctx, shape) {
  52722. if (isStraightLine(shape)) {
  52723. straightLineProto.buildPath.call(this, ctx, shape);
  52724. } else {
  52725. bezierCurveProto.buildPath.call(this, ctx, shape);
  52726. }
  52727. };
  52728. ECLinePath.prototype.pointAt = function (t) {
  52729. if (isStraightLine(this.shape)) {
  52730. return straightLineProto.pointAt.call(this, t);
  52731. } else {
  52732. return bezierCurveProto.pointAt.call(this, t);
  52733. }
  52734. };
  52735. ECLinePath.prototype.tangentAt = function (t) {
  52736. var shape = this.shape;
  52737. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  52738. return normalize(p, p);
  52739. };
  52740. return ECLinePath;
  52741. }(Path);
  52742. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  52743. function makeSymbolTypeKey(symbolCategory) {
  52744. return '_' + symbolCategory + 'Type';
  52745. }
  52746. /**
  52747. * @inner
  52748. */
  52749. function createSymbol$1(name, lineData, idx) {
  52750. var symbolType = lineData.getItemVisual(idx, name);
  52751. if (!symbolType || symbolType === 'none') {
  52752. return;
  52753. }
  52754. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  52755. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  52756. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  52757. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  52758. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  52759. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  52760. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
  52761. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  52762. symbolPath.name = name;
  52763. return symbolPath;
  52764. }
  52765. function createLine(points) {
  52766. var line = new ECLinePath({
  52767. name: 'line',
  52768. subPixelOptimize: true
  52769. });
  52770. setLinePoints(line.shape, points);
  52771. return line;
  52772. }
  52773. function setLinePoints(targetShape, points) {
  52774. targetShape.x1 = points[0][0];
  52775. targetShape.y1 = points[0][1];
  52776. targetShape.x2 = points[1][0];
  52777. targetShape.y2 = points[1][1];
  52778. targetShape.percent = 1;
  52779. var cp1 = points[2];
  52780. if (cp1) {
  52781. targetShape.cpx1 = cp1[0];
  52782. targetShape.cpy1 = cp1[1];
  52783. } else {
  52784. targetShape.cpx1 = NaN;
  52785. targetShape.cpy1 = NaN;
  52786. }
  52787. }
  52788. var Line$1 =
  52789. /** @class */
  52790. function (_super) {
  52791. __extends(Line, _super);
  52792. function Line(lineData, idx, seriesScope) {
  52793. var _this = _super.call(this) || this;
  52794. _this._createLine(lineData, idx, seriesScope);
  52795. return _this;
  52796. }
  52797. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  52798. var seriesModel = lineData.hostModel;
  52799. var linePoints = lineData.getItemLayout(idx);
  52800. var line = createLine(linePoints);
  52801. line.shape.percent = 0;
  52802. initProps(line, {
  52803. shape: {
  52804. percent: 1
  52805. }
  52806. }, seriesModel, idx);
  52807. this.add(line);
  52808. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52809. var symbol = createSymbol$1(symbolCategory, lineData, idx); // symbols must added after line to make sure
  52810. // it will be updated after line#update.
  52811. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  52812. this.add(symbol);
  52813. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  52814. }, this);
  52815. this._updateCommonStl(lineData, idx, seriesScope);
  52816. }; // TODO More strict on the List type in parameters?
  52817. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  52818. var seriesModel = lineData.hostModel;
  52819. var line = this.childOfName('line');
  52820. var linePoints = lineData.getItemLayout(idx);
  52821. var target = {
  52822. shape: {}
  52823. };
  52824. setLinePoints(target.shape, linePoints);
  52825. updateProps(line, target, seriesModel, idx);
  52826. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52827. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  52828. var key = makeSymbolTypeKey(symbolCategory); // Symbol changed
  52829. if (this[key] !== symbolType) {
  52830. this.remove(this.childOfName(symbolCategory));
  52831. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  52832. this.add(symbol);
  52833. }
  52834. this[key] = symbolType;
  52835. }, this);
  52836. this._updateCommonStl(lineData, idx, seriesScope);
  52837. };
  52838. Line.prototype.getLinePath = function () {
  52839. return this.childAt(0);
  52840. };
  52841. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  52842. var seriesModel = lineData.hostModel;
  52843. var line = this.childOfName('line');
  52844. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  52845. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  52846. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  52847. var labelStatesModels = seriesScope && seriesScope.labelStatesModels;
  52848. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  52849. var focus = seriesScope && seriesScope.focus;
  52850. var blurScope = seriesScope && seriesScope.blurScope; // Optimization for large dataset
  52851. if (!seriesScope || lineData.hasItemOption) {
  52852. var itemModel = lineData.getItemModel(idx);
  52853. var emphasisModel = itemModel.getModel('emphasis');
  52854. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  52855. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  52856. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  52857. emphasisDisabled = emphasisModel.get('disabled');
  52858. focus = emphasisModel.get('focus');
  52859. blurScope = emphasisModel.get('blurScope');
  52860. labelStatesModels = getLabelStatesModels(itemModel);
  52861. }
  52862. var lineStyle = lineData.getItemVisual(idx, 'style');
  52863. var visualColor = lineStyle.stroke;
  52864. line.useStyle(lineStyle);
  52865. line.style.fill = null;
  52866. line.style.strokeNoScale = true;
  52867. line.ensureState('emphasis').style = emphasisLineStyle;
  52868. line.ensureState('blur').style = blurLineStyle;
  52869. line.ensureState('select').style = selectLineStyle; // Update symbol
  52870. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52871. var symbol = this.childOfName(symbolCategory);
  52872. if (symbol) {
  52873. // Share opacity and color with line.
  52874. symbol.setColor(visualColor);
  52875. symbol.style.opacity = lineStyle.opacity;
  52876. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  52877. var stateName = SPECIAL_STATES[i];
  52878. var lineState = line.getState(stateName);
  52879. if (lineState) {
  52880. var lineStateStyle = lineState.style || {};
  52881. var state = symbol.ensureState(stateName);
  52882. var stateStyle = state.style || (state.style = {});
  52883. if (lineStateStyle.stroke != null) {
  52884. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  52885. }
  52886. if (lineStateStyle.opacity != null) {
  52887. stateStyle.opacity = lineStateStyle.opacity;
  52888. }
  52889. }
  52890. }
  52891. symbol.markRedraw();
  52892. }
  52893. }, this);
  52894. var rawVal = seriesModel.getRawValue(idx);
  52895. setLabelStyle(this, labelStatesModels, {
  52896. labelDataIndex: idx,
  52897. labelFetcher: {
  52898. getFormattedLabel: function (dataIndex, stateName) {
  52899. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  52900. }
  52901. },
  52902. inheritColor: visualColor || '#000',
  52903. defaultOpacity: lineStyle.opacity,
  52904. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  52905. });
  52906. var label = this.getTextContent(); // Always set `textStyle` even if `normalStyle.text` is null, because default
  52907. // values have to be set on `normalStyle`.
  52908. if (label) {
  52909. var labelNormalModel = labelStatesModels.normal;
  52910. label.__align = label.style.align;
  52911. label.__verticalAlign = label.style.verticalAlign; // 'start', 'middle', 'end'
  52912. label.__position = labelNormalModel.get('position') || 'middle';
  52913. var distance = labelNormalModel.get('distance');
  52914. if (!isArray(distance)) {
  52915. distance = [distance, distance];
  52916. }
  52917. label.__labelDistance = distance;
  52918. }
  52919. this.setTextConfig({
  52920. position: null,
  52921. local: true,
  52922. inside: false // Can't be inside for stroke element.
  52923. });
  52924. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  52925. };
  52926. Line.prototype.highlight = function () {
  52927. enterEmphasis(this);
  52928. };
  52929. Line.prototype.downplay = function () {
  52930. leaveEmphasis(this);
  52931. };
  52932. Line.prototype.updateLayout = function (lineData, idx) {
  52933. this.setLinePoints(lineData.getItemLayout(idx));
  52934. };
  52935. Line.prototype.setLinePoints = function (points) {
  52936. var linePath = this.childOfName('line');
  52937. setLinePoints(linePath.shape, points);
  52938. linePath.dirty();
  52939. };
  52940. Line.prototype.beforeUpdate = function () {
  52941. var lineGroup = this;
  52942. var symbolFrom = lineGroup.childOfName('fromSymbol');
  52943. var symbolTo = lineGroup.childOfName('toSymbol');
  52944. var label = lineGroup.getTextContent(); // Quick reject
  52945. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  52946. return;
  52947. }
  52948. var invScale = 1;
  52949. var parentNode = this.parent;
  52950. while (parentNode) {
  52951. if (parentNode.scaleX) {
  52952. invScale /= parentNode.scaleX;
  52953. }
  52954. parentNode = parentNode.parent;
  52955. }
  52956. var line = lineGroup.childOfName('line'); // If line not changed
  52957. // FIXME Parent scale changed
  52958. if (!this.__dirty && !line.__dirty) {
  52959. return;
  52960. }
  52961. var percent = line.shape.percent;
  52962. var fromPos = line.pointAt(0);
  52963. var toPos = line.pointAt(percent);
  52964. var d = sub([], toPos, fromPos);
  52965. normalize(d, d);
  52966. function setSymbolRotation(symbol, percent) {
  52967. // Fix #12388
  52968. // when symbol is set to be 'arrow' in markLine,
  52969. // symbolRotate value will be ignored, and compulsively use tangent angle.
  52970. // rotate by default if symbol rotation is not specified
  52971. var specifiedRotation = symbol.__specifiedRotation;
  52972. if (specifiedRotation == null) {
  52973. var tangent = line.tangentAt(percent);
  52974. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  52975. } else {
  52976. symbol.attr('rotation', specifiedRotation);
  52977. }
  52978. }
  52979. if (symbolFrom) {
  52980. symbolFrom.setPosition(fromPos);
  52981. setSymbolRotation(symbolFrom, 0);
  52982. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  52983. symbolFrom.markRedraw();
  52984. }
  52985. if (symbolTo) {
  52986. symbolTo.setPosition(toPos);
  52987. setSymbolRotation(symbolTo, 1);
  52988. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  52989. symbolTo.markRedraw();
  52990. }
  52991. if (label && !label.ignore) {
  52992. label.x = label.y = 0;
  52993. label.originX = label.originY = 0;
  52994. var textAlign = void 0;
  52995. var textVerticalAlign = void 0;
  52996. var distance = label.__labelDistance;
  52997. var distanceX = distance[0] * invScale;
  52998. var distanceY = distance[1] * invScale;
  52999. var halfPercent = percent / 2;
  53000. var tangent = line.tangentAt(halfPercent);
  53001. var n = [tangent[1], -tangent[0]];
  53002. var cp = line.pointAt(halfPercent);
  53003. if (n[1] > 0) {
  53004. n[0] = -n[0];
  53005. n[1] = -n[1];
  53006. }
  53007. var dir = tangent[0] < 0 ? -1 : 1;
  53008. if (label.__position !== 'start' && label.__position !== 'end') {
  53009. var rotation = -Math.atan2(tangent[1], tangent[0]);
  53010. if (toPos[0] < fromPos[0]) {
  53011. rotation = Math.PI + rotation;
  53012. }
  53013. label.rotation = rotation;
  53014. }
  53015. var dy = void 0;
  53016. switch (label.__position) {
  53017. case 'insideStartTop':
  53018. case 'insideMiddleTop':
  53019. case 'insideEndTop':
  53020. case 'middle':
  53021. dy = -distanceY;
  53022. textVerticalAlign = 'bottom';
  53023. break;
  53024. case 'insideStartBottom':
  53025. case 'insideMiddleBottom':
  53026. case 'insideEndBottom':
  53027. dy = distanceY;
  53028. textVerticalAlign = 'top';
  53029. break;
  53030. default:
  53031. dy = 0;
  53032. textVerticalAlign = 'middle';
  53033. }
  53034. switch (label.__position) {
  53035. case 'end':
  53036. label.x = d[0] * distanceX + toPos[0];
  53037. label.y = d[1] * distanceY + toPos[1];
  53038. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  53039. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  53040. break;
  53041. case 'start':
  53042. label.x = -d[0] * distanceX + fromPos[0];
  53043. label.y = -d[1] * distanceY + fromPos[1];
  53044. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  53045. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  53046. break;
  53047. case 'insideStartTop':
  53048. case 'insideStart':
  53049. case 'insideStartBottom':
  53050. label.x = distanceX * dir + fromPos[0];
  53051. label.y = fromPos[1] + dy;
  53052. textAlign = tangent[0] < 0 ? 'right' : 'left';
  53053. label.originX = -distanceX * dir;
  53054. label.originY = -dy;
  53055. break;
  53056. case 'insideMiddleTop':
  53057. case 'insideMiddle':
  53058. case 'insideMiddleBottom':
  53059. case 'middle':
  53060. label.x = cp[0];
  53061. label.y = cp[1] + dy;
  53062. textAlign = 'center';
  53063. label.originY = -dy;
  53064. break;
  53065. case 'insideEndTop':
  53066. case 'insideEnd':
  53067. case 'insideEndBottom':
  53068. label.x = -distanceX * dir + toPos[0];
  53069. label.y = toPos[1] + dy;
  53070. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  53071. label.originX = distanceX * dir;
  53072. label.originY = -dy;
  53073. break;
  53074. }
  53075. label.scaleX = label.scaleY = invScale;
  53076. label.setStyle({
  53077. // Use the user specified text align and baseline first
  53078. verticalAlign: label.__verticalAlign || textVerticalAlign,
  53079. align: label.__align || textAlign
  53080. });
  53081. }
  53082. };
  53083. return Line;
  53084. }(Group);
  53085. var LineDraw =
  53086. /** @class */
  53087. function () {
  53088. function LineDraw(LineCtor) {
  53089. this.group = new Group();
  53090. this._LineCtor = LineCtor || Line$1;
  53091. }
  53092. LineDraw.prototype.updateData = function (lineData) {
  53093. var _this = this; // Remove progressive els.
  53094. this._progressiveEls = null;
  53095. var lineDraw = this;
  53096. var group = lineDraw.group;
  53097. var oldLineData = lineDraw._lineData;
  53098. lineDraw._lineData = lineData; // There is no oldLineData only when first rendering or switching from
  53099. // stream mode to normal mode, where previous elements should be removed.
  53100. if (!oldLineData) {
  53101. group.removeAll();
  53102. }
  53103. var seriesScope = makeSeriesScope$1(lineData);
  53104. lineData.diff(oldLineData).add(function (idx) {
  53105. _this._doAdd(lineData, idx, seriesScope);
  53106. }).update(function (newIdx, oldIdx) {
  53107. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  53108. }).remove(function (idx) {
  53109. group.remove(oldLineData.getItemGraphicEl(idx));
  53110. }).execute();
  53111. };
  53112. LineDraw.prototype.updateLayout = function () {
  53113. var lineData = this._lineData; // Do not support update layout in incremental mode.
  53114. if (!lineData) {
  53115. return;
  53116. }
  53117. lineData.eachItemGraphicEl(function (el, idx) {
  53118. el.updateLayout(lineData, idx);
  53119. }, this);
  53120. };
  53121. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  53122. this._seriesScope = makeSeriesScope$1(lineData);
  53123. this._lineData = null;
  53124. this.group.removeAll();
  53125. };
  53126. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  53127. this._progressiveEls = [];
  53128. function updateIncrementalAndHover(el) {
  53129. if (!el.isGroup && !isEffectObject(el)) {
  53130. el.incremental = true;
  53131. el.ensureState('emphasis').hoverLayer = true;
  53132. }
  53133. }
  53134. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  53135. var itemLayout = lineData.getItemLayout(idx);
  53136. if (lineNeedsDraw(itemLayout)) {
  53137. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  53138. el.traverse(updateIncrementalAndHover);
  53139. this.group.add(el);
  53140. lineData.setItemGraphicEl(idx, el);
  53141. this._progressiveEls.push(el);
  53142. }
  53143. }
  53144. };
  53145. LineDraw.prototype.remove = function () {
  53146. this.group.removeAll();
  53147. };
  53148. LineDraw.prototype.eachRendered = function (cb) {
  53149. traverseElements(this._progressiveEls || this.group, cb);
  53150. };
  53151. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  53152. var itemLayout = lineData.getItemLayout(idx);
  53153. if (!lineNeedsDraw(itemLayout)) {
  53154. return;
  53155. }
  53156. var el = new this._LineCtor(lineData, idx, seriesScope);
  53157. lineData.setItemGraphicEl(idx, el);
  53158. this.group.add(el);
  53159. };
  53160. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  53161. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  53162. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  53163. this.group.remove(itemEl);
  53164. return;
  53165. }
  53166. if (!itemEl) {
  53167. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  53168. } else {
  53169. itemEl.updateData(newLineData, newIdx, seriesScope);
  53170. }
  53171. newLineData.setItemGraphicEl(newIdx, itemEl);
  53172. this.group.add(itemEl);
  53173. };
  53174. return LineDraw;
  53175. }();
  53176. function isEffectObject(el) {
  53177. return el.animators && el.animators.length > 0;
  53178. }
  53179. function makeSeriesScope$1(lineData) {
  53180. var hostModel = lineData.hostModel;
  53181. var emphasisModel = hostModel.getModel('emphasis');
  53182. return {
  53183. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  53184. emphasisLineStyle: emphasisModel.getModel(['lineStyle']).getLineStyle(),
  53185. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  53186. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  53187. emphasisDisabled: emphasisModel.get('disabled'),
  53188. blurScope: emphasisModel.get('blurScope'),
  53189. focus: emphasisModel.get('focus'),
  53190. labelStatesModels: getLabelStatesModels(hostModel)
  53191. };
  53192. }
  53193. function isPointNaN(pt) {
  53194. return isNaN(pt[0]) || isNaN(pt[1]);
  53195. }
  53196. function lineNeedsDraw(pts) {
  53197. return pts && !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  53198. }
  53199. var v1 = [];
  53200. var v2 = [];
  53201. var v3 = [];
  53202. var quadraticAt$1 = quadraticAt;
  53203. var v2DistSquare = distSquare;
  53204. var mathAbs$2 = Math.abs;
  53205. function intersectCurveCircle(curvePoints, center, radius) {
  53206. var p0 = curvePoints[0];
  53207. var p1 = curvePoints[1];
  53208. var p2 = curvePoints[2];
  53209. var d = Infinity;
  53210. var t;
  53211. var radiusSquare = radius * radius;
  53212. var interval = 0.1;
  53213. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  53214. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  53215. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  53216. var diff = mathAbs$2(v2DistSquare(v1, center) - radiusSquare);
  53217. if (diff < d) {
  53218. d = diff;
  53219. t = _t;
  53220. }
  53221. } // Assume the segment is monotone,Find root through Bisection method
  53222. // At most 32 iteration
  53223. for (var i = 0; i < 32; i++) {
  53224. // let prev = t - interval;
  53225. var next = t + interval; // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  53226. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  53227. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  53228. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  53229. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  53230. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  53231. var diff = v2DistSquare(v2, center) - radiusSquare;
  53232. if (mathAbs$2(diff) < 1e-2) {
  53233. break;
  53234. } // let prevDiff = v2DistSquare(v1, center) - radiusSquare;
  53235. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  53236. interval /= 2;
  53237. if (diff < 0) {
  53238. if (nextDiff >= 0) {
  53239. t = t + interval;
  53240. } else {
  53241. t = t - interval;
  53242. }
  53243. } else {
  53244. if (nextDiff >= 0) {
  53245. t = t - interval;
  53246. } else {
  53247. t = t + interval;
  53248. }
  53249. }
  53250. }
  53251. return t;
  53252. } // Adjust edge to avoid
  53253. function adjustEdge(graph, scale) {
  53254. var tmp0 = [];
  53255. var quadraticSubdivide$1 = quadraticSubdivide;
  53256. var pts = [[], [], []];
  53257. var pts2 = [[], []];
  53258. var v = [];
  53259. scale /= 2;
  53260. graph.eachEdge(function (edge, idx) {
  53261. var linePoints = edge.getLayout();
  53262. var fromSymbol = edge.getVisual('fromSymbol');
  53263. var toSymbol = edge.getVisual('toSymbol');
  53264. if (!linePoints.__original) {
  53265. linePoints.__original = [clone$1(linePoints[0]), clone$1(linePoints[1])];
  53266. if (linePoints[2]) {
  53267. linePoints.__original.push(clone$1(linePoints[2]));
  53268. }
  53269. }
  53270. var originalPoints = linePoints.__original; // Quadratic curve
  53271. if (linePoints[2] != null) {
  53272. copy(pts[0], originalPoints[0]);
  53273. copy(pts[1], originalPoints[2]);
  53274. copy(pts[2], originalPoints[1]);
  53275. if (fromSymbol && fromSymbol !== 'none') {
  53276. var symbolSize = getSymbolSize(edge.node1);
  53277. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale); // Subdivide and get the second
  53278. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  53279. pts[0][0] = tmp0[3];
  53280. pts[1][0] = tmp0[4];
  53281. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  53282. pts[0][1] = tmp0[3];
  53283. pts[1][1] = tmp0[4];
  53284. }
  53285. if (toSymbol && toSymbol !== 'none') {
  53286. var symbolSize = getSymbolSize(edge.node2);
  53287. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale); // Subdivide and get the first
  53288. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  53289. pts[1][0] = tmp0[1];
  53290. pts[2][0] = tmp0[2];
  53291. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  53292. pts[1][1] = tmp0[1];
  53293. pts[2][1] = tmp0[2];
  53294. } // Copy back to layout
  53295. copy(linePoints[0], pts[0]);
  53296. copy(linePoints[1], pts[2]);
  53297. copy(linePoints[2], pts[1]);
  53298. } // Line
  53299. else {
  53300. copy(pts2[0], originalPoints[0]);
  53301. copy(pts2[1], originalPoints[1]);
  53302. sub(v, pts2[1], pts2[0]);
  53303. normalize(v, v);
  53304. if (fromSymbol && fromSymbol !== 'none') {
  53305. var symbolSize = getSymbolSize(edge.node1);
  53306. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale);
  53307. }
  53308. if (toSymbol && toSymbol !== 'none') {
  53309. var symbolSize = getSymbolSize(edge.node2);
  53310. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale);
  53311. }
  53312. copy(linePoints[0], pts2[0]);
  53313. copy(linePoints[1], pts2[1]);
  53314. }
  53315. });
  53316. }
  53317. function isViewCoordSys(coordSys) {
  53318. return coordSys.type === 'view';
  53319. }
  53320. var GraphView =
  53321. /** @class */
  53322. function (_super) {
  53323. __extends(GraphView, _super);
  53324. function GraphView() {
  53325. var _this = _super !== null && _super.apply(this, arguments) || this;
  53326. _this.type = GraphView.type;
  53327. return _this;
  53328. }
  53329. GraphView.prototype.init = function (ecModel, api) {
  53330. var symbolDraw = new SymbolDraw();
  53331. var lineDraw = new LineDraw();
  53332. var group = this.group;
  53333. this._controller = new RoamController(api.getZr());
  53334. this._controllerHost = {
  53335. target: group
  53336. };
  53337. group.add(symbolDraw.group);
  53338. group.add(lineDraw.group);
  53339. this._symbolDraw = symbolDraw;
  53340. this._lineDraw = lineDraw;
  53341. this._firstRender = true;
  53342. };
  53343. GraphView.prototype.render = function (seriesModel, ecModel, api) {
  53344. var _this = this;
  53345. var coordSys = seriesModel.coordinateSystem;
  53346. this._model = seriesModel;
  53347. var symbolDraw = this._symbolDraw;
  53348. var lineDraw = this._lineDraw;
  53349. var group = this.group;
  53350. if (isViewCoordSys(coordSys)) {
  53351. var groupNewProp = {
  53352. x: coordSys.x,
  53353. y: coordSys.y,
  53354. scaleX: coordSys.scaleX,
  53355. scaleY: coordSys.scaleY
  53356. };
  53357. if (this._firstRender) {
  53358. group.attr(groupNewProp);
  53359. } else {
  53360. updateProps(group, groupNewProp, seriesModel);
  53361. }
  53362. } // Fix edge contact point with node
  53363. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  53364. var data = seriesModel.getData();
  53365. symbolDraw.updateData(data);
  53366. var edgeData = seriesModel.getEdgeData(); // TODO: TYPE
  53367. lineDraw.updateData(edgeData);
  53368. this._updateNodeAndLinkScale();
  53369. this._updateController(seriesModel, ecModel, api);
  53370. clearTimeout(this._layoutTimeout);
  53371. var forceLayout = seriesModel.forceLayout;
  53372. var layoutAnimation = seriesModel.get(['force', 'layoutAnimation']);
  53373. if (forceLayout) {
  53374. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  53375. }
  53376. var layout = seriesModel.get('layout');
  53377. data.graph.eachNode(function (node) {
  53378. var idx = node.dataIndex;
  53379. var el = node.getGraphicEl();
  53380. var itemModel = node.getModel();
  53381. if (!el) {
  53382. return;
  53383. } // Update draggable
  53384. el.off('drag').off('dragend');
  53385. var draggable = itemModel.get('draggable');
  53386. if (draggable) {
  53387. el.on('drag', function (e) {
  53388. switch (layout) {
  53389. case 'force':
  53390. forceLayout.warmUp();
  53391. !_this._layouting && _this._startForceLayoutIteration(forceLayout, layoutAnimation);
  53392. forceLayout.setFixed(idx); // Write position back to layout
  53393. data.setItemLayout(idx, [el.x, el.y]);
  53394. break;
  53395. case 'circular':
  53396. data.setItemLayout(idx, [el.x, el.y]); // mark node fixed
  53397. node.setLayout({
  53398. fixed: true
  53399. }, true); // recalculate circular layout
  53400. circularLayout(seriesModel, 'symbolSize', node, [e.offsetX, e.offsetY]);
  53401. _this.updateLayout(seriesModel);
  53402. break;
  53403. case 'none':
  53404. default:
  53405. data.setItemLayout(idx, [el.x, el.y]); // update edge
  53406. simpleLayoutEdge(seriesModel.getGraph(), seriesModel);
  53407. _this.updateLayout(seriesModel);
  53408. break;
  53409. }
  53410. }).on('dragend', function () {
  53411. if (forceLayout) {
  53412. forceLayout.setUnfixed(idx);
  53413. }
  53414. });
  53415. }
  53416. el.setDraggable(draggable, !!itemModel.get('cursor'));
  53417. var focus = itemModel.get(['emphasis', 'focus']);
  53418. if (focus === 'adjacency') {
  53419. getECData(el).focus = node.getAdjacentDataIndices();
  53420. }
  53421. });
  53422. data.graph.eachEdge(function (edge) {
  53423. var el = edge.getGraphicEl();
  53424. var focus = edge.getModel().get(['emphasis', 'focus']);
  53425. if (!el) {
  53426. return;
  53427. }
  53428. if (focus === 'adjacency') {
  53429. getECData(el).focus = {
  53430. edge: [edge.dataIndex],
  53431. node: [edge.node1.dataIndex, edge.node2.dataIndex]
  53432. };
  53433. }
  53434. });
  53435. var circularRotateLabel = seriesModel.get('layout') === 'circular' && seriesModel.get(['circular', 'rotateLabel']);
  53436. var cx = data.getLayout('cx');
  53437. var cy = data.getLayout('cy');
  53438. data.graph.eachNode(function (node) {
  53439. rotateNodeLabel(node, circularRotateLabel, cx, cy);
  53440. });
  53441. this._firstRender = false;
  53442. };
  53443. GraphView.prototype.dispose = function () {
  53444. this._controller && this._controller.dispose();
  53445. this._controllerHost = null;
  53446. };
  53447. GraphView.prototype._startForceLayoutIteration = function (forceLayout, layoutAnimation) {
  53448. var self = this;
  53449. (function step() {
  53450. forceLayout.step(function (stopped) {
  53451. self.updateLayout(self._model);
  53452. (self._layouting = !stopped) && (layoutAnimation ? self._layoutTimeout = setTimeout(step, 16) : step());
  53453. });
  53454. })();
  53455. };
  53456. GraphView.prototype._updateController = function (seriesModel, ecModel, api) {
  53457. var _this = this;
  53458. var controller = this._controller;
  53459. var controllerHost = this._controllerHost;
  53460. var group = this.group;
  53461. controller.setPointerChecker(function (e, x, y) {
  53462. var rect = group.getBoundingRect();
  53463. rect.applyTransform(group.transform);
  53464. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  53465. });
  53466. if (!isViewCoordSys(seriesModel.coordinateSystem)) {
  53467. controller.disable();
  53468. return;
  53469. }
  53470. controller.enable(seriesModel.get('roam'));
  53471. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  53472. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  53473. controller.off('pan').off('zoom').on('pan', function (e) {
  53474. updateViewOnPan(controllerHost, e.dx, e.dy);
  53475. api.dispatchAction({
  53476. seriesId: seriesModel.id,
  53477. type: 'graphRoam',
  53478. dx: e.dx,
  53479. dy: e.dy
  53480. });
  53481. }).on('zoom', function (e) {
  53482. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  53483. api.dispatchAction({
  53484. seriesId: seriesModel.id,
  53485. type: 'graphRoam',
  53486. zoom: e.scale,
  53487. originX: e.originX,
  53488. originY: e.originY
  53489. });
  53490. _this._updateNodeAndLinkScale();
  53491. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  53492. _this._lineDraw.updateLayout(); // Only update label layout on zoom
  53493. api.updateLabelLayout();
  53494. });
  53495. };
  53496. GraphView.prototype._updateNodeAndLinkScale = function () {
  53497. var seriesModel = this._model;
  53498. var data = seriesModel.getData();
  53499. var nodeScale = getNodeGlobalScale(seriesModel);
  53500. data.eachItemGraphicEl(function (el, idx) {
  53501. el && el.setSymbolScale(nodeScale);
  53502. });
  53503. };
  53504. GraphView.prototype.updateLayout = function (seriesModel) {
  53505. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  53506. this._symbolDraw.updateLayout();
  53507. this._lineDraw.updateLayout();
  53508. };
  53509. GraphView.prototype.remove = function (ecModel, api) {
  53510. this._symbolDraw && this._symbolDraw.remove();
  53511. this._lineDraw && this._lineDraw.remove();
  53512. };
  53513. GraphView.type = 'graph';
  53514. return GraphView;
  53515. }(ChartView);
  53516. function generateNodeKey(id) {
  53517. return '_EC_' + id;
  53518. }
  53519. var Graph =
  53520. /** @class */
  53521. function () {
  53522. function Graph(directed) {
  53523. this.type = 'graph';
  53524. this.nodes = [];
  53525. this.edges = [];
  53526. this._nodesMap = {};
  53527. /**
  53528. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  53529. * @private
  53530. */
  53531. this._edgesMap = {};
  53532. this._directed = directed || false;
  53533. }
  53534. /**
  53535. * If is directed graph
  53536. */
  53537. Graph.prototype.isDirected = function () {
  53538. return this._directed;
  53539. };
  53540. /**
  53541. * Add a new node
  53542. */
  53543. Graph.prototype.addNode = function (id, dataIndex) {
  53544. id = id == null ? '' + dataIndex : '' + id;
  53545. var nodesMap = this._nodesMap;
  53546. if (nodesMap[generateNodeKey(id)]) {
  53547. if ("development" !== 'production') {
  53548. console.error('Graph nodes have duplicate name or id');
  53549. }
  53550. return;
  53551. }
  53552. var node = new GraphNode(id, dataIndex);
  53553. node.hostGraph = this;
  53554. this.nodes.push(node);
  53555. nodesMap[generateNodeKey(id)] = node;
  53556. return node;
  53557. };
  53558. /**
  53559. * Get node by data index
  53560. */
  53561. Graph.prototype.getNodeByIndex = function (dataIndex) {
  53562. var rawIdx = this.data.getRawIndex(dataIndex);
  53563. return this.nodes[rawIdx];
  53564. };
  53565. /**
  53566. * Get node by id
  53567. */
  53568. Graph.prototype.getNodeById = function (id) {
  53569. return this._nodesMap[generateNodeKey(id)];
  53570. };
  53571. /**
  53572. * Add a new edge
  53573. */
  53574. Graph.prototype.addEdge = function (n1, n2, dataIndex) {
  53575. var nodesMap = this._nodesMap;
  53576. var edgesMap = this._edgesMap; // PENDING
  53577. if (isNumber(n1)) {
  53578. n1 = this.nodes[n1];
  53579. }
  53580. if (isNumber(n2)) {
  53581. n2 = this.nodes[n2];
  53582. }
  53583. if (!(n1 instanceof GraphNode)) {
  53584. n1 = nodesMap[generateNodeKey(n1)];
  53585. }
  53586. if (!(n2 instanceof GraphNode)) {
  53587. n2 = nodesMap[generateNodeKey(n2)];
  53588. }
  53589. if (!n1 || !n2) {
  53590. return;
  53591. }
  53592. var key = n1.id + '-' + n2.id;
  53593. var edge = new GraphEdge(n1, n2, dataIndex);
  53594. edge.hostGraph = this;
  53595. if (this._directed) {
  53596. n1.outEdges.push(edge);
  53597. n2.inEdges.push(edge);
  53598. }
  53599. n1.edges.push(edge);
  53600. if (n1 !== n2) {
  53601. n2.edges.push(edge);
  53602. }
  53603. this.edges.push(edge);
  53604. edgesMap[key] = edge;
  53605. return edge;
  53606. };
  53607. /**
  53608. * Get edge by data index
  53609. */
  53610. Graph.prototype.getEdgeByIndex = function (dataIndex) {
  53611. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  53612. return this.edges[rawIdx];
  53613. };
  53614. /**
  53615. * Get edge by two linked nodes
  53616. */
  53617. Graph.prototype.getEdge = function (n1, n2) {
  53618. if (n1 instanceof GraphNode) {
  53619. n1 = n1.id;
  53620. }
  53621. if (n2 instanceof GraphNode) {
  53622. n2 = n2.id;
  53623. }
  53624. var edgesMap = this._edgesMap;
  53625. if (this._directed) {
  53626. return edgesMap[n1 + '-' + n2];
  53627. } else {
  53628. return edgesMap[n1 + '-' + n2] || edgesMap[n2 + '-' + n1];
  53629. }
  53630. };
  53631. /**
  53632. * Iterate all nodes
  53633. */
  53634. Graph.prototype.eachNode = function (cb, context) {
  53635. var nodes = this.nodes;
  53636. var len = nodes.length;
  53637. for (var i = 0; i < len; i++) {
  53638. if (nodes[i].dataIndex >= 0) {
  53639. cb.call(context, nodes[i], i);
  53640. }
  53641. }
  53642. };
  53643. /**
  53644. * Iterate all edges
  53645. */
  53646. Graph.prototype.eachEdge = function (cb, context) {
  53647. var edges = this.edges;
  53648. var len = edges.length;
  53649. for (var i = 0; i < len; i++) {
  53650. if (edges[i].dataIndex >= 0 && edges[i].node1.dataIndex >= 0 && edges[i].node2.dataIndex >= 0) {
  53651. cb.call(context, edges[i], i);
  53652. }
  53653. }
  53654. };
  53655. /**
  53656. * Breadth first traverse
  53657. * Return true to stop traversing
  53658. */
  53659. Graph.prototype.breadthFirstTraverse = function (cb, startNode, direction, context) {
  53660. if (!(startNode instanceof GraphNode)) {
  53661. startNode = this._nodesMap[generateNodeKey(startNode)];
  53662. }
  53663. if (!startNode) {
  53664. return;
  53665. }
  53666. var edgeType = direction === 'out' ? 'outEdges' : direction === 'in' ? 'inEdges' : 'edges';
  53667. for (var i = 0; i < this.nodes.length; i++) {
  53668. this.nodes[i].__visited = false;
  53669. }
  53670. if (cb.call(context, startNode, null)) {
  53671. return;
  53672. }
  53673. var queue = [startNode];
  53674. while (queue.length) {
  53675. var currentNode = queue.shift();
  53676. var edges = currentNode[edgeType];
  53677. for (var i = 0; i < edges.length; i++) {
  53678. var e = edges[i];
  53679. var otherNode = e.node1 === currentNode ? e.node2 : e.node1;
  53680. if (!otherNode.__visited) {
  53681. if (cb.call(context, otherNode, currentNode)) {
  53682. // Stop traversing
  53683. return;
  53684. }
  53685. queue.push(otherNode);
  53686. otherNode.__visited = true;
  53687. }
  53688. }
  53689. }
  53690. };
  53691. // depthFirstTraverse(
  53692. // cb, startNode, direction, context
  53693. // ) {
  53694. // };
  53695. // Filter update
  53696. Graph.prototype.update = function () {
  53697. var data = this.data;
  53698. var edgeData = this.edgeData;
  53699. var nodes = this.nodes;
  53700. var edges = this.edges;
  53701. for (var i = 0, len = nodes.length; i < len; i++) {
  53702. nodes[i].dataIndex = -1;
  53703. }
  53704. for (var i = 0, len = data.count(); i < len; i++) {
  53705. nodes[data.getRawIndex(i)].dataIndex = i;
  53706. }
  53707. edgeData.filterSelf(function (idx) {
  53708. var edge = edges[edgeData.getRawIndex(idx)];
  53709. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  53710. }); // Update edge
  53711. for (var i = 0, len = edges.length; i < len; i++) {
  53712. edges[i].dataIndex = -1;
  53713. }
  53714. for (var i = 0, len = edgeData.count(); i < len; i++) {
  53715. edges[edgeData.getRawIndex(i)].dataIndex = i;
  53716. }
  53717. };
  53718. /**
  53719. * @return {module:echarts/data/Graph}
  53720. */
  53721. Graph.prototype.clone = function () {
  53722. var graph = new Graph(this._directed);
  53723. var nodes = this.nodes;
  53724. var edges = this.edges;
  53725. for (var i = 0; i < nodes.length; i++) {
  53726. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  53727. }
  53728. for (var i = 0; i < edges.length; i++) {
  53729. var e = edges[i];
  53730. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  53731. }
  53732. return graph;
  53733. };
  53734. return Graph;
  53735. }();
  53736. var GraphNode =
  53737. /** @class */
  53738. function () {
  53739. function GraphNode(id, dataIndex) {
  53740. this.inEdges = [];
  53741. this.outEdges = [];
  53742. this.edges = [];
  53743. this.dataIndex = -1;
  53744. this.id = id == null ? '' : id;
  53745. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  53746. }
  53747. /**
  53748. * @return {number}
  53749. */
  53750. GraphNode.prototype.degree = function () {
  53751. return this.edges.length;
  53752. };
  53753. /**
  53754. * @return {number}
  53755. */
  53756. GraphNode.prototype.inDegree = function () {
  53757. return this.inEdges.length;
  53758. };
  53759. /**
  53760. * @return {number}
  53761. */
  53762. GraphNode.prototype.outDegree = function () {
  53763. return this.outEdges.length;
  53764. };
  53765. GraphNode.prototype.getModel = function (path) {
  53766. if (this.dataIndex < 0) {
  53767. return;
  53768. }
  53769. var graph = this.hostGraph;
  53770. var itemModel = graph.data.getItemModel(this.dataIndex);
  53771. return itemModel.getModel(path);
  53772. };
  53773. GraphNode.prototype.getAdjacentDataIndices = function () {
  53774. var dataIndices = {
  53775. edge: [],
  53776. node: []
  53777. };
  53778. for (var i = 0; i < this.edges.length; i++) {
  53779. var adjacentEdge = this.edges[i];
  53780. if (adjacentEdge.dataIndex < 0) {
  53781. continue;
  53782. }
  53783. dataIndices.edge.push(adjacentEdge.dataIndex);
  53784. dataIndices.node.push(adjacentEdge.node1.dataIndex, adjacentEdge.node2.dataIndex);
  53785. }
  53786. return dataIndices;
  53787. };
  53788. return GraphNode;
  53789. }();
  53790. var GraphEdge =
  53791. /** @class */
  53792. function () {
  53793. function GraphEdge(n1, n2, dataIndex) {
  53794. this.dataIndex = -1;
  53795. this.node1 = n1;
  53796. this.node2 = n2;
  53797. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  53798. } // eslint-disable-next-line @typescript-eslint/no-unused-vars
  53799. GraphEdge.prototype.getModel = function (path) {
  53800. if (this.dataIndex < 0) {
  53801. return;
  53802. }
  53803. var graph = this.hostGraph;
  53804. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  53805. return itemModel.getModel(path);
  53806. };
  53807. GraphEdge.prototype.getAdjacentDataIndices = function () {
  53808. return {
  53809. edge: [this.dataIndex],
  53810. node: [this.node1.dataIndex, this.node2.dataIndex]
  53811. };
  53812. };
  53813. return GraphEdge;
  53814. }();
  53815. function createGraphDataProxyMixin(hostName, dataName) {
  53816. return {
  53817. /**
  53818. * @param Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  53819. */
  53820. getValue: function (dimension) {
  53821. var data = this[hostName][dataName];
  53822. return data.getStore().get(data.getDimensionIndex(dimension || 'value'), this.dataIndex);
  53823. },
  53824. // TODO: TYPE stricter type.
  53825. setVisual: function (key, value) {
  53826. this.dataIndex >= 0 && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  53827. },
  53828. getVisual: function (key) {
  53829. return this[hostName][dataName].getItemVisual(this.dataIndex, key);
  53830. },
  53831. setLayout: function (layout, merge) {
  53832. this.dataIndex >= 0 && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge);
  53833. },
  53834. getLayout: function () {
  53835. return this[hostName][dataName].getItemLayout(this.dataIndex);
  53836. },
  53837. getGraphicEl: function () {
  53838. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  53839. },
  53840. getRawIndex: function () {
  53841. return this[hostName][dataName].getRawIndex(this.dataIndex);
  53842. }
  53843. };
  53844. }
  53845. mixin(GraphNode, createGraphDataProxyMixin('hostGraph', 'data'));
  53846. mixin(GraphEdge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  53847. function createGraphFromNodeEdge(nodes, edges, seriesModel, directed, beforeLink) {
  53848. // ??? TODO
  53849. // support dataset?
  53850. var graph = new Graph(directed);
  53851. for (var i = 0; i < nodes.length; i++) {
  53852. graph.addNode(retrieve( // Id, name, dataIndex
  53853. nodes[i].id, nodes[i].name, i), i);
  53854. }
  53855. var linkNameList = [];
  53856. var validEdges = [];
  53857. var linkCount = 0;
  53858. for (var i = 0; i < edges.length; i++) {
  53859. var link = edges[i];
  53860. var source = link.source;
  53861. var target = link.target; // addEdge may fail when source or target not exists
  53862. if (graph.addEdge(source, target, linkCount)) {
  53863. validEdges.push(link);
  53864. linkNameList.push(retrieve(convertOptionIdName(link.id, null), source + ' > ' + target));
  53865. linkCount++;
  53866. }
  53867. }
  53868. var coordSys = seriesModel.get('coordinateSystem');
  53869. var nodeData;
  53870. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  53871. nodeData = createSeriesData(nodes, seriesModel);
  53872. } else {
  53873. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  53874. var coordDimensions = coordSysCtor ? coordSysCtor.dimensions || [] : []; // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  53875. // `value` dimension, but graph need `value` dimension. It's better to
  53876. // uniform this behavior.
  53877. if (indexOf(coordDimensions, 'value') < 0) {
  53878. coordDimensions.concat(['value']);
  53879. }
  53880. var dimensions = prepareSeriesDataSchema(nodes, {
  53881. coordDimensions: coordDimensions,
  53882. encodeDefine: seriesModel.getEncode()
  53883. }).dimensions;
  53884. nodeData = new SeriesData(dimensions, seriesModel);
  53885. nodeData.initData(nodes);
  53886. }
  53887. var edgeData = new SeriesData(['value'], seriesModel);
  53888. edgeData.initData(validEdges, linkNameList);
  53889. beforeLink && beforeLink(nodeData, edgeData);
  53890. linkSeriesData({
  53891. mainData: nodeData,
  53892. struct: graph,
  53893. structAttr: 'graph',
  53894. datas: {
  53895. node: nodeData,
  53896. edge: edgeData
  53897. },
  53898. datasAttr: {
  53899. node: 'data',
  53900. edge: 'edgeData'
  53901. }
  53902. }); // Update dataIndex of nodes and edges because invalid edge may be removed
  53903. graph.update();
  53904. return graph;
  53905. }
  53906. var GraphSeriesModel =
  53907. /** @class */
  53908. function (_super) {
  53909. __extends(GraphSeriesModel, _super);
  53910. function GraphSeriesModel() {
  53911. var _this = _super !== null && _super.apply(this, arguments) || this;
  53912. _this.type = GraphSeriesModel.type;
  53913. _this.hasSymbolVisual = true;
  53914. return _this;
  53915. }
  53916. GraphSeriesModel.prototype.init = function (option) {
  53917. _super.prototype.init.apply(this, arguments);
  53918. var self = this;
  53919. function getCategoriesData() {
  53920. return self._categoriesData;
  53921. } // Provide data for legend select
  53922. this.legendVisualProvider = new LegendVisualProvider(getCategoriesData, getCategoriesData);
  53923. this.fillDataTextStyle(option.edges || option.links);
  53924. this._updateCategoriesData();
  53925. };
  53926. GraphSeriesModel.prototype.mergeOption = function (option) {
  53927. _super.prototype.mergeOption.apply(this, arguments);
  53928. this.fillDataTextStyle(option.edges || option.links);
  53929. this._updateCategoriesData();
  53930. };
  53931. GraphSeriesModel.prototype.mergeDefaultAndTheme = function (option) {
  53932. _super.prototype.mergeDefaultAndTheme.apply(this, arguments);
  53933. defaultEmphasis(option, 'edgeLabel', ['show']);
  53934. };
  53935. GraphSeriesModel.prototype.getInitialData = function (option, ecModel) {
  53936. var edges = option.edges || option.links || [];
  53937. var nodes = option.data || option.nodes || [];
  53938. var self = this;
  53939. if (nodes && edges) {
  53940. // auto curveness
  53941. initCurvenessList(this);
  53942. var graph = createGraphFromNodeEdge(nodes, edges, this, true, beforeLink);
  53943. each(graph.edges, function (edge) {
  53944. createEdgeMapForCurveness(edge.node1, edge.node2, this, edge.dataIndex);
  53945. }, this);
  53946. return graph.data;
  53947. }
  53948. function beforeLink(nodeData, edgeData) {
  53949. // Overwrite nodeData.getItemModel to
  53950. nodeData.wrapMethod('getItemModel', function (model) {
  53951. var categoriesModels = self._categoriesModels;
  53952. var categoryIdx = model.getShallow('category');
  53953. var categoryModel = categoriesModels[categoryIdx];
  53954. if (categoryModel) {
  53955. categoryModel.parentModel = model.parentModel;
  53956. model.parentModel = categoryModel;
  53957. }
  53958. return model;
  53959. }); // TODO Inherit resolveParentPath by default in Model#getModel?
  53960. var oldGetModel = Model.prototype.getModel;
  53961. function newGetModel(path, parentModel) {
  53962. var model = oldGetModel.call(this, path, parentModel);
  53963. model.resolveParentPath = resolveParentPath;
  53964. return model;
  53965. }
  53966. edgeData.wrapMethod('getItemModel', function (model) {
  53967. model.resolveParentPath = resolveParentPath;
  53968. model.getModel = newGetModel;
  53969. return model;
  53970. });
  53971. function resolveParentPath(pathArr) {
  53972. if (pathArr && (pathArr[0] === 'label' || pathArr[1] === 'label')) {
  53973. var newPathArr = pathArr.slice();
  53974. if (pathArr[0] === 'label') {
  53975. newPathArr[0] = 'edgeLabel';
  53976. } else if (pathArr[1] === 'label') {
  53977. newPathArr[1] = 'edgeLabel';
  53978. }
  53979. return newPathArr;
  53980. }
  53981. return pathArr;
  53982. }
  53983. }
  53984. };
  53985. GraphSeriesModel.prototype.getGraph = function () {
  53986. return this.getData().graph;
  53987. };
  53988. GraphSeriesModel.prototype.getEdgeData = function () {
  53989. return this.getGraph().edgeData;
  53990. };
  53991. GraphSeriesModel.prototype.getCategoriesData = function () {
  53992. return this._categoriesData;
  53993. };
  53994. GraphSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  53995. if (dataType === 'edge') {
  53996. var nodeData = this.getData();
  53997. var params = this.getDataParams(dataIndex, dataType);
  53998. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  53999. var sourceName = nodeData.getName(edge.node1.dataIndex);
  54000. var targetName = nodeData.getName(edge.node2.dataIndex);
  54001. var nameArr = [];
  54002. sourceName != null && nameArr.push(sourceName);
  54003. targetName != null && nameArr.push(targetName);
  54004. return createTooltipMarkup('nameValue', {
  54005. name: nameArr.join(' > '),
  54006. value: params.value,
  54007. noValue: params.value == null
  54008. });
  54009. } // dataType === 'node' or empty
  54010. var nodeMarkup = defaultSeriesFormatTooltip({
  54011. series: this,
  54012. dataIndex: dataIndex,
  54013. multipleSeries: multipleSeries
  54014. });
  54015. return nodeMarkup;
  54016. };
  54017. GraphSeriesModel.prototype._updateCategoriesData = function () {
  54018. var categories = map(this.option.categories || [], function (category) {
  54019. // Data must has value
  54020. return category.value != null ? category : extend({
  54021. value: 0
  54022. }, category);
  54023. });
  54024. var categoriesData = new SeriesData(['value'], this);
  54025. categoriesData.initData(categories);
  54026. this._categoriesData = categoriesData;
  54027. this._categoriesModels = categoriesData.mapArray(function (idx) {
  54028. return categoriesData.getItemModel(idx);
  54029. });
  54030. };
  54031. GraphSeriesModel.prototype.setZoom = function (zoom) {
  54032. this.option.zoom = zoom;
  54033. };
  54034. GraphSeriesModel.prototype.setCenter = function (center) {
  54035. this.option.center = center;
  54036. };
  54037. GraphSeriesModel.prototype.isAnimationEnabled = function () {
  54038. return _super.prototype.isAnimationEnabled.call(this) // Not enable animation when do force layout
  54039. && !(this.get('layout') === 'force' && this.get(['force', 'layoutAnimation']));
  54040. };
  54041. GraphSeriesModel.type = 'series.graph';
  54042. GraphSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  54043. GraphSeriesModel.defaultOption = {
  54044. // zlevel: 0,
  54045. z: 2,
  54046. coordinateSystem: 'view',
  54047. // Default option for all coordinate systems
  54048. // xAxisIndex: 0,
  54049. // yAxisIndex: 0,
  54050. // polarIndex: 0,
  54051. // geoIndex: 0,
  54052. legendHoverLink: true,
  54053. layout: null,
  54054. // Configuration of circular layout
  54055. circular: {
  54056. rotateLabel: false
  54057. },
  54058. // Configuration of force directed layout
  54059. force: {
  54060. initLayout: null,
  54061. // Node repulsion. Can be an array to represent range.
  54062. repulsion: [0, 50],
  54063. gravity: 0.1,
  54064. // Initial friction
  54065. friction: 0.6,
  54066. // Edge length. Can be an array to represent range.
  54067. edgeLength: 30,
  54068. layoutAnimation: true
  54069. },
  54070. left: 'center',
  54071. top: 'center',
  54072. // right: null,
  54073. // bottom: null,
  54074. // width: '80%',
  54075. // height: '80%',
  54076. symbol: 'circle',
  54077. symbolSize: 10,
  54078. edgeSymbol: ['none', 'none'],
  54079. edgeSymbolSize: 10,
  54080. edgeLabel: {
  54081. position: 'middle',
  54082. distance: 5
  54083. },
  54084. draggable: false,
  54085. roam: false,
  54086. // Default on center of graph
  54087. center: null,
  54088. zoom: 1,
  54089. // Symbol size scale ratio in roam
  54090. nodeScaleRatio: 0.6,
  54091. // cursor: null,
  54092. // categories: [],
  54093. // data: []
  54094. // Or
  54095. // nodes: []
  54096. //
  54097. // links: []
  54098. // Or
  54099. // edges: []
  54100. label: {
  54101. show: false,
  54102. formatter: '{b}'
  54103. },
  54104. itemStyle: {},
  54105. lineStyle: {
  54106. color: '#aaa',
  54107. width: 1,
  54108. opacity: 0.5
  54109. },
  54110. emphasis: {
  54111. scale: true,
  54112. label: {
  54113. show: true
  54114. }
  54115. },
  54116. select: {
  54117. itemStyle: {
  54118. borderColor: '#212121'
  54119. }
  54120. }
  54121. };
  54122. return GraphSeriesModel;
  54123. }(SeriesModel);
  54124. var actionInfo = {
  54125. type: 'graphRoam',
  54126. event: 'graphRoam',
  54127. update: 'none'
  54128. };
  54129. function install$d(registers) {
  54130. registers.registerChartView(GraphView);
  54131. registers.registerSeriesModel(GraphSeriesModel);
  54132. registers.registerProcessor(categoryFilter);
  54133. registers.registerVisual(categoryVisual);
  54134. registers.registerVisual(graphEdgeVisual);
  54135. registers.registerLayout(graphSimpleLayout);
  54136. registers.registerLayout(registers.PRIORITY.VISUAL.POST_CHART_LAYOUT, graphCircularLayout);
  54137. registers.registerLayout(graphForceLayout);
  54138. registers.registerCoordinateSystem('graphView', {
  54139. dimensions: View.dimensions,
  54140. create: createViewCoordSys
  54141. }); // Register legacy focus actions
  54142. registers.registerAction({
  54143. type: 'focusNodeAdjacency',
  54144. event: 'focusNodeAdjacency',
  54145. update: 'series:focusNodeAdjacency'
  54146. }, noop);
  54147. registers.registerAction({
  54148. type: 'unfocusNodeAdjacency',
  54149. event: 'unfocusNodeAdjacency',
  54150. update: 'series:unfocusNodeAdjacency'
  54151. }, noop); // Register roam action.
  54152. registers.registerAction(actionInfo, function (payload, ecModel, api) {
  54153. ecModel.eachComponent({
  54154. mainType: 'series',
  54155. query: payload
  54156. }, function (seriesModel) {
  54157. var coordSys = seriesModel.coordinateSystem;
  54158. var res = updateCenterAndZoom(coordSys, payload, undefined, api);
  54159. seriesModel.setCenter && seriesModel.setCenter(res.center);
  54160. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  54161. });
  54162. });
  54163. }
  54164. var PointerShape =
  54165. /** @class */
  54166. function () {
  54167. function PointerShape() {
  54168. this.angle = 0;
  54169. this.width = 10;
  54170. this.r = 10;
  54171. this.x = 0;
  54172. this.y = 0;
  54173. }
  54174. return PointerShape;
  54175. }();
  54176. var PointerPath =
  54177. /** @class */
  54178. function (_super) {
  54179. __extends(PointerPath, _super);
  54180. function PointerPath(opts) {
  54181. var _this = _super.call(this, opts) || this;
  54182. _this.type = 'pointer';
  54183. return _this;
  54184. }
  54185. PointerPath.prototype.getDefaultShape = function () {
  54186. return new PointerShape();
  54187. };
  54188. PointerPath.prototype.buildPath = function (ctx, shape) {
  54189. var mathCos = Math.cos;
  54190. var mathSin = Math.sin;
  54191. var r = shape.r;
  54192. var width = shape.width;
  54193. var angle = shape.angle;
  54194. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  54195. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  54196. angle = shape.angle - Math.PI / 2;
  54197. ctx.moveTo(x, y);
  54198. ctx.lineTo(shape.x + mathCos(angle) * width, shape.y + mathSin(angle) * width);
  54199. ctx.lineTo(shape.x + mathCos(shape.angle) * r, shape.y + mathSin(shape.angle) * r);
  54200. ctx.lineTo(shape.x - mathCos(angle) * width, shape.y - mathSin(angle) * width);
  54201. ctx.lineTo(x, y);
  54202. };
  54203. return PointerPath;
  54204. }(Path);
  54205. function parsePosition(seriesModel, api) {
  54206. var center = seriesModel.get('center');
  54207. var width = api.getWidth();
  54208. var height = api.getHeight();
  54209. var size = Math.min(width, height);
  54210. var cx = parsePercent$1(center[0], api.getWidth());
  54211. var cy = parsePercent$1(center[1], api.getHeight());
  54212. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  54213. return {
  54214. cx: cx,
  54215. cy: cy,
  54216. r: r
  54217. };
  54218. }
  54219. function formatLabel(value, labelFormatter) {
  54220. var label = value == null ? '' : value + '';
  54221. if (labelFormatter) {
  54222. if (isString(labelFormatter)) {
  54223. label = labelFormatter.replace('{value}', label);
  54224. } else if (isFunction(labelFormatter)) {
  54225. label = labelFormatter(value);
  54226. }
  54227. }
  54228. return label;
  54229. }
  54230. var GaugeView =
  54231. /** @class */
  54232. function (_super) {
  54233. __extends(GaugeView, _super);
  54234. function GaugeView() {
  54235. var _this = _super !== null && _super.apply(this, arguments) || this;
  54236. _this.type = GaugeView.type;
  54237. return _this;
  54238. }
  54239. GaugeView.prototype.render = function (seriesModel, ecModel, api) {
  54240. this.group.removeAll();
  54241. var colorList = seriesModel.get(['axisLine', 'lineStyle', 'color']);
  54242. var posInfo = parsePosition(seriesModel, api);
  54243. this._renderMain(seriesModel, ecModel, api, colorList, posInfo);
  54244. this._data = seriesModel.getData();
  54245. };
  54246. GaugeView.prototype.dispose = function () {};
  54247. GaugeView.prototype._renderMain = function (seriesModel, ecModel, api, colorList, posInfo) {
  54248. var group = this.group;
  54249. var clockwise = seriesModel.get('clockwise');
  54250. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  54251. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  54252. var axisLineModel = seriesModel.getModel('axisLine');
  54253. var roundCap = axisLineModel.get('roundCap');
  54254. var MainPath = roundCap ? SausagePath : Sector;
  54255. var showAxis = axisLineModel.get('show');
  54256. var lineStyleModel = axisLineModel.getModel('lineStyle');
  54257. var axisLineWidth = lineStyleModel.get('width');
  54258. var angles = [startAngle, endAngle];
  54259. normalizeArcAngles(angles, !clockwise);
  54260. startAngle = angles[0];
  54261. endAngle = angles[1];
  54262. var angleRangeSpan = endAngle - startAngle;
  54263. var prevEndAngle = startAngle;
  54264. var sectors = [];
  54265. for (var i = 0; showAxis && i < colorList.length; i++) {
  54266. // Clamp
  54267. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  54268. endAngle = startAngle + angleRangeSpan * percent;
  54269. var sector = new MainPath({
  54270. shape: {
  54271. startAngle: prevEndAngle,
  54272. endAngle: endAngle,
  54273. cx: posInfo.cx,
  54274. cy: posInfo.cy,
  54275. clockwise: clockwise,
  54276. r0: posInfo.r - axisLineWidth,
  54277. r: posInfo.r
  54278. },
  54279. silent: true
  54280. });
  54281. sector.setStyle({
  54282. fill: colorList[i][1]
  54283. });
  54284. sector.setStyle(lineStyleModel.getLineStyle( // Because we use sector to simulate arc
  54285. // so the properties for stroking are useless
  54286. ['color', 'width']));
  54287. sectors.push(sector);
  54288. prevEndAngle = endAngle;
  54289. }
  54290. sectors.reverse();
  54291. each(sectors, function (sector) {
  54292. return group.add(sector);
  54293. });
  54294. var getColor = function (percent) {
  54295. // Less than 0
  54296. if (percent <= 0) {
  54297. return colorList[0][1];
  54298. }
  54299. var i;
  54300. for (i = 0; i < colorList.length; i++) {
  54301. if (colorList[i][0] >= percent && (i === 0 ? 0 : colorList[i - 1][0]) < percent) {
  54302. return colorList[i][1];
  54303. }
  54304. } // More than 1
  54305. return colorList[i - 1][1];
  54306. };
  54307. this._renderTicks(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  54308. this._renderTitleAndDetail(seriesModel, ecModel, api, getColor, posInfo);
  54309. this._renderAnchor(seriesModel, posInfo);
  54310. this._renderPointer(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  54311. };
  54312. GaugeView.prototype._renderTicks = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  54313. var group = this.group;
  54314. var cx = posInfo.cx;
  54315. var cy = posInfo.cy;
  54316. var r = posInfo.r;
  54317. var minVal = +seriesModel.get('min');
  54318. var maxVal = +seriesModel.get('max');
  54319. var splitLineModel = seriesModel.getModel('splitLine');
  54320. var tickModel = seriesModel.getModel('axisTick');
  54321. var labelModel = seriesModel.getModel('axisLabel');
  54322. var splitNumber = seriesModel.get('splitNumber');
  54323. var subSplitNumber = tickModel.get('splitNumber');
  54324. var splitLineLen = parsePercent$1(splitLineModel.get('length'), r);
  54325. var tickLen = parsePercent$1(tickModel.get('length'), r);
  54326. var angle = startAngle;
  54327. var step = (endAngle - startAngle) / splitNumber;
  54328. var subStep = step / subSplitNumber;
  54329. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  54330. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  54331. var splitLineDistance = splitLineModel.get('distance');
  54332. var unitX;
  54333. var unitY;
  54334. for (var i = 0; i <= splitNumber; i++) {
  54335. unitX = Math.cos(angle);
  54336. unitY = Math.sin(angle); // Split line
  54337. if (splitLineModel.get('show')) {
  54338. var distance = splitLineDistance ? splitLineDistance + axisLineWidth : axisLineWidth;
  54339. var splitLine = new Line({
  54340. shape: {
  54341. x1: unitX * (r - distance) + cx,
  54342. y1: unitY * (r - distance) + cy,
  54343. x2: unitX * (r - splitLineLen - distance) + cx,
  54344. y2: unitY * (r - splitLineLen - distance) + cy
  54345. },
  54346. style: splitLineStyle,
  54347. silent: true
  54348. });
  54349. if (splitLineStyle.stroke === 'auto') {
  54350. splitLine.setStyle({
  54351. stroke: getColor(i / splitNumber)
  54352. });
  54353. }
  54354. group.add(splitLine);
  54355. } // Label
  54356. if (labelModel.get('show')) {
  54357. var distance = labelModel.get('distance') + splitLineDistance;
  54358. var label = formatLabel(round(i / splitNumber * (maxVal - minVal) + minVal), labelModel.get('formatter'));
  54359. var autoColor = getColor(i / splitNumber);
  54360. var textStyleX = unitX * (r - splitLineLen - distance) + cx;
  54361. var textStyleY = unitY * (r - splitLineLen - distance) + cy;
  54362. var rotateType = labelModel.get('rotate');
  54363. var rotate = 0;
  54364. if (rotateType === 'radial') {
  54365. rotate = -angle + 2 * Math.PI;
  54366. if (rotate > Math.PI / 2) {
  54367. rotate += Math.PI;
  54368. }
  54369. } else if (rotateType === 'tangential') {
  54370. rotate = -angle - Math.PI / 2;
  54371. } else if (isNumber(rotateType)) {
  54372. rotate = rotateType * Math.PI / 180;
  54373. }
  54374. if (rotate === 0) {
  54375. group.add(new ZRText({
  54376. style: createTextStyle(labelModel, {
  54377. text: label,
  54378. x: textStyleX,
  54379. y: textStyleY,
  54380. verticalAlign: unitY < -0.8 ? 'top' : unitY > 0.8 ? 'bottom' : 'middle',
  54381. align: unitX < -0.4 ? 'left' : unitX > 0.4 ? 'right' : 'center'
  54382. }, {
  54383. inheritColor: autoColor
  54384. }),
  54385. silent: true
  54386. }));
  54387. } else {
  54388. group.add(new ZRText({
  54389. style: createTextStyle(labelModel, {
  54390. text: label,
  54391. x: textStyleX,
  54392. y: textStyleY,
  54393. verticalAlign: 'middle',
  54394. align: 'center'
  54395. }, {
  54396. inheritColor: autoColor
  54397. }),
  54398. silent: true,
  54399. originX: textStyleX,
  54400. originY: textStyleY,
  54401. rotation: rotate
  54402. }));
  54403. }
  54404. } // Axis tick
  54405. if (tickModel.get('show') && i !== splitNumber) {
  54406. var distance = tickModel.get('distance');
  54407. distance = distance ? distance + axisLineWidth : axisLineWidth;
  54408. for (var j = 0; j <= subSplitNumber; j++) {
  54409. unitX = Math.cos(angle);
  54410. unitY = Math.sin(angle);
  54411. var tickLine = new Line({
  54412. shape: {
  54413. x1: unitX * (r - distance) + cx,
  54414. y1: unitY * (r - distance) + cy,
  54415. x2: unitX * (r - tickLen - distance) + cx,
  54416. y2: unitY * (r - tickLen - distance) + cy
  54417. },
  54418. silent: true,
  54419. style: tickLineStyle
  54420. });
  54421. if (tickLineStyle.stroke === 'auto') {
  54422. tickLine.setStyle({
  54423. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  54424. });
  54425. }
  54426. group.add(tickLine);
  54427. angle += subStep;
  54428. }
  54429. angle -= subStep;
  54430. } else {
  54431. angle += step;
  54432. }
  54433. }
  54434. };
  54435. GaugeView.prototype._renderPointer = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  54436. var group = this.group;
  54437. var oldData = this._data;
  54438. var oldProgressData = this._progressEls;
  54439. var progressList = [];
  54440. var showPointer = seriesModel.get(['pointer', 'show']);
  54441. var progressModel = seriesModel.getModel('progress');
  54442. var showProgress = progressModel.get('show');
  54443. var data = seriesModel.getData();
  54444. var valueDim = data.mapDimension('value');
  54445. var minVal = +seriesModel.get('min');
  54446. var maxVal = +seriesModel.get('max');
  54447. var valueExtent = [minVal, maxVal];
  54448. var angleExtent = [startAngle, endAngle];
  54449. function createPointer(idx, angle) {
  54450. var itemModel = data.getItemModel(idx);
  54451. var pointerModel = itemModel.getModel('pointer');
  54452. var pointerWidth = parsePercent$1(pointerModel.get('width'), posInfo.r);
  54453. var pointerLength = parsePercent$1(pointerModel.get('length'), posInfo.r);
  54454. var pointerStr = seriesModel.get(['pointer', 'icon']);
  54455. var pointerOffset = pointerModel.get('offsetCenter');
  54456. var pointerOffsetX = parsePercent$1(pointerOffset[0], posInfo.r);
  54457. var pointerOffsetY = parsePercent$1(pointerOffset[1], posInfo.r);
  54458. var pointerKeepAspect = pointerModel.get('keepAspect');
  54459. var pointer; // not exist icon type will be set 'rect'
  54460. if (pointerStr) {
  54461. pointer = createSymbol(pointerStr, pointerOffsetX - pointerWidth / 2, pointerOffsetY - pointerLength, pointerWidth, pointerLength, null, pointerKeepAspect);
  54462. } else {
  54463. pointer = new PointerPath({
  54464. shape: {
  54465. angle: -Math.PI / 2,
  54466. width: pointerWidth,
  54467. r: pointerLength,
  54468. x: pointerOffsetX,
  54469. y: pointerOffsetY
  54470. }
  54471. });
  54472. }
  54473. pointer.rotation = -(angle + Math.PI / 2);
  54474. pointer.x = posInfo.cx;
  54475. pointer.y = posInfo.cy;
  54476. return pointer;
  54477. }
  54478. function createProgress(idx, endAngle) {
  54479. var roundCap = progressModel.get('roundCap');
  54480. var ProgressPath = roundCap ? SausagePath : Sector;
  54481. var isOverlap = progressModel.get('overlap');
  54482. var progressWidth = isOverlap ? progressModel.get('width') : axisLineWidth / data.count();
  54483. var r0 = isOverlap ? posInfo.r - progressWidth : posInfo.r - (idx + 1) * progressWidth;
  54484. var r = isOverlap ? posInfo.r : posInfo.r - idx * progressWidth;
  54485. var progress = new ProgressPath({
  54486. shape: {
  54487. startAngle: startAngle,
  54488. endAngle: endAngle,
  54489. cx: posInfo.cx,
  54490. cy: posInfo.cy,
  54491. clockwise: clockwise,
  54492. r0: r0,
  54493. r: r
  54494. }
  54495. });
  54496. isOverlap && (progress.z2 = maxVal - data.get(valueDim, idx) % maxVal);
  54497. return progress;
  54498. }
  54499. if (showProgress || showPointer) {
  54500. data.diff(oldData).add(function (idx) {
  54501. var val = data.get(valueDim, idx);
  54502. if (showPointer) {
  54503. var pointer = createPointer(idx, startAngle); // TODO hide pointer on NaN value?
  54504. initProps(pointer, {
  54505. rotation: -((isNaN(+val) ? angleExtent[0] : linearMap(val, valueExtent, angleExtent, true)) + Math.PI / 2)
  54506. }, seriesModel);
  54507. group.add(pointer);
  54508. data.setItemGraphicEl(idx, pointer);
  54509. }
  54510. if (showProgress) {
  54511. var progress = createProgress(idx, startAngle);
  54512. var isClip = progressModel.get('clip');
  54513. initProps(progress, {
  54514. shape: {
  54515. endAngle: linearMap(val, valueExtent, angleExtent, isClip)
  54516. }
  54517. }, seriesModel);
  54518. group.add(progress); // Add data index and series index for indexing the data by element
  54519. // Useful in tooltip
  54520. setCommonECData(seriesModel.seriesIndex, data.dataType, idx, progress);
  54521. progressList[idx] = progress;
  54522. }
  54523. }).update(function (newIdx, oldIdx) {
  54524. var val = data.get(valueDim, newIdx);
  54525. if (showPointer) {
  54526. var previousPointer = oldData.getItemGraphicEl(oldIdx);
  54527. var previousRotate = previousPointer ? previousPointer.rotation : startAngle;
  54528. var pointer = createPointer(newIdx, previousRotate);
  54529. pointer.rotation = previousRotate;
  54530. updateProps(pointer, {
  54531. rotation: -((isNaN(+val) ? angleExtent[0] : linearMap(val, valueExtent, angleExtent, true)) + Math.PI / 2)
  54532. }, seriesModel);
  54533. group.add(pointer);
  54534. data.setItemGraphicEl(newIdx, pointer);
  54535. }
  54536. if (showProgress) {
  54537. var previousProgress = oldProgressData[oldIdx];
  54538. var previousEndAngle = previousProgress ? previousProgress.shape.endAngle : startAngle;
  54539. var progress = createProgress(newIdx, previousEndAngle);
  54540. var isClip = progressModel.get('clip');
  54541. updateProps(progress, {
  54542. shape: {
  54543. endAngle: linearMap(val, valueExtent, angleExtent, isClip)
  54544. }
  54545. }, seriesModel);
  54546. group.add(progress); // Add data index and series index for indexing the data by element
  54547. // Useful in tooltip
  54548. setCommonECData(seriesModel.seriesIndex, data.dataType, newIdx, progress);
  54549. progressList[newIdx] = progress;
  54550. }
  54551. }).execute();
  54552. data.each(function (idx) {
  54553. var itemModel = data.getItemModel(idx);
  54554. var emphasisModel = itemModel.getModel('emphasis');
  54555. var focus = emphasisModel.get('focus');
  54556. var blurScope = emphasisModel.get('blurScope');
  54557. var emphasisDisabled = emphasisModel.get('disabled');
  54558. if (showPointer) {
  54559. var pointer = data.getItemGraphicEl(idx);
  54560. var symbolStyle = data.getItemVisual(idx, 'style');
  54561. var visualColor = symbolStyle.fill;
  54562. if (pointer instanceof ZRImage) {
  54563. var pathStyle = pointer.style;
  54564. pointer.useStyle(extend({
  54565. image: pathStyle.image,
  54566. x: pathStyle.x,
  54567. y: pathStyle.y,
  54568. width: pathStyle.width,
  54569. height: pathStyle.height
  54570. }, symbolStyle));
  54571. } else {
  54572. pointer.useStyle(symbolStyle);
  54573. pointer.type !== 'pointer' && pointer.setColor(visualColor);
  54574. }
  54575. pointer.setStyle(itemModel.getModel(['pointer', 'itemStyle']).getItemStyle());
  54576. if (pointer.style.fill === 'auto') {
  54577. pointer.setStyle('fill', getColor(linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)));
  54578. }
  54579. pointer.z2EmphasisLift = 0;
  54580. setStatesStylesFromModel(pointer, itemModel);
  54581. toggleHoverEmphasis(pointer, focus, blurScope, emphasisDisabled);
  54582. }
  54583. if (showProgress) {
  54584. var progress = progressList[idx];
  54585. progress.useStyle(data.getItemVisual(idx, 'style'));
  54586. progress.setStyle(itemModel.getModel(['progress', 'itemStyle']).getItemStyle());
  54587. progress.z2EmphasisLift = 0;
  54588. setStatesStylesFromModel(progress, itemModel);
  54589. toggleHoverEmphasis(progress, focus, blurScope, emphasisDisabled);
  54590. }
  54591. });
  54592. this._progressEls = progressList;
  54593. }
  54594. };
  54595. GaugeView.prototype._renderAnchor = function (seriesModel, posInfo) {
  54596. var anchorModel = seriesModel.getModel('anchor');
  54597. var showAnchor = anchorModel.get('show');
  54598. if (showAnchor) {
  54599. var anchorSize = anchorModel.get('size');
  54600. var anchorType = anchorModel.get('icon');
  54601. var offsetCenter = anchorModel.get('offsetCenter');
  54602. var anchorKeepAspect = anchorModel.get('keepAspect');
  54603. var anchor = createSymbol(anchorType, posInfo.cx - anchorSize / 2 + parsePercent$1(offsetCenter[0], posInfo.r), posInfo.cy - anchorSize / 2 + parsePercent$1(offsetCenter[1], posInfo.r), anchorSize, anchorSize, null, anchorKeepAspect);
  54604. anchor.z2 = anchorModel.get('showAbove') ? 1 : 0;
  54605. anchor.setStyle(anchorModel.getModel('itemStyle').getItemStyle());
  54606. this.group.add(anchor);
  54607. }
  54608. };
  54609. GaugeView.prototype._renderTitleAndDetail = function (seriesModel, ecModel, api, getColor, posInfo) {
  54610. var _this = this;
  54611. var data = seriesModel.getData();
  54612. var valueDim = data.mapDimension('value');
  54613. var minVal = +seriesModel.get('min');
  54614. var maxVal = +seriesModel.get('max');
  54615. var contentGroup = new Group();
  54616. var newTitleEls = [];
  54617. var newDetailEls = [];
  54618. var hasAnimation = seriesModel.isAnimationEnabled();
  54619. var showPointerAbove = seriesModel.get(['pointer', 'showAbove']);
  54620. data.diff(this._data).add(function (idx) {
  54621. newTitleEls[idx] = new ZRText({
  54622. silent: true
  54623. });
  54624. newDetailEls[idx] = new ZRText({
  54625. silent: true
  54626. });
  54627. }).update(function (idx, oldIdx) {
  54628. newTitleEls[idx] = _this._titleEls[oldIdx];
  54629. newDetailEls[idx] = _this._detailEls[oldIdx];
  54630. }).execute();
  54631. data.each(function (idx) {
  54632. var itemModel = data.getItemModel(idx);
  54633. var value = data.get(valueDim, idx);
  54634. var itemGroup = new Group();
  54635. var autoColor = getColor(linearMap(value, [minVal, maxVal], [0, 1], true));
  54636. var itemTitleModel = itemModel.getModel('title');
  54637. if (itemTitleModel.get('show')) {
  54638. var titleOffsetCenter = itemTitleModel.get('offsetCenter');
  54639. var titleX = posInfo.cx + parsePercent$1(titleOffsetCenter[0], posInfo.r);
  54640. var titleY = posInfo.cy + parsePercent$1(titleOffsetCenter[1], posInfo.r);
  54641. var labelEl = newTitleEls[idx];
  54642. labelEl.attr({
  54643. z2: showPointerAbove ? 0 : 2,
  54644. style: createTextStyle(itemTitleModel, {
  54645. x: titleX,
  54646. y: titleY,
  54647. text: data.getName(idx),
  54648. align: 'center',
  54649. verticalAlign: 'middle'
  54650. }, {
  54651. inheritColor: autoColor
  54652. })
  54653. });
  54654. itemGroup.add(labelEl);
  54655. }
  54656. var itemDetailModel = itemModel.getModel('detail');
  54657. if (itemDetailModel.get('show')) {
  54658. var detailOffsetCenter = itemDetailModel.get('offsetCenter');
  54659. var detailX = posInfo.cx + parsePercent$1(detailOffsetCenter[0], posInfo.r);
  54660. var detailY = posInfo.cy + parsePercent$1(detailOffsetCenter[1], posInfo.r);
  54661. var width = parsePercent$1(itemDetailModel.get('width'), posInfo.r);
  54662. var height = parsePercent$1(itemDetailModel.get('height'), posInfo.r);
  54663. var detailColor = seriesModel.get(['progress', 'show']) ? data.getItemVisual(idx, 'style').fill : autoColor;
  54664. var labelEl = newDetailEls[idx];
  54665. var formatter_1 = itemDetailModel.get('formatter');
  54666. labelEl.attr({
  54667. z2: showPointerAbove ? 0 : 2,
  54668. style: createTextStyle(itemDetailModel, {
  54669. x: detailX,
  54670. y: detailY,
  54671. text: formatLabel(value, formatter_1),
  54672. width: isNaN(width) ? null : width,
  54673. height: isNaN(height) ? null : height,
  54674. align: 'center',
  54675. verticalAlign: 'middle'
  54676. }, {
  54677. inheritColor: detailColor
  54678. })
  54679. });
  54680. setLabelValueAnimation(labelEl, {
  54681. normal: itemDetailModel
  54682. }, value, function (value) {
  54683. return formatLabel(value, formatter_1);
  54684. });
  54685. hasAnimation && animateLabelValue(labelEl, idx, data, seriesModel, {
  54686. getFormattedLabel: function (labelDataIndex, status, dataType, labelDimIndex, fmt, extendParams) {
  54687. return formatLabel(extendParams ? extendParams.interpolatedValue : value, formatter_1);
  54688. }
  54689. });
  54690. itemGroup.add(labelEl);
  54691. }
  54692. contentGroup.add(itemGroup);
  54693. });
  54694. this.group.add(contentGroup);
  54695. this._titleEls = newTitleEls;
  54696. this._detailEls = newDetailEls;
  54697. };
  54698. GaugeView.type = 'gauge';
  54699. return GaugeView;
  54700. }(ChartView);
  54701. var GaugeSeriesModel =
  54702. /** @class */
  54703. function (_super) {
  54704. __extends(GaugeSeriesModel, _super);
  54705. function GaugeSeriesModel() {
  54706. var _this = _super !== null && _super.apply(this, arguments) || this;
  54707. _this.type = GaugeSeriesModel.type;
  54708. _this.visualStyleAccessPath = 'itemStyle';
  54709. return _this;
  54710. }
  54711. GaugeSeriesModel.prototype.getInitialData = function (option, ecModel) {
  54712. return createSeriesDataSimply(this, ['value']);
  54713. };
  54714. GaugeSeriesModel.type = 'series.gauge';
  54715. GaugeSeriesModel.defaultOption = {
  54716. // zlevel: 0,
  54717. z: 2,
  54718. colorBy: 'data',
  54719. // 默认全局居中
  54720. center: ['50%', '50%'],
  54721. legendHoverLink: true,
  54722. radius: '75%',
  54723. startAngle: 225,
  54724. endAngle: -45,
  54725. clockwise: true,
  54726. // 最小值
  54727. min: 0,
  54728. // 最大值
  54729. max: 100,
  54730. // 分割段数,默认为10
  54731. splitNumber: 10,
  54732. // 坐标轴线
  54733. axisLine: {
  54734. // 默认显示,属性show控制显示与否
  54735. show: true,
  54736. roundCap: false,
  54737. lineStyle: {
  54738. color: [[1, '#E6EBF8']],
  54739. width: 10
  54740. }
  54741. },
  54742. // 坐标轴线
  54743. progress: {
  54744. // 默认显示,属性show控制显示与否
  54745. show: false,
  54746. overlap: true,
  54747. width: 10,
  54748. roundCap: false,
  54749. clip: true
  54750. },
  54751. // 分隔线
  54752. splitLine: {
  54753. // 默认显示,属性show控制显示与否
  54754. show: true,
  54755. // 属性length控制线长
  54756. length: 10,
  54757. distance: 10,
  54758. // 属性lineStyle(详见lineStyle)控制线条样式
  54759. lineStyle: {
  54760. color: '#63677A',
  54761. width: 3,
  54762. type: 'solid'
  54763. }
  54764. },
  54765. // 坐标轴小标记
  54766. axisTick: {
  54767. // 属性show控制显示与否,默认不显示
  54768. show: true,
  54769. // 每份split细分多少段
  54770. splitNumber: 5,
  54771. // 属性length控制线长
  54772. length: 6,
  54773. distance: 10,
  54774. // 属性lineStyle控制线条样式
  54775. lineStyle: {
  54776. color: '#63677A',
  54777. width: 1,
  54778. type: 'solid'
  54779. }
  54780. },
  54781. axisLabel: {
  54782. show: true,
  54783. distance: 15,
  54784. // formatter: null,
  54785. color: '#464646',
  54786. fontSize: 12,
  54787. rotate: 0
  54788. },
  54789. pointer: {
  54790. icon: null,
  54791. offsetCenter: [0, 0],
  54792. show: true,
  54793. showAbove: true,
  54794. length: '60%',
  54795. width: 6,
  54796. keepAspect: false
  54797. },
  54798. anchor: {
  54799. show: false,
  54800. showAbove: false,
  54801. size: 6,
  54802. icon: 'circle',
  54803. offsetCenter: [0, 0],
  54804. keepAspect: false,
  54805. itemStyle: {
  54806. color: '#fff',
  54807. borderWidth: 0,
  54808. borderColor: '#5470c6'
  54809. }
  54810. },
  54811. title: {
  54812. show: true,
  54813. // x, y,单位px
  54814. offsetCenter: [0, '20%'],
  54815. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  54816. color: '#464646',
  54817. fontSize: 16,
  54818. valueAnimation: false
  54819. },
  54820. detail: {
  54821. show: true,
  54822. backgroundColor: 'rgba(0,0,0,0)',
  54823. borderWidth: 0,
  54824. borderColor: '#ccc',
  54825. width: 100,
  54826. height: null,
  54827. padding: [5, 10],
  54828. // x, y,单位px
  54829. offsetCenter: [0, '40%'],
  54830. // formatter: null,
  54831. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  54832. color: '#464646',
  54833. fontSize: 30,
  54834. fontWeight: 'bold',
  54835. lineHeight: 30,
  54836. valueAnimation: false
  54837. }
  54838. };
  54839. return GaugeSeriesModel;
  54840. }(SeriesModel);
  54841. function install$e(registers) {
  54842. registers.registerChartView(GaugeView);
  54843. registers.registerSeriesModel(GaugeSeriesModel);
  54844. }
  54845. var opacityAccessPath = ['itemStyle', 'opacity'];
  54846. /**
  54847. * Piece of pie including Sector, Label, LabelLine
  54848. */
  54849. var FunnelPiece =
  54850. /** @class */
  54851. function (_super) {
  54852. __extends(FunnelPiece, _super);
  54853. function FunnelPiece(data, idx) {
  54854. var _this = _super.call(this) || this;
  54855. var polygon = _this;
  54856. var labelLine = new Polyline();
  54857. var text = new ZRText();
  54858. polygon.setTextContent(text);
  54859. _this.setTextGuideLine(labelLine);
  54860. _this.updateData(data, idx, true);
  54861. return _this;
  54862. }
  54863. FunnelPiece.prototype.updateData = function (data, idx, firstCreate) {
  54864. var polygon = this;
  54865. var seriesModel = data.hostModel;
  54866. var itemModel = data.getItemModel(idx);
  54867. var layout = data.getItemLayout(idx);
  54868. var emphasisModel = itemModel.getModel('emphasis');
  54869. var opacity = itemModel.get(opacityAccessPath);
  54870. opacity = opacity == null ? 1 : opacity;
  54871. if (!firstCreate) {
  54872. saveOldStyle(polygon);
  54873. } // Update common style
  54874. polygon.useStyle(data.getItemVisual(idx, 'style'));
  54875. polygon.style.lineJoin = 'round';
  54876. if (firstCreate) {
  54877. polygon.setShape({
  54878. points: layout.points
  54879. });
  54880. polygon.style.opacity = 0;
  54881. initProps(polygon, {
  54882. style: {
  54883. opacity: opacity
  54884. }
  54885. }, seriesModel, idx);
  54886. } else {
  54887. updateProps(polygon, {
  54888. style: {
  54889. opacity: opacity
  54890. },
  54891. shape: {
  54892. points: layout.points
  54893. }
  54894. }, seriesModel, idx);
  54895. }
  54896. setStatesStylesFromModel(polygon, itemModel);
  54897. this._updateLabel(data, idx);
  54898. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  54899. };
  54900. FunnelPiece.prototype._updateLabel = function (data, idx) {
  54901. var polygon = this;
  54902. var labelLine = this.getTextGuideLine();
  54903. var labelText = polygon.getTextContent();
  54904. var seriesModel = data.hostModel;
  54905. var itemModel = data.getItemModel(idx);
  54906. var layout = data.getItemLayout(idx);
  54907. var labelLayout = layout.label;
  54908. var style = data.getItemVisual(idx, 'style');
  54909. var visualColor = style.fill;
  54910. setLabelStyle( // position will not be used in setLabelStyle
  54911. labelText, getLabelStatesModels(itemModel), {
  54912. labelFetcher: data.hostModel,
  54913. labelDataIndex: idx,
  54914. defaultOpacity: style.opacity,
  54915. defaultText: data.getName(idx)
  54916. }, {
  54917. normal: {
  54918. align: labelLayout.textAlign,
  54919. verticalAlign: labelLayout.verticalAlign
  54920. }
  54921. });
  54922. polygon.setTextConfig({
  54923. local: true,
  54924. inside: !!labelLayout.inside,
  54925. insideStroke: visualColor,
  54926. // insideFill: 'auto',
  54927. outsideFill: visualColor
  54928. });
  54929. var linePoints = labelLayout.linePoints;
  54930. labelLine.setShape({
  54931. points: linePoints
  54932. });
  54933. polygon.textGuideLineConfig = {
  54934. anchor: linePoints ? new Point(linePoints[0][0], linePoints[0][1]) : null
  54935. }; // Make sure update style on labelText after setLabelStyle.
  54936. // Because setLabelStyle will replace a new style on it.
  54937. updateProps(labelText, {
  54938. style: {
  54939. x: labelLayout.x,
  54940. y: labelLayout.y
  54941. }
  54942. }, seriesModel, idx);
  54943. labelText.attr({
  54944. rotation: labelLayout.rotation,
  54945. originX: labelLayout.x,
  54946. originY: labelLayout.y,
  54947. z2: 10
  54948. });
  54949. setLabelLineStyle(polygon, getLabelLineStatesModels(itemModel), {
  54950. // Default use item visual color
  54951. stroke: visualColor
  54952. });
  54953. };
  54954. return FunnelPiece;
  54955. }(Polygon);
  54956. var FunnelView =
  54957. /** @class */
  54958. function (_super) {
  54959. __extends(FunnelView, _super);
  54960. function FunnelView() {
  54961. var _this = _super !== null && _super.apply(this, arguments) || this;
  54962. _this.type = FunnelView.type;
  54963. _this.ignoreLabelLineUpdate = true;
  54964. return _this;
  54965. }
  54966. FunnelView.prototype.render = function (seriesModel, ecModel, api) {
  54967. var data = seriesModel.getData();
  54968. var oldData = this._data;
  54969. var group = this.group;
  54970. data.diff(oldData).add(function (idx) {
  54971. var funnelPiece = new FunnelPiece(data, idx);
  54972. data.setItemGraphicEl(idx, funnelPiece);
  54973. group.add(funnelPiece);
  54974. }).update(function (newIdx, oldIdx) {
  54975. var piece = oldData.getItemGraphicEl(oldIdx);
  54976. piece.updateData(data, newIdx);
  54977. group.add(piece);
  54978. data.setItemGraphicEl(newIdx, piece);
  54979. }).remove(function (idx) {
  54980. var piece = oldData.getItemGraphicEl(idx);
  54981. removeElementWithFadeOut(piece, seriesModel, idx);
  54982. }).execute();
  54983. this._data = data;
  54984. };
  54985. FunnelView.prototype.remove = function () {
  54986. this.group.removeAll();
  54987. this._data = null;
  54988. };
  54989. FunnelView.prototype.dispose = function () {};
  54990. FunnelView.type = 'funnel';
  54991. return FunnelView;
  54992. }(ChartView);
  54993. var FunnelSeriesModel =
  54994. /** @class */
  54995. function (_super) {
  54996. __extends(FunnelSeriesModel, _super);
  54997. function FunnelSeriesModel() {
  54998. var _this = _super !== null && _super.apply(this, arguments) || this;
  54999. _this.type = FunnelSeriesModel.type;
  55000. return _this;
  55001. }
  55002. FunnelSeriesModel.prototype.init = function (option) {
  55003. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  55004. // Use a function instead of direct access because data reference may changed
  55005. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)); // Extend labelLine emphasis
  55006. this._defaultLabelLine(option);
  55007. };
  55008. FunnelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  55009. return createSeriesDataSimply(this, {
  55010. coordDimensions: ['value'],
  55011. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  55012. });
  55013. };
  55014. FunnelSeriesModel.prototype._defaultLabelLine = function (option) {
  55015. // Extend labelLine emphasis
  55016. defaultEmphasis(option, 'labelLine', ['show']);
  55017. var labelLineNormalOpt = option.labelLine;
  55018. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  55019. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  55020. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  55021. }; // Overwrite
  55022. FunnelSeriesModel.prototype.getDataParams = function (dataIndex) {
  55023. var data = this.getData();
  55024. var params = _super.prototype.getDataParams.call(this, dataIndex);
  55025. var valueDim = data.mapDimension('value');
  55026. var sum = data.getSum(valueDim); // Percent is 0 if sum is 0
  55027. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  55028. params.$vars.push('percent');
  55029. return params;
  55030. };
  55031. FunnelSeriesModel.type = 'series.funnel';
  55032. FunnelSeriesModel.defaultOption = {
  55033. // zlevel: 0, // 一级层叠
  55034. z: 2,
  55035. legendHoverLink: true,
  55036. colorBy: 'data',
  55037. left: 80,
  55038. top: 60,
  55039. right: 80,
  55040. bottom: 60,
  55041. // width: {totalWidth} - left - right,
  55042. // height: {totalHeight} - top - bottom,
  55043. // 默认取数据最小最大值
  55044. // min: 0,
  55045. // max: 100,
  55046. minSize: '0%',
  55047. maxSize: '100%',
  55048. sort: 'descending',
  55049. orient: 'vertical',
  55050. gap: 0,
  55051. funnelAlign: 'center',
  55052. label: {
  55053. show: true,
  55054. position: 'outer' // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  55055. },
  55056. labelLine: {
  55057. show: true,
  55058. length: 20,
  55059. lineStyle: {
  55060. // color: 各异,
  55061. width: 1
  55062. }
  55063. },
  55064. itemStyle: {
  55065. // color: 各异,
  55066. borderColor: '#fff',
  55067. borderWidth: 1
  55068. },
  55069. emphasis: {
  55070. label: {
  55071. show: true
  55072. }
  55073. },
  55074. select: {
  55075. itemStyle: {
  55076. borderColor: '#212121'
  55077. }
  55078. }
  55079. };
  55080. return FunnelSeriesModel;
  55081. }(SeriesModel);
  55082. function getViewRect$3(seriesModel, api) {
  55083. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  55084. width: api.getWidth(),
  55085. height: api.getHeight()
  55086. });
  55087. }
  55088. function getSortedIndices(data, sort) {
  55089. var valueDim = data.mapDimension('value');
  55090. var valueArr = data.mapArray(valueDim, function (val) {
  55091. return val;
  55092. });
  55093. var indices = [];
  55094. var isAscending = sort === 'ascending';
  55095. for (var i = 0, len = data.count(); i < len; i++) {
  55096. indices[i] = i;
  55097. } // Add custom sortable function & none sortable opetion by "options.sort"
  55098. if (isFunction(sort)) {
  55099. indices.sort(sort);
  55100. } else if (sort !== 'none') {
  55101. indices.sort(function (a, b) {
  55102. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  55103. });
  55104. }
  55105. return indices;
  55106. }
  55107. function labelLayout(data) {
  55108. var seriesModel = data.hostModel;
  55109. var orient = seriesModel.get('orient');
  55110. data.each(function (idx) {
  55111. var itemModel = data.getItemModel(idx);
  55112. var labelModel = itemModel.getModel('label');
  55113. var labelPosition = labelModel.get('position');
  55114. var labelLineModel = itemModel.getModel('labelLine');
  55115. var layout = data.getItemLayout(idx);
  55116. var points = layout.points;
  55117. var isLabelInside = labelPosition === 'inner' || labelPosition === 'inside' || labelPosition === 'center' || labelPosition === 'insideLeft' || labelPosition === 'insideRight';
  55118. var textAlign;
  55119. var textX;
  55120. var textY;
  55121. var linePoints;
  55122. if (isLabelInside) {
  55123. if (labelPosition === 'insideLeft') {
  55124. textX = (points[0][0] + points[3][0]) / 2 + 5;
  55125. textY = (points[0][1] + points[3][1]) / 2;
  55126. textAlign = 'left';
  55127. } else if (labelPosition === 'insideRight') {
  55128. textX = (points[1][0] + points[2][0]) / 2 - 5;
  55129. textY = (points[1][1] + points[2][1]) / 2;
  55130. textAlign = 'right';
  55131. } else {
  55132. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  55133. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  55134. textAlign = 'center';
  55135. }
  55136. linePoints = [[textX, textY], [textX, textY]];
  55137. } else {
  55138. var x1 = void 0;
  55139. var y1 = void 0;
  55140. var x2 = void 0;
  55141. var y2 = void 0;
  55142. var labelLineLen = labelLineModel.get('length');
  55143. if ("development" !== 'production') {
  55144. if (orient === 'vertical' && ['top', 'bottom'].indexOf(labelPosition) > -1) {
  55145. labelPosition = 'left';
  55146. console.warn('Position error: Funnel chart on vertical orient dose not support top and bottom.');
  55147. }
  55148. if (orient === 'horizontal' && ['left', 'right'].indexOf(labelPosition) > -1) {
  55149. labelPosition = 'bottom';
  55150. console.warn('Position error: Funnel chart on horizontal orient dose not support left and right.');
  55151. }
  55152. }
  55153. if (labelPosition === 'left') {
  55154. // Left side
  55155. x1 = (points[3][0] + points[0][0]) / 2;
  55156. y1 = (points[3][1] + points[0][1]) / 2;
  55157. x2 = x1 - labelLineLen;
  55158. textX = x2 - 5;
  55159. textAlign = 'right';
  55160. } else if (labelPosition === 'right') {
  55161. // Right side
  55162. x1 = (points[1][0] + points[2][0]) / 2;
  55163. y1 = (points[1][1] + points[2][1]) / 2;
  55164. x2 = x1 + labelLineLen;
  55165. textX = x2 + 5;
  55166. textAlign = 'left';
  55167. } else if (labelPosition === 'top') {
  55168. // Top side
  55169. x1 = (points[3][0] + points[0][0]) / 2;
  55170. y1 = (points[3][1] + points[0][1]) / 2;
  55171. y2 = y1 - labelLineLen;
  55172. textY = y2 - 5;
  55173. textAlign = 'center';
  55174. } else if (labelPosition === 'bottom') {
  55175. // Bottom side
  55176. x1 = (points[1][0] + points[2][0]) / 2;
  55177. y1 = (points[1][1] + points[2][1]) / 2;
  55178. y2 = y1 + labelLineLen;
  55179. textY = y2 + 5;
  55180. textAlign = 'center';
  55181. } else if (labelPosition === 'rightTop') {
  55182. // RightTop side
  55183. x1 = orient === 'horizontal' ? points[3][0] : points[1][0];
  55184. y1 = orient === 'horizontal' ? points[3][1] : points[1][1];
  55185. if (orient === 'horizontal') {
  55186. y2 = y1 - labelLineLen;
  55187. textY = y2 - 5;
  55188. textAlign = 'center';
  55189. } else {
  55190. x2 = x1 + labelLineLen;
  55191. textX = x2 + 5;
  55192. textAlign = 'top';
  55193. }
  55194. } else if (labelPosition === 'rightBottom') {
  55195. // RightBottom side
  55196. x1 = points[2][0];
  55197. y1 = points[2][1];
  55198. if (orient === 'horizontal') {
  55199. y2 = y1 + labelLineLen;
  55200. textY = y2 + 5;
  55201. textAlign = 'center';
  55202. } else {
  55203. x2 = x1 + labelLineLen;
  55204. textX = x2 + 5;
  55205. textAlign = 'bottom';
  55206. }
  55207. } else if (labelPosition === 'leftTop') {
  55208. // LeftTop side
  55209. x1 = points[0][0];
  55210. y1 = orient === 'horizontal' ? points[0][1] : points[1][1];
  55211. if (orient === 'horizontal') {
  55212. y2 = y1 - labelLineLen;
  55213. textY = y2 - 5;
  55214. textAlign = 'center';
  55215. } else {
  55216. x2 = x1 - labelLineLen;
  55217. textX = x2 - 5;
  55218. textAlign = 'right';
  55219. }
  55220. } else if (labelPosition === 'leftBottom') {
  55221. // LeftBottom side
  55222. x1 = orient === 'horizontal' ? points[1][0] : points[3][0];
  55223. y1 = orient === 'horizontal' ? points[1][1] : points[2][1];
  55224. if (orient === 'horizontal') {
  55225. y2 = y1 + labelLineLen;
  55226. textY = y2 + 5;
  55227. textAlign = 'center';
  55228. } else {
  55229. x2 = x1 - labelLineLen;
  55230. textX = x2 - 5;
  55231. textAlign = 'right';
  55232. }
  55233. } else {
  55234. // Right side or Bottom side
  55235. x1 = (points[1][0] + points[2][0]) / 2;
  55236. y1 = (points[1][1] + points[2][1]) / 2;
  55237. if (orient === 'horizontal') {
  55238. y2 = y1 + labelLineLen;
  55239. textY = y2 + 5;
  55240. textAlign = 'center';
  55241. } else {
  55242. x2 = x1 + labelLineLen;
  55243. textX = x2 + 5;
  55244. textAlign = 'left';
  55245. }
  55246. }
  55247. if (orient === 'horizontal') {
  55248. x2 = x1;
  55249. textX = x2;
  55250. } else {
  55251. y2 = y1;
  55252. textY = y2;
  55253. }
  55254. linePoints = [[x1, y1], [x2, y2]];
  55255. }
  55256. layout.label = {
  55257. linePoints: linePoints,
  55258. x: textX,
  55259. y: textY,
  55260. verticalAlign: 'middle',
  55261. textAlign: textAlign,
  55262. inside: isLabelInside
  55263. };
  55264. });
  55265. }
  55266. function funnelLayout(ecModel, api) {
  55267. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  55268. var data = seriesModel.getData();
  55269. var valueDim = data.mapDimension('value');
  55270. var sort = seriesModel.get('sort');
  55271. var viewRect = getViewRect$3(seriesModel, api);
  55272. var orient = seriesModel.get('orient');
  55273. var viewWidth = viewRect.width;
  55274. var viewHeight = viewRect.height;
  55275. var indices = getSortedIndices(data, sort);
  55276. var x = viewRect.x;
  55277. var y = viewRect.y;
  55278. var sizeExtent = orient === 'horizontal' ? [parsePercent$1(seriesModel.get('minSize'), viewHeight), parsePercent$1(seriesModel.get('maxSize'), viewHeight)] : [parsePercent$1(seriesModel.get('minSize'), viewWidth), parsePercent$1(seriesModel.get('maxSize'), viewWidth)];
  55279. var dataExtent = data.getDataExtent(valueDim);
  55280. var min = seriesModel.get('min');
  55281. var max = seriesModel.get('max');
  55282. if (min == null) {
  55283. min = Math.min(dataExtent[0], 0);
  55284. }
  55285. if (max == null) {
  55286. max = dataExtent[1];
  55287. }
  55288. var funnelAlign = seriesModel.get('funnelAlign');
  55289. var gap = seriesModel.get('gap');
  55290. var viewSize = orient === 'horizontal' ? viewWidth : viewHeight;
  55291. var itemSize = (viewSize - gap * (data.count() - 1)) / data.count();
  55292. var getLinePoints = function (idx, offset) {
  55293. // End point index is data.count() and we assign it 0
  55294. if (orient === 'horizontal') {
  55295. var val_1 = data.get(valueDim, idx) || 0;
  55296. var itemHeight = linearMap(val_1, [min, max], sizeExtent, true);
  55297. var y0 = void 0;
  55298. switch (funnelAlign) {
  55299. case 'top':
  55300. y0 = y;
  55301. break;
  55302. case 'center':
  55303. y0 = y + (viewHeight - itemHeight) / 2;
  55304. break;
  55305. case 'bottom':
  55306. y0 = y + (viewHeight - itemHeight);
  55307. break;
  55308. }
  55309. return [[offset, y0], [offset, y0 + itemHeight]];
  55310. }
  55311. var val = data.get(valueDim, idx) || 0;
  55312. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  55313. var x0;
  55314. switch (funnelAlign) {
  55315. case 'left':
  55316. x0 = x;
  55317. break;
  55318. case 'center':
  55319. x0 = x + (viewWidth - itemWidth) / 2;
  55320. break;
  55321. case 'right':
  55322. x0 = x + viewWidth - itemWidth;
  55323. break;
  55324. }
  55325. return [[x0, offset], [x0 + itemWidth, offset]];
  55326. };
  55327. if (sort === 'ascending') {
  55328. // From bottom to top
  55329. itemSize = -itemSize;
  55330. gap = -gap;
  55331. if (orient === 'horizontal') {
  55332. x += viewWidth;
  55333. } else {
  55334. y += viewHeight;
  55335. }
  55336. indices = indices.reverse();
  55337. }
  55338. for (var i = 0; i < indices.length; i++) {
  55339. var idx = indices[i];
  55340. var nextIdx = indices[i + 1];
  55341. var itemModel = data.getItemModel(idx);
  55342. if (orient === 'horizontal') {
  55343. var width = itemModel.get(['itemStyle', 'width']);
  55344. if (width == null) {
  55345. width = itemSize;
  55346. } else {
  55347. width = parsePercent$1(width, viewWidth);
  55348. if (sort === 'ascending') {
  55349. width = -width;
  55350. }
  55351. }
  55352. var start = getLinePoints(idx, x);
  55353. var end = getLinePoints(nextIdx, x + width);
  55354. x += width + gap;
  55355. data.setItemLayout(idx, {
  55356. points: start.concat(end.slice().reverse())
  55357. });
  55358. } else {
  55359. var height = itemModel.get(['itemStyle', 'height']);
  55360. if (height == null) {
  55361. height = itemSize;
  55362. } else {
  55363. height = parsePercent$1(height, viewHeight);
  55364. if (sort === 'ascending') {
  55365. height = -height;
  55366. }
  55367. }
  55368. var start = getLinePoints(idx, y);
  55369. var end = getLinePoints(nextIdx, y + height);
  55370. y += height + gap;
  55371. data.setItemLayout(idx, {
  55372. points: start.concat(end.slice().reverse())
  55373. });
  55374. }
  55375. }
  55376. labelLayout(data);
  55377. });
  55378. }
  55379. function install$f(registers) {
  55380. registers.registerChartView(FunnelView);
  55381. registers.registerSeriesModel(FunnelSeriesModel);
  55382. registers.registerLayout(funnelLayout);
  55383. registers.registerProcessor(dataFilter('funnel'));
  55384. }
  55385. var DEFAULT_SMOOTH = 0.3;
  55386. var ParallelView =
  55387. /** @class */
  55388. function (_super) {
  55389. __extends(ParallelView, _super);
  55390. function ParallelView() {
  55391. var _this = _super !== null && _super.apply(this, arguments) || this;
  55392. _this.type = ParallelView.type;
  55393. _this._dataGroup = new Group();
  55394. _this._initialized = false;
  55395. return _this;
  55396. }
  55397. ParallelView.prototype.init = function () {
  55398. this.group.add(this._dataGroup);
  55399. };
  55400. /**
  55401. * @override
  55402. */
  55403. ParallelView.prototype.render = function (seriesModel, ecModel, api, payload) {
  55404. // Clear previously rendered progressive elements.
  55405. this._progressiveEls = null;
  55406. var dataGroup = this._dataGroup;
  55407. var data = seriesModel.getData();
  55408. var oldData = this._data;
  55409. var coordSys = seriesModel.coordinateSystem;
  55410. var dimensions = coordSys.dimensions;
  55411. var seriesScope = makeSeriesScope$2(seriesModel);
  55412. data.diff(oldData).add(add).update(update).remove(remove).execute();
  55413. function add(newDataIndex) {
  55414. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  55415. updateElCommon(line, data, newDataIndex, seriesScope);
  55416. }
  55417. function update(newDataIndex, oldDataIndex) {
  55418. var line = oldData.getItemGraphicEl(oldDataIndex);
  55419. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  55420. data.setItemGraphicEl(newDataIndex, line);
  55421. updateProps(line, {
  55422. shape: {
  55423. points: points
  55424. }
  55425. }, seriesModel, newDataIndex);
  55426. saveOldStyle(line);
  55427. updateElCommon(line, data, newDataIndex, seriesScope);
  55428. }
  55429. function remove(oldDataIndex) {
  55430. var line = oldData.getItemGraphicEl(oldDataIndex);
  55431. dataGroup.remove(line);
  55432. } // First create
  55433. if (!this._initialized) {
  55434. this._initialized = true;
  55435. var clipPath = createGridClipShape(coordSys, seriesModel, function () {
  55436. // Callback will be invoked immediately if there is no animation
  55437. setTimeout(function () {
  55438. dataGroup.removeClipPath();
  55439. });
  55440. });
  55441. dataGroup.setClipPath(clipPath);
  55442. }
  55443. this._data = data;
  55444. };
  55445. ParallelView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  55446. this._initialized = true;
  55447. this._data = null;
  55448. this._dataGroup.removeAll();
  55449. };
  55450. ParallelView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  55451. var data = seriesModel.getData();
  55452. var coordSys = seriesModel.coordinateSystem;
  55453. var dimensions = coordSys.dimensions;
  55454. var seriesScope = makeSeriesScope$2(seriesModel);
  55455. var progressiveEls = this._progressiveEls = [];
  55456. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  55457. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  55458. line.incremental = true;
  55459. updateElCommon(line, data, dataIndex, seriesScope);
  55460. progressiveEls.push(line);
  55461. }
  55462. };
  55463. ParallelView.prototype.remove = function () {
  55464. this._dataGroup && this._dataGroup.removeAll();
  55465. this._data = null;
  55466. };
  55467. ParallelView.type = 'parallel';
  55468. return ParallelView;
  55469. }(ChartView);
  55470. function createGridClipShape(coordSys, seriesModel, cb) {
  55471. var parallelModel = coordSys.model;
  55472. var rect = coordSys.getRect();
  55473. var rectEl = new Rect({
  55474. shape: {
  55475. x: rect.x,
  55476. y: rect.y,
  55477. width: rect.width,
  55478. height: rect.height
  55479. }
  55480. });
  55481. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  55482. rectEl.setShape(dim, 0);
  55483. initProps(rectEl, {
  55484. shape: {
  55485. width: rect.width,
  55486. height: rect.height
  55487. }
  55488. }, seriesModel, cb);
  55489. return rectEl;
  55490. }
  55491. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  55492. var points = [];
  55493. for (var i = 0; i < dimensions.length; i++) {
  55494. var dimName = dimensions[i];
  55495. var value = data.get(data.mapDimension(dimName), dataIndex);
  55496. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  55497. points.push(coordSys.dataToPoint(value, dimName));
  55498. }
  55499. }
  55500. return points;
  55501. }
  55502. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  55503. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  55504. var line = new Polyline({
  55505. shape: {
  55506. points: points
  55507. },
  55508. // silent: true,
  55509. z2: 10
  55510. });
  55511. dataGroup.add(line);
  55512. data.setItemGraphicEl(dataIndex, line);
  55513. return line;
  55514. }
  55515. function makeSeriesScope$2(seriesModel) {
  55516. var smooth = seriesModel.get('smooth', true);
  55517. smooth === true && (smooth = DEFAULT_SMOOTH);
  55518. smooth = numericToNumber(smooth);
  55519. eqNaN(smooth) && (smooth = 0);
  55520. return {
  55521. smooth: smooth
  55522. };
  55523. }
  55524. function updateElCommon(el, data, dataIndex, seriesScope) {
  55525. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  55526. el.style.fill = null;
  55527. el.setShape('smooth', seriesScope.smooth);
  55528. var itemModel = data.getItemModel(dataIndex);
  55529. var emphasisModel = itemModel.getModel('emphasis');
  55530. setStatesStylesFromModel(el, itemModel, 'lineStyle');
  55531. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  55532. } // function simpleDiff(oldData, newData, dimensions) {
  55533. // let oldLen;
  55534. // if (!oldData
  55535. // || !oldData.__plProgressive
  55536. // || (oldLen = oldData.count()) !== newData.count()
  55537. // ) {
  55538. // return true;
  55539. // }
  55540. // let dimLen = dimensions.length;
  55541. // for (let i = 0; i < oldLen; i++) {
  55542. // for (let j = 0; j < dimLen; j++) {
  55543. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  55544. // return true;
  55545. // }
  55546. // }
  55547. // }
  55548. // return false;
  55549. // }
  55550. // FIXME put in common util?
  55551. function isEmptyValue(val, axisType) {
  55552. return axisType === 'category' ? val == null : val == null || isNaN(val); // axisType === 'value'
  55553. }
  55554. var ParallelSeriesModel =
  55555. /** @class */
  55556. function (_super) {
  55557. __extends(ParallelSeriesModel, _super);
  55558. function ParallelSeriesModel() {
  55559. var _this = _super !== null && _super.apply(this, arguments) || this;
  55560. _this.type = ParallelSeriesModel.type;
  55561. _this.visualStyleAccessPath = 'lineStyle';
  55562. _this.visualDrawType = 'stroke';
  55563. return _this;
  55564. }
  55565. ParallelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  55566. return createSeriesData(null, this, {
  55567. useEncodeDefaulter: bind(makeDefaultEncode, null, this)
  55568. });
  55569. };
  55570. /**
  55571. * User can get data raw indices on 'axisAreaSelected' event received.
  55572. *
  55573. * @return Raw indices
  55574. */
  55575. ParallelSeriesModel.prototype.getRawIndicesByActiveState = function (activeState) {
  55576. var coordSys = this.coordinateSystem;
  55577. var data = this.getData();
  55578. var indices = [];
  55579. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  55580. if (activeState === theActiveState) {
  55581. indices.push(data.getRawIndex(dataIndex));
  55582. }
  55583. });
  55584. return indices;
  55585. };
  55586. ParallelSeriesModel.type = 'series.parallel';
  55587. ParallelSeriesModel.dependencies = ['parallel'];
  55588. ParallelSeriesModel.defaultOption = {
  55589. // zlevel: 0,
  55590. z: 2,
  55591. coordinateSystem: 'parallel',
  55592. parallelIndex: 0,
  55593. label: {
  55594. show: false
  55595. },
  55596. inactiveOpacity: 0.05,
  55597. activeOpacity: 1,
  55598. lineStyle: {
  55599. width: 1,
  55600. opacity: 0.45,
  55601. type: 'solid'
  55602. },
  55603. emphasis: {
  55604. label: {
  55605. show: false
  55606. }
  55607. },
  55608. progressive: 500,
  55609. smooth: false,
  55610. animationEasing: 'linear'
  55611. };
  55612. return ParallelSeriesModel;
  55613. }(SeriesModel);
  55614. function makeDefaultEncode(seriesModel) {
  55615. // The mapping of parallelAxis dimension to data dimension can
  55616. // be specified in parallelAxis.option.dim. For example, if
  55617. // parallelAxis.option.dim is 'dim3', it mapping to the third
  55618. // dimension of data. But `data.encode` has higher priority.
  55619. // Moreover, parallelModel.dimension should not be regarded as data
  55620. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  55621. var parallelModel = seriesModel.ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  55622. if (!parallelModel) {
  55623. return;
  55624. }
  55625. var encodeDefine = {};
  55626. each(parallelModel.dimensions, function (axisDim) {
  55627. var dataDimIndex = convertDimNameToNumber(axisDim);
  55628. encodeDefine[axisDim] = dataDimIndex;
  55629. });
  55630. return encodeDefine;
  55631. }
  55632. function convertDimNameToNumber(dimName) {
  55633. return +dimName.replace('dim', '');
  55634. }
  55635. /*
  55636. * Licensed to the Apache Software Foundation (ASF) under one
  55637. * or more contributor license agreements. See the NOTICE file
  55638. * distributed with this work for additional information
  55639. * regarding copyright ownership. The ASF licenses this file
  55640. * to you under the Apache License, Version 2.0 (the
  55641. * "License"); you may not use this file except in compliance
  55642. * with the License. You may obtain a copy of the License at
  55643. *
  55644. * http://www.apache.org/licenses/LICENSE-2.0
  55645. *
  55646. * Unless required by applicable law or agreed to in writing,
  55647. * software distributed under the License is distributed on an
  55648. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55649. * KIND, either express or implied. See the License for the
  55650. * specific language governing permissions and limitations
  55651. * under the License.
  55652. */
  55653. /**
  55654. * AUTO-GENERATED FILE. DO NOT MODIFY.
  55655. */
  55656. /*
  55657. * Licensed to the Apache Software Foundation (ASF) under one
  55658. * or more contributor license agreements. See the NOTICE file
  55659. * distributed with this work for additional information
  55660. * regarding copyright ownership. The ASF licenses this file
  55661. * to you under the Apache License, Version 2.0 (the
  55662. * "License"); you may not use this file except in compliance
  55663. * with the License. You may obtain a copy of the License at
  55664. *
  55665. * http://www.apache.org/licenses/LICENSE-2.0
  55666. *
  55667. * Unless required by applicable law or agreed to in writing,
  55668. * software distributed under the License is distributed on an
  55669. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55670. * KIND, either express or implied. See the License for the
  55671. * specific language governing permissions and limitations
  55672. * under the License.
  55673. */
  55674. var opacityAccessPath$1 = ['lineStyle', 'opacity'];
  55675. var parallelVisual = {
  55676. seriesType: 'parallel',
  55677. reset: function (seriesModel, ecModel) {
  55678. var coordSys = seriesModel.coordinateSystem;
  55679. var opacityMap = {
  55680. normal: seriesModel.get(['lineStyle', 'opacity']),
  55681. active: seriesModel.get('activeOpacity'),
  55682. inactive: seriesModel.get('inactiveOpacity')
  55683. };
  55684. return {
  55685. progress: function (params, data) {
  55686. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  55687. var opacity = opacityMap[activeState];
  55688. if (activeState === 'normal' && data.hasItemOption) {
  55689. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  55690. itemOpacity != null && (opacity = itemOpacity);
  55691. }
  55692. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  55693. existsStyle.opacity = opacity;
  55694. }, params.start, params.end);
  55695. }
  55696. };
  55697. }
  55698. };
  55699. function parallelPreprocessor(option) {
  55700. createParallelIfNeeded(option);
  55701. mergeAxisOptionFromParallel(option);
  55702. }
  55703. /**
  55704. * Create a parallel coordinate if not exists.
  55705. * @inner
  55706. */
  55707. function createParallelIfNeeded(option) {
  55708. if (option.parallel) {
  55709. return;
  55710. }
  55711. var hasParallelSeries = false;
  55712. each(option.series, function (seriesOpt) {
  55713. if (seriesOpt && seriesOpt.type === 'parallel') {
  55714. hasParallelSeries = true;
  55715. }
  55716. });
  55717. if (hasParallelSeries) {
  55718. option.parallel = [{}];
  55719. }
  55720. }
  55721. /**
  55722. * Merge aixs definition from parallel option (if exists) to axis option.
  55723. * @inner
  55724. */
  55725. function mergeAxisOptionFromParallel(option) {
  55726. var axes = normalizeToArray(option.parallelAxis);
  55727. each(axes, function (axisOption) {
  55728. if (!isObject(axisOption)) {
  55729. return;
  55730. }
  55731. var parallelIndex = axisOption.parallelIndex || 0;
  55732. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  55733. if (parallelOption && parallelOption.parallelAxisDefault) {
  55734. merge(axisOption, parallelOption.parallelAxisDefault, false);
  55735. }
  55736. });
  55737. }
  55738. var CLICK_THRESHOLD = 5; // > 4
  55739. var ParallelView$1 =
  55740. /** @class */
  55741. function (_super) {
  55742. __extends(ParallelView, _super);
  55743. function ParallelView() {
  55744. var _this = _super !== null && _super.apply(this, arguments) || this;
  55745. _this.type = ParallelView.type;
  55746. return _this;
  55747. }
  55748. ParallelView.prototype.render = function (parallelModel, ecModel, api) {
  55749. this._model = parallelModel;
  55750. this._api = api;
  55751. if (!this._handlers) {
  55752. this._handlers = {};
  55753. each(handlers, function (handler, eventName) {
  55754. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  55755. }, this);
  55756. }
  55757. createOrUpdate(this, '_throttledDispatchExpand', parallelModel.get('axisExpandRate'), 'fixRate');
  55758. };
  55759. ParallelView.prototype.dispose = function (ecModel, api) {
  55760. clear(this, '_throttledDispatchExpand');
  55761. each(this._handlers, function (handler, eventName) {
  55762. api.getZr().off(eventName, handler);
  55763. });
  55764. this._handlers = null;
  55765. };
  55766. /**
  55767. * @internal
  55768. * @param {Object} [opt] If null, cancel the last action triggering for debounce.
  55769. */
  55770. ParallelView.prototype._throttledDispatchExpand = function (opt) {
  55771. this._dispatchExpand(opt);
  55772. };
  55773. /**
  55774. * @internal
  55775. */
  55776. ParallelView.prototype._dispatchExpand = function (opt) {
  55777. opt && this._api.dispatchAction(extend({
  55778. type: 'parallelAxisExpand'
  55779. }, opt));
  55780. };
  55781. ParallelView.type = 'parallel';
  55782. return ParallelView;
  55783. }(ComponentView);
  55784. var handlers = {
  55785. mousedown: function (e) {
  55786. if (checkTrigger(this, 'click')) {
  55787. this._mouseDownPoint = [e.offsetX, e.offsetY];
  55788. }
  55789. },
  55790. mouseup: function (e) {
  55791. var mouseDownPoint = this._mouseDownPoint;
  55792. if (checkTrigger(this, 'click') && mouseDownPoint) {
  55793. var point = [e.offsetX, e.offsetY];
  55794. var dist = Math.pow(mouseDownPoint[0] - point[0], 2) + Math.pow(mouseDownPoint[1] - point[1], 2);
  55795. if (dist > CLICK_THRESHOLD) {
  55796. return;
  55797. }
  55798. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  55799. result.behavior !== 'none' && this._dispatchExpand({
  55800. axisExpandWindow: result.axisExpandWindow
  55801. });
  55802. }
  55803. this._mouseDownPoint = null;
  55804. },
  55805. mousemove: function (e) {
  55806. // Should do nothing when brushing.
  55807. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  55808. return;
  55809. }
  55810. var model = this._model;
  55811. var result = model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  55812. var behavior = result.behavior;
  55813. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  55814. this._throttledDispatchExpand(behavior === 'none' ? null // Cancel the last trigger, in case that mouse slide out of the area quickly.
  55815. : {
  55816. axisExpandWindow: result.axisExpandWindow,
  55817. // Jumping uses animation, and sliding suppresses animation.
  55818. animation: behavior === 'jump' ? null : {
  55819. duration: 0 // Disable animation.
  55820. }
  55821. });
  55822. }
  55823. };
  55824. function checkTrigger(view, triggerOn) {
  55825. var model = view._model;
  55826. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  55827. }
  55828. var ParallelModel =
  55829. /** @class */
  55830. function (_super) {
  55831. __extends(ParallelModel, _super);
  55832. function ParallelModel() {
  55833. var _this = _super !== null && _super.apply(this, arguments) || this;
  55834. _this.type = ParallelModel.type;
  55835. return _this;
  55836. }
  55837. ParallelModel.prototype.init = function () {
  55838. _super.prototype.init.apply(this, arguments);
  55839. this.mergeOption({});
  55840. };
  55841. ParallelModel.prototype.mergeOption = function (newOption) {
  55842. var thisOption = this.option;
  55843. newOption && merge(thisOption, newOption, true);
  55844. this._initDimensions();
  55845. };
  55846. /**
  55847. * Whether series or axis is in this coordinate system.
  55848. */
  55849. ParallelModel.prototype.contains = function (model, ecModel) {
  55850. var parallelIndex = model.get('parallelIndex');
  55851. return parallelIndex != null && ecModel.getComponent('parallel', parallelIndex) === this;
  55852. };
  55853. ParallelModel.prototype.setAxisExpand = function (opt) {
  55854. each(['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'], function (name) {
  55855. if (opt.hasOwnProperty(name)) {
  55856. // @ts-ignore FIXME: why "never" inferred in this.option[name]?
  55857. this.option[name] = opt[name];
  55858. }
  55859. }, this);
  55860. };
  55861. ParallelModel.prototype._initDimensions = function () {
  55862. var dimensions = this.dimensions = [];
  55863. var parallelAxisIndex = this.parallelAxisIndex = [];
  55864. var axisModels = filter(this.ecModel.queryComponents({
  55865. mainType: 'parallelAxis'
  55866. }), function (axisModel) {
  55867. // Can not use this.contains here, because
  55868. // initialization has not been completed yet.
  55869. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  55870. }, this);
  55871. each(axisModels, function (axisModel) {
  55872. dimensions.push('dim' + axisModel.get('dim'));
  55873. parallelAxisIndex.push(axisModel.componentIndex);
  55874. });
  55875. };
  55876. ParallelModel.type = 'parallel';
  55877. ParallelModel.dependencies = ['parallelAxis'];
  55878. ParallelModel.layoutMode = 'box';
  55879. ParallelModel.defaultOption = {
  55880. // zlevel: 0,
  55881. z: 0,
  55882. left: 80,
  55883. top: 60,
  55884. right: 80,
  55885. bottom: 60,
  55886. // width: {totalWidth} - left - right,
  55887. // height: {totalHeight} - top - bottom,
  55888. layout: 'horizontal',
  55889. // FIXME
  55890. // naming?
  55891. axisExpandable: false,
  55892. axisExpandCenter: null,
  55893. axisExpandCount: 0,
  55894. axisExpandWidth: 50,
  55895. axisExpandRate: 17,
  55896. axisExpandDebounce: 50,
  55897. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  55898. // Do not doc to user until necessary.
  55899. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  55900. axisExpandTriggerOn: 'click',
  55901. parallelAxisDefault: null
  55902. };
  55903. return ParallelModel;
  55904. }(ComponentModel);
  55905. var ParallelAxis =
  55906. /** @class */
  55907. function (_super) {
  55908. __extends(ParallelAxis, _super);
  55909. function ParallelAxis(dim, scale, coordExtent, axisType, axisIndex) {
  55910. var _this = _super.call(this, dim, scale, coordExtent) || this;
  55911. _this.type = axisType || 'value';
  55912. _this.axisIndex = axisIndex;
  55913. return _this;
  55914. }
  55915. ParallelAxis.prototype.isHorizontal = function () {
  55916. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  55917. };
  55918. return ParallelAxis;
  55919. }(Axis);
  55920. /*
  55921. * Licensed to the Apache Software Foundation (ASF) under one
  55922. * or more contributor license agreements. See the NOTICE file
  55923. * distributed with this work for additional information
  55924. * regarding copyright ownership. The ASF licenses this file
  55925. * to you under the Apache License, Version 2.0 (the
  55926. * "License"); you may not use this file except in compliance
  55927. * with the License. You may obtain a copy of the License at
  55928. *
  55929. * http://www.apache.org/licenses/LICENSE-2.0
  55930. *
  55931. * Unless required by applicable law or agreed to in writing,
  55932. * software distributed under the License is distributed on an
  55933. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55934. * KIND, either express or implied. See the License for the
  55935. * specific language governing permissions and limitations
  55936. * under the License.
  55937. */
  55938. /**
  55939. * AUTO-GENERATED FILE. DO NOT MODIFY.
  55940. */
  55941. /*
  55942. * Licensed to the Apache Software Foundation (ASF) under one
  55943. * or more contributor license agreements. See the NOTICE file
  55944. * distributed with this work for additional information
  55945. * regarding copyright ownership. The ASF licenses this file
  55946. * to you under the Apache License, Version 2.0 (the
  55947. * "License"); you may not use this file except in compliance
  55948. * with the License. You may obtain a copy of the License at
  55949. *
  55950. * http://www.apache.org/licenses/LICENSE-2.0
  55951. *
  55952. * Unless required by applicable law or agreed to in writing,
  55953. * software distributed under the License is distributed on an
  55954. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55955. * KIND, either express or implied. See the License for the
  55956. * specific language governing permissions and limitations
  55957. * under the License.
  55958. */
  55959. /**
  55960. * Calculate slider move result.
  55961. * Usage:
  55962. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  55963. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  55964. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  55965. *
  55966. * @param delta Move length.
  55967. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  55968. * handleEnds will be modified in this method.
  55969. * @param extent handleEnds is restricted by extent.
  55970. * extent[0] should less or equals than extent[1].
  55971. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  55972. * @param minSpan The range of dataZoom can not be smaller than that.
  55973. * If not set, handle0 and cross handle1. If set as a non-negative
  55974. * number (including `0`), handles will push each other when reaching
  55975. * the minSpan.
  55976. * @param maxSpan The range of dataZoom can not be larger than that.
  55977. * @return The input handleEnds.
  55978. */
  55979. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  55980. delta = delta || 0;
  55981. var extentSpan = extent[1] - extent[0]; // Notice maxSpan and minSpan can be null/undefined.
  55982. if (minSpan != null) {
  55983. minSpan = restrict(minSpan, [0, extentSpan]);
  55984. }
  55985. if (maxSpan != null) {
  55986. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  55987. }
  55988. if (handleIndex === 'all') {
  55989. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  55990. handleSpan = restrict(handleSpan, [0, extentSpan]);
  55991. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  55992. handleIndex = 0;
  55993. }
  55994. handleEnds[0] = restrict(handleEnds[0], extent);
  55995. handleEnds[1] = restrict(handleEnds[1], extent);
  55996. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  55997. handleEnds[handleIndex] += delta; // Restrict in extent.
  55998. var extentMinSpan = minSpan || 0;
  55999. var realExtent = extent.slice();
  56000. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  56001. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent); // Expand span.
  56002. var currDistSign;
  56003. currDistSign = getSpanSign(handleEnds, handleIndex);
  56004. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  56005. // If minSpan exists, 'cross' is forbidden.
  56006. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  56007. } // Shrink span.
  56008. currDistSign = getSpanSign(handleEnds, handleIndex);
  56009. if (maxSpan != null && currDistSign.span > maxSpan) {
  56010. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  56011. }
  56012. return handleEnds;
  56013. }
  56014. function getSpanSign(handleEnds, handleIndex) {
  56015. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  56016. // is at left of handleEnds[1] for non-cross case.
  56017. return {
  56018. span: Math.abs(dist),
  56019. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  56020. };
  56021. }
  56022. function restrict(value, extend) {
  56023. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  56024. }
  56025. var each$5 = each;
  56026. var mathMin$8 = Math.min;
  56027. var mathMax$8 = Math.max;
  56028. var mathFloor$1 = Math.floor;
  56029. var mathCeil$1 = Math.ceil;
  56030. var round$3 = round;
  56031. var PI$7 = Math.PI;
  56032. var Parallel =
  56033. /** @class */
  56034. function () {
  56035. function Parallel(parallelModel, ecModel, api) {
  56036. this.type = 'parallel';
  56037. /**
  56038. * key: dimension
  56039. */
  56040. this._axesMap = createHashMap();
  56041. /**
  56042. * key: dimension
  56043. * value: {position: [], rotation, }
  56044. */
  56045. this._axesLayout = {};
  56046. this.dimensions = parallelModel.dimensions;
  56047. this._model = parallelModel;
  56048. this._init(parallelModel, ecModel, api);
  56049. }
  56050. Parallel.prototype._init = function (parallelModel, ecModel, api) {
  56051. var dimensions = parallelModel.dimensions;
  56052. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  56053. each$5(dimensions, function (dim, idx) {
  56054. var axisIndex = parallelAxisIndex[idx];
  56055. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  56056. var axis = this._axesMap.set(dim, new ParallelAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisIndex));
  56057. var isCategory = axis.type === 'category';
  56058. axis.onBand = isCategory && axisModel.get('boundaryGap');
  56059. axis.inverse = axisModel.get('inverse'); // Injection
  56060. axisModel.axis = axis;
  56061. axis.model = axisModel;
  56062. axis.coordinateSystem = axisModel.coordinateSystem = this;
  56063. }, this);
  56064. };
  56065. /**
  56066. * Update axis scale after data processed
  56067. */
  56068. Parallel.prototype.update = function (ecModel, api) {
  56069. this._updateAxesFromSeries(this._model, ecModel);
  56070. };
  56071. Parallel.prototype.containPoint = function (point) {
  56072. var layoutInfo = this._makeLayoutInfo();
  56073. var axisBase = layoutInfo.axisBase;
  56074. var layoutBase = layoutInfo.layoutBase;
  56075. var pixelDimIndex = layoutInfo.pixelDimIndex;
  56076. var pAxis = point[1 - pixelDimIndex];
  56077. var pLayout = point[pixelDimIndex];
  56078. return pAxis >= axisBase && pAxis <= axisBase + layoutInfo.axisLength && pLayout >= layoutBase && pLayout <= layoutBase + layoutInfo.layoutLength;
  56079. };
  56080. Parallel.prototype.getModel = function () {
  56081. return this._model;
  56082. };
  56083. /**
  56084. * Update properties from series
  56085. */
  56086. Parallel.prototype._updateAxesFromSeries = function (parallelModel, ecModel) {
  56087. ecModel.eachSeries(function (seriesModel) {
  56088. if (!parallelModel.contains(seriesModel, ecModel)) {
  56089. return;
  56090. }
  56091. var data = seriesModel.getData();
  56092. each$5(this.dimensions, function (dim) {
  56093. var axis = this._axesMap.get(dim);
  56094. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  56095. niceScaleExtent(axis.scale, axis.model);
  56096. }, this);
  56097. }, this);
  56098. };
  56099. /**
  56100. * Resize the parallel coordinate system.
  56101. */
  56102. Parallel.prototype.resize = function (parallelModel, api) {
  56103. this._rect = getLayoutRect(parallelModel.getBoxLayoutParams(), {
  56104. width: api.getWidth(),
  56105. height: api.getHeight()
  56106. });
  56107. this._layoutAxes();
  56108. };
  56109. Parallel.prototype.getRect = function () {
  56110. return this._rect;
  56111. };
  56112. Parallel.prototype._makeLayoutInfo = function () {
  56113. var parallelModel = this._model;
  56114. var rect = this._rect;
  56115. var xy = ['x', 'y'];
  56116. var wh = ['width', 'height'];
  56117. var layout = parallelModel.get('layout');
  56118. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  56119. var layoutLength = rect[wh[pixelDimIndex]];
  56120. var layoutExtent = [0, layoutLength];
  56121. var axisCount = this.dimensions.length;
  56122. var axisExpandWidth = restrict$1(parallelModel.get('axisExpandWidth'), layoutExtent);
  56123. var axisExpandCount = restrict$1(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  56124. var axisExpandable = parallelModel.get('axisExpandable') && axisCount > 3 && axisCount > axisExpandCount && axisExpandCount > 1 && axisExpandWidth > 0 && layoutLength > 0; // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  56125. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  56126. // where collapsed axes should be overlapped.
  56127. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  56128. var winSize;
  56129. if (!axisExpandWindow) {
  56130. winSize = restrict$1(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  56131. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$1(axisCount / 2);
  56132. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  56133. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  56134. } else {
  56135. winSize = restrict$1(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  56136. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  56137. }
  56138. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount); // Avoid axisCollapseWidth is too small.
  56139. axisCollapseWidth < 3 && (axisCollapseWidth = 0); // Find the first and last indices > ewin[0] and < ewin[1].
  56140. var winInnerIndices = [mathFloor$1(round$3(axisExpandWindow[0] / axisExpandWidth, 1)) + 1, mathCeil$1(round$3(axisExpandWindow[1] / axisExpandWidth, 1)) - 1]; // Pos in ec coordinates.
  56141. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  56142. return {
  56143. layout: layout,
  56144. pixelDimIndex: pixelDimIndex,
  56145. layoutBase: rect[xy[pixelDimIndex]],
  56146. layoutLength: layoutLength,
  56147. axisBase: rect[xy[1 - pixelDimIndex]],
  56148. axisLength: rect[wh[1 - pixelDimIndex]],
  56149. axisExpandable: axisExpandable,
  56150. axisExpandWidth: axisExpandWidth,
  56151. axisCollapseWidth: axisCollapseWidth,
  56152. axisExpandWindow: axisExpandWindow,
  56153. axisCount: axisCount,
  56154. winInnerIndices: winInnerIndices,
  56155. axisExpandWindow0Pos: axisExpandWindow0Pos
  56156. };
  56157. };
  56158. Parallel.prototype._layoutAxes = function () {
  56159. var rect = this._rect;
  56160. var axes = this._axesMap;
  56161. var dimensions = this.dimensions;
  56162. var layoutInfo = this._makeLayoutInfo();
  56163. var layout = layoutInfo.layout;
  56164. axes.each(function (axis) {
  56165. var axisExtent = [0, layoutInfo.axisLength];
  56166. var idx = axis.inverse ? 1 : 0;
  56167. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  56168. });
  56169. each$5(dimensions, function (dim, idx) {
  56170. var posInfo = (layoutInfo.axisExpandable ? layoutAxisWithExpand : layoutAxisWithoutExpand)(idx, layoutInfo);
  56171. var positionTable = {
  56172. horizontal: {
  56173. x: posInfo.position,
  56174. y: layoutInfo.axisLength
  56175. },
  56176. vertical: {
  56177. x: 0,
  56178. y: posInfo.position
  56179. }
  56180. };
  56181. var rotationTable = {
  56182. horizontal: PI$7 / 2,
  56183. vertical: 0
  56184. };
  56185. var position = [positionTable[layout].x + rect.x, positionTable[layout].y + rect.y];
  56186. var rotation = rotationTable[layout];
  56187. var transform = create$1();
  56188. rotate(transform, transform, rotation);
  56189. translate(transform, transform, position); // TODO
  56190. // tick layout info
  56191. // TODO
  56192. // update dimensions info based on axis order.
  56193. this._axesLayout[dim] = {
  56194. position: position,
  56195. rotation: rotation,
  56196. transform: transform,
  56197. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  56198. axisLabelShow: posInfo.axisLabelShow,
  56199. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  56200. tickDirection: 1,
  56201. labelDirection: 1
  56202. };
  56203. }, this);
  56204. };
  56205. /**
  56206. * Get axis by dim.
  56207. */
  56208. Parallel.prototype.getAxis = function (dim) {
  56209. return this._axesMap.get(dim);
  56210. };
  56211. /**
  56212. * Convert a dim value of a single item of series data to Point.
  56213. */
  56214. Parallel.prototype.dataToPoint = function (value, dim) {
  56215. return this.axisCoordToPoint(this._axesMap.get(dim).dataToCoord(value), dim);
  56216. };
  56217. /**
  56218. * Travel data for one time, get activeState of each data item.
  56219. * @param start the start dataIndex that travel from.
  56220. * @param end the next dataIndex of the last dataIndex will be travel.
  56221. */
  56222. Parallel.prototype.eachActiveState = function (data, callback, start, end) {
  56223. start == null && (start = 0);
  56224. end == null && (end = data.count());
  56225. var axesMap = this._axesMap;
  56226. var dimensions = this.dimensions;
  56227. var dataDimensions = [];
  56228. var axisModels = [];
  56229. each(dimensions, function (axisDim) {
  56230. dataDimensions.push(data.mapDimension(axisDim));
  56231. axisModels.push(axesMap.get(axisDim).model);
  56232. });
  56233. var hasActiveSet = this.hasAxisBrushed();
  56234. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  56235. var activeState = void 0;
  56236. if (!hasActiveSet) {
  56237. activeState = 'normal';
  56238. } else {
  56239. activeState = 'active';
  56240. var values = data.getValues(dataDimensions, dataIndex);
  56241. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  56242. var state = axisModels[j].getActiveState(values[j]);
  56243. if (state === 'inactive') {
  56244. activeState = 'inactive';
  56245. break;
  56246. }
  56247. }
  56248. }
  56249. callback(activeState, dataIndex);
  56250. }
  56251. };
  56252. /**
  56253. * Whether has any activeSet.
  56254. */
  56255. Parallel.prototype.hasAxisBrushed = function () {
  56256. var dimensions = this.dimensions;
  56257. var axesMap = this._axesMap;
  56258. var hasActiveSet = false;
  56259. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  56260. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  56261. hasActiveSet = true;
  56262. }
  56263. }
  56264. return hasActiveSet;
  56265. };
  56266. /**
  56267. * Convert coords of each axis to Point.
  56268. * Return point. For example: [10, 20]
  56269. */
  56270. Parallel.prototype.axisCoordToPoint = function (coord, dim) {
  56271. var axisLayout = this._axesLayout[dim];
  56272. return applyTransform$1([coord, 0], axisLayout.transform);
  56273. };
  56274. /**
  56275. * Get axis layout.
  56276. */
  56277. Parallel.prototype.getAxisLayout = function (dim) {
  56278. return clone(this._axesLayout[dim]);
  56279. };
  56280. /**
  56281. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  56282. */
  56283. Parallel.prototype.getSlidedAxisExpandWindow = function (point) {
  56284. var layoutInfo = this._makeLayoutInfo();
  56285. var pixelDimIndex = layoutInfo.pixelDimIndex;
  56286. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  56287. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  56288. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)]; // Out of the area of coordinate system.
  56289. if (!this.containPoint(point)) {
  56290. return {
  56291. behavior: 'none',
  56292. axisExpandWindow: axisExpandWindow
  56293. };
  56294. } // Convert the point from global to expand coordinates.
  56295. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos; // For dragging operation convenience, the window should not be
  56296. // slided when mouse is the center area of the window.
  56297. var delta;
  56298. var behavior = 'slide';
  56299. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  56300. var triggerArea = this._model.get('axisExpandSlideTriggerArea'); // But consider touch device, jump is necessary.
  56301. var useJump = triggerArea[0] != null;
  56302. if (axisCollapseWidth) {
  56303. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  56304. behavior = 'jump';
  56305. delta = pointCoord - winSize * triggerArea[2];
  56306. } else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  56307. behavior = 'jump';
  56308. delta = pointCoord - winSize * (1 - triggerArea[2]);
  56309. } else {
  56310. (delta = pointCoord - winSize * triggerArea[1]) >= 0 && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0 && (delta = 0);
  56311. }
  56312. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  56313. delta ? sliderMove(delta, axisExpandWindow, extent, 'all') // Avoid nonsense triger on mousemove.
  56314. : behavior = 'none';
  56315. } // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  56316. else {
  56317. var winSize2 = axisExpandWindow[1] - axisExpandWindow[0];
  56318. var pos = extent[1] * pointCoord / winSize2;
  56319. axisExpandWindow = [mathMax$8(0, pos - winSize2 / 2)];
  56320. axisExpandWindow[1] = mathMin$8(extent[1], axisExpandWindow[0] + winSize2);
  56321. axisExpandWindow[0] = axisExpandWindow[1] - winSize2;
  56322. }
  56323. return {
  56324. axisExpandWindow: axisExpandWindow,
  56325. behavior: behavior
  56326. };
  56327. };
  56328. return Parallel;
  56329. }();
  56330. function restrict$1(len, extent) {
  56331. return mathMin$8(mathMax$8(len, extent[0]), extent[1]);
  56332. }
  56333. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  56334. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  56335. return {
  56336. position: step * axisIndex,
  56337. axisNameAvailableWidth: step,
  56338. axisLabelShow: true
  56339. };
  56340. }
  56341. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  56342. var layoutLength = layoutInfo.layoutLength;
  56343. var axisExpandWidth = layoutInfo.axisExpandWidth;
  56344. var axisCount = layoutInfo.axisCount;
  56345. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  56346. var winInnerIndices = layoutInfo.winInnerIndices;
  56347. var position;
  56348. var axisNameAvailableWidth = axisCollapseWidth;
  56349. var axisLabelShow = false;
  56350. var nameTruncateMaxWidth;
  56351. if (axisIndex < winInnerIndices[0]) {
  56352. position = axisIndex * axisCollapseWidth;
  56353. nameTruncateMaxWidth = axisCollapseWidth;
  56354. } else if (axisIndex <= winInnerIndices[1]) {
  56355. position = layoutInfo.axisExpandWindow0Pos + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  56356. axisNameAvailableWidth = axisExpandWidth;
  56357. axisLabelShow = true;
  56358. } else {
  56359. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  56360. nameTruncateMaxWidth = axisCollapseWidth;
  56361. }
  56362. return {
  56363. position: position,
  56364. axisNameAvailableWidth: axisNameAvailableWidth,
  56365. axisLabelShow: axisLabelShow,
  56366. nameTruncateMaxWidth: nameTruncateMaxWidth
  56367. };
  56368. }
  56369. function createParallelCoordSys(ecModel, api) {
  56370. var coordSysList = [];
  56371. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  56372. var coordSys = new Parallel(parallelModel, ecModel, api);
  56373. coordSys.name = 'parallel_' + idx;
  56374. coordSys.resize(parallelModel, api);
  56375. parallelModel.coordinateSystem = coordSys;
  56376. coordSys.model = parallelModel;
  56377. coordSysList.push(coordSys);
  56378. }); // Inject the coordinateSystems into seriesModel
  56379. ecModel.eachSeries(function (seriesModel) {
  56380. if (seriesModel.get('coordinateSystem') === 'parallel') {
  56381. var parallelModel = seriesModel.getReferringComponents('parallel', SINGLE_REFERRING).models[0];
  56382. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  56383. }
  56384. });
  56385. return coordSysList;
  56386. }
  56387. var parallelCoordSysCreator = {
  56388. create: createParallelCoordSys
  56389. };
  56390. var ParallelAxisModel =
  56391. /** @class */
  56392. function (_super) {
  56393. __extends(ParallelAxisModel, _super);
  56394. function ParallelAxisModel() {
  56395. var _this = _super !== null && _super.apply(this, arguments) || this;
  56396. _this.type = ParallelAxisModel.type;
  56397. /**
  56398. * @readOnly
  56399. */
  56400. _this.activeIntervals = [];
  56401. return _this;
  56402. }
  56403. ParallelAxisModel.prototype.getAreaSelectStyle = function () {
  56404. return makeStyleMapper([['fill', 'color'], ['lineWidth', 'borderWidth'], ['stroke', 'borderColor'], ['width', 'width'], ['opacity', 'opacity'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  56405. // So do not transfer decal directly.
  56406. ])(this.getModel('areaSelectStyle'));
  56407. };
  56408. /**
  56409. * The code of this feature is put on AxisModel but not ParallelAxis,
  56410. * because axisModel can be alive after echarts updating but instance of
  56411. * ParallelAxis having been disposed. this._activeInterval should be kept
  56412. * when action dispatched (i.e. legend click).
  56413. *
  56414. * @param intervals `interval.length === 0` means set all active.
  56415. */
  56416. ParallelAxisModel.prototype.setActiveIntervals = function (intervals) {
  56417. var activeIntervals = this.activeIntervals = clone(intervals); // Normalize
  56418. if (activeIntervals) {
  56419. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  56420. asc(activeIntervals[i]);
  56421. }
  56422. }
  56423. };
  56424. /**
  56425. * @param value When only attempting detect whether 'no activeIntervals set',
  56426. * `value` is not needed to be input.
  56427. */
  56428. ParallelAxisModel.prototype.getActiveState = function (value) {
  56429. var activeIntervals = this.activeIntervals;
  56430. if (!activeIntervals.length) {
  56431. return 'normal';
  56432. }
  56433. if (value == null || isNaN(+value)) {
  56434. return 'inactive';
  56435. } // Simple optimization
  56436. if (activeIntervals.length === 1) {
  56437. var interval = activeIntervals[0];
  56438. if (interval[0] <= value && value <= interval[1]) {
  56439. return 'active';
  56440. }
  56441. } else {
  56442. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  56443. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  56444. return 'active';
  56445. }
  56446. }
  56447. }
  56448. return 'inactive';
  56449. };
  56450. return ParallelAxisModel;
  56451. }(ComponentModel);
  56452. mixin(ParallelAxisModel, AxisModelCommonMixin);
  56453. var BRUSH_PANEL_GLOBAL = true;
  56454. var mathMin$9 = Math.min;
  56455. var mathMax$9 = Math.max;
  56456. var mathPow$2 = Math.pow;
  56457. var COVER_Z = 10000;
  56458. var UNSELECT_THRESHOLD = 6;
  56459. var MIN_RESIZE_LINE_WIDTH = 6;
  56460. var MUTEX_RESOURCE_KEY = 'globalPan';
  56461. var DIRECTION_MAP = {
  56462. w: [0, 0],
  56463. e: [0, 1],
  56464. n: [1, 0],
  56465. s: [1, 1]
  56466. };
  56467. var CURSOR_MAP = {
  56468. w: 'ew',
  56469. e: 'ew',
  56470. n: 'ns',
  56471. s: 'ns',
  56472. ne: 'nesw',
  56473. sw: 'nesw',
  56474. nw: 'nwse',
  56475. se: 'nwse'
  56476. };
  56477. var DEFAULT_BRUSH_OPT = {
  56478. brushStyle: {
  56479. lineWidth: 2,
  56480. stroke: 'rgba(210,219,238,0.3)',
  56481. fill: '#D2DBEE'
  56482. },
  56483. transformable: true,
  56484. brushMode: 'single',
  56485. removeOnClick: false
  56486. };
  56487. var baseUID = 0;
  56488. /**
  56489. * params:
  56490. * areas: Array.<Array>, coord relates to container group,
  56491. * If no container specified, to global.
  56492. * opt {
  56493. * isEnd: boolean,
  56494. * removeOnClick: boolean
  56495. * }
  56496. */
  56497. var BrushController =
  56498. /** @class */
  56499. function (_super) {
  56500. __extends(BrushController, _super);
  56501. function BrushController(zr) {
  56502. var _this = _super.call(this) || this;
  56503. /**
  56504. * @internal
  56505. */
  56506. _this._track = [];
  56507. /**
  56508. * @internal
  56509. */
  56510. _this._covers = [];
  56511. _this._handlers = {};
  56512. if ("development" !== 'production') {
  56513. assert(zr);
  56514. }
  56515. _this._zr = zr;
  56516. _this.group = new Group();
  56517. _this._uid = 'brushController_' + baseUID++;
  56518. each(pointerHandlers, function (handler, eventName) {
  56519. this._handlers[eventName] = bind(handler, this);
  56520. }, _this);
  56521. return _this;
  56522. }
  56523. /**
  56524. * If set to `false`, select disabled.
  56525. */
  56526. BrushController.prototype.enableBrush = function (brushOption) {
  56527. if ("development" !== 'production') {
  56528. assert(this._mounted);
  56529. }
  56530. this._brushType && this._doDisableBrush();
  56531. brushOption.brushType && this._doEnableBrush(brushOption);
  56532. return this;
  56533. };
  56534. BrushController.prototype._doEnableBrush = function (brushOption) {
  56535. var zr = this._zr; // Consider roam, which takes globalPan too.
  56536. if (!this._enableGlobalPan) {
  56537. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  56538. }
  56539. each(this._handlers, function (handler, eventName) {
  56540. zr.on(eventName, handler);
  56541. });
  56542. this._brushType = brushOption.brushType;
  56543. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  56544. };
  56545. BrushController.prototype._doDisableBrush = function () {
  56546. var zr = this._zr;
  56547. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  56548. each(this._handlers, function (handler, eventName) {
  56549. zr.off(eventName, handler);
  56550. });
  56551. this._brushType = this._brushOption = null;
  56552. };
  56553. /**
  56554. * @param panelOpts If not pass, it is global brush.
  56555. */
  56556. BrushController.prototype.setPanels = function (panelOpts) {
  56557. if (panelOpts && panelOpts.length) {
  56558. var panels_1 = this._panels = {};
  56559. each(panelOpts, function (panelOpts) {
  56560. panels_1[panelOpts.panelId] = clone(panelOpts);
  56561. });
  56562. } else {
  56563. this._panels = null;
  56564. }
  56565. return this;
  56566. };
  56567. BrushController.prototype.mount = function (opt) {
  56568. opt = opt || {};
  56569. if ("development" !== 'production') {
  56570. this._mounted = true; // should be at first.
  56571. }
  56572. this._enableGlobalPan = opt.enableGlobalPan;
  56573. var thisGroup = this.group;
  56574. this._zr.add(thisGroup);
  56575. thisGroup.attr({
  56576. x: opt.x || 0,
  56577. y: opt.y || 0,
  56578. rotation: opt.rotation || 0,
  56579. scaleX: opt.scaleX || 1,
  56580. scaleY: opt.scaleY || 1
  56581. });
  56582. this._transform = thisGroup.getLocalTransform();
  56583. return this;
  56584. }; // eachCover(cb, context): void {
  56585. // each(this._covers, cb, context);
  56586. // }
  56587. /**
  56588. * Update covers.
  56589. * @param coverConfigList
  56590. * If coverConfigList is null/undefined, all covers removed.
  56591. */
  56592. BrushController.prototype.updateCovers = function (coverConfigList) {
  56593. if ("development" !== 'production') {
  56594. assert(this._mounted);
  56595. }
  56596. coverConfigList = map(coverConfigList, function (coverConfig) {
  56597. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  56598. });
  56599. var tmpIdPrefix = '\0-brush-index-';
  56600. var oldCovers = this._covers;
  56601. var newCovers = this._covers = [];
  56602. var controller = this;
  56603. var creatingCover = this._creatingCover;
  56604. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  56605. return this;
  56606. function getKey(brushOption, index) {
  56607. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  56608. }
  56609. function oldGetKey(cover, index) {
  56610. return getKey(cover.__brushOption, index);
  56611. }
  56612. function addOrUpdate(newIndex, oldIndex) {
  56613. var newBrushInternal = coverConfigList[newIndex]; // Consider setOption in event listener of brushSelect,
  56614. // where updating cover when creating should be forbidden.
  56615. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  56616. newCovers[newIndex] = oldCovers[oldIndex];
  56617. } else {
  56618. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  56619. updateCoverAfterCreation(controller, cover);
  56620. }
  56621. }
  56622. function remove(oldIndex) {
  56623. if (oldCovers[oldIndex] !== creatingCover) {
  56624. controller.group.remove(oldCovers[oldIndex]);
  56625. }
  56626. }
  56627. };
  56628. BrushController.prototype.unmount = function () {
  56629. if ("development" !== 'production') {
  56630. if (!this._mounted) {
  56631. return;
  56632. }
  56633. }
  56634. this.enableBrush(false); // container may 'removeAll' outside.
  56635. clearCovers(this);
  56636. this._zr.remove(this.group);
  56637. if ("development" !== 'production') {
  56638. this._mounted = false; // should be at last.
  56639. }
  56640. return this;
  56641. };
  56642. BrushController.prototype.dispose = function () {
  56643. this.unmount();
  56644. this.off();
  56645. };
  56646. return BrushController;
  56647. }(Eventful);
  56648. function createCover(controller, brushOption) {
  56649. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  56650. cover.__brushOption = brushOption;
  56651. updateZ(cover, brushOption);
  56652. controller.group.add(cover);
  56653. return cover;
  56654. }
  56655. function endCreating(controller, creatingCover) {
  56656. var coverRenderer = getCoverRenderer(creatingCover);
  56657. if (coverRenderer.endCreating) {
  56658. coverRenderer.endCreating(controller, creatingCover);
  56659. updateZ(creatingCover, creatingCover.__brushOption);
  56660. }
  56661. return creatingCover;
  56662. }
  56663. function updateCoverShape(controller, cover) {
  56664. var brushOption = cover.__brushOption;
  56665. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  56666. }
  56667. function updateZ(cover, brushOption) {
  56668. var z = brushOption.z;
  56669. z == null && (z = COVER_Z);
  56670. cover.traverse(function (el) {
  56671. el.z = z;
  56672. el.z2 = z; // Consider in given container.
  56673. });
  56674. }
  56675. function updateCoverAfterCreation(controller, cover) {
  56676. getCoverRenderer(cover).updateCommon(controller, cover);
  56677. updateCoverShape(controller, cover);
  56678. }
  56679. function getCoverRenderer(cover) {
  56680. return coverRenderers[cover.__brushOption.brushType];
  56681. } // return target panel or `true` (means global panel)
  56682. function getPanelByPoint(controller, e, localCursorPoint) {
  56683. var panels = controller._panels;
  56684. if (!panels) {
  56685. return BRUSH_PANEL_GLOBAL; // Global panel
  56686. }
  56687. var panel;
  56688. var transform = controller._transform;
  56689. each(panels, function (pn) {
  56690. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  56691. });
  56692. return panel;
  56693. } // Return a panel or true
  56694. function getPanelByCover(controller, cover) {
  56695. var panels = controller._panels;
  56696. if (!panels) {
  56697. return BRUSH_PANEL_GLOBAL; // Global panel
  56698. }
  56699. var panelId = cover.__brushOption.panelId; // User may give cover without coord sys info,
  56700. // which is then treated as global panel.
  56701. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  56702. }
  56703. function clearCovers(controller) {
  56704. var covers = controller._covers;
  56705. var originalLength = covers.length;
  56706. each(covers, function (cover) {
  56707. controller.group.remove(cover);
  56708. }, controller);
  56709. covers.length = 0;
  56710. return !!originalLength;
  56711. }
  56712. function trigger$1(controller, opt) {
  56713. var areas = map(controller._covers, function (cover) {
  56714. var brushOption = cover.__brushOption;
  56715. var range = clone(brushOption.range);
  56716. return {
  56717. brushType: brushOption.brushType,
  56718. panelId: brushOption.panelId,
  56719. range: range
  56720. };
  56721. });
  56722. controller.trigger('brush', {
  56723. areas: areas,
  56724. isEnd: !!opt.isEnd,
  56725. removeOnClick: !!opt.removeOnClick
  56726. });
  56727. }
  56728. function shouldShowCover(controller) {
  56729. var track = controller._track;
  56730. if (!track.length) {
  56731. return false;
  56732. }
  56733. var p2 = track[track.length - 1];
  56734. var p1 = track[0];
  56735. var dx = p2[0] - p1[0];
  56736. var dy = p2[1] - p1[1];
  56737. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  56738. return dist > UNSELECT_THRESHOLD;
  56739. }
  56740. function getTrackEnds(track) {
  56741. var tail = track.length - 1;
  56742. tail < 0 && (tail = 0);
  56743. return [track[0], track[tail]];
  56744. }
  56745. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  56746. var cover = new Group();
  56747. cover.add(new Rect({
  56748. name: 'main',
  56749. style: makeStyle(brushOption),
  56750. silent: true,
  56751. draggable: true,
  56752. cursor: 'move',
  56753. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  56754. ondragend: curry(trigger$1, controller, {
  56755. isEnd: true
  56756. })
  56757. }));
  56758. each(edgeNameSequences, function (nameSequence) {
  56759. cover.add(new Rect({
  56760. name: nameSequence.join(''),
  56761. style: {
  56762. opacity: 0
  56763. },
  56764. draggable: true,
  56765. silent: true,
  56766. invisible: true,
  56767. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  56768. ondragend: curry(trigger$1, controller, {
  56769. isEnd: true
  56770. })
  56771. }));
  56772. });
  56773. return cover;
  56774. }
  56775. function updateBaseRect(controller, cover, localRange, brushOption) {
  56776. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  56777. var handleSize = mathMax$9(lineWidth, MIN_RESIZE_LINE_WIDTH);
  56778. var x = localRange[0][0];
  56779. var y = localRange[1][0];
  56780. var xa = x - lineWidth / 2;
  56781. var ya = y - lineWidth / 2;
  56782. var x2 = localRange[0][1];
  56783. var y2 = localRange[1][1];
  56784. var x2a = x2 - handleSize + lineWidth / 2;
  56785. var y2a = y2 - handleSize + lineWidth / 2;
  56786. var width = x2 - x;
  56787. var height = y2 - y;
  56788. var widtha = width + lineWidth;
  56789. var heighta = height + lineWidth;
  56790. updateRectShape(controller, cover, 'main', x, y, width, height);
  56791. if (brushOption.transformable) {
  56792. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  56793. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  56794. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  56795. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  56796. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  56797. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  56798. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  56799. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  56800. }
  56801. }
  56802. function updateCommon(controller, cover) {
  56803. var brushOption = cover.__brushOption;
  56804. var transformable = brushOption.transformable;
  56805. var mainEl = cover.childAt(0);
  56806. mainEl.useStyle(makeStyle(brushOption));
  56807. mainEl.attr({
  56808. silent: !transformable,
  56809. cursor: transformable ? 'move' : 'default'
  56810. });
  56811. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  56812. var el = cover.childOfName(nameSequence.join(''));
  56813. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  56814. el && el.attr({
  56815. silent: !transformable,
  56816. invisible: !transformable,
  56817. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  56818. });
  56819. });
  56820. }
  56821. function updateRectShape(controller, cover, name, x, y, w, h) {
  56822. var el = cover.childOfName(name);
  56823. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  56824. }
  56825. function makeStyle(brushOption) {
  56826. return defaults({
  56827. strokeNoScale: true
  56828. }, brushOption.brushStyle);
  56829. }
  56830. function formatRectRange(x, y, x2, y2) {
  56831. var min = [mathMin$9(x, x2), mathMin$9(y, y2)];
  56832. var max = [mathMax$9(x, x2), mathMax$9(y, y2)];
  56833. return [[min[0], max[0]], [min[1], max[1]] // y range
  56834. ];
  56835. }
  56836. function getTransform$1(controller) {
  56837. return getTransform(controller.group);
  56838. }
  56839. function getGlobalDirection1(controller, localDirName) {
  56840. var map = {
  56841. w: 'left',
  56842. e: 'right',
  56843. n: 'top',
  56844. s: 'bottom'
  56845. };
  56846. var inverseMap = {
  56847. left: 'w',
  56848. right: 'e',
  56849. top: 'n',
  56850. bottom: 's'
  56851. };
  56852. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  56853. return inverseMap[dir];
  56854. }
  56855. function getGlobalDirection2(controller, localDirNameSeq) {
  56856. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  56857. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  56858. return globalDir.join('');
  56859. }
  56860. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  56861. var brushOption = cover.__brushOption;
  56862. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  56863. var localDelta = toLocalDelta(controller, dx, dy);
  56864. each(dirNameSequence, function (dirName) {
  56865. var ind = DIRECTION_MAP[dirName];
  56866. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  56867. });
  56868. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  56869. updateCoverAfterCreation(controller, cover);
  56870. trigger$1(controller, {
  56871. isEnd: false
  56872. });
  56873. }
  56874. function driftPolygon(controller, cover, dx, dy) {
  56875. var range = cover.__brushOption.range;
  56876. var localDelta = toLocalDelta(controller, dx, dy);
  56877. each(range, function (point) {
  56878. point[0] += localDelta[0];
  56879. point[1] += localDelta[1];
  56880. });
  56881. updateCoverAfterCreation(controller, cover);
  56882. trigger$1(controller, {
  56883. isEnd: false
  56884. });
  56885. }
  56886. function toLocalDelta(controller, dx, dy) {
  56887. var thisGroup = controller.group;
  56888. var localD = thisGroup.transformCoordToLocal(dx, dy);
  56889. var localZero = thisGroup.transformCoordToLocal(0, 0);
  56890. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  56891. }
  56892. function clipByPanel(controller, cover, data) {
  56893. var panel = getPanelByCover(controller, cover);
  56894. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  56895. }
  56896. function pointsToRect(points) {
  56897. var xmin = mathMin$9(points[0][0], points[1][0]);
  56898. var ymin = mathMin$9(points[0][1], points[1][1]);
  56899. var xmax = mathMax$9(points[0][0], points[1][0]);
  56900. var ymax = mathMax$9(points[0][1], points[1][1]);
  56901. return {
  56902. x: xmin,
  56903. y: ymin,
  56904. width: xmax - xmin,
  56905. height: ymax - ymin
  56906. };
  56907. }
  56908. function resetCursor(controller, e, localCursorPoint) {
  56909. if ( // Check active
  56910. !controller._brushType // resetCursor should be always called when mouse is in zr area,
  56911. // but not called when mouse is out of zr area to avoid bad influence
  56912. // if `mousemove`, `mouseup` are triggered from `document` event.
  56913. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  56914. return;
  56915. }
  56916. var zr = controller._zr;
  56917. var covers = controller._covers;
  56918. var currPanel = getPanelByPoint(controller, e, localCursorPoint); // Check whether in covers.
  56919. if (!controller._dragging) {
  56920. for (var i = 0; i < covers.length; i++) {
  56921. var brushOption = covers[i].__brushOption;
  56922. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  56923. // Use cursor style set on cover.
  56924. return;
  56925. }
  56926. }
  56927. }
  56928. currPanel && zr.setCursorStyle('crosshair');
  56929. }
  56930. function preventDefault(e) {
  56931. var rawE = e.event;
  56932. rawE.preventDefault && rawE.preventDefault();
  56933. }
  56934. function mainShapeContain(cover, x, y) {
  56935. return cover.childOfName('main').contain(x, y);
  56936. }
  56937. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  56938. var creatingCover = controller._creatingCover;
  56939. var panel = controller._creatingPanel;
  56940. var thisBrushOption = controller._brushOption;
  56941. var eventParams;
  56942. controller._track.push(localCursorPoint.slice());
  56943. if (shouldShowCover(controller) || creatingCover) {
  56944. if (panel && !creatingCover) {
  56945. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  56946. var brushOption = clone(thisBrushOption);
  56947. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  56948. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  56949. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  56950. controller._covers.push(creatingCover);
  56951. }
  56952. if (creatingCover) {
  56953. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  56954. var coverBrushOption = creatingCover.__brushOption;
  56955. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  56956. if (isEnd) {
  56957. endCreating(controller, creatingCover);
  56958. coverRenderer.updateCommon(controller, creatingCover);
  56959. }
  56960. updateCoverShape(controller, creatingCover);
  56961. eventParams = {
  56962. isEnd: isEnd
  56963. };
  56964. }
  56965. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  56966. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  56967. // But a single click do not clear covers, because user may have casual
  56968. // clicks (for example, click on other component and do not expect covers
  56969. // disappear).
  56970. // Only some cover removed, trigger action, but not every click trigger action.
  56971. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  56972. eventParams = {
  56973. isEnd: isEnd,
  56974. removeOnClick: true
  56975. };
  56976. }
  56977. }
  56978. return eventParams;
  56979. }
  56980. function determineBrushType(brushType, panel) {
  56981. if (brushType === 'auto') {
  56982. if ("development" !== 'production') {
  56983. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  56984. }
  56985. return panel.defaultBrushType;
  56986. }
  56987. return brushType;
  56988. }
  56989. var pointerHandlers = {
  56990. mousedown: function (e) {
  56991. if (this._dragging) {
  56992. // In case some browser do not support globalOut,
  56993. // and release mouse out side the browser.
  56994. handleDragEnd(this, e);
  56995. } else if (!e.target || !e.target.draggable) {
  56996. preventDefault(e);
  56997. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  56998. this._creatingCover = null;
  56999. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  57000. if (panel) {
  57001. this._dragging = true;
  57002. this._track = [localCursorPoint.slice()];
  57003. }
  57004. }
  57005. },
  57006. mousemove: function (e) {
  57007. var x = e.offsetX;
  57008. var y = e.offsetY;
  57009. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  57010. resetCursor(this, e, localCursorPoint);
  57011. if (this._dragging) {
  57012. preventDefault(e);
  57013. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  57014. eventParams && trigger$1(this, eventParams);
  57015. }
  57016. },
  57017. mouseup: function (e) {
  57018. handleDragEnd(this, e);
  57019. }
  57020. };
  57021. function handleDragEnd(controller, e) {
  57022. if (controller._dragging) {
  57023. preventDefault(e);
  57024. var x = e.offsetX;
  57025. var y = e.offsetY;
  57026. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  57027. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  57028. controller._dragging = false;
  57029. controller._track = [];
  57030. controller._creatingCover = null; // trigger event should be at final, after procedure will be nested.
  57031. eventParams && trigger$1(controller, eventParams);
  57032. }
  57033. }
  57034. function isOutsideZrArea(controller, x, y) {
  57035. var zr = controller._zr;
  57036. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  57037. }
  57038. /**
  57039. * key: brushType
  57040. */
  57041. var coverRenderers = {
  57042. lineX: getLineRenderer(0),
  57043. lineY: getLineRenderer(1),
  57044. rect: {
  57045. createCover: function (controller, brushOption) {
  57046. function returnInput(range) {
  57047. return range;
  57048. }
  57049. return createBaseRectCover({
  57050. toRectRange: returnInput,
  57051. fromRectRange: returnInput
  57052. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  57053. },
  57054. getCreatingRange: function (localTrack) {
  57055. var ends = getTrackEnds(localTrack);
  57056. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  57057. },
  57058. updateCoverShape: function (controller, cover, localRange, brushOption) {
  57059. updateBaseRect(controller, cover, localRange, brushOption);
  57060. },
  57061. updateCommon: updateCommon,
  57062. contain: mainShapeContain
  57063. },
  57064. polygon: {
  57065. createCover: function (controller, brushOption) {
  57066. var cover = new Group(); // Do not use graphic.Polygon because graphic.Polyline do not close the
  57067. // border of the shape when drawing, which is a better experience for user.
  57068. cover.add(new Polyline({
  57069. name: 'main',
  57070. style: makeStyle(brushOption),
  57071. silent: true
  57072. }));
  57073. return cover;
  57074. },
  57075. getCreatingRange: function (localTrack) {
  57076. return localTrack;
  57077. },
  57078. endCreating: function (controller, cover) {
  57079. cover.remove(cover.childAt(0)); // Use graphic.Polygon close the shape.
  57080. cover.add(new Polygon({
  57081. name: 'main',
  57082. draggable: true,
  57083. drift: curry(driftPolygon, controller, cover),
  57084. ondragend: curry(trigger$1, controller, {
  57085. isEnd: true
  57086. })
  57087. }));
  57088. },
  57089. updateCoverShape: function (controller, cover, localRange, brushOption) {
  57090. cover.childAt(0).setShape({
  57091. points: clipByPanel(controller, cover, localRange)
  57092. });
  57093. },
  57094. updateCommon: updateCommon,
  57095. contain: mainShapeContain
  57096. }
  57097. };
  57098. function getLineRenderer(xyIndex) {
  57099. return {
  57100. createCover: function (controller, brushOption) {
  57101. return createBaseRectCover({
  57102. toRectRange: function (range) {
  57103. var rectRange = [range, [0, 100]];
  57104. xyIndex && rectRange.reverse();
  57105. return rectRange;
  57106. },
  57107. fromRectRange: function (rectRange) {
  57108. return rectRange[xyIndex];
  57109. }
  57110. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  57111. },
  57112. getCreatingRange: function (localTrack) {
  57113. var ends = getTrackEnds(localTrack);
  57114. var min = mathMin$9(ends[0][xyIndex], ends[1][xyIndex]);
  57115. var max = mathMax$9(ends[0][xyIndex], ends[1][xyIndex]);
  57116. return [min, max];
  57117. },
  57118. updateCoverShape: function (controller, cover, localRange, brushOption) {
  57119. var otherExtent; // If brushWidth not specified, fit the panel.
  57120. var panel = getPanelByCover(controller, cover);
  57121. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  57122. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  57123. } else {
  57124. var zr = controller._zr;
  57125. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  57126. }
  57127. var rectRange = [localRange, otherExtent];
  57128. xyIndex && rectRange.reverse();
  57129. updateBaseRect(controller, cover, rectRange, brushOption);
  57130. },
  57131. updateCommon: updateCommon,
  57132. contain: mainShapeContain
  57133. };
  57134. }
  57135. function makeRectPanelClipPath(rect) {
  57136. rect = normalizeRect(rect);
  57137. return function (localPoints) {
  57138. return clipPointsByRect(localPoints, rect);
  57139. };
  57140. }
  57141. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  57142. rect = normalizeRect(rect);
  57143. return function (xyIndex) {
  57144. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  57145. var brushWidth = idx ? rect.width : rect.height;
  57146. var base = idx ? rect.x : rect.y;
  57147. return [base, base + (brushWidth || 0)];
  57148. };
  57149. }
  57150. function makeRectIsTargetByCursor(rect, api, targetModel) {
  57151. var boundingRect = normalizeRect(rect);
  57152. return function (e, localCursorPoint) {
  57153. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  57154. };
  57155. } // Consider width/height is negative.
  57156. function normalizeRect(rect) {
  57157. return BoundingRect.create(rect);
  57158. }
  57159. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  57160. var ParallelAxisView =
  57161. /** @class */
  57162. function (_super) {
  57163. __extends(ParallelAxisView, _super);
  57164. function ParallelAxisView() {
  57165. var _this = _super !== null && _super.apply(this, arguments) || this;
  57166. _this.type = ParallelAxisView.type;
  57167. return _this;
  57168. }
  57169. ParallelAxisView.prototype.init = function (ecModel, api) {
  57170. _super.prototype.init.apply(this, arguments);
  57171. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this));
  57172. };
  57173. ParallelAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  57174. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  57175. return;
  57176. }
  57177. this.axisModel = axisModel;
  57178. this.api = api;
  57179. this.group.removeAll();
  57180. var oldAxisGroup = this._axisGroup;
  57181. this._axisGroup = new Group();
  57182. this.group.add(this._axisGroup);
  57183. if (!axisModel.get('show')) {
  57184. return;
  57185. }
  57186. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  57187. var coordSys = coordSysModel.coordinateSystem;
  57188. var areaSelectStyle = axisModel.getAreaSelectStyle();
  57189. var areaWidth = areaSelectStyle.width;
  57190. var dim = axisModel.axis.dim;
  57191. var axisLayout = coordSys.getAxisLayout(dim);
  57192. var builderOpt = extend({
  57193. strokeContainThreshold: areaWidth
  57194. }, axisLayout);
  57195. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  57196. each(elementList, axisBuilder.add, axisBuilder);
  57197. this._axisGroup.add(axisBuilder.getGroup());
  57198. this._refreshBrushController(builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api);
  57199. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  57200. }; // /**
  57201. // * @override
  57202. // */
  57203. // updateVisual(axisModel, ecModel, api, payload) {
  57204. // this._brushController && this._brushController
  57205. // .updateCovers(getCoverInfoList(axisModel));
  57206. // }
  57207. ParallelAxisView.prototype._refreshBrushController = function (builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api) {
  57208. // After filtering, axis may change, select area needs to be update.
  57209. var extent = axisModel.axis.getExtent();
  57210. var extentLen = extent[1] - extent[0];
  57211. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  57212. // width/height might be negative, which will be
  57213. // normalized in BoundingRect.
  57214. var rect = BoundingRect.create({
  57215. x: extent[0],
  57216. y: -areaWidth / 2,
  57217. width: extentLen,
  57218. height: areaWidth
  57219. });
  57220. rect.x -= extra;
  57221. rect.width += 2 * extra;
  57222. this._brushController.mount({
  57223. enableGlobalPan: true,
  57224. rotation: builderOpt.rotation,
  57225. x: builderOpt.position[0],
  57226. y: builderOpt.position[1]
  57227. }).setPanels([{
  57228. panelId: 'pl',
  57229. clipPath: makeRectPanelClipPath(rect),
  57230. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  57231. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  57232. }]).enableBrush({
  57233. brushType: 'lineX',
  57234. brushStyle: areaSelectStyle,
  57235. removeOnClick: true
  57236. }).updateCovers(getCoverInfoList(axisModel));
  57237. };
  57238. ParallelAxisView.prototype._onBrush = function (eventParam) {
  57239. var coverInfoList = eventParam.areas; // Do not cache these object, because the mey be changed.
  57240. var axisModel = this.axisModel;
  57241. var axis = axisModel.axis;
  57242. var intervals = map(coverInfoList, function (coverInfo) {
  57243. return [axis.coordToData(coverInfo.range[0], true), axis.coordToData(coverInfo.range[1], true)];
  57244. }); // If realtime is true, action is not dispatched on drag end, because
  57245. // the drag end emits the same params with the last drag move event,
  57246. // and may have some delay when using touch pad.
  57247. if (!axisModel.option.realtime === eventParam.isEnd || eventParam.removeOnClick) {
  57248. // jshint ignore:line
  57249. this.api.dispatchAction({
  57250. type: 'axisAreaSelect',
  57251. parallelAxisId: axisModel.id,
  57252. intervals: intervals
  57253. });
  57254. }
  57255. };
  57256. ParallelAxisView.prototype.dispose = function () {
  57257. this._brushController.dispose();
  57258. };
  57259. ParallelAxisView.type = 'parallelAxis';
  57260. return ParallelAxisView;
  57261. }(ComponentView);
  57262. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  57263. return payload && payload.type === 'axisAreaSelect' && ecModel.findComponents({
  57264. mainType: 'parallelAxis',
  57265. query: payload
  57266. })[0] === axisModel;
  57267. }
  57268. function getCoverInfoList(axisModel) {
  57269. var axis = axisModel.axis;
  57270. return map(axisModel.activeIntervals, function (interval) {
  57271. return {
  57272. brushType: 'lineX',
  57273. panelId: 'pl',
  57274. range: [axis.dataToCoord(interval[0], true), axis.dataToCoord(interval[1], true)]
  57275. };
  57276. });
  57277. }
  57278. function getCoordSysModel(axisModel, ecModel) {
  57279. return ecModel.getComponent('parallel', axisModel.get('parallelIndex'));
  57280. }
  57281. /*
  57282. * Licensed to the Apache Software Foundation (ASF) under one
  57283. * or more contributor license agreements. See the NOTICE file
  57284. * distributed with this work for additional information
  57285. * regarding copyright ownership. The ASF licenses this file
  57286. * to you under the Apache License, Version 2.0 (the
  57287. * "License"); you may not use this file except in compliance
  57288. * with the License. You may obtain a copy of the License at
  57289. *
  57290. * http://www.apache.org/licenses/LICENSE-2.0
  57291. *
  57292. * Unless required by applicable law or agreed to in writing,
  57293. * software distributed under the License is distributed on an
  57294. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57295. * KIND, either express or implied. See the License for the
  57296. * specific language governing permissions and limitations
  57297. * under the License.
  57298. */
  57299. /**
  57300. * AUTO-GENERATED FILE. DO NOT MODIFY.
  57301. */
  57302. /*
  57303. * Licensed to the Apache Software Foundation (ASF) under one
  57304. * or more contributor license agreements. See the NOTICE file
  57305. * distributed with this work for additional information
  57306. * regarding copyright ownership. The ASF licenses this file
  57307. * to you under the Apache License, Version 2.0 (the
  57308. * "License"); you may not use this file except in compliance
  57309. * with the License. You may obtain a copy of the License at
  57310. *
  57311. * http://www.apache.org/licenses/LICENSE-2.0
  57312. *
  57313. * Unless required by applicable law or agreed to in writing,
  57314. * software distributed under the License is distributed on an
  57315. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57316. * KIND, either express or implied. See the License for the
  57317. * specific language governing permissions and limitations
  57318. * under the License.
  57319. */
  57320. var actionInfo$1 = {
  57321. type: 'axisAreaSelect',
  57322. event: 'axisAreaSelected' // update: 'updateVisual'
  57323. };
  57324. function installParallelActions(registers) {
  57325. registers.registerAction(actionInfo$1, function (payload, ecModel) {
  57326. ecModel.eachComponent({
  57327. mainType: 'parallelAxis',
  57328. query: payload
  57329. }, function (parallelAxisModel) {
  57330. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  57331. });
  57332. });
  57333. /**
  57334. * @payload
  57335. */
  57336. registers.registerAction('parallelAxisExpand', function (payload, ecModel) {
  57337. ecModel.eachComponent({
  57338. mainType: 'parallel',
  57339. query: payload
  57340. }, function (parallelModel) {
  57341. parallelModel.setAxisExpand(payload);
  57342. });
  57343. });
  57344. }
  57345. var defaultAxisOption = {
  57346. type: 'value',
  57347. areaSelectStyle: {
  57348. width: 20,
  57349. borderWidth: 1,
  57350. borderColor: 'rgba(160,197,232)',
  57351. color: 'rgba(160,197,232)',
  57352. opacity: 0.3
  57353. },
  57354. realtime: true,
  57355. z: 10
  57356. };
  57357. function install$g(registers) {
  57358. registers.registerComponentView(ParallelView$1);
  57359. registers.registerComponentModel(ParallelModel);
  57360. registers.registerCoordinateSystem('parallel', parallelCoordSysCreator);
  57361. registers.registerPreprocessor(parallelPreprocessor);
  57362. registers.registerComponentModel(ParallelAxisModel);
  57363. registers.registerComponentView(ParallelAxisView);
  57364. axisModelCreator(registers, 'parallel', ParallelAxisModel, defaultAxisOption);
  57365. installParallelActions(registers);
  57366. }
  57367. function install$h(registers) {
  57368. use(install$g);
  57369. registers.registerChartView(ParallelView);
  57370. registers.registerSeriesModel(ParallelSeriesModel);
  57371. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, parallelVisual);
  57372. }
  57373. var SankeyPathShape =
  57374. /** @class */
  57375. function () {
  57376. function SankeyPathShape() {
  57377. this.x1 = 0;
  57378. this.y1 = 0;
  57379. this.x2 = 0;
  57380. this.y2 = 0;
  57381. this.cpx1 = 0;
  57382. this.cpy1 = 0;
  57383. this.cpx2 = 0;
  57384. this.cpy2 = 0;
  57385. this.extent = 0;
  57386. }
  57387. return SankeyPathShape;
  57388. }();
  57389. var SankeyPath =
  57390. /** @class */
  57391. function (_super) {
  57392. __extends(SankeyPath, _super);
  57393. function SankeyPath(opts) {
  57394. return _super.call(this, opts) || this;
  57395. }
  57396. SankeyPath.prototype.getDefaultShape = function () {
  57397. return new SankeyPathShape();
  57398. };
  57399. SankeyPath.prototype.buildPath = function (ctx, shape) {
  57400. var extent = shape.extent;
  57401. ctx.moveTo(shape.x1, shape.y1);
  57402. ctx.bezierCurveTo(shape.cpx1, shape.cpy1, shape.cpx2, shape.cpy2, shape.x2, shape.y2);
  57403. if (shape.orient === 'vertical') {
  57404. ctx.lineTo(shape.x2 + extent, shape.y2);
  57405. ctx.bezierCurveTo(shape.cpx2 + extent, shape.cpy2, shape.cpx1 + extent, shape.cpy1, shape.x1 + extent, shape.y1);
  57406. } else {
  57407. ctx.lineTo(shape.x2, shape.y2 + extent);
  57408. ctx.bezierCurveTo(shape.cpx2, shape.cpy2 + extent, shape.cpx1, shape.cpy1 + extent, shape.x1, shape.y1 + extent);
  57409. }
  57410. ctx.closePath();
  57411. };
  57412. SankeyPath.prototype.highlight = function () {
  57413. enterEmphasis(this);
  57414. };
  57415. SankeyPath.prototype.downplay = function () {
  57416. leaveEmphasis(this);
  57417. };
  57418. return SankeyPath;
  57419. }(Path);
  57420. var SankeyView =
  57421. /** @class */
  57422. function (_super) {
  57423. __extends(SankeyView, _super);
  57424. function SankeyView() {
  57425. var _this = _super !== null && _super.apply(this, arguments) || this;
  57426. _this.type = SankeyView.type;
  57427. _this._focusAdjacencyDisabled = false;
  57428. return _this;
  57429. }
  57430. SankeyView.prototype.render = function (seriesModel, ecModel, api) {
  57431. var sankeyView = this;
  57432. var graph = seriesModel.getGraph();
  57433. var group = this.group;
  57434. var layoutInfo = seriesModel.layoutInfo; // view width
  57435. var width = layoutInfo.width; // view height
  57436. var height = layoutInfo.height;
  57437. var nodeData = seriesModel.getData();
  57438. var edgeData = seriesModel.getData('edge');
  57439. var orient = seriesModel.get('orient');
  57440. this._model = seriesModel;
  57441. group.removeAll();
  57442. group.x = layoutInfo.x;
  57443. group.y = layoutInfo.y; // generate a bezire Curve for each edge
  57444. graph.eachEdge(function (edge) {
  57445. var curve = new SankeyPath();
  57446. var ecData = getECData(curve);
  57447. ecData.dataIndex = edge.dataIndex;
  57448. ecData.seriesIndex = seriesModel.seriesIndex;
  57449. ecData.dataType = 'edge';
  57450. var edgeModel = edge.getModel();
  57451. var lineStyleModel = edgeModel.getModel('lineStyle');
  57452. var curvature = lineStyleModel.get('curveness');
  57453. var n1Layout = edge.node1.getLayout();
  57454. var node1Model = edge.node1.getModel();
  57455. var dragX1 = node1Model.get('localX');
  57456. var dragY1 = node1Model.get('localY');
  57457. var n2Layout = edge.node2.getLayout();
  57458. var node2Model = edge.node2.getModel();
  57459. var dragX2 = node2Model.get('localX');
  57460. var dragY2 = node2Model.get('localY');
  57461. var edgeLayout = edge.getLayout();
  57462. var x1;
  57463. var y1;
  57464. var x2;
  57465. var y2;
  57466. var cpx1;
  57467. var cpy1;
  57468. var cpx2;
  57469. var cpy2;
  57470. curve.shape.extent = Math.max(1, edgeLayout.dy);
  57471. curve.shape.orient = orient;
  57472. if (orient === 'vertical') {
  57473. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  57474. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  57475. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  57476. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  57477. cpx1 = x1;
  57478. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  57479. cpx2 = x2;
  57480. cpy2 = y1 * curvature + y2 * (1 - curvature);
  57481. } else {
  57482. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  57483. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  57484. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  57485. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  57486. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  57487. cpy1 = y1;
  57488. cpx2 = x1 * curvature + x2 * (1 - curvature);
  57489. cpy2 = y2;
  57490. }
  57491. curve.setShape({
  57492. x1: x1,
  57493. y1: y1,
  57494. x2: x2,
  57495. y2: y2,
  57496. cpx1: cpx1,
  57497. cpy1: cpy1,
  57498. cpx2: cpx2,
  57499. cpy2: cpy2
  57500. });
  57501. curve.useStyle(lineStyleModel.getItemStyle()); // Special color, use source node color or target node color
  57502. switch (curve.style.fill) {
  57503. case 'source':
  57504. curve.style.fill = edge.node1.getVisual('color');
  57505. curve.style.decal = edge.node1.getVisual('style').decal;
  57506. break;
  57507. case 'target':
  57508. curve.style.fill = edge.node2.getVisual('color');
  57509. curve.style.decal = edge.node2.getVisual('style').decal;
  57510. break;
  57511. case 'gradient':
  57512. var sourceColor = edge.node1.getVisual('color');
  57513. var targetColor = edge.node2.getVisual('color');
  57514. if (isString(sourceColor) && isString(targetColor)) {
  57515. curve.style.fill = new LinearGradient(0, 0, +(orient === 'horizontal'), +(orient === 'vertical'), [{
  57516. color: sourceColor,
  57517. offset: 0
  57518. }, {
  57519. color: targetColor,
  57520. offset: 1
  57521. }]);
  57522. }
  57523. }
  57524. setLabelStyle(curve, getLabelStatesModels(edgeModel, 'edgeLabel'), {
  57525. labelFetcher: seriesModel,
  57526. labelDataIndex: edge.dataIndex,
  57527. defaultText: "" + edgeModel.get('value')
  57528. });
  57529. curve.setTextConfig({
  57530. position: 'inside'
  57531. });
  57532. var emphasisModel = edgeModel.getModel('emphasis');
  57533. setStatesStylesFromModel(curve, edgeModel, 'lineStyle', function (model) {
  57534. return model.getItemStyle();
  57535. });
  57536. group.add(curve);
  57537. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  57538. var focus = emphasisModel.get('focus');
  57539. toggleHoverEmphasis(curve, focus === 'adjacency' ? edge.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  57540. getECData(curve).dataType = 'edge';
  57541. }); // Generate a rect for each node
  57542. graph.eachNode(function (node) {
  57543. var layout = node.getLayout();
  57544. var itemModel = node.getModel();
  57545. var dragX = itemModel.get('localX');
  57546. var dragY = itemModel.get('localY');
  57547. var emphasisModel = itemModel.getModel('emphasis');
  57548. var rect = new Rect({
  57549. shape: {
  57550. x: dragX != null ? dragX * width : layout.x,
  57551. y: dragY != null ? dragY * height : layout.y,
  57552. width: layout.dx,
  57553. height: layout.dy
  57554. },
  57555. style: itemModel.getModel('itemStyle').getItemStyle(),
  57556. z2: 10
  57557. });
  57558. setLabelStyle(rect, getLabelStatesModels(itemModel), {
  57559. labelFetcher: seriesModel,
  57560. labelDataIndex: node.dataIndex,
  57561. defaultText: node.id
  57562. });
  57563. rect.disableLabelAnimation = true;
  57564. rect.setStyle('fill', node.getVisual('color'));
  57565. rect.setStyle('decal', node.getVisual('style').decal);
  57566. setStatesStylesFromModel(rect, itemModel);
  57567. group.add(rect);
  57568. nodeData.setItemGraphicEl(node.dataIndex, rect);
  57569. getECData(rect).dataType = 'node';
  57570. var focus = emphasisModel.get('focus');
  57571. toggleHoverEmphasis(rect, focus === 'adjacency' ? node.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  57572. });
  57573. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  57574. var itemModel = nodeData.getItemModel(dataIndex);
  57575. if (itemModel.get('draggable')) {
  57576. el.drift = function (dx, dy) {
  57577. sankeyView._focusAdjacencyDisabled = true;
  57578. this.shape.x += dx;
  57579. this.shape.y += dy;
  57580. this.dirty();
  57581. api.dispatchAction({
  57582. type: 'dragNode',
  57583. seriesId: seriesModel.id,
  57584. dataIndex: nodeData.getRawIndex(dataIndex),
  57585. localX: this.shape.x / width,
  57586. localY: this.shape.y / height
  57587. });
  57588. };
  57589. el.ondragend = function () {
  57590. sankeyView._focusAdjacencyDisabled = false;
  57591. };
  57592. el.draggable = true;
  57593. el.cursor = 'move';
  57594. }
  57595. });
  57596. if (!this._data && seriesModel.isAnimationEnabled()) {
  57597. group.setClipPath(createGridClipShape$1(group.getBoundingRect(), seriesModel, function () {
  57598. group.removeClipPath();
  57599. }));
  57600. }
  57601. this._data = seriesModel.getData();
  57602. };
  57603. SankeyView.prototype.dispose = function () {};
  57604. SankeyView.type = 'sankey';
  57605. return SankeyView;
  57606. }(ChartView); // Add animation to the view
  57607. function createGridClipShape$1(rect, seriesModel, cb) {
  57608. var rectEl = new Rect({
  57609. shape: {
  57610. x: rect.x - 10,
  57611. y: rect.y - 10,
  57612. width: 0,
  57613. height: rect.height + 20
  57614. }
  57615. });
  57616. initProps(rectEl, {
  57617. shape: {
  57618. width: rect.width + 20
  57619. }
  57620. }, seriesModel, cb);
  57621. return rectEl;
  57622. }
  57623. var SankeySeriesModel =
  57624. /** @class */
  57625. function (_super) {
  57626. __extends(SankeySeriesModel, _super);
  57627. function SankeySeriesModel() {
  57628. var _this = _super !== null && _super.apply(this, arguments) || this;
  57629. _this.type = SankeySeriesModel.type;
  57630. return _this;
  57631. }
  57632. /**
  57633. * Init a graph data structure from data in option series
  57634. */
  57635. SankeySeriesModel.prototype.getInitialData = function (option, ecModel) {
  57636. var links = option.edges || option.links;
  57637. var nodes = option.data || option.nodes;
  57638. var levels = option.levels;
  57639. this.levelModels = [];
  57640. var levelModels = this.levelModels;
  57641. for (var i = 0; i < levels.length; i++) {
  57642. if (levels[i].depth != null && levels[i].depth >= 0) {
  57643. levelModels[levels[i].depth] = new Model(levels[i], this, ecModel);
  57644. } else {
  57645. if ("development" !== 'production') {
  57646. throw new Error('levels[i].depth is mandatory and should be natural number');
  57647. }
  57648. }
  57649. }
  57650. if (nodes && links) {
  57651. var graph = createGraphFromNodeEdge(nodes, links, this, true, beforeLink);
  57652. return graph.data;
  57653. }
  57654. function beforeLink(nodeData, edgeData) {
  57655. nodeData.wrapMethod('getItemModel', function (model, idx) {
  57656. var seriesModel = model.parentModel;
  57657. var layout = seriesModel.getData().getItemLayout(idx);
  57658. if (layout) {
  57659. var nodeDepth = layout.depth;
  57660. var levelModel = seriesModel.levelModels[nodeDepth];
  57661. if (levelModel) {
  57662. model.parentModel = levelModel;
  57663. }
  57664. }
  57665. return model;
  57666. });
  57667. edgeData.wrapMethod('getItemModel', function (model, idx) {
  57668. var seriesModel = model.parentModel;
  57669. var edge = seriesModel.getGraph().getEdgeByIndex(idx);
  57670. var layout = edge.node1.getLayout();
  57671. if (layout) {
  57672. var depth = layout.depth;
  57673. var levelModel = seriesModel.levelModels[depth];
  57674. if (levelModel) {
  57675. model.parentModel = levelModel;
  57676. }
  57677. }
  57678. return model;
  57679. });
  57680. }
  57681. };
  57682. SankeySeriesModel.prototype.setNodePosition = function (dataIndex, localPosition) {
  57683. var nodes = this.option.data || this.option.nodes;
  57684. var dataItem = nodes[dataIndex];
  57685. dataItem.localX = localPosition[0];
  57686. dataItem.localY = localPosition[1];
  57687. };
  57688. /**
  57689. * Return the graphic data structure
  57690. *
  57691. * @return graphic data structure
  57692. */
  57693. SankeySeriesModel.prototype.getGraph = function () {
  57694. return this.getData().graph;
  57695. };
  57696. /**
  57697. * Get edge data of graphic data structure
  57698. *
  57699. * @return data structure of list
  57700. */
  57701. SankeySeriesModel.prototype.getEdgeData = function () {
  57702. return this.getGraph().edgeData;
  57703. };
  57704. SankeySeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  57705. function noValue(val) {
  57706. return isNaN(val) || val == null;
  57707. } // dataType === 'node' or empty do not show tooltip by default
  57708. if (dataType === 'edge') {
  57709. var params = this.getDataParams(dataIndex, dataType);
  57710. var rawDataOpt = params.data;
  57711. var edgeValue = params.value;
  57712. var edgeName = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  57713. return createTooltipMarkup('nameValue', {
  57714. name: edgeName,
  57715. value: edgeValue,
  57716. noValue: noValue(edgeValue)
  57717. });
  57718. } // dataType === 'node'
  57719. else {
  57720. var node = this.getGraph().getNodeByIndex(dataIndex);
  57721. var value = node.getLayout().value;
  57722. var name_1 = this.getDataParams(dataIndex, dataType).data.name;
  57723. return createTooltipMarkup('nameValue', {
  57724. name: name_1 != null ? name_1 + '' : null,
  57725. value: value,
  57726. noValue: noValue(value)
  57727. });
  57728. }
  57729. };
  57730. SankeySeriesModel.prototype.optionUpdated = function () {}; // Override Series.getDataParams()
  57731. SankeySeriesModel.prototype.getDataParams = function (dataIndex, dataType) {
  57732. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  57733. if (params.value == null && dataType === 'node') {
  57734. var node = this.getGraph().getNodeByIndex(dataIndex);
  57735. var nodeValue = node.getLayout().value;
  57736. params.value = nodeValue;
  57737. }
  57738. return params;
  57739. };
  57740. SankeySeriesModel.type = 'series.sankey';
  57741. SankeySeriesModel.defaultOption = {
  57742. // zlevel: 0,
  57743. z: 2,
  57744. coordinateSystem: 'view',
  57745. left: '5%',
  57746. top: '5%',
  57747. right: '20%',
  57748. bottom: '5%',
  57749. orient: 'horizontal',
  57750. nodeWidth: 20,
  57751. nodeGap: 8,
  57752. draggable: true,
  57753. layoutIterations: 32,
  57754. label: {
  57755. show: true,
  57756. position: 'right',
  57757. fontSize: 12
  57758. },
  57759. edgeLabel: {
  57760. show: false,
  57761. fontSize: 12
  57762. },
  57763. levels: [],
  57764. nodeAlign: 'justify',
  57765. lineStyle: {
  57766. color: '#314656',
  57767. opacity: 0.2,
  57768. curveness: 0.5
  57769. },
  57770. emphasis: {
  57771. label: {
  57772. show: true
  57773. },
  57774. lineStyle: {
  57775. opacity: 0.5
  57776. }
  57777. },
  57778. select: {
  57779. itemStyle: {
  57780. borderColor: '#212121'
  57781. }
  57782. },
  57783. animationEasing: 'linear',
  57784. animationDuration: 1000
  57785. };
  57786. return SankeySeriesModel;
  57787. }(SeriesModel);
  57788. function sankeyLayout(ecModel, api) {
  57789. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  57790. var nodeWidth = seriesModel.get('nodeWidth');
  57791. var nodeGap = seriesModel.get('nodeGap');
  57792. var layoutInfo = getViewRect$4(seriesModel, api);
  57793. seriesModel.layoutInfo = layoutInfo;
  57794. var width = layoutInfo.width;
  57795. var height = layoutInfo.height;
  57796. var graph = seriesModel.getGraph();
  57797. var nodes = graph.nodes;
  57798. var edges = graph.edges;
  57799. computeNodeValues(nodes);
  57800. var filteredNodes = filter(nodes, function (node) {
  57801. return node.getLayout().value === 0;
  57802. });
  57803. var iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations');
  57804. var orient = seriesModel.get('orient');
  57805. var nodeAlign = seriesModel.get('nodeAlign');
  57806. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign);
  57807. });
  57808. }
  57809. /**
  57810. * Get the layout position of the whole view
  57811. */
  57812. function getViewRect$4(seriesModel, api) {
  57813. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  57814. width: api.getWidth(),
  57815. height: api.getHeight()
  57816. });
  57817. }
  57818. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign) {
  57819. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign);
  57820. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  57821. computeEdgeDepths(nodes, orient);
  57822. }
  57823. /**
  57824. * Compute the value of each node by summing the associated edge's value
  57825. */
  57826. function computeNodeValues(nodes) {
  57827. each(nodes, function (node) {
  57828. var value1 = sum(node.outEdges, getEdgeValue);
  57829. var value2 = sum(node.inEdges, getEdgeValue);
  57830. var nodeRawValue = node.getValue() || 0;
  57831. var value = Math.max(value1, value2, nodeRawValue);
  57832. node.setLayout({
  57833. value: value
  57834. }, true);
  57835. });
  57836. }
  57837. /**
  57838. * Compute the x-position for each node.
  57839. *
  57840. * Here we use Kahn algorithm to detect cycle when we traverse
  57841. * the node to computer the initial x position.
  57842. */
  57843. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
  57844. // Used to mark whether the edge is deleted. if it is deleted,
  57845. // the value is 0, otherwise it is 1.
  57846. var remainEdges = []; // Storage each node's indegree.
  57847. var indegreeArr = []; // Used to storage the node with indegree is equal to 0.
  57848. var zeroIndegrees = [];
  57849. var nextTargetNode = [];
  57850. var x = 0; // let kx = 0;
  57851. for (var i = 0; i < edges.length; i++) {
  57852. remainEdges[i] = 1;
  57853. }
  57854. for (var i = 0; i < nodes.length; i++) {
  57855. indegreeArr[i] = nodes[i].inEdges.length;
  57856. if (indegreeArr[i] === 0) {
  57857. zeroIndegrees.push(nodes[i]);
  57858. }
  57859. }
  57860. var maxNodeDepth = -1; // Traversing nodes using topological sorting to calculate the
  57861. // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
  57862. // position of the nodes.
  57863. while (zeroIndegrees.length) {
  57864. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  57865. var node = zeroIndegrees[idx];
  57866. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  57867. var isItemDepth = item.depth != null && item.depth >= 0;
  57868. if (isItemDepth && item.depth > maxNodeDepth) {
  57869. maxNodeDepth = item.depth;
  57870. }
  57871. node.setLayout({
  57872. depth: isItemDepth ? item.depth : x
  57873. }, true);
  57874. orient === 'vertical' ? node.setLayout({
  57875. dy: nodeWidth
  57876. }, true) : node.setLayout({
  57877. dx: nodeWidth
  57878. }, true);
  57879. for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
  57880. var edge = node.outEdges[edgeIdx];
  57881. var indexEdge = edges.indexOf(edge);
  57882. remainEdges[indexEdge] = 0;
  57883. var targetNode = edge.node2;
  57884. var nodeIndex = nodes.indexOf(targetNode);
  57885. if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
  57886. nextTargetNode.push(targetNode);
  57887. }
  57888. }
  57889. }
  57890. ++x;
  57891. zeroIndegrees = nextTargetNode;
  57892. nextTargetNode = [];
  57893. }
  57894. for (var i = 0; i < remainEdges.length; i++) {
  57895. if (remainEdges[i] === 1) {
  57896. throw new Error('Sankey is a DAG, the original data has cycle!');
  57897. }
  57898. }
  57899. var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
  57900. if (nodeAlign && nodeAlign !== 'left') {
  57901. adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
  57902. }
  57903. var kx = orient === 'vertical' ? (height - nodeWidth) / maxDepth : (width - nodeWidth) / maxDepth;
  57904. scaleNodeBreadths(nodes, kx, orient);
  57905. }
  57906. function isNodeDepth(node) {
  57907. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  57908. return item.depth != null && item.depth >= 0;
  57909. }
  57910. function adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth) {
  57911. if (nodeAlign === 'right') {
  57912. var nextSourceNode = [];
  57913. var remainNodes = nodes;
  57914. var nodeHeight = 0;
  57915. while (remainNodes.length) {
  57916. for (var i = 0; i < remainNodes.length; i++) {
  57917. var node = remainNodes[i];
  57918. node.setLayout({
  57919. skNodeHeight: nodeHeight
  57920. }, true);
  57921. for (var j = 0; j < node.inEdges.length; j++) {
  57922. var edge = node.inEdges[j];
  57923. if (nextSourceNode.indexOf(edge.node1) < 0) {
  57924. nextSourceNode.push(edge.node1);
  57925. }
  57926. }
  57927. }
  57928. remainNodes = nextSourceNode;
  57929. nextSourceNode = [];
  57930. ++nodeHeight;
  57931. }
  57932. each(nodes, function (node) {
  57933. if (!isNodeDepth(node)) {
  57934. node.setLayout({
  57935. depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)
  57936. }, true);
  57937. }
  57938. });
  57939. } else if (nodeAlign === 'justify') {
  57940. moveSinksRight(nodes, maxDepth);
  57941. }
  57942. }
  57943. /**
  57944. * All the node without outEgdes are assigned maximum x-position and
  57945. * be aligned in the last column.
  57946. *
  57947. * @param nodes. node of sankey view.
  57948. * @param maxDepth. use to assign to node without outEdges as x-position.
  57949. */
  57950. function moveSinksRight(nodes, maxDepth) {
  57951. each(nodes, function (node) {
  57952. if (!isNodeDepth(node) && !node.outEdges.length) {
  57953. node.setLayout({
  57954. depth: maxDepth
  57955. }, true);
  57956. }
  57957. });
  57958. }
  57959. /**
  57960. * Scale node x-position to the width
  57961. *
  57962. * @param nodes node of sankey view
  57963. * @param kx multiple used to scale nodes
  57964. */
  57965. function scaleNodeBreadths(nodes, kx, orient) {
  57966. each(nodes, function (node) {
  57967. var nodeDepth = node.getLayout().depth * kx;
  57968. orient === 'vertical' ? node.setLayout({
  57969. y: nodeDepth
  57970. }, true) : node.setLayout({
  57971. x: nodeDepth
  57972. }, true);
  57973. });
  57974. }
  57975. /**
  57976. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  57977. *
  57978. * @param nodes node of sankey view
  57979. * @param edges edge of sankey view
  57980. * @param height the whole height of the area to draw the view
  57981. * @param nodeGap the vertical distance between two nodes
  57982. * in the same column.
  57983. * @param iterations the number of iterations for the algorithm
  57984. */
  57985. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  57986. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  57987. initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient);
  57988. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  57989. for (var alpha = 1; iterations > 0; iterations--) {
  57990. // 0.99 is a experience parameter, ensure that each iterations of
  57991. // changes as small as possible.
  57992. alpha *= 0.99;
  57993. relaxRightToLeft(nodesByBreadth, alpha, orient);
  57994. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  57995. relaxLeftToRight(nodesByBreadth, alpha, orient);
  57996. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  57997. }
  57998. }
  57999. function prepareNodesByBreadth(nodes, orient) {
  58000. var nodesByBreadth = [];
  58001. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  58002. var groupResult = groupData(nodes, function (node) {
  58003. return node.getLayout()[keyAttr];
  58004. });
  58005. groupResult.keys.sort(function (a, b) {
  58006. return a - b;
  58007. });
  58008. each(groupResult.keys, function (key) {
  58009. nodesByBreadth.push(groupResult.buckets.get(key));
  58010. });
  58011. return nodesByBreadth;
  58012. }
  58013. /**
  58014. * Compute the original y-position for each node
  58015. */
  58016. function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
  58017. var minKy = Infinity;
  58018. each(nodesByBreadth, function (nodes) {
  58019. var n = nodes.length;
  58020. var sum = 0;
  58021. each(nodes, function (node) {
  58022. sum += node.getLayout().value;
  58023. });
  58024. var ky = orient === 'vertical' ? (width - (n - 1) * nodeGap) / sum : (height - (n - 1) * nodeGap) / sum;
  58025. if (ky < minKy) {
  58026. minKy = ky;
  58027. }
  58028. });
  58029. each(nodesByBreadth, function (nodes) {
  58030. each(nodes, function (node, i) {
  58031. var nodeDy = node.getLayout().value * minKy;
  58032. if (orient === 'vertical') {
  58033. node.setLayout({
  58034. x: i
  58035. }, true);
  58036. node.setLayout({
  58037. dx: nodeDy
  58038. }, true);
  58039. } else {
  58040. node.setLayout({
  58041. y: i
  58042. }, true);
  58043. node.setLayout({
  58044. dy: nodeDy
  58045. }, true);
  58046. }
  58047. });
  58048. });
  58049. each(edges, function (edge) {
  58050. var edgeDy = +edge.getValue() * minKy;
  58051. edge.setLayout({
  58052. dy: edgeDy
  58053. }, true);
  58054. });
  58055. }
  58056. /**
  58057. * Resolve the collision of initialized depth (y-position)
  58058. */
  58059. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  58060. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  58061. each(nodesByBreadth, function (nodes) {
  58062. nodes.sort(function (a, b) {
  58063. return a.getLayout()[keyAttr] - b.getLayout()[keyAttr];
  58064. });
  58065. var nodeX;
  58066. var node;
  58067. var dy;
  58068. var y0 = 0;
  58069. var n = nodes.length;
  58070. var nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy';
  58071. for (var i = 0; i < n; i++) {
  58072. node = nodes[i];
  58073. dy = y0 - node.getLayout()[keyAttr];
  58074. if (dy > 0) {
  58075. nodeX = node.getLayout()[keyAttr] + dy;
  58076. orient === 'vertical' ? node.setLayout({
  58077. x: nodeX
  58078. }, true) : node.setLayout({
  58079. y: nodeX
  58080. }, true);
  58081. }
  58082. y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap;
  58083. }
  58084. var viewWidth = orient === 'vertical' ? width : height; // If the bottommost node goes outside the bounds, push it back up
  58085. dy = y0 - nodeGap - viewWidth;
  58086. if (dy > 0) {
  58087. nodeX = node.getLayout()[keyAttr] - dy;
  58088. orient === 'vertical' ? node.setLayout({
  58089. x: nodeX
  58090. }, true) : node.setLayout({
  58091. y: nodeX
  58092. }, true);
  58093. y0 = nodeX;
  58094. for (var i = n - 2; i >= 0; --i) {
  58095. node = nodes[i];
  58096. dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0;
  58097. if (dy > 0) {
  58098. nodeX = node.getLayout()[keyAttr] - dy;
  58099. orient === 'vertical' ? node.setLayout({
  58100. x: nodeX
  58101. }, true) : node.setLayout({
  58102. y: nodeX
  58103. }, true);
  58104. }
  58105. y0 = node.getLayout()[keyAttr];
  58106. }
  58107. }
  58108. });
  58109. }
  58110. /**
  58111. * Change the y-position of the nodes, except most the right side nodes
  58112. * @param nodesByBreadth
  58113. * @param alpha parameter used to adjust the nodes y-position
  58114. */
  58115. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  58116. each(nodesByBreadth.slice().reverse(), function (nodes) {
  58117. each(nodes, function (node) {
  58118. if (node.outEdges.length) {
  58119. var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue);
  58120. if (isNaN(y)) {
  58121. var len = node.outEdges.length;
  58122. y = len ? sum(node.outEdges, centerTarget, orient) / len : 0;
  58123. }
  58124. if (orient === 'vertical') {
  58125. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  58126. node.setLayout({
  58127. x: nodeX
  58128. }, true);
  58129. } else {
  58130. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  58131. node.setLayout({
  58132. y: nodeY
  58133. }, true);
  58134. }
  58135. }
  58136. });
  58137. });
  58138. }
  58139. function weightedTarget(edge, orient) {
  58140. return center$1(edge.node2, orient) * edge.getValue();
  58141. }
  58142. function centerTarget(edge, orient) {
  58143. return center$1(edge.node2, orient);
  58144. }
  58145. function weightedSource(edge, orient) {
  58146. return center$1(edge.node1, orient) * edge.getValue();
  58147. }
  58148. function centerSource(edge, orient) {
  58149. return center$1(edge.node1, orient);
  58150. }
  58151. function center$1(node, orient) {
  58152. return orient === 'vertical' ? node.getLayout().x + node.getLayout().dx / 2 : node.getLayout().y + node.getLayout().dy / 2;
  58153. }
  58154. function getEdgeValue(edge) {
  58155. return edge.getValue();
  58156. }
  58157. function sum(array, cb, orient) {
  58158. var sum = 0;
  58159. var len = array.length;
  58160. var i = -1;
  58161. while (++i < len) {
  58162. var value = +cb(array[i], orient);
  58163. if (!isNaN(value)) {
  58164. sum += value;
  58165. }
  58166. }
  58167. return sum;
  58168. }
  58169. /**
  58170. * Change the y-position of the nodes, except most the left side nodes
  58171. */
  58172. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  58173. each(nodesByBreadth, function (nodes) {
  58174. each(nodes, function (node) {
  58175. if (node.inEdges.length) {
  58176. var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue);
  58177. if (isNaN(y)) {
  58178. var len = node.inEdges.length;
  58179. y = len ? sum(node.inEdges, centerSource, orient) / len : 0;
  58180. }
  58181. if (orient === 'vertical') {
  58182. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  58183. node.setLayout({
  58184. x: nodeX
  58185. }, true);
  58186. } else {
  58187. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  58188. node.setLayout({
  58189. y: nodeY
  58190. }, true);
  58191. }
  58192. }
  58193. });
  58194. });
  58195. }
  58196. /**
  58197. * Compute the depth(y-position) of each edge
  58198. */
  58199. function computeEdgeDepths(nodes, orient) {
  58200. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  58201. each(nodes, function (node) {
  58202. node.outEdges.sort(function (a, b) {
  58203. return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr];
  58204. });
  58205. node.inEdges.sort(function (a, b) {
  58206. return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr];
  58207. });
  58208. });
  58209. each(nodes, function (node) {
  58210. var sy = 0;
  58211. var ty = 0;
  58212. each(node.outEdges, function (edge) {
  58213. edge.setLayout({
  58214. sy: sy
  58215. }, true);
  58216. sy += edge.getLayout().dy;
  58217. });
  58218. each(node.inEdges, function (edge) {
  58219. edge.setLayout({
  58220. ty: ty
  58221. }, true);
  58222. ty += edge.getLayout().dy;
  58223. });
  58224. });
  58225. }
  58226. function sankeyVisual(ecModel) {
  58227. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  58228. var graph = seriesModel.getGraph();
  58229. var nodes = graph.nodes;
  58230. var edges = graph.edges;
  58231. if (nodes.length) {
  58232. var minValue_1 = Infinity;
  58233. var maxValue_1 = -Infinity;
  58234. each(nodes, function (node) {
  58235. var nodeValue = node.getLayout().value;
  58236. if (nodeValue < minValue_1) {
  58237. minValue_1 = nodeValue;
  58238. }
  58239. if (nodeValue > maxValue_1) {
  58240. maxValue_1 = nodeValue;
  58241. }
  58242. });
  58243. each(nodes, function (node) {
  58244. var mapping = new VisualMapping({
  58245. type: 'color',
  58246. mappingMethod: 'linear',
  58247. dataExtent: [minValue_1, maxValue_1],
  58248. visual: seriesModel.get('color')
  58249. });
  58250. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  58251. var customColor = node.getModel().get(['itemStyle', 'color']);
  58252. if (customColor != null) {
  58253. node.setVisual('color', customColor);
  58254. node.setVisual('style', {
  58255. fill: customColor
  58256. });
  58257. } else {
  58258. node.setVisual('color', mapValueToColor);
  58259. node.setVisual('style', {
  58260. fill: mapValueToColor
  58261. });
  58262. }
  58263. });
  58264. }
  58265. if (edges.length) {
  58266. each(edges, function (edge) {
  58267. var edgeStyle = edge.getModel().get('lineStyle');
  58268. edge.setVisual('style', edgeStyle);
  58269. });
  58270. }
  58271. });
  58272. }
  58273. function install$i(registers) {
  58274. registers.registerChartView(SankeyView);
  58275. registers.registerSeriesModel(SankeySeriesModel);
  58276. registers.registerLayout(sankeyLayout);
  58277. registers.registerVisual(sankeyVisual);
  58278. registers.registerAction({
  58279. type: 'dragNode',
  58280. event: 'dragnode',
  58281. // here can only use 'update' now, other value is not support in echarts.
  58282. update: 'update'
  58283. }, function (payload, ecModel) {
  58284. ecModel.eachComponent({
  58285. mainType: 'series',
  58286. subType: 'sankey',
  58287. query: payload
  58288. }, function (seriesModel) {
  58289. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  58290. });
  58291. });
  58292. }
  58293. var WhiskerBoxCommonMixin =
  58294. /** @class */
  58295. function () {
  58296. function WhiskerBoxCommonMixin() {}
  58297. /**
  58298. * @override
  58299. */
  58300. WhiskerBoxCommonMixin.prototype.getInitialData = function (option, ecModel) {
  58301. // When both types of xAxis and yAxis are 'value', layout is
  58302. // needed to be specified by user. Otherwise, layout can be
  58303. // judged by which axis is category.
  58304. var ordinalMeta;
  58305. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  58306. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  58307. var xAxisType = xAxisModel.get('type');
  58308. var yAxisType = yAxisModel.get('type');
  58309. var addOrdinal; // FIXME
  58310. // Consider time axis.
  58311. if (xAxisType === 'category') {
  58312. option.layout = 'horizontal';
  58313. ordinalMeta = xAxisModel.getOrdinalMeta();
  58314. addOrdinal = true;
  58315. } else if (yAxisType === 'category') {
  58316. option.layout = 'vertical';
  58317. ordinalMeta = yAxisModel.getOrdinalMeta();
  58318. addOrdinal = true;
  58319. } else {
  58320. option.layout = option.layout || 'horizontal';
  58321. }
  58322. var coordDims = ['x', 'y'];
  58323. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  58324. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  58325. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  58326. var axisModels = [xAxisModel, yAxisModel];
  58327. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  58328. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  58329. var data = option.data; // Clone a new data for next setOption({}) usage.
  58330. // Avoid modifying current data will affect further update.
  58331. if (data && addOrdinal) {
  58332. var newOptionData_1 = [];
  58333. each(data, function (item, index) {
  58334. var newItem;
  58335. if (isArray(item)) {
  58336. newItem = item.slice(); // Modify current using data.
  58337. item.unshift(index);
  58338. } else if (isArray(item.value)) {
  58339. newItem = extend({}, item);
  58340. newItem.value = newItem.value.slice(); // Modify current using data.
  58341. item.value.unshift(index);
  58342. } else {
  58343. newItem = item;
  58344. }
  58345. newOptionData_1.push(newItem);
  58346. });
  58347. option.data = newOptionData_1;
  58348. }
  58349. var defaultValueDimensions = this.defaultValueDimensions;
  58350. var coordDimensions = [{
  58351. name: baseAxisDim,
  58352. type: getDimensionTypeByAxis(baseAxisType),
  58353. ordinalMeta: ordinalMeta,
  58354. otherDims: {
  58355. tooltip: false,
  58356. itemName: 0
  58357. },
  58358. dimsDef: ['base']
  58359. }, {
  58360. name: otherAxisDim,
  58361. type: getDimensionTypeByAxis(otherAxisType),
  58362. dimsDef: defaultValueDimensions.slice()
  58363. }];
  58364. return createSeriesDataSimply(this, {
  58365. coordDimensions: coordDimensions,
  58366. dimensionsCount: defaultValueDimensions.length + 1,
  58367. encodeDefaulter: curry(makeSeriesEncodeForAxisCoordSys, coordDimensions, this)
  58368. });
  58369. };
  58370. /**
  58371. * If horizontal, base axis is x, otherwise y.
  58372. * @override
  58373. */
  58374. WhiskerBoxCommonMixin.prototype.getBaseAxis = function () {
  58375. var dim = this._baseAxisDim;
  58376. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  58377. };
  58378. return WhiskerBoxCommonMixin;
  58379. }();
  58380. var BoxplotSeriesModel =
  58381. /** @class */
  58382. function (_super) {
  58383. __extends(BoxplotSeriesModel, _super);
  58384. function BoxplotSeriesModel() {
  58385. var _this = _super !== null && _super.apply(this, arguments) || this;
  58386. _this.type = BoxplotSeriesModel.type; // TODO
  58387. // box width represents group size, so dimension should have 'size'.
  58388. /**
  58389. * @see <https://en.wikipedia.org/wiki/Box_plot>
  58390. * The meanings of 'min' and 'max' depend on user,
  58391. * and echarts do not need to know it.
  58392. * @readOnly
  58393. */
  58394. _this.defaultValueDimensions = [{
  58395. name: 'min',
  58396. defaultTooltip: true
  58397. }, {
  58398. name: 'Q1',
  58399. defaultTooltip: true
  58400. }, {
  58401. name: 'median',
  58402. defaultTooltip: true
  58403. }, {
  58404. name: 'Q3',
  58405. defaultTooltip: true
  58406. }, {
  58407. name: 'max',
  58408. defaultTooltip: true
  58409. }];
  58410. _this.visualDrawType = 'stroke';
  58411. return _this;
  58412. }
  58413. BoxplotSeriesModel.type = 'series.boxplot';
  58414. BoxplotSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  58415. BoxplotSeriesModel.defaultOption = {
  58416. // zlevel: 0,
  58417. z: 2,
  58418. coordinateSystem: 'cartesian2d',
  58419. legendHoverLink: true,
  58420. layout: null,
  58421. boxWidth: [7, 50],
  58422. itemStyle: {
  58423. color: '#fff',
  58424. borderWidth: 1
  58425. },
  58426. emphasis: {
  58427. scale: true,
  58428. itemStyle: {
  58429. borderWidth: 2,
  58430. shadowBlur: 5,
  58431. shadowOffsetX: 1,
  58432. shadowOffsetY: 1,
  58433. shadowColor: 'rgba(0,0,0,0.2)'
  58434. }
  58435. },
  58436. animationDuration: 800
  58437. };
  58438. return BoxplotSeriesModel;
  58439. }(SeriesModel);
  58440. mixin(BoxplotSeriesModel, WhiskerBoxCommonMixin, true);
  58441. var BoxplotView =
  58442. /** @class */
  58443. function (_super) {
  58444. __extends(BoxplotView, _super);
  58445. function BoxplotView() {
  58446. var _this = _super !== null && _super.apply(this, arguments) || this;
  58447. _this.type = BoxplotView.type;
  58448. return _this;
  58449. }
  58450. BoxplotView.prototype.render = function (seriesModel, ecModel, api) {
  58451. var data = seriesModel.getData();
  58452. var group = this.group;
  58453. var oldData = this._data; // There is no old data only when first rendering or switching from
  58454. // stream mode to normal mode, where previous elements should be removed.
  58455. if (!this._data) {
  58456. group.removeAll();
  58457. }
  58458. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  58459. data.diff(oldData).add(function (newIdx) {
  58460. if (data.hasValue(newIdx)) {
  58461. var itemLayout = data.getItemLayout(newIdx);
  58462. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  58463. data.setItemGraphicEl(newIdx, symbolEl);
  58464. group.add(symbolEl);
  58465. }
  58466. }).update(function (newIdx, oldIdx) {
  58467. var symbolEl = oldData.getItemGraphicEl(oldIdx); // Empty data
  58468. if (!data.hasValue(newIdx)) {
  58469. group.remove(symbolEl);
  58470. return;
  58471. }
  58472. var itemLayout = data.getItemLayout(newIdx);
  58473. if (!symbolEl) {
  58474. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  58475. } else {
  58476. saveOldStyle(symbolEl);
  58477. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  58478. }
  58479. group.add(symbolEl);
  58480. data.setItemGraphicEl(newIdx, symbolEl);
  58481. }).remove(function (oldIdx) {
  58482. var el = oldData.getItemGraphicEl(oldIdx);
  58483. el && group.remove(el);
  58484. }).execute();
  58485. this._data = data;
  58486. };
  58487. BoxplotView.prototype.remove = function (ecModel) {
  58488. var group = this.group;
  58489. var data = this._data;
  58490. this._data = null;
  58491. data && data.eachItemGraphicEl(function (el) {
  58492. el && group.remove(el);
  58493. });
  58494. };
  58495. BoxplotView.type = 'boxplot';
  58496. return BoxplotView;
  58497. }(ChartView);
  58498. var BoxPathShape =
  58499. /** @class */
  58500. function () {
  58501. function BoxPathShape() {}
  58502. return BoxPathShape;
  58503. }();
  58504. var BoxPath =
  58505. /** @class */
  58506. function (_super) {
  58507. __extends(BoxPath, _super);
  58508. function BoxPath(opts) {
  58509. var _this = _super.call(this, opts) || this;
  58510. _this.type = 'boxplotBoxPath';
  58511. return _this;
  58512. }
  58513. BoxPath.prototype.getDefaultShape = function () {
  58514. return new BoxPathShape();
  58515. };
  58516. BoxPath.prototype.buildPath = function (ctx, shape) {
  58517. var ends = shape.points;
  58518. var i = 0;
  58519. ctx.moveTo(ends[i][0], ends[i][1]);
  58520. i++;
  58521. for (; i < 4; i++) {
  58522. ctx.lineTo(ends[i][0], ends[i][1]);
  58523. }
  58524. ctx.closePath();
  58525. for (; i < ends.length; i++) {
  58526. ctx.moveTo(ends[i][0], ends[i][1]);
  58527. i++;
  58528. ctx.lineTo(ends[i][0], ends[i][1]);
  58529. }
  58530. };
  58531. return BoxPath;
  58532. }(Path);
  58533. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  58534. var ends = itemLayout.ends;
  58535. var el = new BoxPath({
  58536. shape: {
  58537. points: isInit ? transInit(ends, constDim, itemLayout) : ends
  58538. }
  58539. });
  58540. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  58541. return el;
  58542. }
  58543. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  58544. var seriesModel = data.hostModel;
  58545. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  58546. updateMethod(el, {
  58547. shape: {
  58548. points: itemLayout.ends
  58549. }
  58550. }, seriesModel, dataIndex);
  58551. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  58552. el.style.strokeNoScale = true;
  58553. el.z2 = 100;
  58554. var itemModel = data.getItemModel(dataIndex);
  58555. var emphasisModel = itemModel.getModel('emphasis');
  58556. setStatesStylesFromModel(el, itemModel);
  58557. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  58558. }
  58559. function transInit(points, dim, itemLayout) {
  58560. return map(points, function (point) {
  58561. point = point.slice();
  58562. point[dim] = itemLayout.initBaseline;
  58563. return point;
  58564. });
  58565. }
  58566. var each$6 = each;
  58567. function boxplotLayout(ecModel) {
  58568. var groupResult = groupSeriesByAxis(ecModel);
  58569. each$6(groupResult, function (groupItem) {
  58570. var seriesModels = groupItem.seriesModels;
  58571. if (!seriesModels.length) {
  58572. return;
  58573. }
  58574. calculateBase(groupItem);
  58575. each$6(seriesModels, function (seriesModel, idx) {
  58576. layoutSingleSeries(seriesModel, groupItem.boxOffsetList[idx], groupItem.boxWidthList[idx]);
  58577. });
  58578. });
  58579. }
  58580. /**
  58581. * Group series by axis.
  58582. */
  58583. function groupSeriesByAxis(ecModel) {
  58584. var result = [];
  58585. var axisList = [];
  58586. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  58587. var baseAxis = seriesModel.getBaseAxis();
  58588. var idx = indexOf(axisList, baseAxis);
  58589. if (idx < 0) {
  58590. idx = axisList.length;
  58591. axisList[idx] = baseAxis;
  58592. result[idx] = {
  58593. axis: baseAxis,
  58594. seriesModels: []
  58595. };
  58596. }
  58597. result[idx].seriesModels.push(seriesModel);
  58598. });
  58599. return result;
  58600. }
  58601. /**
  58602. * Calculate offset and box width for each series.
  58603. */
  58604. function calculateBase(groupItem) {
  58605. var baseAxis = groupItem.axis;
  58606. var seriesModels = groupItem.seriesModels;
  58607. var seriesCount = seriesModels.length;
  58608. var boxWidthList = groupItem.boxWidthList = [];
  58609. var boxOffsetList = groupItem.boxOffsetList = [];
  58610. var boundList = [];
  58611. var bandWidth;
  58612. if (baseAxis.type === 'category') {
  58613. bandWidth = baseAxis.getBandWidth();
  58614. } else {
  58615. var maxDataCount_1 = 0;
  58616. each$6(seriesModels, function (seriesModel) {
  58617. maxDataCount_1 = Math.max(maxDataCount_1, seriesModel.getData().count());
  58618. });
  58619. var extent = baseAxis.getExtent();
  58620. bandWidth = Math.abs(extent[1] - extent[0]) / maxDataCount_1;
  58621. }
  58622. each$6(seriesModels, function (seriesModel) {
  58623. var boxWidthBound = seriesModel.get('boxWidth');
  58624. if (!isArray(boxWidthBound)) {
  58625. boxWidthBound = [boxWidthBound, boxWidthBound];
  58626. }
  58627. boundList.push([parsePercent$1(boxWidthBound[0], bandWidth) || 0, parsePercent$1(boxWidthBound[1], bandWidth) || 0]);
  58628. });
  58629. var availableWidth = bandWidth * 0.8 - 2;
  58630. var boxGap = availableWidth / seriesCount * 0.3;
  58631. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  58632. var base = boxWidth / 2 - availableWidth / 2;
  58633. each$6(seriesModels, function (seriesModel, idx) {
  58634. boxOffsetList.push(base);
  58635. base += boxGap + boxWidth;
  58636. boxWidthList.push(Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1]));
  58637. });
  58638. }
  58639. /**
  58640. * Calculate points location for each series.
  58641. */
  58642. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  58643. var coordSys = seriesModel.coordinateSystem;
  58644. var data = seriesModel.getData();
  58645. var halfWidth = boxWidth / 2;
  58646. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  58647. var vDimIdx = 1 - cDimIdx;
  58648. var coordDims = ['x', 'y'];
  58649. var cDim = data.mapDimension(coordDims[cDimIdx]);
  58650. var vDims = data.mapDimensionsAll(coordDims[vDimIdx]);
  58651. if (cDim == null || vDims.length < 5) {
  58652. return;
  58653. }
  58654. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  58655. var axisDimVal = data.get(cDim, dataIndex);
  58656. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  58657. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  58658. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  58659. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  58660. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  58661. var ends = [];
  58662. addBodyEnd(ends, end2, false);
  58663. addBodyEnd(ends, end4, true);
  58664. ends.push(end1, end2, end5, end4);
  58665. layEndLine(ends, end1);
  58666. layEndLine(ends, end5);
  58667. layEndLine(ends, median);
  58668. data.setItemLayout(dataIndex, {
  58669. initBaseline: median[vDimIdx],
  58670. ends: ends
  58671. });
  58672. }
  58673. function getPoint(axisDimVal, dim, dataIndex) {
  58674. var val = data.get(dim, dataIndex);
  58675. var p = [];
  58676. p[cDimIdx] = axisDimVal;
  58677. p[vDimIdx] = val;
  58678. var point;
  58679. if (isNaN(axisDimVal) || isNaN(val)) {
  58680. point = [NaN, NaN];
  58681. } else {
  58682. point = coordSys.dataToPoint(p);
  58683. point[cDimIdx] += offset;
  58684. }
  58685. return point;
  58686. }
  58687. function addBodyEnd(ends, point, start) {
  58688. var point1 = point.slice();
  58689. var point2 = point.slice();
  58690. point1[cDimIdx] += halfWidth;
  58691. point2[cDimIdx] -= halfWidth;
  58692. start ? ends.push(point1, point2) : ends.push(point2, point1);
  58693. }
  58694. function layEndLine(ends, endCenter) {
  58695. var from = endCenter.slice();
  58696. var to = endCenter.slice();
  58697. from[cDimIdx] -= halfWidth;
  58698. to[cDimIdx] += halfWidth;
  58699. ends.push(from, to);
  58700. }
  58701. }
  58702. /**
  58703. * See:
  58704. * <https://en.wikipedia.org/wiki/Box_plot#cite_note-frigge_hoaglin_iglewicz-2>
  58705. * <http://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/boxplot.stats.html>
  58706. *
  58707. * Helper method for preparing data.
  58708. *
  58709. * @param rawData like
  58710. * [
  58711. * [12,232,443], (raw data set for the first box)
  58712. * [3843,5545,1232], (raw data set for the second box)
  58713. * ...
  58714. * ]
  58715. * @param opt.boundIQR=1.5 Data less than min bound is outlier.
  58716. * default 1.5, means Q1 - 1.5 * (Q3 - Q1).
  58717. * If 'none'/0 passed, min bound will not be used.
  58718. */
  58719. function prepareBoxplotData(rawData, opt) {
  58720. opt = opt || {};
  58721. var boxData = [];
  58722. var outliers = [];
  58723. var boundIQR = opt.boundIQR;
  58724. var useExtreme = boundIQR === 'none' || boundIQR === 0;
  58725. for (var i = 0; i < rawData.length; i++) {
  58726. var ascList = asc(rawData[i].slice());
  58727. var Q1 = quantile(ascList, 0.25);
  58728. var Q2 = quantile(ascList, 0.5);
  58729. var Q3 = quantile(ascList, 0.75);
  58730. var min = ascList[0];
  58731. var max = ascList[ascList.length - 1];
  58732. var bound = (boundIQR == null ? 1.5 : boundIQR) * (Q3 - Q1);
  58733. var low = useExtreme ? min : Math.max(min, Q1 - bound);
  58734. var high = useExtreme ? max : Math.min(max, Q3 + bound);
  58735. var itemNameFormatter = opt.itemNameFormatter;
  58736. var itemName = isFunction(itemNameFormatter) ? itemNameFormatter({
  58737. value: i
  58738. }) : isString(itemNameFormatter) ? itemNameFormatter.replace('{value}', i + '') : i + '';
  58739. boxData.push([itemName, low, Q1, Q2, Q3, high]);
  58740. for (var j = 0; j < ascList.length; j++) {
  58741. var dataItem = ascList[j];
  58742. if (dataItem < low || dataItem > high) {
  58743. var outlier = [itemName, dataItem];
  58744. outliers.push(outlier);
  58745. }
  58746. }
  58747. }
  58748. return {
  58749. boxData: boxData,
  58750. outliers: outliers
  58751. };
  58752. }
  58753. var boxplotTransform = {
  58754. type: 'echarts:boxplot',
  58755. transform: function transform(params) {
  58756. var upstream = params.upstream;
  58757. if (upstream.sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS) {
  58758. var errMsg = '';
  58759. if ("development" !== 'production') {
  58760. errMsg = makePrintable('source data is not applicable for this boxplot transform. Expect number[][].');
  58761. }
  58762. throwError(errMsg);
  58763. }
  58764. var result = prepareBoxplotData(upstream.getRawData(), params.config);
  58765. return [{
  58766. dimensions: ['ItemName', 'Low', 'Q1', 'Q2', 'Q3', 'High'],
  58767. data: result.boxData
  58768. }, {
  58769. data: result.outliers
  58770. }];
  58771. }
  58772. };
  58773. function install$j(registers) {
  58774. registers.registerSeriesModel(BoxplotSeriesModel);
  58775. registers.registerChartView(BoxplotView);
  58776. registers.registerLayout(boxplotLayout);
  58777. registers.registerTransform(boxplotTransform);
  58778. }
  58779. var SKIP_PROPS = ['color', 'borderColor'];
  58780. var CandlestickView =
  58781. /** @class */
  58782. function (_super) {
  58783. __extends(CandlestickView, _super);
  58784. function CandlestickView() {
  58785. var _this = _super !== null && _super.apply(this, arguments) || this;
  58786. _this.type = CandlestickView.type;
  58787. return _this;
  58788. }
  58789. CandlestickView.prototype.render = function (seriesModel, ecModel, api) {
  58790. // If there is clipPath created in large mode. Remove it.
  58791. this.group.removeClipPath(); // Clear previously rendered progressive elements.
  58792. this._progressiveEls = null;
  58793. this._updateDrawMode(seriesModel);
  58794. this._isLargeDraw ? this._renderLarge(seriesModel) : this._renderNormal(seriesModel);
  58795. };
  58796. CandlestickView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  58797. this._clear();
  58798. this._updateDrawMode(seriesModel);
  58799. };
  58800. CandlestickView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  58801. this._progressiveEls = [];
  58802. this._isLargeDraw ? this._incrementalRenderLarge(params, seriesModel) : this._incrementalRenderNormal(params, seriesModel);
  58803. };
  58804. CandlestickView.prototype.eachRendered = function (cb) {
  58805. traverseElements(this._progressiveEls || this.group, cb);
  58806. };
  58807. CandlestickView.prototype._updateDrawMode = function (seriesModel) {
  58808. var isLargeDraw = seriesModel.pipelineContext.large;
  58809. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  58810. this._isLargeDraw = isLargeDraw;
  58811. this._clear();
  58812. }
  58813. };
  58814. CandlestickView.prototype._renderNormal = function (seriesModel) {
  58815. var data = seriesModel.getData();
  58816. var oldData = this._data;
  58817. var group = this.group;
  58818. var isSimpleBox = data.getLayout('isSimpleBox');
  58819. var needsClip = seriesModel.get('clip', true);
  58820. var coord = seriesModel.coordinateSystem;
  58821. var clipArea = coord.getArea && coord.getArea(); // There is no old data only when first rendering or switching from
  58822. // stream mode to normal mode, where previous elements should be removed.
  58823. if (!this._data) {
  58824. group.removeAll();
  58825. }
  58826. data.diff(oldData).add(function (newIdx) {
  58827. if (data.hasValue(newIdx)) {
  58828. var itemLayout = data.getItemLayout(newIdx);
  58829. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  58830. return;
  58831. }
  58832. var el = createNormalBox$1(itemLayout, newIdx, true);
  58833. initProps(el, {
  58834. shape: {
  58835. points: itemLayout.ends
  58836. }
  58837. }, seriesModel, newIdx);
  58838. setBoxCommon(el, data, newIdx, isSimpleBox);
  58839. group.add(el);
  58840. data.setItemGraphicEl(newIdx, el);
  58841. }
  58842. }).update(function (newIdx, oldIdx) {
  58843. var el = oldData.getItemGraphicEl(oldIdx); // Empty data
  58844. if (!data.hasValue(newIdx)) {
  58845. group.remove(el);
  58846. return;
  58847. }
  58848. var itemLayout = data.getItemLayout(newIdx);
  58849. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  58850. group.remove(el);
  58851. return;
  58852. }
  58853. if (!el) {
  58854. el = createNormalBox$1(itemLayout);
  58855. } else {
  58856. updateProps(el, {
  58857. shape: {
  58858. points: itemLayout.ends
  58859. }
  58860. }, seriesModel, newIdx);
  58861. saveOldStyle(el);
  58862. }
  58863. setBoxCommon(el, data, newIdx, isSimpleBox);
  58864. group.add(el);
  58865. data.setItemGraphicEl(newIdx, el);
  58866. }).remove(function (oldIdx) {
  58867. var el = oldData.getItemGraphicEl(oldIdx);
  58868. el && group.remove(el);
  58869. }).execute();
  58870. this._data = data;
  58871. };
  58872. CandlestickView.prototype._renderLarge = function (seriesModel) {
  58873. this._clear();
  58874. createLarge$1(seriesModel, this.group);
  58875. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  58876. if (clipPath) {
  58877. this.group.setClipPath(clipPath);
  58878. } else {
  58879. this.group.removeClipPath();
  58880. }
  58881. };
  58882. CandlestickView.prototype._incrementalRenderNormal = function (params, seriesModel) {
  58883. var data = seriesModel.getData();
  58884. var isSimpleBox = data.getLayout('isSimpleBox');
  58885. var dataIndex;
  58886. while ((dataIndex = params.next()) != null) {
  58887. var itemLayout = data.getItemLayout(dataIndex);
  58888. var el = createNormalBox$1(itemLayout);
  58889. setBoxCommon(el, data, dataIndex, isSimpleBox);
  58890. el.incremental = true;
  58891. this.group.add(el);
  58892. this._progressiveEls.push(el);
  58893. }
  58894. };
  58895. CandlestickView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  58896. createLarge$1(seriesModel, this.group, this._progressiveEls, true);
  58897. };
  58898. CandlestickView.prototype.remove = function (ecModel) {
  58899. this._clear();
  58900. };
  58901. CandlestickView.prototype._clear = function () {
  58902. this.group.removeAll();
  58903. this._data = null;
  58904. };
  58905. CandlestickView.type = 'candlestick';
  58906. return CandlestickView;
  58907. }(ChartView);
  58908. var NormalBoxPathShape =
  58909. /** @class */
  58910. function () {
  58911. function NormalBoxPathShape() {}
  58912. return NormalBoxPathShape;
  58913. }();
  58914. var NormalBoxPath =
  58915. /** @class */
  58916. function (_super) {
  58917. __extends(NormalBoxPath, _super);
  58918. function NormalBoxPath(opts) {
  58919. var _this = _super.call(this, opts) || this;
  58920. _this.type = 'normalCandlestickBox';
  58921. return _this;
  58922. }
  58923. NormalBoxPath.prototype.getDefaultShape = function () {
  58924. return new NormalBoxPathShape();
  58925. };
  58926. NormalBoxPath.prototype.buildPath = function (ctx, shape) {
  58927. var ends = shape.points;
  58928. if (this.__simpleBox) {
  58929. ctx.moveTo(ends[4][0], ends[4][1]);
  58930. ctx.lineTo(ends[6][0], ends[6][1]);
  58931. } else {
  58932. ctx.moveTo(ends[0][0], ends[0][1]);
  58933. ctx.lineTo(ends[1][0], ends[1][1]);
  58934. ctx.lineTo(ends[2][0], ends[2][1]);
  58935. ctx.lineTo(ends[3][0], ends[3][1]);
  58936. ctx.closePath();
  58937. ctx.moveTo(ends[4][0], ends[4][1]);
  58938. ctx.lineTo(ends[5][0], ends[5][1]);
  58939. ctx.moveTo(ends[6][0], ends[6][1]);
  58940. ctx.lineTo(ends[7][0], ends[7][1]);
  58941. }
  58942. };
  58943. return NormalBoxPath;
  58944. }(Path);
  58945. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  58946. var ends = itemLayout.ends;
  58947. return new NormalBoxPath({
  58948. shape: {
  58949. points: isInit ? transInit$1(ends, itemLayout) : ends
  58950. },
  58951. z2: 100
  58952. });
  58953. }
  58954. function isNormalBoxClipped(clipArea, itemLayout) {
  58955. var clipped = true;
  58956. for (var i = 0; i < itemLayout.ends.length; i++) {
  58957. // If any point are in the region.
  58958. if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) {
  58959. clipped = false;
  58960. break;
  58961. }
  58962. }
  58963. return clipped;
  58964. }
  58965. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  58966. var itemModel = data.getItemModel(dataIndex);
  58967. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  58968. el.style.strokeNoScale = true;
  58969. el.__simpleBox = isSimpleBox;
  58970. setStatesStylesFromModel(el, itemModel);
  58971. }
  58972. function transInit$1(points, itemLayout) {
  58973. return map(points, function (point) {
  58974. point = point.slice();
  58975. point[1] = itemLayout.initBaseline;
  58976. return point;
  58977. });
  58978. }
  58979. var LargeBoxPathShape =
  58980. /** @class */
  58981. function () {
  58982. function LargeBoxPathShape() {}
  58983. return LargeBoxPathShape;
  58984. }();
  58985. var LargeBoxPath =
  58986. /** @class */
  58987. function (_super) {
  58988. __extends(LargeBoxPath, _super);
  58989. function LargeBoxPath(opts) {
  58990. var _this = _super.call(this, opts) || this;
  58991. _this.type = 'largeCandlestickBox';
  58992. return _this;
  58993. }
  58994. LargeBoxPath.prototype.getDefaultShape = function () {
  58995. return new LargeBoxPathShape();
  58996. };
  58997. LargeBoxPath.prototype.buildPath = function (ctx, shape) {
  58998. // Drawing lines is more efficient than drawing
  58999. // a whole line or drawing rects.
  59000. var points = shape.points;
  59001. for (var i = 0; i < points.length;) {
  59002. if (this.__sign === points[i++]) {
  59003. var x = points[i++];
  59004. ctx.moveTo(x, points[i++]);
  59005. ctx.lineTo(x, points[i++]);
  59006. } else {
  59007. i += 3;
  59008. }
  59009. }
  59010. };
  59011. return LargeBoxPath;
  59012. }(Path);
  59013. function createLarge$1(seriesModel, group, progressiveEls, incremental) {
  59014. var data = seriesModel.getData();
  59015. var largePoints = data.getLayout('largePoints');
  59016. var elP = new LargeBoxPath({
  59017. shape: {
  59018. points: largePoints
  59019. },
  59020. __sign: 1,
  59021. ignoreCoarsePointer: true
  59022. });
  59023. group.add(elP);
  59024. var elN = new LargeBoxPath({
  59025. shape: {
  59026. points: largePoints
  59027. },
  59028. __sign: -1,
  59029. ignoreCoarsePointer: true
  59030. });
  59031. group.add(elN);
  59032. var elDoji = new LargeBoxPath({
  59033. shape: {
  59034. points: largePoints
  59035. },
  59036. __sign: 0,
  59037. ignoreCoarsePointer: true
  59038. });
  59039. group.add(elDoji);
  59040. setLargeStyle(1, elP, seriesModel);
  59041. setLargeStyle(-1, elN, seriesModel);
  59042. setLargeStyle(0, elDoji, seriesModel);
  59043. if (incremental) {
  59044. elP.incremental = true;
  59045. elN.incremental = true;
  59046. }
  59047. if (progressiveEls) {
  59048. progressiveEls.push(elP, elN);
  59049. }
  59050. }
  59051. function setLargeStyle(sign, el, seriesModel, data) {
  59052. // TODO put in visual?
  59053. var borderColor = seriesModel.get(['itemStyle', sign > 0 ? 'borderColor' : 'borderColor0']) // Use color for border color by default.
  59054. || seriesModel.get(['itemStyle', sign > 0 ? 'color' : 'color0']);
  59055. if (sign === 0) {
  59056. borderColor = seriesModel.get(['itemStyle', 'borderColorDoji']);
  59057. } // Color must be excluded.
  59058. // Because symbol provide setColor individually to set fill and stroke
  59059. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(SKIP_PROPS);
  59060. el.useStyle(itemStyle);
  59061. el.style.fill = null;
  59062. el.style.stroke = borderColor;
  59063. }
  59064. var CandlestickSeriesModel =
  59065. /** @class */
  59066. function (_super) {
  59067. __extends(CandlestickSeriesModel, _super);
  59068. function CandlestickSeriesModel() {
  59069. var _this = _super !== null && _super.apply(this, arguments) || this;
  59070. _this.type = CandlestickSeriesModel.type;
  59071. _this.defaultValueDimensions = [{
  59072. name: 'open',
  59073. defaultTooltip: true
  59074. }, {
  59075. name: 'close',
  59076. defaultTooltip: true
  59077. }, {
  59078. name: 'lowest',
  59079. defaultTooltip: true
  59080. }, {
  59081. name: 'highest',
  59082. defaultTooltip: true
  59083. }];
  59084. return _this;
  59085. }
  59086. /**
  59087. * Get dimension for shadow in dataZoom
  59088. * @return dimension name
  59089. */
  59090. CandlestickSeriesModel.prototype.getShadowDim = function () {
  59091. return 'open';
  59092. };
  59093. CandlestickSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  59094. var itemLayout = data.getItemLayout(dataIndex);
  59095. return itemLayout && selectors.rect(itemLayout.brushRect);
  59096. };
  59097. CandlestickSeriesModel.type = 'series.candlestick';
  59098. CandlestickSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  59099. CandlestickSeriesModel.defaultOption = {
  59100. // zlevel: 0,
  59101. z: 2,
  59102. coordinateSystem: 'cartesian2d',
  59103. legendHoverLink: true,
  59104. // xAxisIndex: 0,
  59105. // yAxisIndex: 0,
  59106. layout: null,
  59107. clip: true,
  59108. itemStyle: {
  59109. color: '#eb5454',
  59110. color0: '#47b262',
  59111. borderColor: '#eb5454',
  59112. borderColor0: '#47b262',
  59113. borderColorDoji: null,
  59114. // borderColor: '#d24040',
  59115. // borderColor0: '#398f4f',
  59116. borderWidth: 1
  59117. },
  59118. emphasis: {
  59119. scale: true,
  59120. itemStyle: {
  59121. borderWidth: 2
  59122. }
  59123. },
  59124. barMaxWidth: null,
  59125. barMinWidth: null,
  59126. barWidth: null,
  59127. large: true,
  59128. largeThreshold: 600,
  59129. progressive: 3e3,
  59130. progressiveThreshold: 1e4,
  59131. progressiveChunkMode: 'mod',
  59132. animationEasing: 'linear',
  59133. animationDuration: 300
  59134. };
  59135. return CandlestickSeriesModel;
  59136. }(SeriesModel);
  59137. mixin(CandlestickSeriesModel, WhiskerBoxCommonMixin, true);
  59138. function candlestickPreprocessor(option) {
  59139. if (!option || !isArray(option.series)) {
  59140. return;
  59141. } // Translate 'k' to 'candlestick'.
  59142. each(option.series, function (seriesItem) {
  59143. if (isObject(seriesItem) && seriesItem.type === 'k') {
  59144. seriesItem.type = 'candlestick';
  59145. }
  59146. });
  59147. }
  59148. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  59149. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  59150. var dojiBorderColorQuery = ['itemStyle', 'borderColorDoji'];
  59151. var positiveColorQuery = ['itemStyle', 'color'];
  59152. var negativeColorQuery = ['itemStyle', 'color0'];
  59153. var candlestickVisual = {
  59154. seriesType: 'candlestick',
  59155. plan: createRenderPlanner(),
  59156. // For legend.
  59157. performRawSeries: true,
  59158. reset: function (seriesModel, ecModel) {
  59159. function getColor(sign, model) {
  59160. return model.get(sign > 0 ? positiveColorQuery : negativeColorQuery);
  59161. }
  59162. function getBorderColor(sign, model) {
  59163. return model.get(sign === 0 ? dojiBorderColorQuery : sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery);
  59164. } // Only visible series has each data be visual encoded
  59165. if (ecModel.isSeriesFiltered(seriesModel)) {
  59166. return;
  59167. }
  59168. var isLargeRender = seriesModel.pipelineContext.large;
  59169. return !isLargeRender && {
  59170. progress: function (params, data) {
  59171. var dataIndex;
  59172. while ((dataIndex = params.next()) != null) {
  59173. var itemModel = data.getItemModel(dataIndex);
  59174. var sign = data.getItemLayout(dataIndex).sign;
  59175. var style = itemModel.getItemStyle();
  59176. style.fill = getColor(sign, itemModel);
  59177. style.stroke = getBorderColor(sign, itemModel) || style.fill;
  59178. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  59179. extend(existsStyle, style);
  59180. }
  59181. }
  59182. };
  59183. }
  59184. };
  59185. var candlestickLayout = {
  59186. seriesType: 'candlestick',
  59187. plan: createRenderPlanner(),
  59188. reset: function (seriesModel) {
  59189. var coordSys = seriesModel.coordinateSystem;
  59190. var data = seriesModel.getData();
  59191. var candleWidth = calculateCandleWidth(seriesModel, data);
  59192. var cDimIdx = 0;
  59193. var vDimIdx = 1;
  59194. var coordDims = ['x', 'y'];
  59195. var cDimI = data.getDimensionIndex(data.mapDimension(coordDims[cDimIdx]));
  59196. var vDimsI = map(data.mapDimensionsAll(coordDims[vDimIdx]), data.getDimensionIndex, data);
  59197. var openDimI = vDimsI[0];
  59198. var closeDimI = vDimsI[1];
  59199. var lowestDimI = vDimsI[2];
  59200. var highestDimI = vDimsI[3];
  59201. data.setLayout({
  59202. candleWidth: candleWidth,
  59203. // The value is experimented visually.
  59204. isSimpleBox: candleWidth <= 1.3
  59205. });
  59206. if (cDimI < 0 || vDimsI.length < 4) {
  59207. return;
  59208. }
  59209. return {
  59210. progress: seriesModel.pipelineContext.large ? largeProgress : normalProgress
  59211. };
  59212. function normalProgress(params, data) {
  59213. var dataIndex;
  59214. var store = data.getStore();
  59215. while ((dataIndex = params.next()) != null) {
  59216. var axisDimVal = store.get(cDimI, dataIndex);
  59217. var openVal = store.get(openDimI, dataIndex);
  59218. var closeVal = store.get(closeDimI, dataIndex);
  59219. var lowestVal = store.get(lowestDimI, dataIndex);
  59220. var highestVal = store.get(highestDimI, dataIndex);
  59221. var ocLow = Math.min(openVal, closeVal);
  59222. var ocHigh = Math.max(openVal, closeVal);
  59223. var ocLowPoint = getPoint(ocLow, axisDimVal);
  59224. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  59225. var lowestPoint = getPoint(lowestVal, axisDimVal);
  59226. var highestPoint = getPoint(highestVal, axisDimVal);
  59227. var ends = [];
  59228. addBodyEnd(ends, ocHighPoint, 0);
  59229. addBodyEnd(ends, ocLowPoint, 1);
  59230. ends.push(subPixelOptimizePoint(highestPoint), subPixelOptimizePoint(ocHighPoint), subPixelOptimizePoint(lowestPoint), subPixelOptimizePoint(ocLowPoint));
  59231. var itemModel = data.getItemModel(dataIndex);
  59232. var hasDojiColor = !!itemModel.get(['itemStyle', 'borderColorDoji']);
  59233. data.setItemLayout(dataIndex, {
  59234. sign: getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor),
  59235. initBaseline: openVal > closeVal ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx],
  59236. ends: ends,
  59237. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  59238. });
  59239. }
  59240. function getPoint(val, axisDimVal) {
  59241. var p = [];
  59242. p[cDimIdx] = axisDimVal;
  59243. p[vDimIdx] = val;
  59244. return isNaN(axisDimVal) || isNaN(val) ? [NaN, NaN] : coordSys.dataToPoint(p);
  59245. }
  59246. function addBodyEnd(ends, point, start) {
  59247. var point1 = point.slice();
  59248. var point2 = point.slice();
  59249. point1[cDimIdx] = subPixelOptimize$1(point1[cDimIdx] + candleWidth / 2, 1, false);
  59250. point2[cDimIdx] = subPixelOptimize$1(point2[cDimIdx] - candleWidth / 2, 1, true);
  59251. start ? ends.push(point1, point2) : ends.push(point2, point1);
  59252. }
  59253. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  59254. var pmin = getPoint(lowestVal, axisDimVal);
  59255. var pmax = getPoint(highestVal, axisDimVal);
  59256. pmin[cDimIdx] -= candleWidth / 2;
  59257. pmax[cDimIdx] -= candleWidth / 2;
  59258. return {
  59259. x: pmin[0],
  59260. y: pmin[1],
  59261. width: candleWidth ,
  59262. height: pmax[1] - pmin[1]
  59263. };
  59264. }
  59265. function subPixelOptimizePoint(point) {
  59266. point[cDimIdx] = subPixelOptimize$1(point[cDimIdx], 1);
  59267. return point;
  59268. }
  59269. }
  59270. function largeProgress(params, data) {
  59271. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  59272. var points = createFloat32Array(params.count * 4);
  59273. var offset = 0;
  59274. var point;
  59275. var tmpIn = [];
  59276. var tmpOut = [];
  59277. var dataIndex;
  59278. var store = data.getStore();
  59279. var hasDojiColor = !!seriesModel.get(['itemStyle', 'borderColorDoji']);
  59280. while ((dataIndex = params.next()) != null) {
  59281. var axisDimVal = store.get(cDimI, dataIndex);
  59282. var openVal = store.get(openDimI, dataIndex);
  59283. var closeVal = store.get(closeDimI, dataIndex);
  59284. var lowestVal = store.get(lowestDimI, dataIndex);
  59285. var highestVal = store.get(highestDimI, dataIndex);
  59286. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  59287. points[offset++] = NaN;
  59288. offset += 3;
  59289. continue;
  59290. }
  59291. points[offset++] = getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor);
  59292. tmpIn[cDimIdx] = axisDimVal;
  59293. tmpIn[vDimIdx] = lowestVal;
  59294. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  59295. points[offset++] = point ? point[0] : NaN;
  59296. points[offset++] = point ? point[1] : NaN;
  59297. tmpIn[vDimIdx] = highestVal;
  59298. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  59299. points[offset++] = point ? point[1] : NaN;
  59300. }
  59301. data.setLayout('largePoints', points);
  59302. }
  59303. }
  59304. };
  59305. /**
  59306. * Get the sign of a single data.
  59307. *
  59308. * @returns 0 for doji with hasDojiColor: true,
  59309. * 1 for positive,
  59310. * -1 for negative.
  59311. */
  59312. function getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor) {
  59313. var sign;
  59314. if (openVal > closeVal) {
  59315. sign = -1;
  59316. } else if (openVal < closeVal) {
  59317. sign = 1;
  59318. } else {
  59319. sign = hasDojiColor // When doji color is set, use it instead of color/color0.
  59320. ? 0 : dataIndex > 0 // If close === open, compare with close of last record
  59321. ? store.get(closeDimI, dataIndex - 1) <= closeVal ? 1 : -1 : // No record of previous, set to be positive
  59322. 1;
  59323. }
  59324. return sign;
  59325. }
  59326. function calculateCandleWidth(seriesModel, data) {
  59327. var baseAxis = seriesModel.getBaseAxis();
  59328. var extent;
  59329. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : (extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / data.count());
  59330. var barMaxWidth = parsePercent$1(retrieve2(seriesModel.get('barMaxWidth'), bandWidth), bandWidth);
  59331. var barMinWidth = parsePercent$1(retrieve2(seriesModel.get('barMinWidth'), 1), bandWidth);
  59332. var barWidth = seriesModel.get('barWidth');
  59333. return barWidth != null ? parsePercent$1(barWidth, bandWidth) // Put max outer to ensure bar visible in spite of overlap.
  59334. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  59335. }
  59336. function install$k(registers) {
  59337. registers.registerChartView(CandlestickView);
  59338. registers.registerSeriesModel(CandlestickSeriesModel);
  59339. registers.registerPreprocessor(candlestickPreprocessor);
  59340. registers.registerVisual(candlestickVisual);
  59341. registers.registerLayout(candlestickLayout);
  59342. }
  59343. function updateRipplePath(rippleGroup, effectCfg) {
  59344. var color = effectCfg.rippleEffectColor || effectCfg.color;
  59345. rippleGroup.eachChild(function (ripplePath) {
  59346. ripplePath.attr({
  59347. z: effectCfg.z,
  59348. zlevel: effectCfg.zlevel,
  59349. style: {
  59350. stroke: effectCfg.brushType === 'stroke' ? color : null,
  59351. fill: effectCfg.brushType === 'fill' ? color : null
  59352. }
  59353. });
  59354. });
  59355. }
  59356. var EffectSymbol =
  59357. /** @class */
  59358. function (_super) {
  59359. __extends(EffectSymbol, _super);
  59360. function EffectSymbol(data, idx) {
  59361. var _this = _super.call(this) || this;
  59362. var symbol = new Symbol(data, idx);
  59363. var rippleGroup = new Group();
  59364. _this.add(symbol);
  59365. _this.add(rippleGroup);
  59366. _this.updateData(data, idx);
  59367. return _this;
  59368. }
  59369. EffectSymbol.prototype.stopEffectAnimation = function () {
  59370. this.childAt(1).removeAll();
  59371. };
  59372. EffectSymbol.prototype.startEffectAnimation = function (effectCfg) {
  59373. var symbolType = effectCfg.symbolType;
  59374. var color = effectCfg.color;
  59375. var rippleNumber = effectCfg.rippleNumber;
  59376. var rippleGroup = this.childAt(1);
  59377. for (var i = 0; i < rippleNumber; i++) {
  59378. // If width/height are set too small (e.g., set to 1) on ios10
  59379. // and macOS Sierra, a circle stroke become a rect, no matter what
  59380. // the scale is set. So we set width/height as 2. See #4136.
  59381. var ripplePath = createSymbol(symbolType, -1, -1, 2, 2, color);
  59382. ripplePath.attr({
  59383. style: {
  59384. strokeNoScale: true
  59385. },
  59386. z2: 99,
  59387. silent: true,
  59388. scaleX: 0.5,
  59389. scaleY: 0.5
  59390. });
  59391. var delay = -i / rippleNumber * effectCfg.period + effectCfg.effectOffset;
  59392. ripplePath.animate('', true).when(effectCfg.period, {
  59393. scaleX: effectCfg.rippleScale / 2,
  59394. scaleY: effectCfg.rippleScale / 2
  59395. }).delay(delay).start();
  59396. ripplePath.animateStyle(true).when(effectCfg.period, {
  59397. opacity: 0
  59398. }).delay(delay).start();
  59399. rippleGroup.add(ripplePath);
  59400. }
  59401. updateRipplePath(rippleGroup, effectCfg);
  59402. };
  59403. /**
  59404. * Update effect symbol
  59405. */
  59406. EffectSymbol.prototype.updateEffectAnimation = function (effectCfg) {
  59407. var oldEffectCfg = this._effectCfg;
  59408. var rippleGroup = this.childAt(1); // Must reinitialize effect if following configuration changed
  59409. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale', 'rippleNumber'];
  59410. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  59411. var propName = DIFFICULT_PROPS[i];
  59412. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  59413. this.stopEffectAnimation();
  59414. this.startEffectAnimation(effectCfg);
  59415. return;
  59416. }
  59417. }
  59418. updateRipplePath(rippleGroup, effectCfg);
  59419. };
  59420. /**
  59421. * Highlight symbol
  59422. */
  59423. EffectSymbol.prototype.highlight = function () {
  59424. enterEmphasis(this);
  59425. };
  59426. /**
  59427. * Downplay symbol
  59428. */
  59429. EffectSymbol.prototype.downplay = function () {
  59430. leaveEmphasis(this);
  59431. };
  59432. EffectSymbol.prototype.getSymbolType = function () {
  59433. var symbol = this.childAt(0);
  59434. return symbol && symbol.getSymbolType();
  59435. };
  59436. /**
  59437. * Update symbol properties
  59438. */
  59439. EffectSymbol.prototype.updateData = function (data, idx) {
  59440. var _this = this;
  59441. var seriesModel = data.hostModel;
  59442. this.childAt(0).updateData(data, idx);
  59443. var rippleGroup = this.childAt(1);
  59444. var itemModel = data.getItemModel(idx);
  59445. var symbolType = data.getItemVisual(idx, 'symbol');
  59446. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  59447. var symbolStyle = data.getItemVisual(idx, 'style');
  59448. var color = symbolStyle && symbolStyle.fill;
  59449. var emphasisModel = itemModel.getModel('emphasis');
  59450. rippleGroup.setScale(symbolSize);
  59451. rippleGroup.traverse(function (ripplePath) {
  59452. ripplePath.setStyle('fill', color);
  59453. });
  59454. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  59455. if (symbolOffset) {
  59456. rippleGroup.x = symbolOffset[0];
  59457. rippleGroup.y = symbolOffset[1];
  59458. }
  59459. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  59460. rippleGroup.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  59461. var effectCfg = {};
  59462. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  59463. effectCfg.rippleScale = itemModel.get(['rippleEffect', 'scale']);
  59464. effectCfg.brushType = itemModel.get(['rippleEffect', 'brushType']);
  59465. effectCfg.period = itemModel.get(['rippleEffect', 'period']) * 1000;
  59466. effectCfg.effectOffset = idx / data.count();
  59467. effectCfg.z = seriesModel.getShallow('z') || 0;
  59468. effectCfg.zlevel = seriesModel.getShallow('zlevel') || 0;
  59469. effectCfg.symbolType = symbolType;
  59470. effectCfg.color = color;
  59471. effectCfg.rippleEffectColor = itemModel.get(['rippleEffect', 'color']);
  59472. effectCfg.rippleNumber = itemModel.get(['rippleEffect', 'number']);
  59473. if (effectCfg.showEffectOn === 'render') {
  59474. this._effectCfg ? this.updateEffectAnimation(effectCfg) : this.startEffectAnimation(effectCfg);
  59475. this._effectCfg = effectCfg;
  59476. } else {
  59477. // Not keep old effect config
  59478. this._effectCfg = null;
  59479. this.stopEffectAnimation();
  59480. this.onHoverStateChange = function (toState) {
  59481. if (toState === 'emphasis') {
  59482. if (effectCfg.showEffectOn !== 'render') {
  59483. _this.startEffectAnimation(effectCfg);
  59484. }
  59485. } else if (toState === 'normal') {
  59486. if (effectCfg.showEffectOn !== 'render') {
  59487. _this.stopEffectAnimation();
  59488. }
  59489. }
  59490. };
  59491. }
  59492. this._effectCfg = effectCfg;
  59493. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  59494. };
  59495. EffectSymbol.prototype.fadeOut = function (cb) {
  59496. cb && cb();
  59497. };
  59498. return EffectSymbol;
  59499. }(Group);
  59500. var EffectScatterView =
  59501. /** @class */
  59502. function (_super) {
  59503. __extends(EffectScatterView, _super);
  59504. function EffectScatterView() {
  59505. var _this = _super !== null && _super.apply(this, arguments) || this;
  59506. _this.type = EffectScatterView.type;
  59507. return _this;
  59508. }
  59509. EffectScatterView.prototype.init = function () {
  59510. this._symbolDraw = new SymbolDraw(EffectSymbol);
  59511. };
  59512. EffectScatterView.prototype.render = function (seriesModel, ecModel, api) {
  59513. var data = seriesModel.getData();
  59514. var effectSymbolDraw = this._symbolDraw;
  59515. effectSymbolDraw.updateData(data, {
  59516. clipShape: this._getClipShape(seriesModel)
  59517. });
  59518. this.group.add(effectSymbolDraw.group);
  59519. };
  59520. EffectScatterView.prototype._getClipShape = function (seriesModel) {
  59521. var coordSys = seriesModel.coordinateSystem;
  59522. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  59523. return seriesModel.get('clip', true) ? clipArea : null;
  59524. };
  59525. EffectScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  59526. var data = seriesModel.getData();
  59527. this.group.dirty();
  59528. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  59529. if (res.progress) {
  59530. res.progress({
  59531. start: 0,
  59532. end: data.count(),
  59533. count: data.count()
  59534. }, data);
  59535. }
  59536. this._symbolDraw.updateLayout();
  59537. };
  59538. EffectScatterView.prototype._updateGroupTransform = function (seriesModel) {
  59539. var coordSys = seriesModel.coordinateSystem;
  59540. if (coordSys && coordSys.getRoamTransform) {
  59541. this.group.transform = clone$2(coordSys.getRoamTransform());
  59542. this.group.decomposeTransform();
  59543. }
  59544. };
  59545. EffectScatterView.prototype.remove = function (ecModel, api) {
  59546. this._symbolDraw && this._symbolDraw.remove(true);
  59547. };
  59548. EffectScatterView.type = 'effectScatter';
  59549. return EffectScatterView;
  59550. }(ChartView);
  59551. var EffectScatterSeriesModel =
  59552. /** @class */
  59553. function (_super) {
  59554. __extends(EffectScatterSeriesModel, _super);
  59555. function EffectScatterSeriesModel() {
  59556. var _this = _super !== null && _super.apply(this, arguments) || this;
  59557. _this.type = EffectScatterSeriesModel.type;
  59558. _this.hasSymbolVisual = true;
  59559. return _this;
  59560. }
  59561. EffectScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  59562. return createSeriesData(null, this, {
  59563. useEncodeDefaulter: true
  59564. });
  59565. };
  59566. EffectScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  59567. return selectors.point(data.getItemLayout(dataIndex));
  59568. };
  59569. EffectScatterSeriesModel.type = 'series.effectScatter';
  59570. EffectScatterSeriesModel.dependencies = ['grid', 'polar'];
  59571. EffectScatterSeriesModel.defaultOption = {
  59572. coordinateSystem: 'cartesian2d',
  59573. // zlevel: 0,
  59574. z: 2,
  59575. legendHoverLink: true,
  59576. effectType: 'ripple',
  59577. progressive: 0,
  59578. // When to show the effect, option: 'render'|'emphasis'
  59579. showEffectOn: 'render',
  59580. clip: true,
  59581. // Ripple effect config
  59582. rippleEffect: {
  59583. period: 4,
  59584. // Scale of ripple
  59585. scale: 2.5,
  59586. // Brush type can be fill or stroke
  59587. brushType: 'fill',
  59588. // Ripple number
  59589. number: 3
  59590. },
  59591. universalTransition: {
  59592. divideShape: 'clone'
  59593. },
  59594. // Cartesian coordinate system
  59595. // xAxisIndex: 0,
  59596. // yAxisIndex: 0,
  59597. // Polar coordinate system
  59598. // polarIndex: 0,
  59599. // Geo coordinate system
  59600. // geoIndex: 0,
  59601. // symbol: null, // 图形类型
  59602. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  59603. // symbolRotate: null, // 图形旋转控制
  59604. // itemStyle: {
  59605. // opacity: 1
  59606. // }
  59607. };
  59608. return EffectScatterSeriesModel;
  59609. }(SeriesModel);
  59610. function install$l(registers) {
  59611. registers.registerChartView(EffectScatterView);
  59612. registers.registerSeriesModel(EffectScatterSeriesModel);
  59613. registers.registerLayout(pointsLayout('effectScatter'));
  59614. }
  59615. var EffectLine =
  59616. /** @class */
  59617. function (_super) {
  59618. __extends(EffectLine, _super);
  59619. function EffectLine(lineData, idx, seriesScope) {
  59620. var _this = _super.call(this) || this;
  59621. _this.add(_this.createLine(lineData, idx, seriesScope));
  59622. _this._updateEffectSymbol(lineData, idx);
  59623. return _this;
  59624. }
  59625. EffectLine.prototype.createLine = function (lineData, idx, seriesScope) {
  59626. return new Line$1(lineData, idx, seriesScope);
  59627. };
  59628. EffectLine.prototype._updateEffectSymbol = function (lineData, idx) {
  59629. var itemModel = lineData.getItemModel(idx);
  59630. var effectModel = itemModel.getModel('effect');
  59631. var size = effectModel.get('symbolSize');
  59632. var symbolType = effectModel.get('symbol');
  59633. if (!isArray(size)) {
  59634. size = [size, size];
  59635. }
  59636. var lineStyle = lineData.getItemVisual(idx, 'style');
  59637. var color = effectModel.get('color') || lineStyle && lineStyle.stroke;
  59638. var symbol = this.childAt(1);
  59639. if (this._symbolType !== symbolType) {
  59640. // Remove previous
  59641. this.remove(symbol);
  59642. symbol = createSymbol(symbolType, -0.5, -0.5, 1, 1, color);
  59643. symbol.z2 = 100;
  59644. symbol.culling = true;
  59645. this.add(symbol);
  59646. } // Symbol may be removed if loop is false
  59647. if (!symbol) {
  59648. return;
  59649. } // Shadow color is same with color in default
  59650. symbol.setStyle('shadowColor', color);
  59651. symbol.setStyle(effectModel.getItemStyle(['color']));
  59652. symbol.scaleX = size[0];
  59653. symbol.scaleY = size[1];
  59654. symbol.setColor(color);
  59655. this._symbolType = symbolType;
  59656. this._symbolScale = size;
  59657. this._updateEffectAnimation(lineData, effectModel, idx);
  59658. };
  59659. EffectLine.prototype._updateEffectAnimation = function (lineData, effectModel, idx) {
  59660. var symbol = this.childAt(1);
  59661. if (!symbol) {
  59662. return;
  59663. }
  59664. var points = lineData.getItemLayout(idx);
  59665. var period = effectModel.get('period') * 1000;
  59666. var loop = effectModel.get('loop');
  59667. var roundTrip = effectModel.get('roundTrip');
  59668. var constantSpeed = effectModel.get('constantSpeed');
  59669. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  59670. return idx / lineData.count() * period / 3;
  59671. }); // Ignore when updating
  59672. symbol.ignore = true;
  59673. this._updateAnimationPoints(symbol, points);
  59674. if (constantSpeed > 0) {
  59675. period = this._getLineLength(symbol) / constantSpeed * 1000;
  59676. }
  59677. if (period !== this._period || loop !== this._loop || roundTrip !== this._roundTrip) {
  59678. symbol.stopAnimation();
  59679. var delayNum = void 0;
  59680. if (isFunction(delayExpr)) {
  59681. delayNum = delayExpr(idx);
  59682. } else {
  59683. delayNum = delayExpr;
  59684. }
  59685. if (symbol.__t > 0) {
  59686. delayNum = -period * symbol.__t;
  59687. }
  59688. this._animateSymbol(symbol, period, delayNum, loop, roundTrip);
  59689. }
  59690. this._period = period;
  59691. this._loop = loop;
  59692. this._roundTrip = roundTrip;
  59693. };
  59694. EffectLine.prototype._animateSymbol = function (symbol, period, delayNum, loop, roundTrip) {
  59695. if (period > 0) {
  59696. symbol.__t = 0;
  59697. var self_1 = this;
  59698. var animator = symbol.animate('', loop).when(roundTrip ? period * 2 : period, {
  59699. __t: roundTrip ? 2 : 1
  59700. }).delay(delayNum).during(function () {
  59701. self_1._updateSymbolPosition(symbol);
  59702. });
  59703. if (!loop) {
  59704. animator.done(function () {
  59705. self_1.remove(symbol);
  59706. });
  59707. }
  59708. animator.start();
  59709. }
  59710. };
  59711. EffectLine.prototype._getLineLength = function (symbol) {
  59712. // Not so accurate
  59713. return dist(symbol.__p1, symbol.__cp1) + dist(symbol.__cp1, symbol.__p2);
  59714. };
  59715. EffectLine.prototype._updateAnimationPoints = function (symbol, points) {
  59716. symbol.__p1 = points[0];
  59717. symbol.__p2 = points[1];
  59718. symbol.__cp1 = points[2] || [(points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2];
  59719. };
  59720. EffectLine.prototype.updateData = function (lineData, idx, seriesScope) {
  59721. this.childAt(0).updateData(lineData, idx, seriesScope);
  59722. this._updateEffectSymbol(lineData, idx);
  59723. };
  59724. EffectLine.prototype._updateSymbolPosition = function (symbol) {
  59725. var p1 = symbol.__p1;
  59726. var p2 = symbol.__p2;
  59727. var cp1 = symbol.__cp1;
  59728. var t = symbol.__t < 1 ? symbol.__t : 2 - symbol.__t;
  59729. var pos = [symbol.x, symbol.y];
  59730. var lastPos = pos.slice();
  59731. var quadraticAt$1 = quadraticAt;
  59732. var quadraticDerivativeAt$1 = quadraticDerivativeAt;
  59733. pos[0] = quadraticAt$1(p1[0], cp1[0], p2[0], t);
  59734. pos[1] = quadraticAt$1(p1[1], cp1[1], p2[1], t); // Tangent
  59735. var tx = symbol.__t < 1 ? quadraticDerivativeAt$1(p1[0], cp1[0], p2[0], t) : quadraticDerivativeAt$1(p2[0], cp1[0], p1[0], 1 - t);
  59736. var ty = symbol.__t < 1 ? quadraticDerivativeAt$1(p1[1], cp1[1], p2[1], t) : quadraticDerivativeAt$1(p2[1], cp1[1], p1[1], 1 - t);
  59737. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2; // enable continuity trail for 'line', 'rect', 'roundRect' symbolType
  59738. if (this._symbolType === 'line' || this._symbolType === 'rect' || this._symbolType === 'roundRect') {
  59739. if (symbol.__lastT !== undefined && symbol.__lastT < symbol.__t) {
  59740. symbol.scaleY = dist(lastPos, pos) * 1.05; // make sure the last segment render within endPoint
  59741. if (t === 1) {
  59742. pos[0] = lastPos[0] + (pos[0] - lastPos[0]) / 2;
  59743. pos[1] = lastPos[1] + (pos[1] - lastPos[1]) / 2;
  59744. }
  59745. } else if (symbol.__lastT === 1) {
  59746. // After first loop, symbol.__t does NOT start with 0, so connect p1 to pos directly.
  59747. symbol.scaleY = 2 * dist(p1, pos);
  59748. } else {
  59749. symbol.scaleY = this._symbolScale[1];
  59750. }
  59751. }
  59752. symbol.__lastT = symbol.__t;
  59753. symbol.ignore = false;
  59754. symbol.x = pos[0];
  59755. symbol.y = pos[1];
  59756. };
  59757. EffectLine.prototype.updateLayout = function (lineData, idx) {
  59758. this.childAt(0).updateLayout(lineData, idx);
  59759. var effectModel = lineData.getItemModel(idx).getModel('effect');
  59760. this._updateEffectAnimation(lineData, effectModel, idx);
  59761. };
  59762. return EffectLine;
  59763. }(Group);
  59764. var Polyline$1 =
  59765. /** @class */
  59766. function (_super) {
  59767. __extends(Polyline$1, _super);
  59768. function Polyline$1(lineData, idx, seriesScope) {
  59769. var _this = _super.call(this) || this;
  59770. _this._createPolyline(lineData, idx, seriesScope);
  59771. return _this;
  59772. }
  59773. Polyline$1.prototype._createPolyline = function (lineData, idx, seriesScope) {
  59774. // let seriesModel = lineData.hostModel;
  59775. var points = lineData.getItemLayout(idx);
  59776. var line = new Polyline({
  59777. shape: {
  59778. points: points
  59779. }
  59780. });
  59781. this.add(line);
  59782. this._updateCommonStl(lineData, idx, seriesScope);
  59783. };
  59784. Polyline$1.prototype.updateData = function (lineData, idx, seriesScope) {
  59785. var seriesModel = lineData.hostModel;
  59786. var line = this.childAt(0);
  59787. var target = {
  59788. shape: {
  59789. points: lineData.getItemLayout(idx)
  59790. }
  59791. };
  59792. updateProps(line, target, seriesModel, idx);
  59793. this._updateCommonStl(lineData, idx, seriesScope);
  59794. };
  59795. Polyline$1.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  59796. var line = this.childAt(0);
  59797. var itemModel = lineData.getItemModel(idx);
  59798. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  59799. var focus = seriesScope && seriesScope.focus;
  59800. var blurScope = seriesScope && seriesScope.blurScope;
  59801. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  59802. if (!seriesScope || lineData.hasItemOption) {
  59803. var emphasisModel = itemModel.getModel('emphasis');
  59804. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  59805. emphasisDisabled = emphasisModel.get('disabled');
  59806. focus = emphasisModel.get('focus');
  59807. blurScope = emphasisModel.get('blurScope');
  59808. }
  59809. line.useStyle(lineData.getItemVisual(idx, 'style'));
  59810. line.style.fill = null;
  59811. line.style.strokeNoScale = true;
  59812. var lineEmphasisState = line.ensureState('emphasis');
  59813. lineEmphasisState.style = emphasisLineStyle;
  59814. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  59815. };
  59816. Polyline$1.prototype.updateLayout = function (lineData, idx) {
  59817. var polyline = this.childAt(0);
  59818. polyline.setShape('points', lineData.getItemLayout(idx));
  59819. };
  59820. return Polyline$1;
  59821. }(Group);
  59822. var EffectPolyline =
  59823. /** @class */
  59824. function (_super) {
  59825. __extends(EffectPolyline, _super);
  59826. function EffectPolyline() {
  59827. var _this = _super !== null && _super.apply(this, arguments) || this;
  59828. _this._lastFrame = 0;
  59829. _this._lastFramePercent = 0;
  59830. return _this;
  59831. } // Override
  59832. EffectPolyline.prototype.createLine = function (lineData, idx, seriesScope) {
  59833. return new Polyline$1(lineData, idx, seriesScope);
  59834. };
  59835. EffectPolyline.prototype._updateAnimationPoints = function (symbol, points) {
  59836. this._points = points;
  59837. var accLenArr = [0];
  59838. var len = 0;
  59839. for (var i = 1; i < points.length; i++) {
  59840. var p1 = points[i - 1];
  59841. var p2 = points[i];
  59842. len += dist(p1, p2);
  59843. accLenArr.push(len);
  59844. }
  59845. if (len === 0) {
  59846. this._length = 0;
  59847. return;
  59848. }
  59849. for (var i = 0; i < accLenArr.length; i++) {
  59850. accLenArr[i] /= len;
  59851. }
  59852. this._offsets = accLenArr;
  59853. this._length = len;
  59854. };
  59855. EffectPolyline.prototype._getLineLength = function () {
  59856. return this._length;
  59857. };
  59858. EffectPolyline.prototype._updateSymbolPosition = function (symbol) {
  59859. var t = symbol.__t < 1 ? symbol.__t : 2 - symbol.__t;
  59860. var points = this._points;
  59861. var offsets = this._offsets;
  59862. var len = points.length;
  59863. if (!offsets) {
  59864. // Has length 0
  59865. return;
  59866. }
  59867. var lastFrame = this._lastFrame;
  59868. var frame;
  59869. if (t < this._lastFramePercent) {
  59870. // Start from the next frame
  59871. // PENDING start from lastFrame ?
  59872. var start = Math.min(lastFrame + 1, len - 1);
  59873. for (frame = start; frame >= 0; frame--) {
  59874. if (offsets[frame] <= t) {
  59875. break;
  59876. }
  59877. } // PENDING really need to do this ?
  59878. frame = Math.min(frame, len - 2);
  59879. } else {
  59880. for (frame = lastFrame; frame < len; frame++) {
  59881. if (offsets[frame] > t) {
  59882. break;
  59883. }
  59884. }
  59885. frame = Math.min(frame - 1, len - 2);
  59886. }
  59887. var p = (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame]);
  59888. var p0 = points[frame];
  59889. var p1 = points[frame + 1];
  59890. symbol.x = p0[0] * (1 - p) + p * p1[0];
  59891. symbol.y = p0[1] * (1 - p) + p * p1[1];
  59892. var tx = symbol.__t < 1 ? p1[0] - p0[0] : p0[0] - p1[0];
  59893. var ty = symbol.__t < 1 ? p1[1] - p0[1] : p0[1] - p1[1];
  59894. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  59895. this._lastFrame = frame;
  59896. this._lastFramePercent = t;
  59897. symbol.ignore = false;
  59898. };
  59899. return EffectPolyline;
  59900. }(EffectLine);
  59901. var LargeLinesPathShape =
  59902. /** @class */
  59903. function () {
  59904. function LargeLinesPathShape() {
  59905. this.polyline = false;
  59906. this.curveness = 0;
  59907. this.segs = [];
  59908. }
  59909. return LargeLinesPathShape;
  59910. }();
  59911. var LargeLinesPath =
  59912. /** @class */
  59913. function (_super) {
  59914. __extends(LargeLinesPath, _super);
  59915. function LargeLinesPath(opts) {
  59916. var _this = _super.call(this, opts) || this;
  59917. _this._off = 0;
  59918. _this.hoverDataIdx = -1;
  59919. return _this;
  59920. }
  59921. LargeLinesPath.prototype.reset = function () {
  59922. this.notClear = false;
  59923. this._off = 0;
  59924. };
  59925. LargeLinesPath.prototype.getDefaultStyle = function () {
  59926. return {
  59927. stroke: '#000',
  59928. fill: null
  59929. };
  59930. };
  59931. LargeLinesPath.prototype.getDefaultShape = function () {
  59932. return new LargeLinesPathShape();
  59933. };
  59934. LargeLinesPath.prototype.buildPath = function (ctx, shape) {
  59935. var segs = shape.segs;
  59936. var curveness = shape.curveness;
  59937. var i;
  59938. if (shape.polyline) {
  59939. for (i = this._off; i < segs.length;) {
  59940. var count = segs[i++];
  59941. if (count > 0) {
  59942. ctx.moveTo(segs[i++], segs[i++]);
  59943. for (var k = 1; k < count; k++) {
  59944. ctx.lineTo(segs[i++], segs[i++]);
  59945. }
  59946. }
  59947. }
  59948. } else {
  59949. for (i = this._off; i < segs.length;) {
  59950. var x0 = segs[i++];
  59951. var y0 = segs[i++];
  59952. var x1 = segs[i++];
  59953. var y1 = segs[i++];
  59954. ctx.moveTo(x0, y0);
  59955. if (curveness > 0) {
  59956. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  59957. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  59958. ctx.quadraticCurveTo(x2, y2, x1, y1);
  59959. } else {
  59960. ctx.lineTo(x1, y1);
  59961. }
  59962. }
  59963. }
  59964. if (this.incremental) {
  59965. this._off = i;
  59966. this.notClear = true;
  59967. }
  59968. };
  59969. LargeLinesPath.prototype.findDataIndex = function (x, y) {
  59970. var shape = this.shape;
  59971. var segs = shape.segs;
  59972. var curveness = shape.curveness;
  59973. var lineWidth = this.style.lineWidth;
  59974. if (shape.polyline) {
  59975. var dataIndex = 0;
  59976. for (var i = 0; i < segs.length;) {
  59977. var count = segs[i++];
  59978. if (count > 0) {
  59979. var x0 = segs[i++];
  59980. var y0 = segs[i++];
  59981. for (var k = 1; k < count; k++) {
  59982. var x1 = segs[i++];
  59983. var y1 = segs[i++];
  59984. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  59985. return dataIndex;
  59986. }
  59987. }
  59988. }
  59989. dataIndex++;
  59990. }
  59991. } else {
  59992. var dataIndex = 0;
  59993. for (var i = 0; i < segs.length;) {
  59994. var x0 = segs[i++];
  59995. var y0 = segs[i++];
  59996. var x1 = segs[i++];
  59997. var y1 = segs[i++];
  59998. if (curveness > 0) {
  59999. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  60000. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  60001. if (containStroke$2(x0, y0, x2, y2, x1, y1, lineWidth, x, y)) {
  60002. return dataIndex;
  60003. }
  60004. } else {
  60005. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  60006. return dataIndex;
  60007. }
  60008. }
  60009. dataIndex++;
  60010. }
  60011. }
  60012. return -1;
  60013. };
  60014. LargeLinesPath.prototype.contain = function (x, y) {
  60015. var localPos = this.transformCoordToLocal(x, y);
  60016. var rect = this.getBoundingRect();
  60017. x = localPos[0];
  60018. y = localPos[1];
  60019. if (rect.contain(x, y)) {
  60020. // Cache found data index.
  60021. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  60022. return dataIdx >= 0;
  60023. }
  60024. this.hoverDataIdx = -1;
  60025. return false;
  60026. };
  60027. LargeLinesPath.prototype.getBoundingRect = function () {
  60028. // Ignore stroke for large symbol draw.
  60029. var rect = this._rect;
  60030. if (!rect) {
  60031. var shape = this.shape;
  60032. var points = shape.segs;
  60033. var minX = Infinity;
  60034. var minY = Infinity;
  60035. var maxX = -Infinity;
  60036. var maxY = -Infinity;
  60037. for (var i = 0; i < points.length;) {
  60038. var x = points[i++];
  60039. var y = points[i++];
  60040. minX = Math.min(x, minX);
  60041. maxX = Math.max(x, maxX);
  60042. minY = Math.min(y, minY);
  60043. maxY = Math.max(y, maxY);
  60044. }
  60045. rect = this._rect = new BoundingRect(minX, minY, maxX, maxY);
  60046. }
  60047. return rect;
  60048. };
  60049. return LargeLinesPath;
  60050. }(Path);
  60051. var LargeLineDraw =
  60052. /** @class */
  60053. function () {
  60054. function LargeLineDraw() {
  60055. this.group = new Group();
  60056. }
  60057. /**
  60058. * Update symbols draw by new data
  60059. */
  60060. LargeLineDraw.prototype.updateData = function (data) {
  60061. this._clear();
  60062. var lineEl = this._create();
  60063. lineEl.setShape({
  60064. segs: data.getLayout('linesPoints')
  60065. });
  60066. this._setCommon(lineEl, data);
  60067. };
  60068. /**
  60069. * @override
  60070. */
  60071. LargeLineDraw.prototype.incrementalPrepareUpdate = function (data) {
  60072. this.group.removeAll();
  60073. this._clear();
  60074. };
  60075. /**
  60076. * @override
  60077. */
  60078. LargeLineDraw.prototype.incrementalUpdate = function (taskParams, data) {
  60079. var lastAdded = this._newAdded[0];
  60080. var linePoints = data.getLayout('linesPoints');
  60081. var oldSegs = lastAdded && lastAdded.shape.segs; // Merging the exists. Each element has 1e4 points.
  60082. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  60083. if (oldSegs && oldSegs.length < 2e4) {
  60084. var oldLen = oldSegs.length;
  60085. var newSegs = new Float32Array(oldLen + linePoints.length); // Concat two array
  60086. newSegs.set(oldSegs);
  60087. newSegs.set(linePoints, oldLen);
  60088. lastAdded.setShape({
  60089. segs: newSegs
  60090. });
  60091. } else {
  60092. // Clear
  60093. this._newAdded = [];
  60094. var lineEl = this._create();
  60095. lineEl.incremental = true;
  60096. lineEl.setShape({
  60097. segs: linePoints
  60098. });
  60099. this._setCommon(lineEl, data);
  60100. lineEl.__startIndex = taskParams.start;
  60101. }
  60102. };
  60103. /**
  60104. * @override
  60105. */
  60106. LargeLineDraw.prototype.remove = function () {
  60107. this._clear();
  60108. };
  60109. LargeLineDraw.prototype.eachRendered = function (cb) {
  60110. this._newAdded[0] && cb(this._newAdded[0]);
  60111. };
  60112. LargeLineDraw.prototype._create = function () {
  60113. var lineEl = new LargeLinesPath({
  60114. cursor: 'default',
  60115. ignoreCoarsePointer: true
  60116. });
  60117. this._newAdded.push(lineEl);
  60118. this.group.add(lineEl);
  60119. return lineEl;
  60120. };
  60121. LargeLineDraw.prototype._setCommon = function (lineEl, data, isIncremental) {
  60122. var hostModel = data.hostModel;
  60123. lineEl.setShape({
  60124. polyline: hostModel.get('polyline'),
  60125. curveness: hostModel.get(['lineStyle', 'curveness'])
  60126. });
  60127. lineEl.useStyle(hostModel.getModel('lineStyle').getLineStyle());
  60128. lineEl.style.strokeNoScale = true;
  60129. var style = data.getVisual('style');
  60130. if (style && style.stroke) {
  60131. lineEl.setStyle('stroke', style.stroke);
  60132. }
  60133. lineEl.setStyle('fill', null);
  60134. var ecData = getECData(lineEl); // Enable tooltip
  60135. // PENDING May have performance issue when path is extremely large
  60136. ecData.seriesIndex = hostModel.seriesIndex;
  60137. lineEl.on('mousemove', function (e) {
  60138. ecData.dataIndex = null;
  60139. var dataIndex = lineEl.hoverDataIdx;
  60140. if (dataIndex > 0) {
  60141. // Provide dataIndex for tooltip
  60142. ecData.dataIndex = dataIndex + lineEl.__startIndex;
  60143. }
  60144. });
  60145. };
  60146. LargeLineDraw.prototype._clear = function () {
  60147. this._newAdded = [];
  60148. this.group.removeAll();
  60149. };
  60150. return LargeLineDraw;
  60151. }();
  60152. var linesLayout = {
  60153. seriesType: 'lines',
  60154. plan: createRenderPlanner(),
  60155. reset: function (seriesModel) {
  60156. var coordSys = seriesModel.coordinateSystem;
  60157. if (!coordSys) {
  60158. if ("development" !== 'production') {
  60159. error('The lines series must have a coordinate system.');
  60160. }
  60161. return;
  60162. }
  60163. var isPolyline = seriesModel.get('polyline');
  60164. var isLarge = seriesModel.pipelineContext.large;
  60165. return {
  60166. progress: function (params, lineData) {
  60167. var lineCoords = [];
  60168. if (isLarge) {
  60169. var points = void 0;
  60170. var segCount = params.end - params.start;
  60171. if (isPolyline) {
  60172. var totalCoordsCount = 0;
  60173. for (var i = params.start; i < params.end; i++) {
  60174. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  60175. }
  60176. points = new Float32Array(segCount + totalCoordsCount * 2);
  60177. } else {
  60178. points = new Float32Array(segCount * 4);
  60179. }
  60180. var offset = 0;
  60181. var pt = [];
  60182. for (var i = params.start; i < params.end; i++) {
  60183. var len = seriesModel.getLineCoords(i, lineCoords);
  60184. if (isPolyline) {
  60185. points[offset++] = len;
  60186. }
  60187. for (var k = 0; k < len; k++) {
  60188. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  60189. points[offset++] = pt[0];
  60190. points[offset++] = pt[1];
  60191. }
  60192. }
  60193. lineData.setLayout('linesPoints', points);
  60194. } else {
  60195. for (var i = params.start; i < params.end; i++) {
  60196. var itemModel = lineData.getItemModel(i);
  60197. var len = seriesModel.getLineCoords(i, lineCoords);
  60198. var pts = [];
  60199. if (isPolyline) {
  60200. for (var j = 0; j < len; j++) {
  60201. pts.push(coordSys.dataToPoint(lineCoords[j]));
  60202. }
  60203. } else {
  60204. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  60205. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  60206. var curveness = itemModel.get(['lineStyle', 'curveness']);
  60207. if (+curveness) {
  60208. pts[2] = [(pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness, (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness];
  60209. }
  60210. }
  60211. lineData.setItemLayout(i, pts);
  60212. }
  60213. }
  60214. }
  60215. };
  60216. }
  60217. };
  60218. var LinesView =
  60219. /** @class */
  60220. function (_super) {
  60221. __extends(LinesView, _super);
  60222. function LinesView() {
  60223. var _this = _super !== null && _super.apply(this, arguments) || this;
  60224. _this.type = LinesView.type;
  60225. return _this;
  60226. }
  60227. LinesView.prototype.render = function (seriesModel, ecModel, api) {
  60228. var data = seriesModel.getData();
  60229. var lineDraw = this._updateLineDraw(data, seriesModel);
  60230. var zlevel = seriesModel.get('zlevel');
  60231. var trailLength = seriesModel.get(['effect', 'trailLength']);
  60232. var zr = api.getZr(); // Avoid the drag cause ghost shadow
  60233. // FIXME Better way ?
  60234. // SVG doesn't support
  60235. var isSvg = zr.painter.getType() === 'svg';
  60236. if (!isSvg) {
  60237. zr.painter.getLayer(zlevel).clear(true);
  60238. } // Config layer with motion blur
  60239. if (this._lastZlevel != null && !isSvg) {
  60240. zr.configLayer(this._lastZlevel, {
  60241. motionBlur: false
  60242. });
  60243. }
  60244. if (this._showEffect(seriesModel) && trailLength > 0) {
  60245. if (!isSvg) {
  60246. zr.configLayer(zlevel, {
  60247. motionBlur: true,
  60248. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  60249. });
  60250. } else if ("development" !== 'production') {
  60251. console.warn('SVG render mode doesn\'t support lines with trail effect');
  60252. }
  60253. }
  60254. lineDraw.updateData(data);
  60255. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  60256. if (clipPath) {
  60257. this.group.setClipPath(clipPath);
  60258. } else {
  60259. this.group.removeClipPath();
  60260. }
  60261. this._lastZlevel = zlevel;
  60262. this._finished = true;
  60263. };
  60264. LinesView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  60265. var data = seriesModel.getData();
  60266. var lineDraw = this._updateLineDraw(data, seriesModel);
  60267. lineDraw.incrementalPrepareUpdate(data);
  60268. this._clearLayer(api);
  60269. this._finished = false;
  60270. };
  60271. LinesView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  60272. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  60273. this._finished = taskParams.end === seriesModel.getData().count();
  60274. };
  60275. LinesView.prototype.eachRendered = function (cb) {
  60276. this._lineDraw && this._lineDraw.eachRendered(cb);
  60277. };
  60278. LinesView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  60279. var data = seriesModel.getData();
  60280. var pipelineContext = seriesModel.pipelineContext;
  60281. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  60282. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  60283. return {
  60284. update: true
  60285. };
  60286. } else {
  60287. // TODO Use same logic with ScatterView.
  60288. // Manually update layout
  60289. var res = linesLayout.reset(seriesModel, ecModel, api);
  60290. if (res.progress) {
  60291. res.progress({
  60292. start: 0,
  60293. end: data.count(),
  60294. count: data.count()
  60295. }, data);
  60296. } // Not in large mode
  60297. this._lineDraw.updateLayout();
  60298. this._clearLayer(api);
  60299. }
  60300. };
  60301. LinesView.prototype._updateLineDraw = function (data, seriesModel) {
  60302. var lineDraw = this._lineDraw;
  60303. var hasEffect = this._showEffect(seriesModel);
  60304. var isPolyline = !!seriesModel.get('polyline');
  60305. var pipelineContext = seriesModel.pipelineContext;
  60306. var isLargeDraw = pipelineContext.large;
  60307. if ("development" !== 'production') {
  60308. if (hasEffect && isLargeDraw) {
  60309. console.warn('Large lines not support effect');
  60310. }
  60311. }
  60312. if (!lineDraw || hasEffect !== this._hasEffet || isPolyline !== this._isPolyline || isLargeDraw !== this._isLargeDraw) {
  60313. if (lineDraw) {
  60314. lineDraw.remove();
  60315. }
  60316. lineDraw = this._lineDraw = isLargeDraw ? new LargeLineDraw() : new LineDraw(isPolyline ? hasEffect ? EffectPolyline : Polyline$1 : hasEffect ? EffectLine : Line$1);
  60317. this._hasEffet = hasEffect;
  60318. this._isPolyline = isPolyline;
  60319. this._isLargeDraw = isLargeDraw;
  60320. }
  60321. this.group.add(lineDraw.group);
  60322. return lineDraw;
  60323. };
  60324. LinesView.prototype._showEffect = function (seriesModel) {
  60325. return !!seriesModel.get(['effect', 'show']);
  60326. };
  60327. LinesView.prototype._clearLayer = function (api) {
  60328. // Not use motion when dragging or zooming
  60329. var zr = api.getZr();
  60330. var isSvg = zr.painter.getType() === 'svg';
  60331. if (!isSvg && this._lastZlevel != null) {
  60332. zr.painter.getLayer(this._lastZlevel).clear(true);
  60333. }
  60334. };
  60335. LinesView.prototype.remove = function (ecModel, api) {
  60336. this._lineDraw && this._lineDraw.remove();
  60337. this._lineDraw = null; // Clear motion when lineDraw is removed
  60338. this._clearLayer(api);
  60339. };
  60340. LinesView.prototype.dispose = function (ecModel, api) {
  60341. this.remove(ecModel, api);
  60342. };
  60343. LinesView.type = 'lines';
  60344. return LinesView;
  60345. }(ChartView);
  60346. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  60347. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  60348. function compatEc2(seriesOpt) {
  60349. var data = seriesOpt.data;
  60350. if (data && data[0] && data[0][0] && data[0][0].coord) {
  60351. if ("development" !== 'production') {
  60352. console.warn('Lines data configuration has been changed to' + ' { coords:[[1,2],[2,3]] }');
  60353. }
  60354. seriesOpt.data = map(data, function (itemOpt) {
  60355. var coords = [itemOpt[0].coord, itemOpt[1].coord];
  60356. var target = {
  60357. coords: coords
  60358. };
  60359. if (itemOpt[0].name) {
  60360. target.fromName = itemOpt[0].name;
  60361. }
  60362. if (itemOpt[1].name) {
  60363. target.toName = itemOpt[1].name;
  60364. }
  60365. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  60366. });
  60367. }
  60368. }
  60369. var LinesSeriesModel =
  60370. /** @class */
  60371. function (_super) {
  60372. __extends(LinesSeriesModel, _super);
  60373. function LinesSeriesModel() {
  60374. var _this = _super !== null && _super.apply(this, arguments) || this;
  60375. _this.type = LinesSeriesModel.type;
  60376. _this.visualStyleAccessPath = 'lineStyle';
  60377. _this.visualDrawType = 'stroke';
  60378. return _this;
  60379. }
  60380. LinesSeriesModel.prototype.init = function (option) {
  60381. // The input data may be null/undefined.
  60382. option.data = option.data || []; // Not using preprocessor because mergeOption may not have series.type
  60383. compatEc2(option);
  60384. var result = this._processFlatCoordsArray(option.data);
  60385. this._flatCoords = result.flatCoords;
  60386. this._flatCoordsOffset = result.flatCoordsOffset;
  60387. if (result.flatCoords) {
  60388. option.data = new Float32Array(result.count);
  60389. }
  60390. _super.prototype.init.apply(this, arguments);
  60391. };
  60392. LinesSeriesModel.prototype.mergeOption = function (option) {
  60393. compatEc2(option);
  60394. if (option.data) {
  60395. // Only update when have option data to merge.
  60396. var result = this._processFlatCoordsArray(option.data);
  60397. this._flatCoords = result.flatCoords;
  60398. this._flatCoordsOffset = result.flatCoordsOffset;
  60399. if (result.flatCoords) {
  60400. option.data = new Float32Array(result.count);
  60401. }
  60402. }
  60403. _super.prototype.mergeOption.apply(this, arguments);
  60404. };
  60405. LinesSeriesModel.prototype.appendData = function (params) {
  60406. var result = this._processFlatCoordsArray(params.data);
  60407. if (result.flatCoords) {
  60408. if (!this._flatCoords) {
  60409. this._flatCoords = result.flatCoords;
  60410. this._flatCoordsOffset = result.flatCoordsOffset;
  60411. } else {
  60412. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  60413. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  60414. }
  60415. params.data = new Float32Array(result.count);
  60416. }
  60417. this.getRawData().appendData(params.data);
  60418. };
  60419. LinesSeriesModel.prototype._getCoordsFromItemModel = function (idx) {
  60420. var itemModel = this.getData().getItemModel(idx);
  60421. var coords = itemModel.option instanceof Array ? itemModel.option : itemModel.getShallow('coords');
  60422. if ("development" !== 'production') {
  60423. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  60424. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  60425. }
  60426. }
  60427. return coords;
  60428. };
  60429. LinesSeriesModel.prototype.getLineCoordsCount = function (idx) {
  60430. if (this._flatCoordsOffset) {
  60431. return this._flatCoordsOffset[idx * 2 + 1];
  60432. } else {
  60433. return this._getCoordsFromItemModel(idx).length;
  60434. }
  60435. };
  60436. LinesSeriesModel.prototype.getLineCoords = function (idx, out) {
  60437. if (this._flatCoordsOffset) {
  60438. var offset = this._flatCoordsOffset[idx * 2];
  60439. var len = this._flatCoordsOffset[idx * 2 + 1];
  60440. for (var i = 0; i < len; i++) {
  60441. out[i] = out[i] || [];
  60442. out[i][0] = this._flatCoords[offset + i * 2];
  60443. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  60444. }
  60445. return len;
  60446. } else {
  60447. var coords = this._getCoordsFromItemModel(idx);
  60448. for (var i = 0; i < coords.length; i++) {
  60449. out[i] = out[i] || [];
  60450. out[i][0] = coords[i][0];
  60451. out[i][1] = coords[i][1];
  60452. }
  60453. return coords.length;
  60454. }
  60455. };
  60456. LinesSeriesModel.prototype._processFlatCoordsArray = function (data) {
  60457. var startOffset = 0;
  60458. if (this._flatCoords) {
  60459. startOffset = this._flatCoords.length;
  60460. } // Stored as a typed array. In format
  60461. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  60462. if (isNumber(data[0])) {
  60463. var len = data.length; // Store offset and len of each segment
  60464. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  60465. var coordsStorage = new Float64Arr(len);
  60466. var coordsCursor = 0;
  60467. var offsetCursor = 0;
  60468. var dataCount = 0;
  60469. for (var i = 0; i < len;) {
  60470. dataCount++;
  60471. var count = data[i++]; // Offset
  60472. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset; // Len
  60473. coordsOffsetAndLenStorage[offsetCursor++] = count;
  60474. for (var k = 0; k < count; k++) {
  60475. var x = data[i++];
  60476. var y = data[i++];
  60477. coordsStorage[coordsCursor++] = x;
  60478. coordsStorage[coordsCursor++] = y;
  60479. if (i > len) {
  60480. if ("development" !== 'production') {
  60481. throw new Error('Invalid data format.');
  60482. }
  60483. }
  60484. }
  60485. }
  60486. return {
  60487. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  60488. flatCoords: coordsStorage,
  60489. count: dataCount
  60490. };
  60491. }
  60492. return {
  60493. flatCoordsOffset: null,
  60494. flatCoords: null,
  60495. count: data.length
  60496. };
  60497. };
  60498. LinesSeriesModel.prototype.getInitialData = function (option, ecModel) {
  60499. if ("development" !== 'production') {
  60500. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  60501. if (!CoordSys) {
  60502. throw new Error('Unknown coordinate system ' + option.coordinateSystem);
  60503. }
  60504. }
  60505. var lineData = new SeriesData(['value'], this);
  60506. lineData.hasItemOption = false;
  60507. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  60508. // dataItem is simply coords
  60509. if (dataItem instanceof Array) {
  60510. return NaN;
  60511. } else {
  60512. lineData.hasItemOption = true;
  60513. var value = dataItem.value;
  60514. if (value != null) {
  60515. return value instanceof Array ? value[dimIndex] : value;
  60516. }
  60517. }
  60518. });
  60519. return lineData;
  60520. };
  60521. LinesSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  60522. var data = this.getData();
  60523. var itemModel = data.getItemModel(dataIndex);
  60524. var name = itemModel.get('name');
  60525. if (name) {
  60526. return name;
  60527. }
  60528. var fromName = itemModel.get('fromName');
  60529. var toName = itemModel.get('toName');
  60530. var nameArr = [];
  60531. fromName != null && nameArr.push(fromName);
  60532. toName != null && nameArr.push(toName);
  60533. return createTooltipMarkup('nameValue', {
  60534. name: nameArr.join(' > ')
  60535. });
  60536. };
  60537. LinesSeriesModel.prototype.preventIncremental = function () {
  60538. return !!this.get(['effect', 'show']);
  60539. };
  60540. LinesSeriesModel.prototype.getProgressive = function () {
  60541. var progressive = this.option.progressive;
  60542. if (progressive == null) {
  60543. return this.option.large ? 1e4 : this.get('progressive');
  60544. }
  60545. return progressive;
  60546. };
  60547. LinesSeriesModel.prototype.getProgressiveThreshold = function () {
  60548. var progressiveThreshold = this.option.progressiveThreshold;
  60549. if (progressiveThreshold == null) {
  60550. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  60551. }
  60552. return progressiveThreshold;
  60553. };
  60554. LinesSeriesModel.prototype.getZLevelKey = function () {
  60555. var effectModel = this.getModel('effect');
  60556. var trailLength = effectModel.get('trailLength');
  60557. return this.getData().count() > this.getProgressiveThreshold() // Each progressive series has individual key.
  60558. ? this.id : effectModel.get('show') && trailLength > 0 ? trailLength + '' : '';
  60559. };
  60560. LinesSeriesModel.type = 'series.lines';
  60561. LinesSeriesModel.dependencies = ['grid', 'polar', 'geo', 'calendar'];
  60562. LinesSeriesModel.defaultOption = {
  60563. coordinateSystem: 'geo',
  60564. // zlevel: 0,
  60565. z: 2,
  60566. legendHoverLink: true,
  60567. // Cartesian coordinate system
  60568. xAxisIndex: 0,
  60569. yAxisIndex: 0,
  60570. symbol: ['none', 'none'],
  60571. symbolSize: [10, 10],
  60572. // Geo coordinate system
  60573. geoIndex: 0,
  60574. effect: {
  60575. show: false,
  60576. period: 4,
  60577. constantSpeed: 0,
  60578. symbol: 'circle',
  60579. symbolSize: 3,
  60580. loop: true,
  60581. trailLength: 0.2
  60582. },
  60583. large: false,
  60584. // Available when large is true
  60585. largeThreshold: 2000,
  60586. polyline: false,
  60587. clip: true,
  60588. label: {
  60589. show: false,
  60590. position: 'end' // distance: 5,
  60591. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  60592. },
  60593. lineStyle: {
  60594. opacity: 0.5
  60595. }
  60596. };
  60597. return LinesSeriesModel;
  60598. }(SeriesModel);
  60599. /*
  60600. * Licensed to the Apache Software Foundation (ASF) under one
  60601. * or more contributor license agreements. See the NOTICE file
  60602. * distributed with this work for additional information
  60603. * regarding copyright ownership. The ASF licenses this file
  60604. * to you under the Apache License, Version 2.0 (the
  60605. * "License"); you may not use this file except in compliance
  60606. * with the License. You may obtain a copy of the License at
  60607. *
  60608. * http://www.apache.org/licenses/LICENSE-2.0
  60609. *
  60610. * Unless required by applicable law or agreed to in writing,
  60611. * software distributed under the License is distributed on an
  60612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60613. * KIND, either express or implied. See the License for the
  60614. * specific language governing permissions and limitations
  60615. * under the License.
  60616. */
  60617. /**
  60618. * AUTO-GENERATED FILE. DO NOT MODIFY.
  60619. */
  60620. /*
  60621. * Licensed to the Apache Software Foundation (ASF) under one
  60622. * or more contributor license agreements. See the NOTICE file
  60623. * distributed with this work for additional information
  60624. * regarding copyright ownership. The ASF licenses this file
  60625. * to you under the Apache License, Version 2.0 (the
  60626. * "License"); you may not use this file except in compliance
  60627. * with the License. You may obtain a copy of the License at
  60628. *
  60629. * http://www.apache.org/licenses/LICENSE-2.0
  60630. *
  60631. * Unless required by applicable law or agreed to in writing,
  60632. * software distributed under the License is distributed on an
  60633. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60634. * KIND, either express or implied. See the License for the
  60635. * specific language governing permissions and limitations
  60636. * under the License.
  60637. */
  60638. function normalize$3(a) {
  60639. if (!(a instanceof Array)) {
  60640. a = [a, a];
  60641. }
  60642. return a;
  60643. }
  60644. var linesVisual = {
  60645. seriesType: 'lines',
  60646. reset: function (seriesModel) {
  60647. var symbolType = normalize$3(seriesModel.get('symbol'));
  60648. var symbolSize = normalize$3(seriesModel.get('symbolSize'));
  60649. var data = seriesModel.getData();
  60650. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  60651. data.setVisual('toSymbol', symbolType && symbolType[1]);
  60652. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  60653. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  60654. function dataEach(data, idx) {
  60655. var itemModel = data.getItemModel(idx);
  60656. var symbolType = normalize$3(itemModel.getShallow('symbol', true));
  60657. var symbolSize = normalize$3(itemModel.getShallow('symbolSize', true));
  60658. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  60659. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  60660. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  60661. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  60662. }
  60663. return {
  60664. dataEach: data.hasItemOption ? dataEach : null
  60665. };
  60666. }
  60667. };
  60668. function install$m(registers) {
  60669. registers.registerChartView(LinesView);
  60670. registers.registerSeriesModel(LinesSeriesModel);
  60671. registers.registerLayout(linesLayout);
  60672. registers.registerVisual(linesVisual);
  60673. }
  60674. var GRADIENT_LEVELS = 256;
  60675. var HeatmapLayer =
  60676. /** @class */
  60677. function () {
  60678. function HeatmapLayer() {
  60679. this.blurSize = 30;
  60680. this.pointSize = 20;
  60681. this.maxOpacity = 1;
  60682. this.minOpacity = 0;
  60683. this._gradientPixels = {
  60684. inRange: null,
  60685. outOfRange: null
  60686. };
  60687. var canvas = platformApi.createCanvas();
  60688. this.canvas = canvas;
  60689. }
  60690. /**
  60691. * Renders Heatmap and returns the rendered canvas
  60692. * @param data array of data, each has x, y, value
  60693. * @param width canvas width
  60694. * @param height canvas height
  60695. */
  60696. HeatmapLayer.prototype.update = function (data, width, height, normalize, colorFunc, isInRange) {
  60697. var brush = this._getBrush();
  60698. var gradientInRange = this._getGradient(colorFunc, 'inRange');
  60699. var gradientOutOfRange = this._getGradient(colorFunc, 'outOfRange');
  60700. var r = this.pointSize + this.blurSize;
  60701. var canvas = this.canvas;
  60702. var ctx = canvas.getContext('2d');
  60703. var len = data.length;
  60704. canvas.width = width;
  60705. canvas.height = height;
  60706. for (var i = 0; i < len; ++i) {
  60707. var p = data[i];
  60708. var x = p[0];
  60709. var y = p[1];
  60710. var value = p[2]; // calculate alpha using value
  60711. var alpha = normalize(value); // draw with the circle brush with alpha
  60712. ctx.globalAlpha = alpha;
  60713. ctx.drawImage(brush, x - r, y - r);
  60714. }
  60715. if (!canvas.width || !canvas.height) {
  60716. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  60717. // 'CanvasRenderingContext2D': The source height is 0."
  60718. return canvas;
  60719. } // colorize the canvas using alpha value and set with gradient
  60720. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  60721. var pixels = imageData.data;
  60722. var offset = 0;
  60723. var pixelLen = pixels.length;
  60724. var minOpacity = this.minOpacity;
  60725. var maxOpacity = this.maxOpacity;
  60726. var diffOpacity = maxOpacity - minOpacity;
  60727. while (offset < pixelLen) {
  60728. var alpha = pixels[offset + 3] / 256;
  60729. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4; // Simple optimize to ignore the empty data
  60730. if (alpha > 0) {
  60731. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange; // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  60732. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  60733. pixels[offset++] = gradient[gradientOffset];
  60734. pixels[offset++] = gradient[gradientOffset + 1];
  60735. pixels[offset++] = gradient[gradientOffset + 2];
  60736. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  60737. } else {
  60738. offset += 4;
  60739. }
  60740. }
  60741. ctx.putImageData(imageData, 0, 0);
  60742. return canvas;
  60743. };
  60744. /**
  60745. * get canvas of a black circle brush used for canvas to draw later
  60746. */
  60747. HeatmapLayer.prototype._getBrush = function () {
  60748. var brushCanvas = this._brushCanvas || (this._brushCanvas = platformApi.createCanvas()); // set brush size
  60749. var r = this.pointSize + this.blurSize;
  60750. var d = r * 2;
  60751. brushCanvas.width = d;
  60752. brushCanvas.height = d;
  60753. var ctx = brushCanvas.getContext('2d');
  60754. ctx.clearRect(0, 0, d, d); // in order to render shadow without the distinct circle,
  60755. // draw the distinct circle in an invisible place,
  60756. // and use shadowOffset to draw shadow in the center of the canvas
  60757. ctx.shadowOffsetX = d;
  60758. ctx.shadowBlur = this.blurSize; // draw the shadow in black, and use alpha and shadow blur to generate
  60759. // color in color map
  60760. ctx.shadowColor = '#000'; // draw circle in the left to the canvas
  60761. ctx.beginPath();
  60762. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  60763. ctx.closePath();
  60764. ctx.fill();
  60765. return brushCanvas;
  60766. };
  60767. /**
  60768. * get gradient color map
  60769. * @private
  60770. */
  60771. HeatmapLayer.prototype._getGradient = function (colorFunc, state) {
  60772. var gradientPixels = this._gradientPixels;
  60773. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  60774. var color = [0, 0, 0, 0];
  60775. var off = 0;
  60776. for (var i = 0; i < 256; i++) {
  60777. colorFunc[state](i / 255, true, color);
  60778. pixelsSingleState[off++] = color[0];
  60779. pixelsSingleState[off++] = color[1];
  60780. pixelsSingleState[off++] = color[2];
  60781. pixelsSingleState[off++] = color[3];
  60782. }
  60783. return pixelsSingleState;
  60784. };
  60785. return HeatmapLayer;
  60786. }();
  60787. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  60788. var dataSpan = dataExtent[1] - dataExtent[0];
  60789. pieceList = map(pieceList, function (piece) {
  60790. return {
  60791. interval: [(piece.interval[0] - dataExtent[0]) / dataSpan, (piece.interval[1] - dataExtent[0]) / dataSpan]
  60792. };
  60793. });
  60794. var len = pieceList.length;
  60795. var lastIndex = 0;
  60796. return function (val) {
  60797. var i; // Try to find in the location of the last found
  60798. for (i = lastIndex; i < len; i++) {
  60799. var interval = pieceList[i].interval;
  60800. if (interval[0] <= val && val <= interval[1]) {
  60801. lastIndex = i;
  60802. break;
  60803. }
  60804. }
  60805. if (i === len) {
  60806. // Not found, back interation
  60807. for (i = lastIndex - 1; i >= 0; i--) {
  60808. var interval = pieceList[i].interval;
  60809. if (interval[0] <= val && val <= interval[1]) {
  60810. lastIndex = i;
  60811. break;
  60812. }
  60813. }
  60814. }
  60815. return i >= 0 && i < len && selected[i];
  60816. };
  60817. }
  60818. function getIsInContinuousRange(dataExtent, range) {
  60819. var dataSpan = dataExtent[1] - dataExtent[0];
  60820. range = [(range[0] - dataExtent[0]) / dataSpan, (range[1] - dataExtent[0]) / dataSpan];
  60821. return function (val) {
  60822. return val >= range[0] && val <= range[1];
  60823. };
  60824. }
  60825. function isGeoCoordSys(coordSys) {
  60826. var dimensions = coordSys.dimensions; // Not use coordSys.type === 'geo' because coordSys maybe extended
  60827. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  60828. }
  60829. var HeatmapView =
  60830. /** @class */
  60831. function (_super) {
  60832. __extends(HeatmapView, _super);
  60833. function HeatmapView() {
  60834. var _this = _super !== null && _super.apply(this, arguments) || this;
  60835. _this.type = HeatmapView.type;
  60836. return _this;
  60837. }
  60838. HeatmapView.prototype.render = function (seriesModel, ecModel, api) {
  60839. var visualMapOfThisSeries;
  60840. ecModel.eachComponent('visualMap', function (visualMap) {
  60841. visualMap.eachTargetSeries(function (targetSeries) {
  60842. if (targetSeries === seriesModel) {
  60843. visualMapOfThisSeries = visualMap;
  60844. }
  60845. });
  60846. });
  60847. if ("development" !== 'production') {
  60848. if (!visualMapOfThisSeries) {
  60849. throw new Error('Heatmap must use with visualMap');
  60850. }
  60851. } // Clear previously rendered progressive elements.
  60852. this._progressiveEls = null;
  60853. this.group.removeAll();
  60854. var coordSys = seriesModel.coordinateSystem;
  60855. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  60856. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  60857. } else if (isGeoCoordSys(coordSys)) {
  60858. this._renderOnGeo(coordSys, seriesModel, visualMapOfThisSeries, api);
  60859. }
  60860. };
  60861. HeatmapView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  60862. this.group.removeAll();
  60863. };
  60864. HeatmapView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  60865. var coordSys = seriesModel.coordinateSystem;
  60866. if (coordSys) {
  60867. // geo does not support incremental rendering?
  60868. if (isGeoCoordSys(coordSys)) {
  60869. this.render(seriesModel, ecModel, api);
  60870. } else {
  60871. this._progressiveEls = [];
  60872. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  60873. }
  60874. }
  60875. };
  60876. HeatmapView.prototype.eachRendered = function (cb) {
  60877. traverseElements(this._progressiveEls || this.group, cb);
  60878. };
  60879. HeatmapView.prototype._renderOnCartesianAndCalendar = function (seriesModel, api, start, end, incremental) {
  60880. var coordSys = seriesModel.coordinateSystem;
  60881. var isCartesian2d = isCoordinateSystemType(coordSys, 'cartesian2d');
  60882. var width;
  60883. var height;
  60884. var xAxisExtent;
  60885. var yAxisExtent;
  60886. if (isCartesian2d) {
  60887. var xAxis = coordSys.getAxis('x');
  60888. var yAxis = coordSys.getAxis('y');
  60889. if ("development" !== 'production') {
  60890. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  60891. throw new Error('Heatmap on cartesian must have two category axes');
  60892. }
  60893. if (!(xAxis.onBand && yAxis.onBand)) {
  60894. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  60895. }
  60896. } // add 0.5px to avoid the gaps
  60897. width = xAxis.getBandWidth() + .5;
  60898. height = yAxis.getBandWidth() + .5;
  60899. xAxisExtent = xAxis.scale.getExtent();
  60900. yAxisExtent = yAxis.scale.getExtent();
  60901. }
  60902. var group = this.group;
  60903. var data = seriesModel.getData();
  60904. var emphasisStyle = seriesModel.getModel(['emphasis', 'itemStyle']).getItemStyle();
  60905. var blurStyle = seriesModel.getModel(['blur', 'itemStyle']).getItemStyle();
  60906. var selectStyle = seriesModel.getModel(['select', 'itemStyle']).getItemStyle();
  60907. var borderRadius = seriesModel.get(['itemStyle', 'borderRadius']);
  60908. var labelStatesModels = getLabelStatesModels(seriesModel);
  60909. var emphasisModel = seriesModel.getModel('emphasis');
  60910. var focus = emphasisModel.get('focus');
  60911. var blurScope = emphasisModel.get('blurScope');
  60912. var emphasisDisabled = emphasisModel.get('disabled');
  60913. var dataDims = isCartesian2d ? [data.mapDimension('x'), data.mapDimension('y'), data.mapDimension('value')] : [data.mapDimension('time'), data.mapDimension('value')];
  60914. for (var idx = start; idx < end; idx++) {
  60915. var rect = void 0;
  60916. var style = data.getItemVisual(idx, 'style');
  60917. if (isCartesian2d) {
  60918. var dataDimX = data.get(dataDims[0], idx);
  60919. var dataDimY = data.get(dataDims[1], idx); // Ignore empty data and out of extent data
  60920. if (isNaN(data.get(dataDims[2], idx)) || isNaN(dataDimX) || isNaN(dataDimY) || dataDimX < xAxisExtent[0] || dataDimX > xAxisExtent[1] || dataDimY < yAxisExtent[0] || dataDimY > yAxisExtent[1]) {
  60921. continue;
  60922. }
  60923. var point = coordSys.dataToPoint([dataDimX, dataDimY]);
  60924. rect = new Rect({
  60925. shape: {
  60926. x: point[0] - width / 2,
  60927. y: point[1] - height / 2,
  60928. width: width,
  60929. height: height
  60930. },
  60931. style: style
  60932. });
  60933. } else {
  60934. // Ignore empty data
  60935. if (isNaN(data.get(dataDims[1], idx))) {
  60936. continue;
  60937. }
  60938. rect = new Rect({
  60939. z2: 1,
  60940. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  60941. style: style
  60942. });
  60943. } // Optimization for large dataset
  60944. if (data.hasItemOption) {
  60945. var itemModel = data.getItemModel(idx);
  60946. var emphasisModel_1 = itemModel.getModel('emphasis');
  60947. emphasisStyle = emphasisModel_1.getModel('itemStyle').getItemStyle();
  60948. blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  60949. selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle(); // Each item value struct in the data would be firstly
  60950. // {
  60951. // itemStyle: { borderRadius: [30, 30] },
  60952. // value: [2022, 02, 22]
  60953. // }
  60954. borderRadius = itemModel.get(['itemStyle', 'borderRadius']);
  60955. focus = emphasisModel_1.get('focus');
  60956. blurScope = emphasisModel_1.get('blurScope');
  60957. emphasisDisabled = emphasisModel_1.get('disabled');
  60958. labelStatesModels = getLabelStatesModels(itemModel);
  60959. }
  60960. rect.shape.r = borderRadius;
  60961. var rawValue = seriesModel.getRawValue(idx);
  60962. var defaultText = '-';
  60963. if (rawValue && rawValue[2] != null) {
  60964. defaultText = rawValue[2] + '';
  60965. }
  60966. setLabelStyle(rect, labelStatesModels, {
  60967. labelFetcher: seriesModel,
  60968. labelDataIndex: idx,
  60969. defaultOpacity: style.opacity,
  60970. defaultText: defaultText
  60971. });
  60972. rect.ensureState('emphasis').style = emphasisStyle;
  60973. rect.ensureState('blur').style = blurStyle;
  60974. rect.ensureState('select').style = selectStyle;
  60975. toggleHoverEmphasis(rect, focus, blurScope, emphasisDisabled);
  60976. rect.incremental = incremental; // PENDING
  60977. if (incremental) {
  60978. // Rect must use hover layer if it's incremental.
  60979. rect.states.emphasis.hoverLayer = true;
  60980. }
  60981. group.add(rect);
  60982. data.setItemGraphicEl(idx, rect);
  60983. if (this._progressiveEls) {
  60984. this._progressiveEls.push(rect);
  60985. }
  60986. }
  60987. };
  60988. HeatmapView.prototype._renderOnGeo = function (geo, seriesModel, visualMapModel, api) {
  60989. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  60990. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange; // if (!visualMapping) {
  60991. // throw new Error('Data range must have color visuals');
  60992. // }
  60993. var data = seriesModel.getData();
  60994. var hmLayer = this._hmLayer || this._hmLayer || new HeatmapLayer();
  60995. hmLayer.blurSize = seriesModel.get('blurSize');
  60996. hmLayer.pointSize = seriesModel.get('pointSize');
  60997. hmLayer.minOpacity = seriesModel.get('minOpacity');
  60998. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  60999. var rect = geo.getViewRect().clone();
  61000. var roamTransform = geo.getRoamTransform();
  61001. rect.applyTransform(roamTransform); // Clamp on viewport
  61002. var x = Math.max(rect.x, 0);
  61003. var y = Math.max(rect.y, 0);
  61004. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  61005. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  61006. var width = x2 - x;
  61007. var height = y2 - y;
  61008. var dims = [data.mapDimension('lng'), data.mapDimension('lat'), data.mapDimension('value')];
  61009. var points = data.mapArray(dims, function (lng, lat, value) {
  61010. var pt = geo.dataToPoint([lng, lat]);
  61011. pt[0] -= x;
  61012. pt[1] -= y;
  61013. pt.push(value);
  61014. return pt;
  61015. });
  61016. var dataExtent = visualMapModel.getExtent();
  61017. var isInRange = visualMapModel.type === 'visualMap.continuous' ? getIsInContinuousRange(dataExtent, visualMapModel.option.range) : getIsInPiecewiseRange(dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected);
  61018. hmLayer.update(points, width, height, inRangeVisuals.color.getNormalizer(), {
  61019. inRange: inRangeVisuals.color.getColorMapper(),
  61020. outOfRange: outOfRangeVisuals.color.getColorMapper()
  61021. }, isInRange);
  61022. var img = new ZRImage({
  61023. style: {
  61024. width: width,
  61025. height: height,
  61026. x: x,
  61027. y: y,
  61028. image: hmLayer.canvas
  61029. },
  61030. silent: true
  61031. });
  61032. this.group.add(img);
  61033. };
  61034. HeatmapView.type = 'heatmap';
  61035. return HeatmapView;
  61036. }(ChartView);
  61037. var HeatmapSeriesModel =
  61038. /** @class */
  61039. function (_super) {
  61040. __extends(HeatmapSeriesModel, _super);
  61041. function HeatmapSeriesModel() {
  61042. var _this = _super !== null && _super.apply(this, arguments) || this;
  61043. _this.type = HeatmapSeriesModel.type;
  61044. return _this;
  61045. }
  61046. HeatmapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  61047. return createSeriesData(null, this, {
  61048. generateCoord: 'value'
  61049. });
  61050. };
  61051. HeatmapSeriesModel.prototype.preventIncremental = function () {
  61052. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  61053. if (coordSysCreator && coordSysCreator.dimensions) {
  61054. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  61055. }
  61056. };
  61057. HeatmapSeriesModel.type = 'series.heatmap';
  61058. HeatmapSeriesModel.dependencies = ['grid', 'geo', 'calendar'];
  61059. HeatmapSeriesModel.defaultOption = {
  61060. coordinateSystem: 'cartesian2d',
  61061. // zlevel: 0,
  61062. z: 2,
  61063. // Cartesian coordinate system
  61064. // xAxisIndex: 0,
  61065. // yAxisIndex: 0,
  61066. // Geo coordinate system
  61067. geoIndex: 0,
  61068. blurSize: 30,
  61069. pointSize: 20,
  61070. maxOpacity: 1,
  61071. minOpacity: 0,
  61072. select: {
  61073. itemStyle: {
  61074. borderColor: '#212121'
  61075. }
  61076. }
  61077. };
  61078. return HeatmapSeriesModel;
  61079. }(SeriesModel);
  61080. function install$n(registers) {
  61081. registers.registerChartView(HeatmapView);
  61082. registers.registerSeriesModel(HeatmapSeriesModel);
  61083. }
  61084. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'borderWidth']; // index: +isHorizontal
  61085. var LAYOUT_ATTRS = [{
  61086. xy: 'x',
  61087. wh: 'width',
  61088. index: 0,
  61089. posDesc: ['left', 'right']
  61090. }, {
  61091. xy: 'y',
  61092. wh: 'height',
  61093. index: 1,
  61094. posDesc: ['top', 'bottom']
  61095. }];
  61096. var pathForLineWidth = new Circle();
  61097. var PictorialBarView =
  61098. /** @class */
  61099. function (_super) {
  61100. __extends(PictorialBarView, _super);
  61101. function PictorialBarView() {
  61102. var _this = _super !== null && _super.apply(this, arguments) || this;
  61103. _this.type = PictorialBarView.type;
  61104. return _this;
  61105. }
  61106. PictorialBarView.prototype.render = function (seriesModel, ecModel, api) {
  61107. var group = this.group;
  61108. var data = seriesModel.getData();
  61109. var oldData = this._data;
  61110. var cartesian = seriesModel.coordinateSystem;
  61111. var baseAxis = cartesian.getBaseAxis();
  61112. var isHorizontal = baseAxis.isHorizontal();
  61113. var coordSysRect = cartesian.master.getRect();
  61114. var opt = {
  61115. ecSize: {
  61116. width: api.getWidth(),
  61117. height: api.getHeight()
  61118. },
  61119. seriesModel: seriesModel,
  61120. coordSys: cartesian,
  61121. coordSysExtent: [[coordSysRect.x, coordSysRect.x + coordSysRect.width], [coordSysRect.y, coordSysRect.y + coordSysRect.height]],
  61122. isHorizontal: isHorizontal,
  61123. valueDim: LAYOUT_ATTRS[+isHorizontal],
  61124. categoryDim: LAYOUT_ATTRS[1 - +isHorizontal]
  61125. };
  61126. data.diff(oldData).add(function (dataIndex) {
  61127. if (!data.hasValue(dataIndex)) {
  61128. return;
  61129. }
  61130. var itemModel = getItemModel(data, dataIndex);
  61131. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  61132. var bar = createBar(data, opt, symbolMeta);
  61133. data.setItemGraphicEl(dataIndex, bar);
  61134. group.add(bar);
  61135. updateCommon$1(bar, opt, symbolMeta);
  61136. }).update(function (newIndex, oldIndex) {
  61137. var bar = oldData.getItemGraphicEl(oldIndex);
  61138. if (!data.hasValue(newIndex)) {
  61139. group.remove(bar);
  61140. return;
  61141. }
  61142. var itemModel = getItemModel(data, newIndex);
  61143. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  61144. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  61145. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  61146. group.remove(bar);
  61147. data.setItemGraphicEl(newIndex, null);
  61148. bar = null;
  61149. }
  61150. if (bar) {
  61151. updateBar(bar, opt, symbolMeta);
  61152. } else {
  61153. bar = createBar(data, opt, symbolMeta, true);
  61154. }
  61155. data.setItemGraphicEl(newIndex, bar);
  61156. bar.__pictorialSymbolMeta = symbolMeta; // Add back
  61157. group.add(bar);
  61158. updateCommon$1(bar, opt, symbolMeta);
  61159. }).remove(function (dataIndex) {
  61160. var bar = oldData.getItemGraphicEl(dataIndex);
  61161. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  61162. }).execute();
  61163. this._data = data;
  61164. return this.group;
  61165. };
  61166. PictorialBarView.prototype.remove = function (ecModel, api) {
  61167. var group = this.group;
  61168. var data = this._data;
  61169. if (ecModel.get('animation')) {
  61170. if (data) {
  61171. data.eachItemGraphicEl(function (bar) {
  61172. removeBar(data, getECData(bar).dataIndex, ecModel, bar);
  61173. });
  61174. }
  61175. } else {
  61176. group.removeAll();
  61177. }
  61178. };
  61179. PictorialBarView.type = 'pictorialBar';
  61180. return PictorialBarView;
  61181. }(ChartView); // Set or calculate default value about symbol, and calculate layout info.
  61182. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  61183. var layout = data.getItemLayout(dataIndex);
  61184. var symbolRepeat = itemModel.get('symbolRepeat');
  61185. var symbolClip = itemModel.get('symbolClip');
  61186. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  61187. var symbolRotate = itemModel.get('symbolRotate');
  61188. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  61189. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  61190. var isAnimationEnabled = itemModel.isAnimationEnabled();
  61191. var symbolMeta = {
  61192. dataIndex: dataIndex,
  61193. layout: layout,
  61194. itemModel: itemModel,
  61195. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  61196. style: data.getItemVisual(dataIndex, 'style'),
  61197. symbolClip: symbolClip,
  61198. symbolRepeat: symbolRepeat,
  61199. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  61200. symbolPatternSize: symbolPatternSize,
  61201. rotation: rotation,
  61202. animationModel: isAnimationEnabled ? itemModel : null,
  61203. hoverScale: isAnimationEnabled && itemModel.get(['emphasis', 'scale']),
  61204. z2: itemModel.getShallow('z', true) || 0
  61205. };
  61206. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  61207. prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength, symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta);
  61208. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  61209. var symbolSize = symbolMeta.symbolSize;
  61210. var symbolOffset = normalizeSymbolOffset(itemModel.get('symbolOffset'), symbolSize);
  61211. prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength, opt, symbolMeta);
  61212. return symbolMeta;
  61213. } // bar length can be negative.
  61214. function prepareBarLength(itemModel, symbolRepeat, layout, opt, outputSymbolMeta) {
  61215. var valueDim = opt.valueDim;
  61216. var symbolBoundingData = itemModel.get('symbolBoundingData');
  61217. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  61218. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  61219. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  61220. var boundingLength;
  61221. if (isArray(symbolBoundingData)) {
  61222. var symbolBoundingExtent = [convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx, convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx];
  61223. symbolBoundingExtent[1] < symbolBoundingExtent[0] && symbolBoundingExtent.reverse();
  61224. boundingLength = symbolBoundingExtent[pxSignIdx];
  61225. } else if (symbolBoundingData != null) {
  61226. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  61227. } else if (symbolRepeat) {
  61228. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  61229. } else {
  61230. boundingLength = layout[valueDim.wh];
  61231. }
  61232. outputSymbolMeta.boundingLength = boundingLength;
  61233. if (symbolRepeat) {
  61234. outputSymbolMeta.repeatCutLength = layout[valueDim.wh];
  61235. } // if 'pxSign' means sign of pixel, it can't be zero, or symbolScale will be zero
  61236. // and when borderWidth be settled, the actual linewidth will be NaN
  61237. outputSymbolMeta.pxSign = boundingLength > 0 ? 1 : -1;
  61238. }
  61239. function convertToCoordOnAxis(axis, value) {
  61240. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  61241. } // Support ['100%', '100%']
  61242. function prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength, pxSign, symbolPatternSize, opt, outputSymbolMeta) {
  61243. var valueDim = opt.valueDim;
  61244. var categoryDim = opt.categoryDim;
  61245. var categorySize = Math.abs(layout[categoryDim.wh]);
  61246. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  61247. var parsedSymbolSize;
  61248. if (isArray(symbolSize)) {
  61249. parsedSymbolSize = symbolSize.slice();
  61250. } else {
  61251. if (symbolSize == null) {
  61252. // will parse to number below
  61253. parsedSymbolSize = ['100%', '100%'];
  61254. } else {
  61255. parsedSymbolSize = [symbolSize, symbolSize];
  61256. }
  61257. } // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  61258. // to complicated to calculate real percent value if considering scaled lineWidth.
  61259. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  61260. // which can be tolerated in pictorial chart.
  61261. parsedSymbolSize[categoryDim.index] = parsePercent$1(parsedSymbolSize[categoryDim.index], categorySize);
  61262. parsedSymbolSize[valueDim.index] = parsePercent$1(parsedSymbolSize[valueDim.index], symbolRepeat ? categorySize : Math.abs(boundingLength));
  61263. outputSymbolMeta.symbolSize = parsedSymbolSize; // If x or y is less than zero, show reversed shape.
  61264. var symbolScale = outputSymbolMeta.symbolScale = [parsedSymbolSize[0] / symbolPatternSize, parsedSymbolSize[1] / symbolPatternSize]; // Follow convention, 'right' and 'top' is the normal scale.
  61265. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  61266. }
  61267. function prepareLineWidth(itemModel, symbolScale, rotation, opt, outputSymbolMeta) {
  61268. // In symbols are drawn with scale, so do not need to care about the case that width
  61269. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  61270. // be calculated.
  61271. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  61272. if (valueLineWidth) {
  61273. pathForLineWidth.attr({
  61274. scaleX: symbolScale[0],
  61275. scaleY: symbolScale[1],
  61276. rotation: rotation
  61277. });
  61278. pathForLineWidth.updateTransform();
  61279. valueLineWidth /= pathForLineWidth.getLineScale();
  61280. valueLineWidth *= symbolScale[opt.valueDim.index];
  61281. }
  61282. outputSymbolMeta.valueLineWidth = valueLineWidth || 0;
  61283. }
  61284. function prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, outputSymbolMeta) {
  61285. var categoryDim = opt.categoryDim;
  61286. var valueDim = opt.valueDim;
  61287. var pxSign = outputSymbolMeta.pxSign;
  61288. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  61289. var pathLen = unitLength; // Note: rotation will not effect the layout of symbols, because user may
  61290. // want symbols to rotate on its center, which should not be translated
  61291. // when rotating.
  61292. if (symbolRepeat) {
  61293. var absBoundingLength = Math.abs(boundingLength);
  61294. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  61295. var hasEndGap = false;
  61296. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  61297. hasEndGap = true;
  61298. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  61299. }
  61300. var symbolMarginNumeric = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  61301. var uLenWithMargin = Math.max(unitLength + symbolMarginNumeric * 2, 0); // When symbol margin is less than 0, margin at both ends will be subtracted
  61302. // to ensure that all of the symbols will not be overflow the given area.
  61303. var endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Both final repeatTimes and final symbolMarginNumeric area calculated based on
  61304. // boundingLength.
  61305. var repeatSpecified = isNumeric(symbolRepeat);
  61306. var repeatTimes = repeatSpecified ? symbolRepeat : toIntTimes((absBoundingLength + endFix) / uLenWithMargin); // Adjust calculate margin, to ensure each symbol is displayed
  61307. // entirely in the given layout area.
  61308. var mDiff = absBoundingLength - repeatTimes * unitLength;
  61309. symbolMarginNumeric = mDiff / 2 / (hasEndGap ? repeatTimes : Math.max(repeatTimes - 1, 1));
  61310. uLenWithMargin = unitLength + symbolMarginNumeric * 2;
  61311. endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Update repeatTimes when not all symbol will be shown.
  61312. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  61313. repeatTimes = repeatCutLength ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin) : 0;
  61314. }
  61315. pathLen = repeatTimes * uLenWithMargin - endFix;
  61316. outputSymbolMeta.repeatTimes = repeatTimes;
  61317. outputSymbolMeta.symbolMargin = symbolMarginNumeric;
  61318. }
  61319. var sizeFix = pxSign * (pathLen / 2);
  61320. var pathPosition = outputSymbolMeta.pathPosition = [];
  61321. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  61322. pathPosition[valueDim.index] = symbolPosition === 'start' ? sizeFix : symbolPosition === 'end' ? boundingLength - sizeFix : boundingLength / 2; // 'center'
  61323. if (symbolOffset) {
  61324. pathPosition[0] += symbolOffset[0];
  61325. pathPosition[1] += symbolOffset[1];
  61326. }
  61327. var bundlePosition = outputSymbolMeta.bundlePosition = [];
  61328. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  61329. bundlePosition[valueDim.index] = layout[valueDim.xy];
  61330. var barRectShape = outputSymbolMeta.barRectShape = extend({}, layout);
  61331. barRectShape[valueDim.wh] = pxSign * Math.max(Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix));
  61332. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  61333. var clipShape = outputSymbolMeta.clipShape = {}; // Consider that symbol may be overflow layout rect.
  61334. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  61335. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  61336. clipShape[valueDim.xy] = 0;
  61337. clipShape[valueDim.wh] = layout[valueDim.wh];
  61338. }
  61339. function createPath(symbolMeta) {
  61340. var symbolPatternSize = symbolMeta.symbolPatternSize;
  61341. var path = createSymbol( // Consider texture img, make a big size.
  61342. symbolMeta.symbolType, -symbolPatternSize / 2, -symbolPatternSize / 2, symbolPatternSize, symbolPatternSize);
  61343. path.attr({
  61344. culling: true
  61345. });
  61346. path.type !== 'image' && path.setStyle({
  61347. strokeNoScale: true
  61348. });
  61349. return path;
  61350. }
  61351. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  61352. var bundle = bar.__pictorialBundle;
  61353. var symbolSize = symbolMeta.symbolSize;
  61354. var valueLineWidth = symbolMeta.valueLineWidth;
  61355. var pathPosition = symbolMeta.pathPosition;
  61356. var valueDim = opt.valueDim;
  61357. var repeatTimes = symbolMeta.repeatTimes || 0;
  61358. var index = 0;
  61359. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  61360. eachPath(bar, function (path) {
  61361. path.__pictorialAnimationIndex = index;
  61362. path.__pictorialRepeatTimes = repeatTimes;
  61363. if (index < repeatTimes) {
  61364. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  61365. } else {
  61366. updateAttr(path, null, {
  61367. scaleX: 0,
  61368. scaleY: 0
  61369. }, symbolMeta, isUpdate, function () {
  61370. bundle.remove(path);
  61371. });
  61372. } // updateHoverAnimation(path, symbolMeta);
  61373. index++;
  61374. });
  61375. for (; index < repeatTimes; index++) {
  61376. var path = createPath(symbolMeta);
  61377. path.__pictorialAnimationIndex = index;
  61378. path.__pictorialRepeatTimes = repeatTimes;
  61379. bundle.add(path);
  61380. var target = makeTarget(index);
  61381. updateAttr(path, {
  61382. x: target.x,
  61383. y: target.y,
  61384. scaleX: 0,
  61385. scaleY: 0
  61386. }, {
  61387. scaleX: target.scaleX,
  61388. scaleY: target.scaleY,
  61389. rotation: target.rotation
  61390. }, symbolMeta, isUpdate);
  61391. }
  61392. function makeTarget(index) {
  61393. var position = pathPosition.slice(); // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  61394. // Otherwise: i = index;
  61395. var pxSign = symbolMeta.pxSign;
  61396. var i = index;
  61397. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  61398. i = repeatTimes - 1 - index;
  61399. }
  61400. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  61401. return {
  61402. x: position[0],
  61403. y: position[1],
  61404. scaleX: symbolMeta.symbolScale[0],
  61405. scaleY: symbolMeta.symbolScale[1],
  61406. rotation: symbolMeta.rotation
  61407. };
  61408. }
  61409. }
  61410. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  61411. var bundle = bar.__pictorialBundle;
  61412. var mainPath = bar.__pictorialMainPath;
  61413. if (!mainPath) {
  61414. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  61415. bundle.add(mainPath);
  61416. updateAttr(mainPath, {
  61417. x: symbolMeta.pathPosition[0],
  61418. y: symbolMeta.pathPosition[1],
  61419. scaleX: 0,
  61420. scaleY: 0,
  61421. rotation: symbolMeta.rotation
  61422. }, {
  61423. scaleX: symbolMeta.symbolScale[0],
  61424. scaleY: symbolMeta.symbolScale[1]
  61425. }, symbolMeta, isUpdate);
  61426. } else {
  61427. updateAttr(mainPath, null, {
  61428. x: symbolMeta.pathPosition[0],
  61429. y: symbolMeta.pathPosition[1],
  61430. scaleX: symbolMeta.symbolScale[0],
  61431. scaleY: symbolMeta.symbolScale[1],
  61432. rotation: symbolMeta.rotation
  61433. }, symbolMeta, isUpdate);
  61434. }
  61435. } // bar rect is used for label.
  61436. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  61437. var rectShape = extend({}, symbolMeta.barRectShape);
  61438. var barRect = bar.__pictorialBarRect;
  61439. if (!barRect) {
  61440. barRect = bar.__pictorialBarRect = new Rect({
  61441. z2: 2,
  61442. shape: rectShape,
  61443. silent: true,
  61444. style: {
  61445. stroke: 'transparent',
  61446. fill: 'transparent',
  61447. lineWidth: 0
  61448. }
  61449. });
  61450. barRect.disableMorphing = true;
  61451. bar.add(barRect);
  61452. } else {
  61453. updateAttr(barRect, null, {
  61454. shape: rectShape
  61455. }, symbolMeta, isUpdate);
  61456. }
  61457. }
  61458. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  61459. // If not clip, symbol will be remove and rebuilt.
  61460. if (symbolMeta.symbolClip) {
  61461. var clipPath = bar.__pictorialClipPath;
  61462. var clipShape = extend({}, symbolMeta.clipShape);
  61463. var valueDim = opt.valueDim;
  61464. var animationModel = symbolMeta.animationModel;
  61465. var dataIndex = symbolMeta.dataIndex;
  61466. if (clipPath) {
  61467. updateProps(clipPath, {
  61468. shape: clipShape
  61469. }, animationModel, dataIndex);
  61470. } else {
  61471. clipShape[valueDim.wh] = 0;
  61472. clipPath = new Rect({
  61473. shape: clipShape
  61474. });
  61475. bar.__pictorialBundle.setClipPath(clipPath);
  61476. bar.__pictorialClipPath = clipPath;
  61477. var target = {};
  61478. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  61479. graphic[isUpdate ? 'updateProps' : 'initProps'](clipPath, {
  61480. shape: target
  61481. }, animationModel, dataIndex);
  61482. }
  61483. }
  61484. }
  61485. function getItemModel(data, dataIndex) {
  61486. var itemModel = data.getItemModel(dataIndex);
  61487. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  61488. itemModel.isAnimationEnabled = isAnimationEnabled;
  61489. return itemModel;
  61490. }
  61491. function getAnimationDelayParams(path) {
  61492. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  61493. return {
  61494. index: path.__pictorialAnimationIndex,
  61495. count: path.__pictorialRepeatTimes
  61496. };
  61497. }
  61498. function isAnimationEnabled() {
  61499. // `animation` prop can be set on itemModel in pictorial bar chart.
  61500. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  61501. }
  61502. function createBar(data, opt, symbolMeta, isUpdate) {
  61503. // bar is the main element for each data.
  61504. var bar = new Group(); // bundle is used for location and clip.
  61505. var bundle = new Group();
  61506. bar.add(bundle);
  61507. bar.__pictorialBundle = bundle;
  61508. bundle.x = symbolMeta.bundlePosition[0];
  61509. bundle.y = symbolMeta.bundlePosition[1];
  61510. if (symbolMeta.symbolRepeat) {
  61511. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  61512. } else {
  61513. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  61514. }
  61515. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  61516. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  61517. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  61518. bar.__pictorialSymbolMeta = symbolMeta;
  61519. return bar;
  61520. }
  61521. function updateBar(bar, opt, symbolMeta) {
  61522. var animationModel = symbolMeta.animationModel;
  61523. var dataIndex = symbolMeta.dataIndex;
  61524. var bundle = bar.__pictorialBundle;
  61525. updateProps(bundle, {
  61526. x: symbolMeta.bundlePosition[0],
  61527. y: symbolMeta.bundlePosition[1]
  61528. }, animationModel, dataIndex);
  61529. if (symbolMeta.symbolRepeat) {
  61530. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  61531. } else {
  61532. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  61533. }
  61534. createOrUpdateBarRect(bar, symbolMeta, true);
  61535. createOrUpdateClip(bar, opt, symbolMeta, true);
  61536. }
  61537. function removeBar(data, dataIndex, animationModel, bar) {
  61538. // Not show text when animating
  61539. var labelRect = bar.__pictorialBarRect;
  61540. labelRect && labelRect.removeTextContent();
  61541. var paths = [];
  61542. eachPath(bar, function (path) {
  61543. paths.push(path);
  61544. });
  61545. bar.__pictorialMainPath && paths.push(bar.__pictorialMainPath); // I do not find proper remove animation for clip yet.
  61546. bar.__pictorialClipPath && (animationModel = null);
  61547. each(paths, function (path) {
  61548. removeElement(path, {
  61549. scaleX: 0,
  61550. scaleY: 0
  61551. }, animationModel, dataIndex, function () {
  61552. bar.parent && bar.parent.remove(bar);
  61553. });
  61554. });
  61555. data.setItemGraphicEl(dataIndex, null);
  61556. }
  61557. function getShapeStr(data, symbolMeta) {
  61558. return [data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none', !!symbolMeta.symbolRepeat, !!symbolMeta.symbolClip].join(':');
  61559. }
  61560. function eachPath(bar, cb, context) {
  61561. // Do not use Group#eachChild, because it do not support remove.
  61562. each(bar.__pictorialBundle.children(), function (el) {
  61563. el !== bar.__pictorialBarRect && cb.call(context, el);
  61564. });
  61565. }
  61566. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  61567. immediateAttrs && el.attr(immediateAttrs); // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  61568. if (symbolMeta.symbolClip && !isUpdate) {
  61569. animationAttrs && el.attr(animationAttrs);
  61570. } else {
  61571. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb);
  61572. }
  61573. }
  61574. function updateCommon$1(bar, opt, symbolMeta) {
  61575. var dataIndex = symbolMeta.dataIndex;
  61576. var itemModel = symbolMeta.itemModel; // Color must be excluded.
  61577. // Because symbol provide setColor individually to set fill and stroke
  61578. var emphasisModel = itemModel.getModel('emphasis');
  61579. var emphasisStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  61580. var blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  61581. var selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  61582. var cursorStyle = itemModel.getShallow('cursor');
  61583. var focus = emphasisModel.get('focus');
  61584. var blurScope = emphasisModel.get('blurScope');
  61585. var hoverScale = emphasisModel.get('scale');
  61586. eachPath(bar, function (path) {
  61587. if (path instanceof ZRImage) {
  61588. var pathStyle = path.style;
  61589. path.useStyle(extend({
  61590. // TODO other properties like dx, dy ?
  61591. image: pathStyle.image,
  61592. x: pathStyle.x,
  61593. y: pathStyle.y,
  61594. width: pathStyle.width,
  61595. height: pathStyle.height
  61596. }, symbolMeta.style));
  61597. } else {
  61598. path.useStyle(symbolMeta.style);
  61599. }
  61600. var emphasisState = path.ensureState('emphasis');
  61601. emphasisState.style = emphasisStyle;
  61602. if (hoverScale) {
  61603. // NOTE: Must after scale is set after updateAttr
  61604. emphasisState.scaleX = path.scaleX * 1.1;
  61605. emphasisState.scaleY = path.scaleY * 1.1;
  61606. }
  61607. path.ensureState('blur').style = blurStyle;
  61608. path.ensureState('select').style = selectStyle;
  61609. cursorStyle && (path.cursor = cursorStyle);
  61610. path.z2 = symbolMeta.z2;
  61611. });
  61612. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  61613. var barRect = bar.__pictorialBarRect;
  61614. setLabelStyle(barRect, getLabelStatesModels(itemModel), {
  61615. labelFetcher: opt.seriesModel,
  61616. labelDataIndex: dataIndex,
  61617. defaultText: getDefaultLabel(opt.seriesModel.getData(), dataIndex),
  61618. inheritColor: symbolMeta.style.fill,
  61619. defaultOpacity: symbolMeta.style.opacity,
  61620. defaultOutsidePosition: barPositionOutside
  61621. });
  61622. toggleHoverEmphasis(bar, focus, blurScope, emphasisModel.get('disabled'));
  61623. }
  61624. function toIntTimes(times) {
  61625. var roundedTimes = Math.round(times); // Escapse accurate error
  61626. return Math.abs(times - roundedTimes) < 1e-4 ? roundedTimes : Math.ceil(times);
  61627. }
  61628. var PictorialBarSeriesModel =
  61629. /** @class */
  61630. function (_super) {
  61631. __extends(PictorialBarSeriesModel, _super);
  61632. function PictorialBarSeriesModel() {
  61633. var _this = _super !== null && _super.apply(this, arguments) || this;
  61634. _this.type = PictorialBarSeriesModel.type;
  61635. _this.hasSymbolVisual = true;
  61636. _this.defaultSymbol = 'roundRect';
  61637. return _this;
  61638. }
  61639. PictorialBarSeriesModel.prototype.getInitialData = function (option) {
  61640. // Disable stack.
  61641. option.stack = null;
  61642. return _super.prototype.getInitialData.apply(this, arguments);
  61643. };
  61644. PictorialBarSeriesModel.type = 'series.pictorialBar';
  61645. PictorialBarSeriesModel.dependencies = ['grid'];
  61646. PictorialBarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  61647. symbol: 'circle',
  61648. symbolSize: null,
  61649. symbolRotate: null,
  61650. symbolPosition: null,
  61651. symbolOffset: null,
  61652. symbolMargin: null,
  61653. symbolRepeat: false,
  61654. symbolRepeatDirection: 'end',
  61655. symbolClip: false,
  61656. symbolBoundingData: null,
  61657. symbolPatternSize: 400,
  61658. barGap: '-100%',
  61659. // z can be set in data item, which is z2 actually.
  61660. // Disable progressive
  61661. progressive: 0,
  61662. emphasis: {
  61663. // By default pictorialBar do not hover scale. Hover scale is not suitable
  61664. // for the case that both has foreground and background.
  61665. scale: false
  61666. },
  61667. select: {
  61668. itemStyle: {
  61669. borderColor: '#212121'
  61670. }
  61671. }
  61672. });
  61673. return PictorialBarSeriesModel;
  61674. }(BaseBarSeriesModel);
  61675. function install$o(registers) {
  61676. registers.registerChartView(PictorialBarView);
  61677. registers.registerSeriesModel(PictorialBarSeriesModel);
  61678. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'pictorialBar')); // Do layout after other overall layout, which can prepare some information.
  61679. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('pictorialBar'));
  61680. }
  61681. var ThemeRiverView =
  61682. /** @class */
  61683. function (_super) {
  61684. __extends(ThemeRiverView, _super);
  61685. function ThemeRiverView() {
  61686. var _this = _super !== null && _super.apply(this, arguments) || this;
  61687. _this.type = ThemeRiverView.type;
  61688. _this._layers = [];
  61689. return _this;
  61690. }
  61691. ThemeRiverView.prototype.render = function (seriesModel, ecModel, api) {
  61692. var data = seriesModel.getData();
  61693. var self = this;
  61694. var group = this.group;
  61695. var layersSeries = seriesModel.getLayerSeries();
  61696. var layoutInfo = data.getLayout('layoutInfo');
  61697. var rect = layoutInfo.rect;
  61698. var boundaryGap = layoutInfo.boundaryGap;
  61699. group.x = 0;
  61700. group.y = rect.y + boundaryGap[0];
  61701. function keyGetter(item) {
  61702. return item.name;
  61703. }
  61704. var dataDiffer = new DataDiffer(this._layersSeries || [], layersSeries, keyGetter, keyGetter);
  61705. var newLayersGroups = [];
  61706. dataDiffer.add(bind(process, this, 'add')).update(bind(process, this, 'update')).remove(bind(process, this, 'remove')).execute();
  61707. function process(status, idx, oldIdx) {
  61708. var oldLayersGroups = self._layers;
  61709. if (status === 'remove') {
  61710. group.remove(oldLayersGroups[idx]);
  61711. return;
  61712. }
  61713. var points0 = [];
  61714. var points1 = [];
  61715. var style;
  61716. var indices = layersSeries[idx].indices;
  61717. var j = 0;
  61718. for (; j < indices.length; j++) {
  61719. var layout = data.getItemLayout(indices[j]);
  61720. var x = layout.x;
  61721. var y0 = layout.y0;
  61722. var y = layout.y;
  61723. points0.push(x, y0);
  61724. points1.push(x, y0 + y);
  61725. style = data.getItemVisual(indices[j], 'style');
  61726. }
  61727. var polygon;
  61728. var textLayout = data.getItemLayout(indices[0]);
  61729. var labelModel = seriesModel.getModel('label');
  61730. var margin = labelModel.get('margin');
  61731. var emphasisModel = seriesModel.getModel('emphasis');
  61732. if (status === 'add') {
  61733. var layerGroup = newLayersGroups[idx] = new Group();
  61734. polygon = new ECPolygon({
  61735. shape: {
  61736. points: points0,
  61737. stackedOnPoints: points1,
  61738. smooth: 0.4,
  61739. stackedOnSmooth: 0.4,
  61740. smoothConstraint: false
  61741. },
  61742. z2: 0
  61743. });
  61744. layerGroup.add(polygon);
  61745. group.add(layerGroup);
  61746. if (seriesModel.isAnimationEnabled()) {
  61747. polygon.setClipPath(createGridClipShape$2(polygon.getBoundingRect(), seriesModel, function () {
  61748. polygon.removeClipPath();
  61749. }));
  61750. }
  61751. } else {
  61752. var layerGroup = oldLayersGroups[oldIdx];
  61753. polygon = layerGroup.childAt(0);
  61754. group.add(layerGroup);
  61755. newLayersGroups[idx] = layerGroup;
  61756. updateProps(polygon, {
  61757. shape: {
  61758. points: points0,
  61759. stackedOnPoints: points1
  61760. }
  61761. }, seriesModel);
  61762. saveOldStyle(polygon);
  61763. }
  61764. setLabelStyle(polygon, getLabelStatesModels(seriesModel), {
  61765. labelDataIndex: indices[j - 1],
  61766. defaultText: data.getName(indices[j - 1]),
  61767. inheritColor: style.fill
  61768. }, {
  61769. normal: {
  61770. verticalAlign: 'middle' // align: 'right'
  61771. }
  61772. });
  61773. polygon.setTextConfig({
  61774. position: null,
  61775. local: true
  61776. });
  61777. var labelEl = polygon.getTextContent(); // TODO More label position options.
  61778. if (labelEl) {
  61779. labelEl.x = textLayout.x - margin;
  61780. labelEl.y = textLayout.y0 + textLayout.y / 2;
  61781. }
  61782. polygon.useStyle(style);
  61783. data.setItemGraphicEl(idx, polygon);
  61784. setStatesStylesFromModel(polygon, seriesModel);
  61785. toggleHoverEmphasis(polygon, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  61786. }
  61787. this._layersSeries = layersSeries;
  61788. this._layers = newLayersGroups;
  61789. };
  61790. ThemeRiverView.type = 'themeRiver';
  61791. return ThemeRiverView;
  61792. }(ChartView);
  61793. function createGridClipShape$2(rect, seriesModel, cb) {
  61794. var rectEl = new Rect({
  61795. shape: {
  61796. x: rect.x - 10,
  61797. y: rect.y - 10,
  61798. width: 0,
  61799. height: rect.height + 20
  61800. }
  61801. });
  61802. initProps(rectEl, {
  61803. shape: {
  61804. x: rect.x - 50,
  61805. width: rect.width + 100,
  61806. height: rect.height + 20
  61807. }
  61808. }, seriesModel, cb);
  61809. return rectEl;
  61810. }
  61811. var DATA_NAME_INDEX = 2;
  61812. var ThemeRiverSeriesModel =
  61813. /** @class */
  61814. function (_super) {
  61815. __extends(ThemeRiverSeriesModel, _super);
  61816. function ThemeRiverSeriesModel() {
  61817. var _this = _super !== null && _super.apply(this, arguments) || this;
  61818. _this.type = ThemeRiverSeriesModel.type;
  61819. return _this;
  61820. }
  61821. /**
  61822. * @override
  61823. */
  61824. ThemeRiverSeriesModel.prototype.init = function (option) {
  61825. // eslint-disable-next-line
  61826. _super.prototype.init.apply(this, arguments); // Put this function here is for the sake of consistency of code style.
  61827. // Enable legend selection for each data item
  61828. // Use a function instead of direct access because data reference may changed
  61829. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  61830. };
  61831. /**
  61832. * If there is no value of a certain point in the time for some event,set it value to 0.
  61833. *
  61834. * @param {Array} data initial data in the option
  61835. * @return {Array}
  61836. */
  61837. ThemeRiverSeriesModel.prototype.fixData = function (data) {
  61838. var rawDataLength = data.length;
  61839. /**
  61840. * Make sure every layer data get the same keys.
  61841. * The value index tells which layer has visited.
  61842. * {
  61843. * 2014/01/01: -1
  61844. * }
  61845. */
  61846. var timeValueKeys = {}; // grouped data by name
  61847. var groupResult = groupData(data, function (item) {
  61848. if (!timeValueKeys.hasOwnProperty(item[0] + '')) {
  61849. timeValueKeys[item[0] + ''] = -1;
  61850. }
  61851. return item[2];
  61852. });
  61853. var layerData = [];
  61854. groupResult.buckets.each(function (items, key) {
  61855. layerData.push({
  61856. name: key,
  61857. dataList: items
  61858. });
  61859. });
  61860. var layerNum = layerData.length;
  61861. for (var k = 0; k < layerNum; ++k) {
  61862. var name_1 = layerData[k].name;
  61863. for (var j = 0; j < layerData[k].dataList.length; ++j) {
  61864. var timeValue = layerData[k].dataList[j][0] + '';
  61865. timeValueKeys[timeValue] = k;
  61866. }
  61867. for (var timeValue in timeValueKeys) {
  61868. if (timeValueKeys.hasOwnProperty(timeValue) && timeValueKeys[timeValue] !== k) {
  61869. timeValueKeys[timeValue] = k;
  61870. data[rawDataLength] = [timeValue, 0, name_1];
  61871. rawDataLength++;
  61872. }
  61873. }
  61874. }
  61875. return data;
  61876. };
  61877. /**
  61878. * @override
  61879. * @param option the initial option that user gave
  61880. * @param ecModel the model object for themeRiver option
  61881. */
  61882. ThemeRiverSeriesModel.prototype.getInitialData = function (option, ecModel) {
  61883. var singleAxisModel = this.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  61884. var axisType = singleAxisModel.get('type'); // filter the data item with the value of label is undefined
  61885. var filterData = filter(option.data, function (dataItem) {
  61886. return dataItem[2] !== undefined;
  61887. }); // ??? TODO design a stage to transfer data for themeRiver and lines?
  61888. var data = this.fixData(filterData || []);
  61889. var nameList = [];
  61890. var nameMap = this.nameMap = createHashMap();
  61891. var count = 0;
  61892. for (var i = 0; i < data.length; ++i) {
  61893. nameList.push(data[i][DATA_NAME_INDEX]);
  61894. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  61895. nameMap.set(data[i][DATA_NAME_INDEX], count);
  61896. count++;
  61897. }
  61898. }
  61899. var dimensions = prepareSeriesDataSchema(data, {
  61900. coordDimensions: ['single'],
  61901. dimensionsDefine: [{
  61902. name: 'time',
  61903. type: getDimensionTypeByAxis(axisType)
  61904. }, {
  61905. name: 'value',
  61906. type: 'float'
  61907. }, {
  61908. name: 'name',
  61909. type: 'ordinal'
  61910. }],
  61911. encodeDefine: {
  61912. single: 0,
  61913. value: 1,
  61914. itemName: 2
  61915. }
  61916. }).dimensions;
  61917. var list = new SeriesData(dimensions, this);
  61918. list.initData(data);
  61919. return list;
  61920. };
  61921. /**
  61922. * The raw data is divided into multiple layers and each layer
  61923. * has same name.
  61924. */
  61925. ThemeRiverSeriesModel.prototype.getLayerSeries = function () {
  61926. var data = this.getData();
  61927. var lenCount = data.count();
  61928. var indexArr = [];
  61929. for (var i = 0; i < lenCount; ++i) {
  61930. indexArr[i] = i;
  61931. }
  61932. var timeDim = data.mapDimension('single'); // data group by name
  61933. var groupResult = groupData(indexArr, function (index) {
  61934. return data.get('name', index);
  61935. });
  61936. var layerSeries = [];
  61937. groupResult.buckets.each(function (items, key) {
  61938. items.sort(function (index1, index2) {
  61939. return data.get(timeDim, index1) - data.get(timeDim, index2);
  61940. });
  61941. layerSeries.push({
  61942. name: key,
  61943. indices: items
  61944. });
  61945. });
  61946. return layerSeries;
  61947. };
  61948. /**
  61949. * Get data indices for show tooltip content
  61950. */
  61951. ThemeRiverSeriesModel.prototype.getAxisTooltipData = function (dim, value, baseAxis) {
  61952. if (!isArray(dim)) {
  61953. dim = dim ? [dim] : [];
  61954. }
  61955. var data = this.getData();
  61956. var layerSeries = this.getLayerSeries();
  61957. var indices = [];
  61958. var layerNum = layerSeries.length;
  61959. var nestestValue;
  61960. for (var i = 0; i < layerNum; ++i) {
  61961. var minDist = Number.MAX_VALUE;
  61962. var nearestIdx = -1;
  61963. var pointNum = layerSeries[i].indices.length;
  61964. for (var j = 0; j < pointNum; ++j) {
  61965. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  61966. var dist = Math.abs(theValue - value);
  61967. if (dist <= minDist) {
  61968. nestestValue = theValue;
  61969. minDist = dist;
  61970. nearestIdx = layerSeries[i].indices[j];
  61971. }
  61972. }
  61973. indices.push(nearestIdx);
  61974. }
  61975. return {
  61976. dataIndices: indices,
  61977. nestestValue: nestestValue
  61978. };
  61979. };
  61980. ThemeRiverSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  61981. var data = this.getData();
  61982. var name = data.getName(dataIndex);
  61983. var value = data.get(data.mapDimension('value'), dataIndex);
  61984. return createTooltipMarkup('nameValue', {
  61985. name: name,
  61986. value: value
  61987. });
  61988. };
  61989. ThemeRiverSeriesModel.type = 'series.themeRiver';
  61990. ThemeRiverSeriesModel.dependencies = ['singleAxis'];
  61991. ThemeRiverSeriesModel.defaultOption = {
  61992. // zlevel: 0,
  61993. z: 2,
  61994. colorBy: 'data',
  61995. coordinateSystem: 'singleAxis',
  61996. // gap in axis's orthogonal orientation
  61997. boundaryGap: ['10%', '10%'],
  61998. // legendHoverLink: true,
  61999. singleAxisIndex: 0,
  62000. animationEasing: 'linear',
  62001. label: {
  62002. margin: 4,
  62003. show: true,
  62004. position: 'left',
  62005. fontSize: 11
  62006. },
  62007. emphasis: {
  62008. label: {
  62009. show: true
  62010. }
  62011. }
  62012. };
  62013. return ThemeRiverSeriesModel;
  62014. }(SeriesModel);
  62015. function themeRiverLayout(ecModel, api) {
  62016. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  62017. var data = seriesModel.getData();
  62018. var single = seriesModel.coordinateSystem;
  62019. var layoutInfo = {}; // use the axis boundingRect for view
  62020. var rect = single.getRect();
  62021. layoutInfo.rect = rect;
  62022. var boundaryGap = seriesModel.get('boundaryGap');
  62023. var axis = single.getAxis();
  62024. layoutInfo.boundaryGap = boundaryGap;
  62025. if (axis.orient === 'horizontal') {
  62026. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  62027. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  62028. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  62029. doThemeRiverLayout(data, seriesModel, height);
  62030. } else {
  62031. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  62032. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  62033. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  62034. doThemeRiverLayout(data, seriesModel, width);
  62035. }
  62036. data.setLayout('layoutInfo', layoutInfo);
  62037. });
  62038. }
  62039. /**
  62040. * The layout information about themeriver
  62041. *
  62042. * @param data data in the series
  62043. * @param seriesModel the model object of themeRiver series
  62044. * @param height value used to compute every series height
  62045. */
  62046. function doThemeRiverLayout(data, seriesModel, height) {
  62047. if (!data.count()) {
  62048. return;
  62049. }
  62050. var coordSys = seriesModel.coordinateSystem; // the data in each layer are organized into a series.
  62051. var layerSeries = seriesModel.getLayerSeries(); // the points in each layer.
  62052. var timeDim = data.mapDimension('single');
  62053. var valueDim = data.mapDimension('value');
  62054. var layerPoints = map(layerSeries, function (singleLayer) {
  62055. return map(singleLayer.indices, function (idx) {
  62056. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  62057. pt[1] = data.get(valueDim, idx);
  62058. return pt;
  62059. });
  62060. });
  62061. var base = computeBaseline(layerPoints);
  62062. var baseLine = base.y0;
  62063. var ky = height / base.max; // set layout information for each item.
  62064. var n = layerSeries.length;
  62065. var m = layerSeries[0].indices.length;
  62066. var baseY0;
  62067. for (var j = 0; j < m; ++j) {
  62068. baseY0 = baseLine[j] * ky;
  62069. data.setItemLayout(layerSeries[0].indices[j], {
  62070. layerIndex: 0,
  62071. x: layerPoints[0][j][0],
  62072. y0: baseY0,
  62073. y: layerPoints[0][j][1] * ky
  62074. });
  62075. for (var i = 1; i < n; ++i) {
  62076. baseY0 += layerPoints[i - 1][j][1] * ky;
  62077. data.setItemLayout(layerSeries[i].indices[j], {
  62078. layerIndex: i,
  62079. x: layerPoints[i][j][0],
  62080. y0: baseY0,
  62081. y: layerPoints[i][j][1] * ky
  62082. });
  62083. }
  62084. }
  62085. }
  62086. /**
  62087. * Compute the baseLine of the rawdata
  62088. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  62089. *
  62090. * @param data the points in each layer
  62091. */
  62092. function computeBaseline(data) {
  62093. var layerNum = data.length;
  62094. var pointNum = data[0].length;
  62095. var sums = [];
  62096. var y0 = [];
  62097. var max = 0;
  62098. for (var i = 0; i < pointNum; ++i) {
  62099. var temp = 0;
  62100. for (var j = 0; j < layerNum; ++j) {
  62101. temp += data[j][i][1];
  62102. }
  62103. if (temp > max) {
  62104. max = temp;
  62105. }
  62106. sums.push(temp);
  62107. }
  62108. for (var k = 0; k < pointNum; ++k) {
  62109. y0[k] = (max - sums[k]) / 2;
  62110. }
  62111. max = 0;
  62112. for (var l = 0; l < pointNum; ++l) {
  62113. var sum = sums[l] + y0[l];
  62114. if (sum > max) {
  62115. max = sum;
  62116. }
  62117. }
  62118. return {
  62119. y0: y0,
  62120. max: max
  62121. };
  62122. }
  62123. function install$p(registers) {
  62124. registers.registerChartView(ThemeRiverView);
  62125. registers.registerSeriesModel(ThemeRiverSeriesModel);
  62126. registers.registerLayout(themeRiverLayout);
  62127. registers.registerProcessor(dataFilter('themeRiver'));
  62128. }
  62129. var DEFAULT_SECTOR_Z = 2;
  62130. var DEFAULT_TEXT_Z = 4;
  62131. /**
  62132. * Sunburstce of Sunburst including Sector, Label, LabelLine
  62133. */
  62134. var SunburstPiece =
  62135. /** @class */
  62136. function (_super) {
  62137. __extends(SunburstPiece, _super);
  62138. function SunburstPiece(node, seriesModel, ecModel, api) {
  62139. var _this = _super.call(this) || this;
  62140. _this.z2 = DEFAULT_SECTOR_Z;
  62141. _this.textConfig = {
  62142. inside: true
  62143. };
  62144. getECData(_this).seriesIndex = seriesModel.seriesIndex;
  62145. var text = new ZRText({
  62146. z2: DEFAULT_TEXT_Z,
  62147. silent: node.getModel().get(['label', 'silent'])
  62148. });
  62149. _this.setTextContent(text);
  62150. _this.updateData(true, node, seriesModel, ecModel, api);
  62151. return _this;
  62152. }
  62153. SunburstPiece.prototype.updateData = function (firstCreate, node, // state: 'emphasis' | 'normal' | 'highlight' | 'downplay',
  62154. seriesModel, ecModel, api) {
  62155. this.node = node;
  62156. node.piece = this;
  62157. seriesModel = seriesModel || this._seriesModel;
  62158. ecModel = ecModel || this._ecModel;
  62159. var sector = this;
  62160. getECData(sector).dataIndex = node.dataIndex;
  62161. var itemModel = node.getModel();
  62162. var emphasisModel = itemModel.getModel('emphasis');
  62163. var layout = node.getLayout();
  62164. var sectorShape = extend({}, layout);
  62165. sectorShape.label = null;
  62166. var normalStyle = node.getVisual('style');
  62167. normalStyle.lineJoin = 'bevel';
  62168. var decal = node.getVisual('decal');
  62169. if (decal) {
  62170. normalStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  62171. }
  62172. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  62173. extend(sectorShape, cornerRadius);
  62174. each(SPECIAL_STATES, function (stateName) {
  62175. var state = sector.ensureState(stateName);
  62176. var itemStyleModel = itemModel.getModel([stateName, 'itemStyle']);
  62177. state.style = itemStyleModel.getItemStyle(); // border radius
  62178. var cornerRadius = getSectorCornerRadius(itemStyleModel, sectorShape);
  62179. if (cornerRadius) {
  62180. state.shape = cornerRadius;
  62181. }
  62182. });
  62183. if (firstCreate) {
  62184. sector.setShape(sectorShape);
  62185. sector.shape.r = layout.r0;
  62186. initProps(sector, {
  62187. shape: {
  62188. r: layout.r
  62189. }
  62190. }, seriesModel, node.dataIndex);
  62191. } else {
  62192. // Disable animation for gradient since no interpolation method
  62193. // is supported for gradient
  62194. updateProps(sector, {
  62195. shape: sectorShape
  62196. }, seriesModel);
  62197. saveOldStyle(sector);
  62198. }
  62199. sector.useStyle(normalStyle);
  62200. this._updateLabel(seriesModel);
  62201. var cursorStyle = itemModel.getShallow('cursor');
  62202. cursorStyle && sector.attr('cursor', cursorStyle);
  62203. this._seriesModel = seriesModel || this._seriesModel;
  62204. this._ecModel = ecModel || this._ecModel;
  62205. var focus = emphasisModel.get('focus');
  62206. var focusOrIndices = focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : focus;
  62207. toggleHoverEmphasis(this, focusOrIndices, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  62208. };
  62209. SunburstPiece.prototype._updateLabel = function (seriesModel) {
  62210. var _this = this;
  62211. var itemModel = this.node.getModel();
  62212. var normalLabelModel = itemModel.getModel('label');
  62213. var layout = this.node.getLayout();
  62214. var angle = layout.endAngle - layout.startAngle;
  62215. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  62216. var dx = Math.cos(midAngle);
  62217. var dy = Math.sin(midAngle);
  62218. var sector = this;
  62219. var label = sector.getTextContent();
  62220. var dataIndex = this.node.dataIndex;
  62221. var labelMinAngle = normalLabelModel.get('minAngle') / 180 * Math.PI;
  62222. var isNormalShown = normalLabelModel.get('show') && !(labelMinAngle != null && Math.abs(angle) < labelMinAngle);
  62223. label.ignore = !isNormalShown; // TODO use setLabelStyle
  62224. each(DISPLAY_STATES, function (stateName) {
  62225. var labelStateModel = stateName === 'normal' ? itemModel.getModel('label') : itemModel.getModel([stateName, 'label']);
  62226. var isNormal = stateName === 'normal';
  62227. var state = isNormal ? label : label.ensureState(stateName);
  62228. var text = seriesModel.getFormattedLabel(dataIndex, stateName);
  62229. if (isNormal) {
  62230. text = text || _this.node.name;
  62231. }
  62232. state.style = createTextStyle(labelStateModel, {}, null, stateName !== 'normal', true);
  62233. if (text) {
  62234. state.style.text = text;
  62235. } // Not displaying text when angle is too small
  62236. var isShown = labelStateModel.get('show');
  62237. if (isShown != null && !isNormal) {
  62238. state.ignore = !isShown;
  62239. }
  62240. var labelPosition = getLabelAttr(labelStateModel, 'position');
  62241. var sectorState = isNormal ? sector : sector.states[stateName];
  62242. var labelColor = sectorState.style.fill;
  62243. sectorState.textConfig = {
  62244. outsideFill: labelStateModel.get('color') === 'inherit' ? labelColor : null,
  62245. inside: labelPosition !== 'outside'
  62246. };
  62247. var r;
  62248. var labelPadding = getLabelAttr(labelStateModel, 'distance') || 0;
  62249. var textAlign = getLabelAttr(labelStateModel, 'align');
  62250. if (labelPosition === 'outside') {
  62251. r = layout.r + labelPadding;
  62252. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  62253. } else {
  62254. if (!textAlign || textAlign === 'center') {
  62255. // Put label in the center if it's a circle
  62256. if (angle === 2 * Math.PI && layout.r0 === 0) {
  62257. r = 0;
  62258. } else {
  62259. r = (layout.r + layout.r0) / 2;
  62260. }
  62261. textAlign = 'center';
  62262. } else if (textAlign === 'left') {
  62263. r = layout.r0 + labelPadding;
  62264. if (midAngle > Math.PI / 2) {
  62265. textAlign = 'right';
  62266. }
  62267. } else if (textAlign === 'right') {
  62268. r = layout.r - labelPadding;
  62269. if (midAngle > Math.PI / 2) {
  62270. textAlign = 'left';
  62271. }
  62272. }
  62273. }
  62274. state.style.align = textAlign;
  62275. state.style.verticalAlign = getLabelAttr(labelStateModel, 'verticalAlign') || 'middle';
  62276. state.x = r * dx + layout.cx;
  62277. state.y = r * dy + layout.cy;
  62278. var rotateType = getLabelAttr(labelStateModel, 'rotate');
  62279. var rotate = 0;
  62280. if (rotateType === 'radial') {
  62281. rotate = normalizeRadian(-midAngle);
  62282. if (rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  62283. rotate += Math.PI;
  62284. }
  62285. } else if (rotateType === 'tangential') {
  62286. rotate = Math.PI / 2 - midAngle;
  62287. if (rotate > Math.PI / 2) {
  62288. rotate -= Math.PI;
  62289. } else if (rotate < -Math.PI / 2) {
  62290. rotate += Math.PI;
  62291. }
  62292. } else if (isNumber(rotateType)) {
  62293. rotate = rotateType * Math.PI / 180;
  62294. }
  62295. state.rotation = rotate;
  62296. });
  62297. function getLabelAttr(model, name) {
  62298. var stateAttr = model.get(name);
  62299. if (stateAttr == null) {
  62300. return normalLabelModel.get(name);
  62301. }
  62302. return stateAttr;
  62303. }
  62304. label.dirtyStyle();
  62305. };
  62306. return SunburstPiece;
  62307. }(Sector);
  62308. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  62309. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  62310. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  62311. function installSunburstAction(registers) {
  62312. registers.registerAction({
  62313. type: ROOT_TO_NODE_ACTION,
  62314. update: 'updateView'
  62315. }, function (payload, ecModel) {
  62316. ecModel.eachComponent({
  62317. mainType: 'series',
  62318. subType: 'sunburst',
  62319. query: payload
  62320. }, handleRootToNode);
  62321. function handleRootToNode(model, index) {
  62322. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION], model);
  62323. if (targetInfo) {
  62324. var originViewRoot = model.getViewRoot();
  62325. if (originViewRoot) {
  62326. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  62327. }
  62328. model.resetViewRoot(targetInfo.node);
  62329. }
  62330. }
  62331. });
  62332. registers.registerAction({
  62333. type: HIGHLIGHT_ACTION,
  62334. update: 'none'
  62335. }, function (payload, ecModel, api) {
  62336. // Clone
  62337. payload = extend({}, payload);
  62338. ecModel.eachComponent({
  62339. mainType: 'series',
  62340. subType: 'sunburst',
  62341. query: payload
  62342. }, handleHighlight);
  62343. function handleHighlight(model) {
  62344. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  62345. if (targetInfo) {
  62346. payload.dataIndex = targetInfo.node.dataIndex;
  62347. }
  62348. }
  62349. if ("development" !== 'production') {
  62350. deprecateReplaceLog('sunburstHighlight', 'highlight');
  62351. } // Fast forward action
  62352. api.dispatchAction(extend(payload, {
  62353. type: 'highlight'
  62354. }));
  62355. });
  62356. registers.registerAction({
  62357. type: UNHIGHLIGHT_ACTION,
  62358. update: 'updateView'
  62359. }, function (payload, ecModel, api) {
  62360. payload = extend({}, payload);
  62361. if ("development" !== 'production') {
  62362. deprecateReplaceLog('sunburstUnhighlight', 'downplay');
  62363. }
  62364. api.dispatchAction(extend(payload, {
  62365. type: 'downplay'
  62366. }));
  62367. });
  62368. }
  62369. var SunburstView =
  62370. /** @class */
  62371. function (_super) {
  62372. __extends(SunburstView, _super);
  62373. function SunburstView() {
  62374. var _this = _super !== null && _super.apply(this, arguments) || this;
  62375. _this.type = SunburstView.type;
  62376. return _this;
  62377. }
  62378. SunburstView.prototype.render = function (seriesModel, ecModel, api, // @ts-ignore
  62379. payload) {
  62380. var self = this;
  62381. this.seriesModel = seriesModel;
  62382. this.api = api;
  62383. this.ecModel = ecModel;
  62384. var data = seriesModel.getData();
  62385. var virtualRoot = data.tree.root;
  62386. var newRoot = seriesModel.getViewRoot();
  62387. var group = this.group;
  62388. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  62389. var newChildren = [];
  62390. newRoot.eachNode(function (node) {
  62391. newChildren.push(node);
  62392. });
  62393. var oldChildren = this._oldChildren || [];
  62394. dualTravel(newChildren, oldChildren);
  62395. renderRollUp(virtualRoot, newRoot);
  62396. this._initEvents();
  62397. this._oldChildren = newChildren;
  62398. function dualTravel(newChildren, oldChildren) {
  62399. if (newChildren.length === 0 && oldChildren.length === 0) {
  62400. return;
  62401. }
  62402. new DataDiffer(oldChildren, newChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  62403. function getKey(node) {
  62404. return node.getId();
  62405. }
  62406. function processNode(newIdx, oldIdx) {
  62407. var newNode = newIdx == null ? null : newChildren[newIdx];
  62408. var oldNode = oldIdx == null ? null : oldChildren[oldIdx];
  62409. doRenderNode(newNode, oldNode);
  62410. }
  62411. }
  62412. function doRenderNode(newNode, oldNode) {
  62413. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  62414. // Not render data with value 0
  62415. newNode = null;
  62416. }
  62417. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  62418. if (oldNode && oldNode.piece) {
  62419. if (newNode) {
  62420. // Update
  62421. oldNode.piece.updateData(false, newNode, seriesModel, ecModel, api); // For tooltip
  62422. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  62423. } else {
  62424. // Remove
  62425. removeNode(oldNode);
  62426. }
  62427. } else if (newNode) {
  62428. // Add
  62429. var piece = new SunburstPiece(newNode, seriesModel, ecModel, api);
  62430. group.add(piece); // For tooltip
  62431. data.setItemGraphicEl(newNode.dataIndex, piece);
  62432. }
  62433. }
  62434. }
  62435. function removeNode(node) {
  62436. if (!node) {
  62437. return;
  62438. }
  62439. if (node.piece) {
  62440. group.remove(node.piece);
  62441. node.piece = null;
  62442. }
  62443. }
  62444. function renderRollUp(virtualRoot, viewRoot) {
  62445. if (viewRoot.depth > 0) {
  62446. // Render
  62447. if (self.virtualPiece) {
  62448. // Update
  62449. self.virtualPiece.updateData(false, virtualRoot, seriesModel, ecModel, api);
  62450. } else {
  62451. // Add
  62452. self.virtualPiece = new SunburstPiece(virtualRoot, seriesModel, ecModel, api);
  62453. group.add(self.virtualPiece);
  62454. } // TODO event scope
  62455. viewRoot.piece.off('click');
  62456. self.virtualPiece.on('click', function (e) {
  62457. self._rootToNode(viewRoot.parentNode);
  62458. });
  62459. } else if (self.virtualPiece) {
  62460. // Remove
  62461. group.remove(self.virtualPiece);
  62462. self.virtualPiece = null;
  62463. }
  62464. }
  62465. };
  62466. /**
  62467. * @private
  62468. */
  62469. SunburstView.prototype._initEvents = function () {
  62470. var _this = this;
  62471. this.group.off('click');
  62472. this.group.on('click', function (e) {
  62473. var targetFound = false;
  62474. var viewRoot = _this.seriesModel.getViewRoot();
  62475. viewRoot.eachNode(function (node) {
  62476. if (!targetFound && node.piece && node.piece === e.target) {
  62477. var nodeClick = node.getModel().get('nodeClick');
  62478. if (nodeClick === 'rootToNode') {
  62479. _this._rootToNode(node);
  62480. } else if (nodeClick === 'link') {
  62481. var itemModel = node.getModel();
  62482. var link = itemModel.get('link');
  62483. if (link) {
  62484. var linkTarget = itemModel.get('target', true) || '_blank';
  62485. windowOpen(link, linkTarget);
  62486. }
  62487. }
  62488. targetFound = true;
  62489. }
  62490. });
  62491. });
  62492. };
  62493. /**
  62494. * @private
  62495. */
  62496. SunburstView.prototype._rootToNode = function (node) {
  62497. if (node !== this.seriesModel.getViewRoot()) {
  62498. this.api.dispatchAction({
  62499. type: ROOT_TO_NODE_ACTION,
  62500. from: this.uid,
  62501. seriesId: this.seriesModel.id,
  62502. targetNode: node
  62503. });
  62504. }
  62505. };
  62506. /**
  62507. * @implement
  62508. */
  62509. SunburstView.prototype.containPoint = function (point, seriesModel) {
  62510. var treeRoot = seriesModel.getData();
  62511. var itemLayout = treeRoot.getItemLayout(0);
  62512. if (itemLayout) {
  62513. var dx = point[0] - itemLayout.cx;
  62514. var dy = point[1] - itemLayout.cy;
  62515. var radius = Math.sqrt(dx * dx + dy * dy);
  62516. return radius <= itemLayout.r && radius >= itemLayout.r0;
  62517. }
  62518. };
  62519. SunburstView.type = 'sunburst';
  62520. return SunburstView;
  62521. }(ChartView);
  62522. var SunburstSeriesModel =
  62523. /** @class */
  62524. function (_super) {
  62525. __extends(SunburstSeriesModel, _super);
  62526. function SunburstSeriesModel() {
  62527. var _this = _super !== null && _super.apply(this, arguments) || this;
  62528. _this.type = SunburstSeriesModel.type;
  62529. _this.ignoreStyleOnData = true;
  62530. return _this;
  62531. }
  62532. SunburstSeriesModel.prototype.getInitialData = function (option, ecModel) {
  62533. // Create a virtual root.
  62534. var root = {
  62535. name: option.name,
  62536. children: option.data
  62537. };
  62538. completeTreeValue$1(root);
  62539. var levelModels = this._levelModels = map(option.levels || [], function (levelDefine) {
  62540. return new Model(levelDefine, this, ecModel);
  62541. }, this); // Make sure always a new tree is created when setOption,
  62542. // in TreemapView, we check whether oldTree === newTree
  62543. // to choose mappings approach among old shapes and new shapes.
  62544. var tree = Tree.createTree(root, this, beforeLink);
  62545. function beforeLink(nodeData) {
  62546. nodeData.wrapMethod('getItemModel', function (model, idx) {
  62547. var node = tree.getNodeByDataIndex(idx);
  62548. var levelModel = levelModels[node.depth];
  62549. levelModel && (model.parentModel = levelModel);
  62550. return model;
  62551. });
  62552. }
  62553. return tree.data;
  62554. };
  62555. SunburstSeriesModel.prototype.optionUpdated = function () {
  62556. this.resetViewRoot();
  62557. };
  62558. /*
  62559. * @override
  62560. */
  62561. SunburstSeriesModel.prototype.getDataParams = function (dataIndex) {
  62562. var params = _super.prototype.getDataParams.apply(this, arguments);
  62563. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  62564. params.treePathInfo = wrapTreePathInfo(node, this);
  62565. return params;
  62566. };
  62567. SunburstSeriesModel.prototype.getLevelModel = function (node) {
  62568. return this._levelModels && this._levelModels[node.depth];
  62569. };
  62570. SunburstSeriesModel.prototype.getViewRoot = function () {
  62571. return this._viewRoot;
  62572. };
  62573. SunburstSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  62574. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  62575. var root = this.getRawData().tree.root;
  62576. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  62577. this._viewRoot = root;
  62578. }
  62579. };
  62580. SunburstSeriesModel.prototype.enableAriaDecal = function () {
  62581. enableAriaDecalForTree(this);
  62582. };
  62583. SunburstSeriesModel.type = 'series.sunburst';
  62584. SunburstSeriesModel.defaultOption = {
  62585. // zlevel: 0,
  62586. z: 2,
  62587. // 默认全局居中
  62588. center: ['50%', '50%'],
  62589. radius: [0, '75%'],
  62590. // 默认顺时针
  62591. clockwise: true,
  62592. startAngle: 90,
  62593. // 最小角度改为0
  62594. minAngle: 0,
  62595. // If still show when all data zero.
  62596. stillShowZeroSum: true,
  62597. // 'rootToNode', 'link', or false
  62598. nodeClick: 'rootToNode',
  62599. renderLabelForZeroData: false,
  62600. label: {
  62601. // could be: 'radial', 'tangential', or 'none'
  62602. rotate: 'radial',
  62603. show: true,
  62604. opacity: 1,
  62605. // 'left' is for inner side of inside, and 'right' is for outer
  62606. // side for inside
  62607. align: 'center',
  62608. position: 'inside',
  62609. distance: 5,
  62610. silent: true
  62611. },
  62612. itemStyle: {
  62613. borderWidth: 1,
  62614. borderColor: 'white',
  62615. borderType: 'solid',
  62616. shadowBlur: 0,
  62617. shadowColor: 'rgba(0, 0, 0, 0.2)',
  62618. shadowOffsetX: 0,
  62619. shadowOffsetY: 0,
  62620. opacity: 1
  62621. },
  62622. emphasis: {
  62623. focus: 'descendant'
  62624. },
  62625. blur: {
  62626. itemStyle: {
  62627. opacity: 0.2
  62628. },
  62629. label: {
  62630. opacity: 0.1
  62631. }
  62632. },
  62633. // Animation type can be expansion, scale.
  62634. animationType: 'expansion',
  62635. animationDuration: 1000,
  62636. animationDurationUpdate: 500,
  62637. data: [],
  62638. /**
  62639. * Sort order.
  62640. *
  62641. * Valid values: 'desc', 'asc', null, or callback function.
  62642. * 'desc' and 'asc' for descend and ascendant order;
  62643. * null for not sorting;
  62644. * example of callback function:
  62645. * function(nodeA, nodeB) {
  62646. * return nodeA.getValue() - nodeB.getValue();
  62647. * }
  62648. */
  62649. sort: 'desc'
  62650. };
  62651. return SunburstSeriesModel;
  62652. }(SeriesModel);
  62653. function completeTreeValue$1(dataNode) {
  62654. // Postorder travel tree.
  62655. // If value of none-leaf node is not set,
  62656. // calculate it by suming up the value of all children.
  62657. var sum = 0;
  62658. each(dataNode.children, function (child) {
  62659. completeTreeValue$1(child);
  62660. var childValue = child.value; // TODO First value of array must be a number
  62661. isArray(childValue) && (childValue = childValue[0]);
  62662. sum += childValue;
  62663. });
  62664. var thisValue = dataNode.value;
  62665. if (isArray(thisValue)) {
  62666. thisValue = thisValue[0];
  62667. }
  62668. if (thisValue == null || isNaN(thisValue)) {
  62669. thisValue = sum;
  62670. } // Value should not less than 0.
  62671. if (thisValue < 0) {
  62672. thisValue = 0;
  62673. }
  62674. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  62675. }
  62676. var RADIAN$2 = Math.PI / 180;
  62677. function sunburstLayout(seriesType, ecModel, api) {
  62678. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  62679. var center = seriesModel.get('center');
  62680. var radius = seriesModel.get('radius');
  62681. if (!isArray(radius)) {
  62682. radius = [0, radius];
  62683. }
  62684. if (!isArray(center)) {
  62685. center = [center, center];
  62686. }
  62687. var width = api.getWidth();
  62688. var height = api.getHeight();
  62689. var size = Math.min(width, height);
  62690. var cx = parsePercent$1(center[0], width);
  62691. var cy = parsePercent$1(center[1], height);
  62692. var r0 = parsePercent$1(radius[0], size / 2);
  62693. var r = parsePercent$1(radius[1], size / 2);
  62694. var startAngle = -seriesModel.get('startAngle') * RADIAN$2;
  62695. var minAngle = seriesModel.get('minAngle') * RADIAN$2;
  62696. var virtualRoot = seriesModel.getData().tree.root;
  62697. var treeRoot = seriesModel.getViewRoot();
  62698. var rootDepth = treeRoot.depth;
  62699. var sort = seriesModel.get('sort');
  62700. if (sort != null) {
  62701. initChildren$1(treeRoot, sort);
  62702. }
  62703. var validDataCount = 0;
  62704. each(treeRoot.children, function (child) {
  62705. !isNaN(child.getValue()) && validDataCount++;
  62706. });
  62707. var sum = treeRoot.getValue(); // Sum may be 0
  62708. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  62709. var renderRollupNode = treeRoot.depth > 0;
  62710. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  62711. var rPerLevel = (r - r0) / (levels || 1);
  62712. var clockwise = seriesModel.get('clockwise');
  62713. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // In the case some sector angle is smaller than minAngle
  62714. // let restAngle = PI2;
  62715. // let valueSumLargerThanMinAngle = 0;
  62716. var dir = clockwise ? 1 : -1;
  62717. /**
  62718. * Render a tree
  62719. * @return increased angle
  62720. */
  62721. var renderNode = function (node, startAngle) {
  62722. if (!node) {
  62723. return;
  62724. }
  62725. var endAngle = startAngle; // Render self
  62726. if (node !== virtualRoot) {
  62727. // Tree node is virtual, so it doesn't need to be drawn
  62728. var value = node.getValue();
  62729. var angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  62730. if (angle < minAngle) {
  62731. angle = minAngle; // restAngle -= minAngle;
  62732. } // else {
  62733. // valueSumLargerThanMinAngle += value;
  62734. // }
  62735. endAngle = startAngle + dir * angle;
  62736. var depth = node.depth - rootDepth - (renderRollupNode ? -1 : 1);
  62737. var rStart = r0 + rPerLevel * depth;
  62738. var rEnd = r0 + rPerLevel * (depth + 1);
  62739. var levelModel = seriesModel.getLevelModel(node);
  62740. if (levelModel) {
  62741. var r0_1 = levelModel.get('r0', true);
  62742. var r_1 = levelModel.get('r', true);
  62743. var radius_1 = levelModel.get('radius', true);
  62744. if (radius_1 != null) {
  62745. r0_1 = radius_1[0];
  62746. r_1 = radius_1[1];
  62747. }
  62748. r0_1 != null && (rStart = parsePercent$1(r0_1, size / 2));
  62749. r_1 != null && (rEnd = parsePercent$1(r_1, size / 2));
  62750. }
  62751. node.setLayout({
  62752. angle: angle,
  62753. startAngle: startAngle,
  62754. endAngle: endAngle,
  62755. clockwise: clockwise,
  62756. cx: cx,
  62757. cy: cy,
  62758. r0: rStart,
  62759. r: rEnd
  62760. });
  62761. } // Render children
  62762. if (node.children && node.children.length) {
  62763. // currentAngle = startAngle;
  62764. var siblingAngle_1 = 0;
  62765. each(node.children, function (node) {
  62766. siblingAngle_1 += renderNode(node, startAngle + siblingAngle_1);
  62767. });
  62768. }
  62769. return endAngle - startAngle;
  62770. }; // Virtual root node for roll up
  62771. if (renderRollupNode) {
  62772. var rStart = r0;
  62773. var rEnd = r0 + rPerLevel;
  62774. var angle = Math.PI * 2;
  62775. virtualRoot.setLayout({
  62776. angle: angle,
  62777. startAngle: startAngle,
  62778. endAngle: startAngle + angle,
  62779. clockwise: clockwise,
  62780. cx: cx,
  62781. cy: cy,
  62782. r0: rStart,
  62783. r: rEnd
  62784. });
  62785. }
  62786. renderNode(treeRoot, startAngle);
  62787. });
  62788. }
  62789. /**
  62790. * Init node children by order and update visual
  62791. */
  62792. function initChildren$1(node, sortOrder) {
  62793. var children = node.children || [];
  62794. node.children = sort$2(children, sortOrder); // Init children recursively
  62795. if (children.length) {
  62796. each(node.children, function (child) {
  62797. initChildren$1(child, sortOrder);
  62798. });
  62799. }
  62800. }
  62801. /**
  62802. * Sort children nodes
  62803. *
  62804. * @param {TreeNode[]} children children of node to be sorted
  62805. * @param {string | function | null} sort sort method
  62806. * See SunburstSeries.js for details.
  62807. */
  62808. function sort$2(children, sortOrder) {
  62809. if (isFunction(sortOrder)) {
  62810. var sortTargets = map(children, function (child, idx) {
  62811. var value = child.getValue();
  62812. return {
  62813. params: {
  62814. depth: child.depth,
  62815. height: child.height,
  62816. dataIndex: child.dataIndex,
  62817. getValue: function () {
  62818. return value;
  62819. }
  62820. },
  62821. index: idx
  62822. };
  62823. });
  62824. sortTargets.sort(function (a, b) {
  62825. return sortOrder(a.params, b.params);
  62826. });
  62827. return map(sortTargets, function (target) {
  62828. return children[target.index];
  62829. });
  62830. } else {
  62831. var isAsc_1 = sortOrder === 'asc';
  62832. return children.sort(function (a, b) {
  62833. var diff = (a.getValue() - b.getValue()) * (isAsc_1 ? 1 : -1);
  62834. return diff === 0 ? (a.dataIndex - b.dataIndex) * (isAsc_1 ? -1 : 1) : diff;
  62835. });
  62836. }
  62837. }
  62838. function sunburstVisual(ecModel) {
  62839. var paletteScope = {}; // Default color strategy
  62840. function pickColor(node, seriesModel, treeHeight) {
  62841. // Choose color from palette based on the first level.
  62842. var current = node;
  62843. while (current && current.depth > 1) {
  62844. current = current.parentNode;
  62845. }
  62846. var color = seriesModel.getColorFromPalette(current.name || current.dataIndex + '', paletteScope);
  62847. if (node.depth > 1 && isString(color)) {
  62848. // Lighter on the deeper level.
  62849. color = lift(color, (node.depth - 1) / (treeHeight - 1) * 0.5);
  62850. }
  62851. return color;
  62852. }
  62853. ecModel.eachSeriesByType('sunburst', function (seriesModel) {
  62854. var data = seriesModel.getData();
  62855. var tree = data.tree;
  62856. tree.eachNode(function (node) {
  62857. var model = node.getModel();
  62858. var style = model.getModel('itemStyle').getItemStyle();
  62859. if (!style.fill) {
  62860. style.fill = pickColor(node, seriesModel, tree.root.height);
  62861. }
  62862. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  62863. extend(existsStyle, style);
  62864. });
  62865. });
  62866. }
  62867. function install$q(registers) {
  62868. registers.registerChartView(SunburstView);
  62869. registers.registerSeriesModel(SunburstSeriesModel);
  62870. registers.registerLayout(curry(sunburstLayout, 'sunburst'));
  62871. registers.registerProcessor(curry(dataFilter, 'sunburst'));
  62872. registers.registerVisual(sunburstVisual);
  62873. installSunburstAction(registers);
  62874. }
  62875. // `visual('color') visual('borderColor')` is supported.
  62876. var STYLE_VISUAL_TYPE = {
  62877. color: 'fill',
  62878. borderColor: 'stroke'
  62879. };
  62880. var NON_STYLE_VISUAL_PROPS = {
  62881. symbol: 1,
  62882. symbolSize: 1,
  62883. symbolKeepAspect: 1,
  62884. legendIcon: 1,
  62885. visualMeta: 1,
  62886. liftZ: 1,
  62887. decal: 1
  62888. };
  62889. var customInnerStore = makeInner();
  62890. var CustomSeriesModel =
  62891. /** @class */
  62892. function (_super) {
  62893. __extends(CustomSeriesModel, _super);
  62894. function CustomSeriesModel() {
  62895. var _this = _super !== null && _super.apply(this, arguments) || this;
  62896. _this.type = CustomSeriesModel.type;
  62897. return _this;
  62898. }
  62899. CustomSeriesModel.prototype.optionUpdated = function () {
  62900. this.currentZLevel = this.get('zlevel', true);
  62901. this.currentZ = this.get('z', true);
  62902. };
  62903. CustomSeriesModel.prototype.getInitialData = function (option, ecModel) {
  62904. return createSeriesData(null, this);
  62905. };
  62906. CustomSeriesModel.prototype.getDataParams = function (dataIndex, dataType, el) {
  62907. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  62908. el && (params.info = customInnerStore(el).info);
  62909. return params;
  62910. };
  62911. CustomSeriesModel.type = 'series.custom';
  62912. CustomSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  62913. CustomSeriesModel.defaultOption = {
  62914. coordinateSystem: 'cartesian2d',
  62915. // zlevel: 0,
  62916. z: 2,
  62917. legendHoverLink: true,
  62918. // Custom series will not clip by default.
  62919. // Some case will use custom series to draw label
  62920. // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
  62921. clip: false // Cartesian coordinate system
  62922. // xAxisIndex: 0,
  62923. // yAxisIndex: 0,
  62924. // Polar coordinate system
  62925. // polarIndex: 0,
  62926. // Geo coordinate system
  62927. // geoIndex: 0,
  62928. };
  62929. return CustomSeriesModel;
  62930. }(SeriesModel);
  62931. function dataToCoordSize(dataSize, dataItem) {
  62932. // dataItem is necessary in log axis.
  62933. dataItem = dataItem || [0, 0];
  62934. return map(['x', 'y'], function (dim, dimIdx) {
  62935. var axis = this.getAxis(dim);
  62936. var val = dataItem[dimIdx];
  62937. var halfSize = dataSize[dimIdx] / 2;
  62938. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  62939. }, this);
  62940. }
  62941. function cartesianPrepareCustom(coordSys) {
  62942. var rect = coordSys.master.getRect();
  62943. return {
  62944. coordSys: {
  62945. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  62946. type: 'cartesian2d',
  62947. x: rect.x,
  62948. y: rect.y,
  62949. width: rect.width,
  62950. height: rect.height
  62951. },
  62952. api: {
  62953. coord: function (data) {
  62954. // do not provide "out" param
  62955. return coordSys.dataToPoint(data);
  62956. },
  62957. size: bind(dataToCoordSize, coordSys)
  62958. }
  62959. };
  62960. }
  62961. function dataToCoordSize$1(dataSize, dataItem) {
  62962. dataItem = dataItem || [0, 0];
  62963. return map([0, 1], function (dimIdx) {
  62964. var val = dataItem[dimIdx];
  62965. var halfSize = dataSize[dimIdx] / 2;
  62966. var p1 = [];
  62967. var p2 = [];
  62968. p1[dimIdx] = val - halfSize;
  62969. p2[dimIdx] = val + halfSize;
  62970. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  62971. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  62972. }, this);
  62973. }
  62974. function geoPrepareCustom(coordSys) {
  62975. var rect = coordSys.getBoundingRect();
  62976. return {
  62977. coordSys: {
  62978. type: 'geo',
  62979. x: rect.x,
  62980. y: rect.y,
  62981. width: rect.width,
  62982. height: rect.height,
  62983. zoom: coordSys.getZoom()
  62984. },
  62985. api: {
  62986. coord: function (data) {
  62987. // do not provide "out" and noRoam param,
  62988. // Compatible with this usage:
  62989. // echarts.util.map(item.points, api.coord)
  62990. return coordSys.dataToPoint(data);
  62991. },
  62992. size: bind(dataToCoordSize$1, coordSys)
  62993. }
  62994. };
  62995. }
  62996. function dataToCoordSize$2(dataSize, dataItem) {
  62997. // dataItem is necessary in log axis.
  62998. var axis = this.getAxis();
  62999. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  63000. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  63001. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63002. }
  63003. function singlePrepareCustom(coordSys) {
  63004. var rect = coordSys.getRect();
  63005. return {
  63006. coordSys: {
  63007. type: 'singleAxis',
  63008. x: rect.x,
  63009. y: rect.y,
  63010. width: rect.width,
  63011. height: rect.height
  63012. },
  63013. api: {
  63014. coord: function (val) {
  63015. // do not provide "out" param
  63016. return coordSys.dataToPoint(val);
  63017. },
  63018. size: bind(dataToCoordSize$2, coordSys)
  63019. }
  63020. };
  63021. }
  63022. function dataToCoordSize$3(dataSize, dataItem) {
  63023. // dataItem is necessary in log axis.
  63024. dataItem = dataItem || [0, 0];
  63025. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  63026. var getterName = 'get' + dim + 'Axis'; // TODO: TYPE Check Angle Axis
  63027. var axis = this[getterName]();
  63028. var val = dataItem[dimIdx];
  63029. var halfSize = dataSize[dimIdx] / 2;
  63030. var result = axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63031. if (dim === 'Angle') {
  63032. result = result * Math.PI / 180;
  63033. }
  63034. return result;
  63035. }, this);
  63036. }
  63037. function polarPrepareCustom(coordSys) {
  63038. var radiusAxis = coordSys.getRadiusAxis();
  63039. var angleAxis = coordSys.getAngleAxis();
  63040. var radius = radiusAxis.getExtent();
  63041. radius[0] > radius[1] && radius.reverse();
  63042. return {
  63043. coordSys: {
  63044. type: 'polar',
  63045. cx: coordSys.cx,
  63046. cy: coordSys.cy,
  63047. r: radius[1],
  63048. r0: radius[0]
  63049. },
  63050. api: {
  63051. coord: function (data) {
  63052. var radius = radiusAxis.dataToRadius(data[0]);
  63053. var angle = angleAxis.dataToAngle(data[1]);
  63054. var coord = coordSys.coordToPoint([radius, angle]);
  63055. coord.push(radius, angle * Math.PI / 180);
  63056. return coord;
  63057. },
  63058. size: bind(dataToCoordSize$3, coordSys)
  63059. }
  63060. };
  63061. }
  63062. /*
  63063. * Licensed to the Apache Software Foundation (ASF) under one
  63064. * or more contributor license agreements. See the NOTICE file
  63065. * distributed with this work for additional information
  63066. * regarding copyright ownership. The ASF licenses this file
  63067. * to you under the Apache License, Version 2.0 (the
  63068. * "License"); you may not use this file except in compliance
  63069. * with the License. You may obtain a copy of the License at
  63070. *
  63071. * http://www.apache.org/licenses/LICENSE-2.0
  63072. *
  63073. * Unless required by applicable law or agreed to in writing,
  63074. * software distributed under the License is distributed on an
  63075. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63076. * KIND, either express or implied. See the License for the
  63077. * specific language governing permissions and limitations
  63078. * under the License.
  63079. */
  63080. /**
  63081. * AUTO-GENERATED FILE. DO NOT MODIFY.
  63082. */
  63083. /*
  63084. * Licensed to the Apache Software Foundation (ASF) under one
  63085. * or more contributor license agreements. See the NOTICE file
  63086. * distributed with this work for additional information
  63087. * regarding copyright ownership. The ASF licenses this file
  63088. * to you under the Apache License, Version 2.0 (the
  63089. * "License"); you may not use this file except in compliance
  63090. * with the License. You may obtain a copy of the License at
  63091. *
  63092. * http://www.apache.org/licenses/LICENSE-2.0
  63093. *
  63094. * Unless required by applicable law or agreed to in writing,
  63095. * software distributed under the License is distributed on an
  63096. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63097. * KIND, either express or implied. See the License for the
  63098. * specific language governing permissions and limitations
  63099. * under the License.
  63100. */
  63101. function calendarPrepareCustom(coordSys) {
  63102. var rect = coordSys.getRect();
  63103. var rangeInfo = coordSys.getRangeInfo();
  63104. return {
  63105. coordSys: {
  63106. type: 'calendar',
  63107. x: rect.x,
  63108. y: rect.y,
  63109. width: rect.width,
  63110. height: rect.height,
  63111. cellWidth: coordSys.getCellWidth(),
  63112. cellHeight: coordSys.getCellHeight(),
  63113. rangeInfo: {
  63114. start: rangeInfo.start,
  63115. end: rangeInfo.end,
  63116. weeks: rangeInfo.weeks,
  63117. dayCount: rangeInfo.allDay
  63118. }
  63119. },
  63120. api: {
  63121. coord: function (data, clamp) {
  63122. return coordSys.dataToPoint(data, clamp);
  63123. }
  63124. }
  63125. };
  63126. }
  63127. var deprecatedLogs = {};
  63128. /**
  63129. * Whether need to call `convertEC4CompatibleStyle`.
  63130. */
  63131. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  63132. // Since echarts5, `RectText` is separated from its host element and style.text
  63133. // does not exist any more. The compat work brings some extra burden on performance.
  63134. // So we provide:
  63135. // `legacy: true` force make compat.
  63136. // `legacy: false`, force do not compat.
  63137. // `legacy` not set: auto detect whether legacy.
  63138. // But in this case we do not compat (difficult to detect and rare case):
  63139. // Becuse custom series and graphic component support "merge", users may firstly
  63140. // only set `textStrokeWidth` style or secondly only set `text`.
  63141. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan' // Difficult to detect whether legacy for a "text" el.
  63142. && (elType === 'text' || hasOwn(style, 'text')));
  63143. }
  63144. /**
  63145. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  63146. * @param hostStyle The properties might be modified.
  63147. * @return If be text el, `textContentStyle` and `textConfig` will not be returned.
  63148. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  63149. * retried from the `hostStyle`.
  63150. */
  63151. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  63152. var srcStyle = hostStyle;
  63153. var textConfig;
  63154. var textContent;
  63155. var textContentStyle;
  63156. if (elType === 'text') {
  63157. textContentStyle = srcStyle;
  63158. } else {
  63159. textContentStyle = {};
  63160. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  63161. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  63162. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  63163. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  63164. hasOwn(srcStyle, 'fontFamily') && (textContentStyle.fontFamily = srcStyle.fontFamily);
  63165. hasOwn(srcStyle, 'fontSize') && (textContentStyle.fontSize = srcStyle.fontSize);
  63166. hasOwn(srcStyle, 'fontStyle') && (textContentStyle.fontStyle = srcStyle.fontStyle);
  63167. hasOwn(srcStyle, 'fontWeight') && (textContentStyle.fontWeight = srcStyle.fontWeight);
  63168. textContent = {
  63169. type: 'text',
  63170. style: textContentStyle,
  63171. // ec4 does not support rectText trigger.
  63172. // And when text position is different in normal and emphasis
  63173. // => hover text trigger emphasis;
  63174. // => text position changed, leave mouse pointer immediately;
  63175. // That might cause incorrect state.
  63176. silent: true
  63177. };
  63178. textConfig = {};
  63179. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  63180. if (isNormal) {
  63181. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  63182. } else {
  63183. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  63184. }
  63185. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  63186. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  63187. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  63188. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  63189. }
  63190. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  63191. each(textContentStyle.rich, function (richItem) {
  63192. convertEC4CompatibleRichItem(richItem, richItem);
  63193. });
  63194. return {
  63195. textConfig: textConfig,
  63196. textContent: textContent
  63197. };
  63198. }
  63199. /**
  63200. * The result will be set to `out`.
  63201. */
  63202. function convertEC4CompatibleRichItem(out, richItem) {
  63203. if (!richItem) {
  63204. return;
  63205. } // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  63206. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  63207. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  63208. // richText in ec5.
  63209. // (2) `out === richItem` if and only if `out` is text el or rich item.
  63210. // So we can overwrite existing props in `out` since textXXX has higher priority.
  63211. richItem.font = richItem.textFont || richItem.font;
  63212. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  63213. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  63214. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  63215. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  63216. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  63217. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  63218. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  63219. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  63220. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  63221. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  63222. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  63223. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  63224. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  63225. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  63226. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  63227. }
  63228. /**
  63229. * Convert to pure echarts4 format style.
  63230. * `itemStyle` will be modified, added with ec4 style properties from
  63231. * `textStyle` and `textConfig`.
  63232. *
  63233. * [Caveat]: For simplicity, `insideRollback` in ec4 does not compat, where
  63234. * `styleEmphasis: {textFill: 'red'}` will remove the normal auto added stroke.
  63235. */
  63236. function convertToEC4StyleForCustomSerise(itemStl, txStl, txCfg) {
  63237. var out = itemStl; // See `custom.ts`, a trick to set extra `textPosition` firstly.
  63238. out.textPosition = out.textPosition || txCfg.position || 'inside';
  63239. txCfg.offset != null && (out.textOffset = txCfg.offset);
  63240. txCfg.rotation != null && (out.textRotation = txCfg.rotation);
  63241. txCfg.distance != null && (out.textDistance = txCfg.distance);
  63242. var isInside = out.textPosition.indexOf('inside') >= 0;
  63243. var hostFill = itemStl.fill || '#000';
  63244. convertToEC4RichItem(out, txStl);
  63245. var textFillNotSet = out.textFill == null;
  63246. if (isInside) {
  63247. if (textFillNotSet) {
  63248. out.textFill = txCfg.insideFill || '#fff';
  63249. !out.textStroke && txCfg.insideStroke && (out.textStroke = txCfg.insideStroke);
  63250. !out.textStroke && (out.textStroke = hostFill);
  63251. out.textStrokeWidth == null && (out.textStrokeWidth = 2);
  63252. }
  63253. } else {
  63254. if (textFillNotSet) {
  63255. out.textFill = itemStl.fill || txCfg.outsideFill || '#000';
  63256. }
  63257. !out.textStroke && txCfg.outsideStroke && (out.textStroke = txCfg.outsideStroke);
  63258. }
  63259. out.text = txStl.text;
  63260. out.rich = txStl.rich;
  63261. each(txStl.rich, function (richItem) {
  63262. convertToEC4RichItem(richItem, richItem);
  63263. });
  63264. return out;
  63265. }
  63266. function convertToEC4RichItem(out, richItem) {
  63267. if (!richItem) {
  63268. return;
  63269. }
  63270. hasOwn(richItem, 'fill') && (out.textFill = richItem.fill);
  63271. hasOwn(richItem, 'stroke') && (out.textStroke = richItem.fill);
  63272. hasOwn(richItem, 'lineWidth') && (out.textStrokeWidth = richItem.lineWidth);
  63273. hasOwn(richItem, 'font') && (out.font = richItem.font);
  63274. hasOwn(richItem, 'fontStyle') && (out.fontStyle = richItem.fontStyle);
  63275. hasOwn(richItem, 'fontWeight') && (out.fontWeight = richItem.fontWeight);
  63276. hasOwn(richItem, 'fontSize') && (out.fontSize = richItem.fontSize);
  63277. hasOwn(richItem, 'fontFamily') && (out.fontFamily = richItem.fontFamily);
  63278. hasOwn(richItem, 'align') && (out.textAlign = richItem.align);
  63279. hasOwn(richItem, 'verticalAlign') && (out.textVerticalAlign = richItem.verticalAlign);
  63280. hasOwn(richItem, 'lineHeight') && (out.textLineHeight = richItem.lineHeight);
  63281. hasOwn(richItem, 'width') && (out.textWidth = richItem.width);
  63282. hasOwn(richItem, 'height') && (out.textHeight = richItem.height);
  63283. hasOwn(richItem, 'backgroundColor') && (out.textBackgroundColor = richItem.backgroundColor);
  63284. hasOwn(richItem, 'padding') && (out.textPadding = richItem.padding);
  63285. hasOwn(richItem, 'borderColor') && (out.textBorderColor = richItem.borderColor);
  63286. hasOwn(richItem, 'borderWidth') && (out.textBorderWidth = richItem.borderWidth);
  63287. hasOwn(richItem, 'borderRadius') && (out.textBorderRadius = richItem.borderRadius);
  63288. hasOwn(richItem, 'shadowColor') && (out.textBoxShadowColor = richItem.shadowColor);
  63289. hasOwn(richItem, 'shadowBlur') && (out.textBoxShadowBlur = richItem.shadowBlur);
  63290. hasOwn(richItem, 'shadowOffsetX') && (out.textBoxShadowOffsetX = richItem.shadowOffsetX);
  63291. hasOwn(richItem, 'shadowOffsetY') && (out.textBoxShadowOffsetY = richItem.shadowOffsetY);
  63292. hasOwn(richItem, 'textShadowColor') && (out.textShadowColor = richItem.textShadowColor);
  63293. hasOwn(richItem, 'textShadowBlur') && (out.textShadowBlur = richItem.textShadowBlur);
  63294. hasOwn(richItem, 'textShadowOffsetX') && (out.textShadowOffsetX = richItem.textShadowOffsetX);
  63295. hasOwn(richItem, 'textShadowOffsetY') && (out.textShadowOffsetY = richItem.textShadowOffsetY);
  63296. }
  63297. function warnDeprecated(deprecated, insteadApproach) {
  63298. if ("development" !== 'production') {
  63299. var key = deprecated + '^_^' + insteadApproach;
  63300. if (!deprecatedLogs[key]) {
  63301. console.warn("[ECharts] DEPRECATED: \"" + deprecated + "\" has been deprecated. " + insteadApproach);
  63302. deprecatedLogs[key] = true;
  63303. }
  63304. }
  63305. }
  63306. var LEGACY_TRANSFORM_PROPS_MAP = {
  63307. position: ['x', 'y'],
  63308. scale: ['scaleX', 'scaleY'],
  63309. origin: ['originX', 'originY']
  63310. };
  63311. var LEGACY_TRANSFORM_PROPS = keys(LEGACY_TRANSFORM_PROPS_MAP);
  63312. var TRANSFORM_PROPS_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  63313. obj[key] = 1;
  63314. return obj;
  63315. }, {});
  63316. var transformPropNamesStr = TRANSFORMABLE_PROPS.join(', '); // '' means root
  63317. var ELEMENT_ANIMATABLE_PROPS = ['', 'style', 'shape', 'extra'];
  63318. var transitionInnerStore = makeInner();
  63319. function getElementAnimationConfig(animationType, el, elOption, parentModel, dataIndex) {
  63320. var animationProp = animationType + "Animation";
  63321. var config = getAnimationConfig(animationType, parentModel, dataIndex) || {};
  63322. var userDuring = transitionInnerStore(el).userDuring; // Only set when duration is > 0 and it's need to be animated.
  63323. if (config.duration > 0) {
  63324. // For simplicity, if during not specified, the previous during will not work any more.
  63325. config.during = userDuring ? bind(duringCall, {
  63326. el: el,
  63327. userDuring: userDuring
  63328. }) : null;
  63329. config.setToFinal = true;
  63330. config.scope = animationType;
  63331. }
  63332. extend(config, elOption[animationProp]);
  63333. return config;
  63334. }
  63335. function applyUpdateTransition(el, elOption, animatableModel, opts) {
  63336. opts = opts || {};
  63337. var dataIndex = opts.dataIndex,
  63338. isInit = opts.isInit,
  63339. clearStyle = opts.clearStyle;
  63340. var hasAnimation = animatableModel.isAnimationEnabled(); // Save the meta info for further morphing. Like apply on the sub morphing elements.
  63341. var store = transitionInnerStore(el);
  63342. var styleOpt = elOption.style;
  63343. store.userDuring = elOption.during;
  63344. var transFromProps = {};
  63345. var propsToSet = {};
  63346. prepareTransformAllPropsFinal(el, elOption, propsToSet);
  63347. prepareShapeOrExtraAllPropsFinal('shape', elOption, propsToSet);
  63348. prepareShapeOrExtraAllPropsFinal('extra', elOption, propsToSet);
  63349. if (!isInit && hasAnimation) {
  63350. prepareTransformTransitionFrom(el, elOption, transFromProps);
  63351. prepareShapeOrExtraTransitionFrom('shape', el, elOption, transFromProps);
  63352. prepareShapeOrExtraTransitionFrom('extra', el, elOption, transFromProps);
  63353. prepareStyleTransitionFrom(el, elOption, styleOpt, transFromProps);
  63354. }
  63355. propsToSet.style = styleOpt;
  63356. applyPropsDirectly(el, propsToSet, clearStyle);
  63357. applyMiscProps(el, elOption);
  63358. if (hasAnimation) {
  63359. if (isInit) {
  63360. var enterFromProps_1 = {};
  63361. each(ELEMENT_ANIMATABLE_PROPS, function (propName) {
  63362. var prop = propName ? elOption[propName] : elOption;
  63363. if (prop && prop.enterFrom) {
  63364. if (propName) {
  63365. enterFromProps_1[propName] = enterFromProps_1[propName] || {};
  63366. }
  63367. extend(propName ? enterFromProps_1[propName] : enterFromProps_1, prop.enterFrom);
  63368. }
  63369. });
  63370. var config = getElementAnimationConfig('enter', el, elOption, animatableModel, dataIndex);
  63371. if (config.duration > 0) {
  63372. el.animateFrom(enterFromProps_1, config);
  63373. }
  63374. } else {
  63375. applyPropsTransition(el, elOption, dataIndex || 0, animatableModel, transFromProps);
  63376. }
  63377. } // Store leave to be used in leave transition.
  63378. updateLeaveTo(el, elOption);
  63379. styleOpt ? el.dirty() : el.markRedraw();
  63380. }
  63381. function updateLeaveTo(el, elOption) {
  63382. // Try merge to previous set leaveTo
  63383. var leaveToProps = transitionInnerStore(el).leaveToProps;
  63384. for (var i = 0; i < ELEMENT_ANIMATABLE_PROPS.length; i++) {
  63385. var propName = ELEMENT_ANIMATABLE_PROPS[i];
  63386. var prop = propName ? elOption[propName] : elOption;
  63387. if (prop && prop.leaveTo) {
  63388. if (!leaveToProps) {
  63389. leaveToProps = transitionInnerStore(el).leaveToProps = {};
  63390. }
  63391. if (propName) {
  63392. leaveToProps[propName] = leaveToProps[propName] || {};
  63393. }
  63394. extend(propName ? leaveToProps[propName] : leaveToProps, prop.leaveTo);
  63395. }
  63396. }
  63397. }
  63398. function applyLeaveTransition(el, elOption, animatableModel, onRemove) {
  63399. if (el) {
  63400. var parent_1 = el.parent;
  63401. var leaveToProps = transitionInnerStore(el).leaveToProps;
  63402. if (leaveToProps) {
  63403. // TODO TODO use leave after leaveAnimation in series is introduced
  63404. // TODO Data index?
  63405. var config = getElementAnimationConfig('update', el, elOption, animatableModel, 0);
  63406. config.done = function () {
  63407. parent_1.remove(el);
  63408. onRemove && onRemove();
  63409. };
  63410. el.animateTo(leaveToProps, config);
  63411. } else {
  63412. parent_1.remove(el);
  63413. onRemove && onRemove();
  63414. }
  63415. }
  63416. }
  63417. function isTransitionAll(transition) {
  63418. return transition === 'all';
  63419. }
  63420. function applyPropsDirectly(el, // Can be null/undefined
  63421. allPropsFinal, clearStyle) {
  63422. var styleOpt = allPropsFinal.style;
  63423. if (!el.isGroup && styleOpt) {
  63424. if (clearStyle) {
  63425. el.useStyle({}); // When style object changed, how to trade the existing animation?
  63426. // It is probably complicated and not needed to cover all the cases.
  63427. // But still need consider the case:
  63428. // (1) When using init animation on `style.opacity`, and before the animation
  63429. // ended users triggers an update by mousewhel. At that time the init
  63430. // animation should better be continued rather than terminated.
  63431. // So after `useStyle` called, we should change the animation target manually
  63432. // to continue the effect of the init animation.
  63433. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  63434. // to update the value to `val2` and no animation declared, should be terminate
  63435. // the previous animation or just modify the target of the animation?
  63436. // Therotically That will happen not only on `style` but also on `shape` and
  63437. // `transfrom` props. But we haven't handle this case at present yet.
  63438. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  63439. var animators = el.animators;
  63440. for (var i = 0; i < animators.length; i++) {
  63441. var animator = animators[i]; // targetName is the "topKey".
  63442. if (animator.targetName === 'style') {
  63443. animator.changeTarget(el.style);
  63444. }
  63445. }
  63446. }
  63447. el.setStyle(styleOpt);
  63448. }
  63449. if (allPropsFinal) {
  63450. // Not set style here.
  63451. allPropsFinal.style = null; // Set el to the final state firstly.
  63452. allPropsFinal && el.attr(allPropsFinal);
  63453. allPropsFinal.style = styleOpt;
  63454. }
  63455. }
  63456. function applyPropsTransition(el, elOption, dataIndex, model, // Can be null/undefined
  63457. transFromProps) {
  63458. if (transFromProps) {
  63459. var config = getElementAnimationConfig('update', el, elOption, model, dataIndex);
  63460. if (config.duration > 0) {
  63461. el.animateFrom(transFromProps, config);
  63462. }
  63463. }
  63464. }
  63465. function applyMiscProps(el, elOption) {
  63466. // Merge by default.
  63467. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  63468. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  63469. if (el instanceof Displayable) {
  63470. hasOwn(elOption, 'invisible') && (el.invisible = elOption.invisible);
  63471. }
  63472. if (el instanceof Path) {
  63473. hasOwn(elOption, 'autoBatch') && (el.autoBatch = elOption.autoBatch);
  63474. }
  63475. } // Use it to avoid it be exposed to user.
  63476. var tmpDuringScope = {};
  63477. var transitionDuringAPI = {
  63478. // Usually other props do not need to be changed in animation during.
  63479. setTransform: function (key, val) {
  63480. if ("development" !== 'production') {
  63481. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  63482. }
  63483. tmpDuringScope.el[key] = val;
  63484. return this;
  63485. },
  63486. getTransform: function (key) {
  63487. if ("development" !== 'production') {
  63488. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  63489. }
  63490. return tmpDuringScope.el[key];
  63491. },
  63492. setShape: function (key, val) {
  63493. if ("development" !== 'production') {
  63494. assertNotReserved(key);
  63495. }
  63496. var el = tmpDuringScope.el;
  63497. var shape = el.shape || (el.shape = {});
  63498. shape[key] = val;
  63499. el.dirtyShape && el.dirtyShape();
  63500. return this;
  63501. },
  63502. getShape: function (key) {
  63503. if ("development" !== 'production') {
  63504. assertNotReserved(key);
  63505. }
  63506. var shape = tmpDuringScope.el.shape;
  63507. if (shape) {
  63508. return shape[key];
  63509. }
  63510. },
  63511. setStyle: function (key, val) {
  63512. if ("development" !== 'production') {
  63513. assertNotReserved(key);
  63514. }
  63515. var el = tmpDuringScope.el;
  63516. var style = el.style;
  63517. if (style) {
  63518. if ("development" !== 'production') {
  63519. if (eqNaN(val)) {
  63520. warn('style.' + key + ' must not be assigned with NaN.');
  63521. }
  63522. }
  63523. style[key] = val;
  63524. el.dirtyStyle && el.dirtyStyle();
  63525. }
  63526. return this;
  63527. },
  63528. getStyle: function (key) {
  63529. if ("development" !== 'production') {
  63530. assertNotReserved(key);
  63531. }
  63532. var style = tmpDuringScope.el.style;
  63533. if (style) {
  63534. return style[key];
  63535. }
  63536. },
  63537. setExtra: function (key, val) {
  63538. if ("development" !== 'production') {
  63539. assertNotReserved(key);
  63540. }
  63541. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  63542. extra[key] = val;
  63543. return this;
  63544. },
  63545. getExtra: function (key) {
  63546. if ("development" !== 'production') {
  63547. assertNotReserved(key);
  63548. }
  63549. var extra = tmpDuringScope.el.extra;
  63550. if (extra) {
  63551. return extra[key];
  63552. }
  63553. }
  63554. };
  63555. function assertNotReserved(key) {
  63556. if ("development" !== 'production') {
  63557. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  63558. throw new Error('key must not be "' + key + '"');
  63559. }
  63560. }
  63561. }
  63562. function duringCall() {
  63563. // Do not provide "percent" until some requirements come.
  63564. // Because consider thies case:
  63565. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  63566. // And enter duration is different from update duration.
  63567. // Thus it might be confused about the meaning of "percent" in during callback.
  63568. var scope = this;
  63569. var el = scope.el;
  63570. if (!el) {
  63571. return;
  63572. } // If el is remove from zr by reason like legend, during still need to called,
  63573. // because el will be added back to zr and the prop value should not be incorrect.
  63574. var latestUserDuring = transitionInnerStore(el).userDuring;
  63575. var scopeUserDuring = scope.userDuring; // Ensured a during is only called once in each animation frame.
  63576. // If a during is called multiple times in one frame, maybe some users' calculation logic
  63577. // might be wrong (not sure whether this usage exists).
  63578. // The case of a during might be called twice can be: by default there is a animator for
  63579. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  63580. // another animators for 'style'/'shape'/'extra'.
  63581. if (latestUserDuring !== scopeUserDuring) {
  63582. // release
  63583. scope.el = scope.userDuring = null;
  63584. return;
  63585. }
  63586. tmpDuringScope.el = el; // Give no `this` to user in "during" calling.
  63587. scopeUserDuring(transitionDuringAPI); // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  63588. // consider the issue that the prop might be incorrect when return to "normal" state.
  63589. }
  63590. function prepareShapeOrExtraTransitionFrom(mainAttr, fromEl, elOption, transFromProps) {
  63591. var attrOpt = elOption[mainAttr];
  63592. if (!attrOpt) {
  63593. return;
  63594. }
  63595. var elPropsInAttr = fromEl[mainAttr];
  63596. var transFromPropsInAttr;
  63597. if (elPropsInAttr) {
  63598. var transition = elOption.transition;
  63599. var attrTransition = attrOpt.transition;
  63600. if (attrTransition) {
  63601. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  63602. if (isTransitionAll(attrTransition)) {
  63603. extend(transFromPropsInAttr, elPropsInAttr);
  63604. } else {
  63605. var transitionKeys = normalizeToArray(attrTransition);
  63606. for (var i = 0; i < transitionKeys.length; i++) {
  63607. var key = transitionKeys[i];
  63608. var elVal = elPropsInAttr[key];
  63609. transFromPropsInAttr[key] = elVal;
  63610. }
  63611. }
  63612. } else if (isTransitionAll(transition) || indexOf(transition, mainAttr) >= 0) {
  63613. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  63614. var elPropsInAttrKeys = keys(elPropsInAttr);
  63615. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  63616. var key = elPropsInAttrKeys[i];
  63617. var elVal = elPropsInAttr[key];
  63618. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  63619. transFromPropsInAttr[key] = elVal;
  63620. }
  63621. }
  63622. }
  63623. }
  63624. }
  63625. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  63626. var attrOpt = elOption[mainAttr];
  63627. if (!attrOpt) {
  63628. return;
  63629. }
  63630. var allPropsInAttr = allProps[mainAttr] = {};
  63631. var keysInAttr = keys(attrOpt);
  63632. for (var i = 0; i < keysInAttr.length; i++) {
  63633. var key = keysInAttr[i]; // To avoid share one object with different element, and
  63634. // to avoid user modify the object inexpectedly, have to clone.
  63635. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  63636. }
  63637. }
  63638. function prepareTransformTransitionFrom(el, elOption, transFromProps) {
  63639. var transition = elOption.transition;
  63640. var transitionKeys = isTransitionAll(transition) ? TRANSFORMABLE_PROPS : normalizeToArray(transition || []);
  63641. for (var i = 0; i < transitionKeys.length; i++) {
  63642. var key = transitionKeys[i];
  63643. if (key === 'style' || key === 'shape' || key === 'extra') {
  63644. continue;
  63645. }
  63646. var elVal = el[key];
  63647. if ("development" !== 'production') {
  63648. checkTransformPropRefer(key, 'el.transition');
  63649. } // Do not clone, animator will perform that clone.
  63650. transFromProps[key] = elVal;
  63651. }
  63652. }
  63653. function prepareTransformAllPropsFinal(el, elOption, allProps) {
  63654. for (var i = 0; i < LEGACY_TRANSFORM_PROPS.length; i++) {
  63655. var legacyName = LEGACY_TRANSFORM_PROPS[i];
  63656. var xyName = LEGACY_TRANSFORM_PROPS_MAP[legacyName];
  63657. var legacyArr = elOption[legacyName];
  63658. if (legacyArr) {
  63659. allProps[xyName[0]] = legacyArr[0];
  63660. allProps[xyName[1]] = legacyArr[1];
  63661. }
  63662. }
  63663. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  63664. var key = TRANSFORMABLE_PROPS[i];
  63665. if (elOption[key] != null) {
  63666. allProps[key] = elOption[key];
  63667. }
  63668. }
  63669. }
  63670. function prepareStyleTransitionFrom(fromEl, elOption, styleOpt, transFromProps) {
  63671. if (!styleOpt) {
  63672. return;
  63673. }
  63674. var fromElStyle = fromEl.style;
  63675. var transFromStyleProps;
  63676. if (fromElStyle) {
  63677. var styleTransition = styleOpt.transition;
  63678. var elTransition = elOption.transition;
  63679. if (styleTransition && !isTransitionAll(styleTransition)) {
  63680. var transitionKeys = normalizeToArray(styleTransition);
  63681. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  63682. for (var i = 0; i < transitionKeys.length; i++) {
  63683. var key = transitionKeys[i];
  63684. var elVal = fromElStyle[key]; // Do not clone, see `checkNonStyleTansitionRefer`.
  63685. transFromStyleProps[key] = elVal;
  63686. }
  63687. } else if (fromEl.getAnimationStyleProps && (isTransitionAll(elTransition) || isTransitionAll(styleTransition) || indexOf(elTransition, 'style') >= 0)) {
  63688. var animationProps = fromEl.getAnimationStyleProps();
  63689. var animationStyleProps = animationProps ? animationProps.style : null;
  63690. if (animationStyleProps) {
  63691. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  63692. var styleKeys = keys(styleOpt);
  63693. for (var i = 0; i < styleKeys.length; i++) {
  63694. var key = styleKeys[i];
  63695. if (animationStyleProps[key]) {
  63696. var elVal = fromElStyle[key];
  63697. transFromStyleProps[key] = elVal;
  63698. }
  63699. }
  63700. }
  63701. }
  63702. }
  63703. }
  63704. function isNonStyleTransitionEnabled(optVal, elVal) {
  63705. // The same as `checkNonStyleTansitionRefer`.
  63706. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  63707. }
  63708. var checkTransformPropRefer;
  63709. if ("development" !== 'production') {
  63710. checkTransformPropRefer = function (key, usedIn) {
  63711. if (!hasOwn(TRANSFORM_PROPS_MAP, key)) {
  63712. warn('Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS_MAP).join('`, `') + '` are permitted.');
  63713. }
  63714. };
  63715. }
  63716. var getStateToRestore = makeInner();
  63717. var KEYFRAME_EXCLUDE_KEYS = ['percent', 'easing', 'shape', 'style', 'extra'];
  63718. /**
  63719. * Stop previous keyframe animation and restore the attributes.
  63720. * Avoid new keyframe animation starts with wrong internal state when the percent: 0 is not set.
  63721. */
  63722. function stopPreviousKeyframeAnimationAndRestore(el) {
  63723. // Stop previous keyframe animation.
  63724. el.stopAnimation('keyframe'); // Restore
  63725. el.attr(getStateToRestore(el));
  63726. }
  63727. function applyKeyframeAnimation(el, animationOpts, animatableModel) {
  63728. if (!animatableModel.isAnimationEnabled() || !animationOpts) {
  63729. return;
  63730. }
  63731. if (isArray(animationOpts)) {
  63732. each(animationOpts, function (singleAnimationOpts) {
  63733. applyKeyframeAnimation(el, singleAnimationOpts, animatableModel);
  63734. });
  63735. return;
  63736. }
  63737. var keyframes = animationOpts.keyframes;
  63738. var duration = animationOpts.duration;
  63739. if (animatableModel && duration == null) {
  63740. // Default to use duration of config.
  63741. // NOTE: animation config from payload will be ignored because they are mainly for transitions.
  63742. var config = getAnimationConfig('enter', animatableModel, 0);
  63743. duration = config && config.duration;
  63744. }
  63745. if (!keyframes || !duration) {
  63746. return;
  63747. }
  63748. var stateToRestore = getStateToRestore(el);
  63749. each(ELEMENT_ANIMATABLE_PROPS, function (targetPropName) {
  63750. if (targetPropName && !el[targetPropName]) {
  63751. return;
  63752. }
  63753. var animator;
  63754. var endFrameIsSet = false; // Sort keyframes by percent.
  63755. keyframes.sort(function (a, b) {
  63756. return a.percent - b.percent;
  63757. });
  63758. each(keyframes, function (kf) {
  63759. // Stop current animation.
  63760. var animators = el.animators;
  63761. var kfValues = targetPropName ? kf[targetPropName] : kf;
  63762. if ("development" !== 'production') {
  63763. if (kf.percent >= 1) {
  63764. endFrameIsSet = true;
  63765. }
  63766. }
  63767. if (!kfValues) {
  63768. return;
  63769. }
  63770. var propKeys = keys(kfValues);
  63771. if (!targetPropName) {
  63772. // PENDING performance?
  63773. propKeys = filter(propKeys, function (key) {
  63774. return indexOf(KEYFRAME_EXCLUDE_KEYS, key) < 0;
  63775. });
  63776. }
  63777. if (!propKeys.length) {
  63778. return;
  63779. }
  63780. if (!animator) {
  63781. animator = el.animate(targetPropName, animationOpts.loop, true);
  63782. animator.scope = 'keyframe';
  63783. }
  63784. for (var i = 0; i < animators.length; i++) {
  63785. // Stop all other animation that is not keyframe.
  63786. if (animators[i] !== animator && animators[i].targetName === animator.targetName) {
  63787. animators[i].stopTracks(propKeys);
  63788. }
  63789. }
  63790. targetPropName && (stateToRestore[targetPropName] = stateToRestore[targetPropName] || {});
  63791. var savedTarget = targetPropName ? stateToRestore[targetPropName] : stateToRestore;
  63792. each(propKeys, function (key) {
  63793. // Save original value.
  63794. savedTarget[key] = ((targetPropName ? el[targetPropName] : el) || {})[key];
  63795. });
  63796. animator.whenWithKeys(duration * kf.percent, kfValues, propKeys, kf.easing);
  63797. });
  63798. if (!animator) {
  63799. return;
  63800. }
  63801. if ("development" !== 'production') {
  63802. if (!endFrameIsSet) {
  63803. warn('End frame with percent: 1 is missing in the keyframeAnimation.', true);
  63804. }
  63805. }
  63806. animator.delay(animationOpts.delay || 0).duration(duration).start(animationOpts.easing);
  63807. });
  63808. }
  63809. var EMPHASIS = 'emphasis';
  63810. var NORMAL = 'normal';
  63811. var BLUR = 'blur';
  63812. var SELECT = 'select';
  63813. var STATES = [NORMAL, EMPHASIS, BLUR, SELECT];
  63814. var PATH_ITEM_STYLE = {
  63815. normal: ['itemStyle'],
  63816. emphasis: [EMPHASIS, 'itemStyle'],
  63817. blur: [BLUR, 'itemStyle'],
  63818. select: [SELECT, 'itemStyle']
  63819. };
  63820. var PATH_LABEL = {
  63821. normal: ['label'],
  63822. emphasis: [EMPHASIS, 'label'],
  63823. blur: [BLUR, 'label'],
  63824. select: [SELECT, 'label']
  63825. };
  63826. var DEFAULT_TRANSITION = ['x', 'y']; // Use prefix to avoid index to be the same as el.name,
  63827. // which will cause weird update animation.
  63828. var GROUP_DIFF_PREFIX = 'e\0\0';
  63829. var attachedTxInfoTmp = {
  63830. normal: {},
  63831. emphasis: {},
  63832. blur: {},
  63833. select: {}
  63834. };
  63835. /**
  63836. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  63837. * of each coordinate systems are not required by each coordinate systems directly, but
  63838. * required by the module `custom`.
  63839. *
  63840. * prepareInfoForCustomSeries {Function}: optional
  63841. * @return {Object} {coordSys: {...}, api: {
  63842. * coord: function (data, clamp) {}, // return point in global.
  63843. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  63844. * }}
  63845. */
  63846. var prepareCustoms = {
  63847. cartesian2d: cartesianPrepareCustom,
  63848. geo: geoPrepareCustom,
  63849. single: singlePrepareCustom,
  63850. polar: polarPrepareCustom,
  63851. calendar: calendarPrepareCustom
  63852. };
  63853. function isPath$1(el) {
  63854. return el instanceof Path;
  63855. }
  63856. function isDisplayable(el) {
  63857. return el instanceof Displayable;
  63858. }
  63859. function copyElement(sourceEl, targetEl) {
  63860. targetEl.copyTransform(sourceEl);
  63861. if (isDisplayable(targetEl) && isDisplayable(sourceEl)) {
  63862. targetEl.setStyle(sourceEl.style);
  63863. targetEl.z = sourceEl.z;
  63864. targetEl.z2 = sourceEl.z2;
  63865. targetEl.zlevel = sourceEl.zlevel;
  63866. targetEl.invisible = sourceEl.invisible;
  63867. targetEl.ignore = sourceEl.ignore;
  63868. if (isPath$1(targetEl) && isPath$1(sourceEl)) {
  63869. targetEl.setShape(sourceEl.shape);
  63870. }
  63871. }
  63872. }
  63873. var CustomChartView =
  63874. /** @class */
  63875. function (_super) {
  63876. __extends(CustomChartView, _super);
  63877. function CustomChartView() {
  63878. var _this = _super !== null && _super.apply(this, arguments) || this;
  63879. _this.type = CustomChartView.type;
  63880. return _this;
  63881. }
  63882. CustomChartView.prototype.render = function (customSeries, ecModel, api, payload) {
  63883. // Clear previously rendered progressive elements.
  63884. this._progressiveEls = null;
  63885. var oldData = this._data;
  63886. var data = customSeries.getData();
  63887. var group = this.group;
  63888. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  63889. if (!oldData) {
  63890. // Previous render is incremental render or first render.
  63891. // Needs remove the incremental rendered elements.
  63892. group.removeAll();
  63893. }
  63894. data.diff(oldData).add(function (newIdx) {
  63895. createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  63896. }).remove(function (oldIdx) {
  63897. var el = oldData.getItemGraphicEl(oldIdx);
  63898. el && applyLeaveTransition(el, customInnerStore(el).option, customSeries);
  63899. }).update(function (newIdx, oldIdx) {
  63900. var oldEl = oldData.getItemGraphicEl(oldIdx);
  63901. createOrUpdateItem(api, oldEl, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  63902. }).execute(); // Do clipping
  63903. var clipPath = customSeries.get('clip', true) ? createClipPath(customSeries.coordinateSystem, false, customSeries) : null;
  63904. if (clipPath) {
  63905. group.setClipPath(clipPath);
  63906. } else {
  63907. group.removeClipPath();
  63908. }
  63909. this._data = data;
  63910. };
  63911. CustomChartView.prototype.incrementalPrepareRender = function (customSeries, ecModel, api) {
  63912. this.group.removeAll();
  63913. this._data = null;
  63914. };
  63915. CustomChartView.prototype.incrementalRender = function (params, customSeries, ecModel, api, payload) {
  63916. var data = customSeries.getData();
  63917. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  63918. var progressiveEls = this._progressiveEls = [];
  63919. function setIncrementalAndHoverLayer(el) {
  63920. if (!el.isGroup) {
  63921. el.incremental = true;
  63922. el.ensureState('emphasis').hoverLayer = true;
  63923. }
  63924. }
  63925. for (var idx = params.start; idx < params.end; idx++) {
  63926. var el = createOrUpdateItem(null, null, idx, renderItem(idx, payload), customSeries, this.group, data);
  63927. if (el) {
  63928. el.traverse(setIncrementalAndHoverLayer);
  63929. progressiveEls.push(el);
  63930. }
  63931. }
  63932. };
  63933. CustomChartView.prototype.eachRendered = function (cb) {
  63934. traverseElements(this._progressiveEls || this.group, cb);
  63935. };
  63936. CustomChartView.prototype.filterForExposedEvent = function (eventType, query, targetEl, packedEvent) {
  63937. var elementName = query.element;
  63938. if (elementName == null || targetEl.name === elementName) {
  63939. return true;
  63940. } // Enable to give a name on a group made by `renderItem`, and listen
  63941. // events that are triggered by its descendents.
  63942. while ((targetEl = targetEl.__hostTarget || targetEl.parent) && targetEl !== this.group) {
  63943. if (targetEl.name === elementName) {
  63944. return true;
  63945. }
  63946. }
  63947. return false;
  63948. };
  63949. CustomChartView.type = 'custom';
  63950. return CustomChartView;
  63951. }(ChartView);
  63952. function createEl(elOption) {
  63953. var graphicType = elOption.type;
  63954. var el; // Those graphic elements are not shapes. They should not be
  63955. // overwritten by users, so do them first.
  63956. if (graphicType === 'path') {
  63957. var shape = elOption.shape; // Using pathRect brings convenience to users sacle svg path.
  63958. var pathRect = shape.width != null && shape.height != null ? {
  63959. x: shape.x || 0,
  63960. y: shape.y || 0,
  63961. width: shape.width,
  63962. height: shape.height
  63963. } : null;
  63964. var pathData = getPathData(shape); // Path is also used for icon, so layout 'center' by default.
  63965. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  63966. customInnerStore(el).customPathData = pathData;
  63967. } else if (graphicType === 'image') {
  63968. el = new ZRImage({});
  63969. customInnerStore(el).customImagePath = elOption.style.image;
  63970. } else if (graphicType === 'text') {
  63971. el = new ZRText({}); // customInnerStore(el).customText = (elOption.style as TextStyleProps).text;
  63972. } else if (graphicType === 'group') {
  63973. el = new Group();
  63974. } else if (graphicType === 'compoundPath') {
  63975. throw new Error('"compoundPath" is not supported yet.');
  63976. } else {
  63977. var Clz = getShapeClass(graphicType);
  63978. if (!Clz) {
  63979. var errMsg = '';
  63980. if ("development" !== 'production') {
  63981. errMsg = 'graphic type "' + graphicType + '" can not be found.';
  63982. }
  63983. throwError(errMsg);
  63984. }
  63985. el = new Clz();
  63986. }
  63987. customInnerStore(el).customGraphicType = graphicType;
  63988. el.name = elOption.name; // Compat ec4: the default z2 lift is 1. If changing the number,
  63989. // some cases probably be broken: hierarchy layout along z, like circle packing,
  63990. // where emphasis only intending to modify color/border rather than lift z2.
  63991. el.z2EmphasisLift = 1;
  63992. el.z2SelectLift = 1;
  63993. return el;
  63994. }
  63995. function updateElNormal( // Can be null/undefined
  63996. api, el, dataIndex, elOption, attachedTxInfo, seriesModel, isInit) {
  63997. // Stop and restore before update any other attributes.
  63998. stopPreviousKeyframeAnimationAndRestore(el);
  63999. var txCfgOpt = attachedTxInfo && attachedTxInfo.normal.cfg;
  64000. if (txCfgOpt) {
  64001. // PENDING: whether use user object directly rather than clone?
  64002. // TODO:5.0 textConfig transition animation?
  64003. el.setTextConfig(txCfgOpt);
  64004. } // Default transition ['x', 'y']
  64005. if (elOption && elOption.transition == null) {
  64006. elOption.transition = DEFAULT_TRANSITION;
  64007. } // Do some normalization on style.
  64008. var styleOpt = elOption && elOption.style;
  64009. if (styleOpt) {
  64010. if (el.type === 'text') {
  64011. var textOptionStyle = styleOpt; // Compatible with ec4: if `textFill` or `textStroke` exists use them.
  64012. hasOwn(textOptionStyle, 'textFill') && (textOptionStyle.fill = textOptionStyle.textFill);
  64013. hasOwn(textOptionStyle, 'textStroke') && (textOptionStyle.stroke = textOptionStyle.textStroke);
  64014. }
  64015. var decalPattern = void 0;
  64016. var decalObj = isPath$1(el) ? styleOpt.decal : null;
  64017. if (api && decalObj) {
  64018. decalObj.dirty = true;
  64019. decalPattern = createOrUpdatePatternFromDecal(decalObj, api);
  64020. } // Always overwrite in case user specify this prop.
  64021. styleOpt.__decalPattern = decalPattern;
  64022. }
  64023. if (isDisplayable(el)) {
  64024. if (styleOpt) {
  64025. var decalPattern = styleOpt.__decalPattern;
  64026. if (decalPattern) {
  64027. styleOpt.decal = decalPattern;
  64028. }
  64029. }
  64030. }
  64031. applyUpdateTransition(el, elOption, seriesModel, {
  64032. dataIndex: dataIndex,
  64033. isInit: isInit,
  64034. clearStyle: true
  64035. });
  64036. applyKeyframeAnimation(el, elOption.keyframeAnimation, seriesModel);
  64037. }
  64038. function updateElOnState(state, el, elStateOpt, styleOpt, attachedTxInfo) {
  64039. var elDisplayable = el.isGroup ? null : el;
  64040. var txCfgOpt = attachedTxInfo && attachedTxInfo[state].cfg; // PENDING:5.0 support customize scale change and transition animation?
  64041. if (elDisplayable) {
  64042. // By default support auto lift color when hover whether `emphasis` specified.
  64043. var stateObj = elDisplayable.ensureState(state);
  64044. if (styleOpt === false) {
  64045. var existingEmphasisState = elDisplayable.getState(state);
  64046. if (existingEmphasisState) {
  64047. existingEmphasisState.style = null;
  64048. }
  64049. } else {
  64050. // style is needed to enable default emphasis.
  64051. stateObj.style = styleOpt || null;
  64052. } // If `elOption.styleEmphasis` or `elOption.emphasis.style` is `false`,
  64053. // remove hover style.
  64054. // If `elOption.textConfig` or `elOption.emphasis.textConfig` is null/undefined, it does not
  64055. // make sense. So for simplicity, we do not ditinguish `hasOwnProperty` and null/undefined.
  64056. if (txCfgOpt) {
  64057. stateObj.textConfig = txCfgOpt;
  64058. }
  64059. setDefaultStateProxy(elDisplayable);
  64060. }
  64061. }
  64062. function updateZ$1(el, elOption, seriesModel) {
  64063. // Group not support textContent and not support z yet.
  64064. if (el.isGroup) {
  64065. return;
  64066. }
  64067. var elDisplayable = el;
  64068. var currentZ = seriesModel.currentZ;
  64069. var currentZLevel = seriesModel.currentZLevel; // Always erase.
  64070. elDisplayable.z = currentZ;
  64071. elDisplayable.zlevel = currentZLevel; // z2 must not be null/undefined, otherwise sort error may occur.
  64072. var optZ2 = elOption.z2;
  64073. optZ2 != null && (elDisplayable.z2 = optZ2 || 0);
  64074. for (var i = 0; i < STATES.length; i++) {
  64075. updateZForEachState(elDisplayable, elOption, STATES[i]);
  64076. }
  64077. }
  64078. function updateZForEachState(elDisplayable, elOption, state) {
  64079. var isNormal = state === NORMAL;
  64080. var elStateOpt = isNormal ? elOption : retrieveStateOption(elOption, state);
  64081. var optZ2 = elStateOpt ? elStateOpt.z2 : null;
  64082. var stateObj;
  64083. if (optZ2 != null) {
  64084. // Do not `ensureState` until required.
  64085. stateObj = isNormal ? elDisplayable : elDisplayable.ensureState(state);
  64086. stateObj.z2 = optZ2 || 0;
  64087. }
  64088. }
  64089. function makeRenderItem(customSeries, data, ecModel, api) {
  64090. var renderItem = customSeries.get('renderItem');
  64091. var coordSys = customSeries.coordinateSystem;
  64092. var prepareResult = {};
  64093. if (coordSys) {
  64094. if ("development" !== 'production') {
  64095. assert(renderItem, 'series.render is required.');
  64096. assert(coordSys.prepareCustoms || prepareCustoms[coordSys.type], 'This coordSys does not support custom series.');
  64097. } // `coordSys.prepareCustoms` is used for external coord sys like bmap.
  64098. prepareResult = coordSys.prepareCustoms ? coordSys.prepareCustoms(coordSys) : prepareCustoms[coordSys.type](coordSys);
  64099. }
  64100. var userAPI = defaults({
  64101. getWidth: api.getWidth,
  64102. getHeight: api.getHeight,
  64103. getZr: api.getZr,
  64104. getDevicePixelRatio: api.getDevicePixelRatio,
  64105. value: value,
  64106. style: style,
  64107. ordinalRawValue: ordinalRawValue,
  64108. styleEmphasis: styleEmphasis,
  64109. visual: visual,
  64110. barLayout: barLayout,
  64111. currentSeriesIndices: currentSeriesIndices,
  64112. font: font
  64113. }, prepareResult.api || {});
  64114. var userParams = {
  64115. // The life cycle of context: current round of rendering.
  64116. // The global life cycle is probably not necessary, because
  64117. // user can store global status by themselves.
  64118. context: {},
  64119. seriesId: customSeries.id,
  64120. seriesName: customSeries.name,
  64121. seriesIndex: customSeries.seriesIndex,
  64122. coordSys: prepareResult.coordSys,
  64123. dataInsideLength: data.count(),
  64124. encode: wrapEncodeDef(customSeries.getData())
  64125. }; // If someday intending to refactor them to a class, should consider do not
  64126. // break change: currently these attribute member are encapsulated in a closure
  64127. // so that do not need to force user to call these method with a scope.
  64128. // Do not support call `api` asynchronously without dataIndexInside input.
  64129. var currDataIndexInside;
  64130. var currItemModel;
  64131. var currItemStyleModels = {};
  64132. var currLabelModels = {};
  64133. var seriesItemStyleModels = {};
  64134. var seriesLabelModels = {};
  64135. for (var i = 0; i < STATES.length; i++) {
  64136. var stateName = STATES[i];
  64137. seriesItemStyleModels[stateName] = customSeries.getModel(PATH_ITEM_STYLE[stateName]);
  64138. seriesLabelModels[stateName] = customSeries.getModel(PATH_LABEL[stateName]);
  64139. }
  64140. function getItemModel(dataIndexInside) {
  64141. return dataIndexInside === currDataIndexInside ? currItemModel || (currItemModel = data.getItemModel(dataIndexInside)) : data.getItemModel(dataIndexInside);
  64142. }
  64143. function getItemStyleModel(dataIndexInside, state) {
  64144. return !data.hasItemOption ? seriesItemStyleModels[state] : dataIndexInside === currDataIndexInside ? currItemStyleModels[state] || (currItemStyleModels[state] = getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state])) : getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state]);
  64145. }
  64146. function getLabelModel(dataIndexInside, state) {
  64147. return !data.hasItemOption ? seriesLabelModels[state] : dataIndexInside === currDataIndexInside ? currLabelModels[state] || (currLabelModels[state] = getItemModel(dataIndexInside).getModel(PATH_LABEL[state])) : getItemModel(dataIndexInside).getModel(PATH_LABEL[state]);
  64148. }
  64149. return function (dataIndexInside, payload) {
  64150. currDataIndexInside = dataIndexInside;
  64151. currItemModel = null;
  64152. currItemStyleModels = {};
  64153. currLabelModels = {};
  64154. return renderItem && renderItem(defaults({
  64155. dataIndexInside: dataIndexInside,
  64156. dataIndex: data.getRawIndex(dataIndexInside),
  64157. // Can be used for optimization when zoom or roam.
  64158. actionType: payload ? payload.type : null
  64159. }, userParams), userAPI);
  64160. };
  64161. /**
  64162. * @public
  64163. * @param dim by default 0.
  64164. * @param dataIndexInside by default `currDataIndexInside`.
  64165. */
  64166. function value(dim, dataIndexInside) {
  64167. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64168. return data.getStore().get(data.getDimensionIndex(dim || 0), dataIndexInside);
  64169. }
  64170. /**
  64171. * @public
  64172. * @param dim by default 0.
  64173. * @param dataIndexInside by default `currDataIndexInside`.
  64174. */
  64175. function ordinalRawValue(dim, dataIndexInside) {
  64176. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64177. dim = dim || 0;
  64178. var dimInfo = data.getDimensionInfo(dim);
  64179. if (!dimInfo) {
  64180. var dimIndex = data.getDimensionIndex(dim);
  64181. return dimIndex >= 0 ? data.getStore().get(dimIndex, dataIndexInside) : undefined;
  64182. }
  64183. var val = data.get(dimInfo.name, dataIndexInside);
  64184. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  64185. return ordinalMeta ? ordinalMeta.categories[val] : val;
  64186. }
  64187. /**
  64188. * @deprecated The original intention of `api.style` is enable to set itemStyle
  64189. * like other series. But it is not necessary and not easy to give a strict definition
  64190. * of what it returns. And since echarts5 it needs to be make compat work. So
  64191. * deprecates it since echarts5.
  64192. *
  64193. * By default, `visual` is applied to style (to support visualMap).
  64194. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  64195. * it can be implemented as:
  64196. * `api.style({stroke: api.visual('color'), fill: null})`;
  64197. *
  64198. * [Compat]: since ec5, RectText has been separated from its hosts el.
  64199. * so `api.style()` will only return the style from `itemStyle` but not handle `label`
  64200. * any more. But `series.label` config is never published in doc.
  64201. * We still compat it in `api.style()`. But not encourage to use it and will still not
  64202. * to pulish it to doc.
  64203. * @public
  64204. * @param dataIndexInside by default `currDataIndexInside`.
  64205. */
  64206. function style(userProps, dataIndexInside) {
  64207. if ("development" !== 'production') {
  64208. warnDeprecated('api.style', 'Please write literal style directly instead.');
  64209. }
  64210. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64211. var style = data.getItemVisual(dataIndexInside, 'style');
  64212. var visualColor = style && style.fill;
  64213. var opacity = style && style.opacity;
  64214. var itemStyle = getItemStyleModel(dataIndexInside, NORMAL).getItemStyle();
  64215. visualColor != null && (itemStyle.fill = visualColor);
  64216. opacity != null && (itemStyle.opacity = opacity);
  64217. var opt = {
  64218. inheritColor: isString(visualColor) ? visualColor : '#000'
  64219. };
  64220. var labelModel = getLabelModel(dataIndexInside, NORMAL); // Now that the feature of "auto adjust text fill/stroke" has been migrated to zrender
  64221. // since ec5, we should set `isAttached` as `false` here and make compat in
  64222. // `convertToEC4StyleForCustomSerise`.
  64223. var textStyle = createTextStyle(labelModel, null, opt, false, true);
  64224. textStyle.text = labelModel.getShallow('show') ? retrieve2(customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  64225. var textConfig = createTextConfig(labelModel, opt, false);
  64226. preFetchFromExtra(userProps, itemStyle);
  64227. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  64228. userProps && applyUserPropsAfter(itemStyle, userProps);
  64229. itemStyle.legacy = true;
  64230. return itemStyle;
  64231. }
  64232. /**
  64233. * @deprecated The reason see `api.style()`
  64234. * @public
  64235. * @param dataIndexInside by default `currDataIndexInside`.
  64236. */
  64237. function styleEmphasis(userProps, dataIndexInside) {
  64238. if ("development" !== 'production') {
  64239. warnDeprecated('api.styleEmphasis', 'Please write literal style directly instead.');
  64240. }
  64241. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64242. var itemStyle = getItemStyleModel(dataIndexInside, EMPHASIS).getItemStyle();
  64243. var labelModel = getLabelModel(dataIndexInside, EMPHASIS);
  64244. var textStyle = createTextStyle(labelModel, null, null, true, true);
  64245. textStyle.text = labelModel.getShallow('show') ? retrieve3(customSeries.getFormattedLabel(dataIndexInside, EMPHASIS), customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  64246. var textConfig = createTextConfig(labelModel, null, true);
  64247. preFetchFromExtra(userProps, itemStyle);
  64248. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  64249. userProps && applyUserPropsAfter(itemStyle, userProps);
  64250. itemStyle.legacy = true;
  64251. return itemStyle;
  64252. }
  64253. function applyUserPropsAfter(itemStyle, extra) {
  64254. for (var key in extra) {
  64255. if (hasOwn(extra, key)) {
  64256. itemStyle[key] = extra[key];
  64257. }
  64258. }
  64259. }
  64260. function preFetchFromExtra(extra, itemStyle) {
  64261. // A trick to retrieve those props firstly, which are used to
  64262. // apply auto inside fill/stroke in `convertToEC4StyleForCustomSerise`.
  64263. // (It's not reasonable but only for a degree of compat)
  64264. if (extra) {
  64265. extra.textFill && (itemStyle.textFill = extra.textFill);
  64266. extra.textPosition && (itemStyle.textPosition = extra.textPosition);
  64267. }
  64268. }
  64269. /**
  64270. * @public
  64271. * @param dataIndexInside by default `currDataIndexInside`.
  64272. */
  64273. function visual(visualType, dataIndexInside) {
  64274. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64275. if (hasOwn(STYLE_VISUAL_TYPE, visualType)) {
  64276. var style_1 = data.getItemVisual(dataIndexInside, 'style');
  64277. return style_1 ? style_1[STYLE_VISUAL_TYPE[visualType]] : null;
  64278. } // Only support these visuals. Other visual might be inner tricky
  64279. // for performance (like `style`), do not expose to users.
  64280. if (hasOwn(NON_STYLE_VISUAL_PROPS, visualType)) {
  64281. return data.getItemVisual(dataIndexInside, visualType);
  64282. }
  64283. }
  64284. /**
  64285. * @public
  64286. * @return If not support, return undefined.
  64287. */
  64288. function barLayout(opt) {
  64289. if (coordSys.type === 'cartesian2d') {
  64290. var baseAxis = coordSys.getBaseAxis();
  64291. return getLayoutOnAxis(defaults({
  64292. axis: baseAxis
  64293. }, opt));
  64294. }
  64295. }
  64296. /**
  64297. * @public
  64298. */
  64299. function currentSeriesIndices() {
  64300. return ecModel.getCurrentSeriesIndices();
  64301. }
  64302. /**
  64303. * @public
  64304. * @return font string
  64305. */
  64306. function font(opt) {
  64307. return getFont(opt, ecModel);
  64308. }
  64309. }
  64310. function wrapEncodeDef(data) {
  64311. var encodeDef = {};
  64312. each(data.dimensions, function (dimName) {
  64313. var dimInfo = data.getDimensionInfo(dimName);
  64314. if (!dimInfo.isExtraCoord) {
  64315. var coordDim = dimInfo.coordDim;
  64316. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  64317. dataDims[dimInfo.coordDimIndex] = data.getDimensionIndex(dimName);
  64318. }
  64319. });
  64320. return encodeDef;
  64321. }
  64322. function createOrUpdateItem(api, existsEl, dataIndex, elOption, seriesModel, group, data) {
  64323. // [Rule]
  64324. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  64325. // (It seems that violate the "merge" principle, but most of users probably intuitively
  64326. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  64327. // most cases.)
  64328. // The rule or "merge" see [STRATEGY_MERGE].
  64329. // If `elOption` is `null`/`undefined`/`false` (when `renderItem` returns nothing).
  64330. if (!elOption) {
  64331. group.remove(existsEl);
  64332. return;
  64333. }
  64334. var el = doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group);
  64335. el && data.setItemGraphicEl(dataIndex, el);
  64336. el && toggleHoverEmphasis(el, elOption.focus, elOption.blurScope, elOption.emphasisDisabled);
  64337. return el;
  64338. }
  64339. function doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group) {
  64340. if ("development" !== 'production') {
  64341. assert(elOption, 'should not have an null/undefined element setting');
  64342. }
  64343. var toBeReplacedIdx = -1;
  64344. var oldEl = existsEl;
  64345. if (existsEl && doesElNeedRecreate(existsEl, elOption, seriesModel) // || (
  64346. // // PENDING: even in one-to-one mapping case, if el is marked as morph,
  64347. // // do not sure whether the el will be mapped to another el with different
  64348. // // hierarchy in Group tree. So always recreate el rather than reuse the el.
  64349. // morphHelper && morphHelper.isOneToOneFrom(el)
  64350. // )
  64351. ) {
  64352. // Should keep at the original index, otherwise "merge by index" will be incorrect.
  64353. toBeReplacedIdx = indexOf(group.childrenRef(), existsEl);
  64354. existsEl = null;
  64355. }
  64356. var isInit = !existsEl;
  64357. var el = existsEl;
  64358. if (!el) {
  64359. el = createEl(elOption);
  64360. if (oldEl) {
  64361. copyElement(oldEl, el);
  64362. }
  64363. } else {
  64364. // FIMXE:NEXT unified clearState?
  64365. // If in some case the performance issue arised, consider
  64366. // do not clearState but update cached normal state directly.
  64367. el.clearStates();
  64368. } // Need to set morph: false explictly to disable automatically morphing.
  64369. if (elOption.morph === false) {
  64370. el.disableMorphing = true;
  64371. } else if (el.disableMorphing) {
  64372. el.disableMorphing = false;
  64373. }
  64374. attachedTxInfoTmp.normal.cfg = attachedTxInfoTmp.normal.conOpt = attachedTxInfoTmp.emphasis.cfg = attachedTxInfoTmp.emphasis.conOpt = attachedTxInfoTmp.blur.cfg = attachedTxInfoTmp.blur.conOpt = attachedTxInfoTmp.select.cfg = attachedTxInfoTmp.select.conOpt = null;
  64375. attachedTxInfoTmp.isLegacy = false;
  64376. doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfoTmp);
  64377. doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit);
  64378. updateElNormal(api, el, dataIndex, elOption, attachedTxInfoTmp, seriesModel, isInit); // `elOption.info` enables user to mount some info on
  64379. // elements and use them in event handlers.
  64380. // Update them only when user specified, otherwise, remain.
  64381. hasOwn(elOption, 'info') && (customInnerStore(el).info = elOption.info);
  64382. for (var i = 0; i < STATES.length; i++) {
  64383. var stateName = STATES[i];
  64384. if (stateName !== NORMAL) {
  64385. var otherStateOpt = retrieveStateOption(elOption, stateName);
  64386. var otherStyleOpt = retrieveStyleOptionOnState(elOption, otherStateOpt, stateName);
  64387. updateElOnState(stateName, el, otherStateOpt, otherStyleOpt, attachedTxInfoTmp);
  64388. }
  64389. }
  64390. updateZ$1(el, elOption, seriesModel);
  64391. if (elOption.type === 'group') {
  64392. mergeChildren(api, el, dataIndex, elOption, seriesModel);
  64393. }
  64394. if (toBeReplacedIdx >= 0) {
  64395. group.replaceAt(el, toBeReplacedIdx);
  64396. } else {
  64397. group.add(el);
  64398. }
  64399. return el;
  64400. } // `el` must not be null/undefined.
  64401. function doesElNeedRecreate(el, elOption, seriesModel) {
  64402. var elInner = customInnerStore(el);
  64403. var elOptionType = elOption.type;
  64404. var elOptionShape = elOption.shape;
  64405. var elOptionStyle = elOption.style;
  64406. return (// Always create new if universal transition is enabled.
  64407. // Because we do transition after render. It needs to know what old element is. Replacement will loose it.
  64408. seriesModel.isUniversalTransitionEnabled() // If `elOptionType` is `null`, follow the merge principle.
  64409. || elOptionType != null && elOptionType !== elInner.customGraphicType || elOptionType === 'path' && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== elInner.customPathData || elOptionType === 'image' && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== elInner.customImagePath // // FIXME test and remove this restriction?
  64410. // || (elOptionType === 'text'
  64411. // && hasOwn(elOptionStyle, 'text')
  64412. // && (elOptionStyle as TextStyleProps).text !== elInner.customText
  64413. // )
  64414. );
  64415. }
  64416. function doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit) {
  64417. // Based on the "merge" principle, if no clipPath provided,
  64418. // do nothing. The exists clip will be totally removed only if
  64419. // `el.clipPath` is `false`. Otherwise it will be merged/replaced.
  64420. var clipPathOpt = elOption.clipPath;
  64421. if (clipPathOpt === false) {
  64422. if (el && el.getClipPath()) {
  64423. el.removeClipPath();
  64424. }
  64425. } else if (clipPathOpt) {
  64426. var clipPath = el.getClipPath();
  64427. if (clipPath && doesElNeedRecreate(clipPath, clipPathOpt, seriesModel)) {
  64428. clipPath = null;
  64429. }
  64430. if (!clipPath) {
  64431. clipPath = createEl(clipPathOpt);
  64432. if ("development" !== 'production') {
  64433. assert(isPath$1(clipPath), 'Only any type of `path` can be used in `clipPath`, rather than ' + clipPath.type + '.');
  64434. }
  64435. el.setClipPath(clipPath);
  64436. }
  64437. updateElNormal(null, clipPath, dataIndex, clipPathOpt, null, seriesModel, isInit);
  64438. } // If not define `clipPath` in option, do nothing unnecessary.
  64439. }
  64440. function doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfo) {
  64441. // Group does not support textContent temporarily until necessary.
  64442. if (el.isGroup) {
  64443. return;
  64444. } // Normal must be called before emphasis, for `isLegacy` detection.
  64445. processTxInfo(elOption, null, attachedTxInfo);
  64446. processTxInfo(elOption, EMPHASIS, attachedTxInfo); // If `elOption.textConfig` or `elOption.textContent` is null/undefined, it does not make sense.
  64447. // So for simplicity, if "elOption hasOwnProperty of them but be null/undefined", we do not
  64448. // trade them as set to null to el.
  64449. // Especially:
  64450. // `elOption.textContent: false` means remove textContent.
  64451. // `elOption.textContent.emphasis.style: false` means remove the style from emphasis state.
  64452. var txConOptNormal = attachedTxInfo.normal.conOpt;
  64453. var txConOptEmphasis = attachedTxInfo.emphasis.conOpt;
  64454. var txConOptBlur = attachedTxInfo.blur.conOpt;
  64455. var txConOptSelect = attachedTxInfo.select.conOpt;
  64456. if (txConOptNormal != null || txConOptEmphasis != null || txConOptSelect != null || txConOptBlur != null) {
  64457. var textContent = el.getTextContent();
  64458. if (txConOptNormal === false) {
  64459. textContent && el.removeTextContent();
  64460. } else {
  64461. txConOptNormal = attachedTxInfo.normal.conOpt = txConOptNormal || {
  64462. type: 'text'
  64463. };
  64464. if (!textContent) {
  64465. textContent = createEl(txConOptNormal);
  64466. el.setTextContent(textContent);
  64467. } else {
  64468. // If in some case the performance issue arised, consider
  64469. // do not clearState but update cached normal state directly.
  64470. textContent.clearStates();
  64471. }
  64472. updateElNormal(null, textContent, dataIndex, txConOptNormal, null, seriesModel, isInit);
  64473. var txConStlOptNormal = txConOptNormal && txConOptNormal.style;
  64474. for (var i = 0; i < STATES.length; i++) {
  64475. var stateName = STATES[i];
  64476. if (stateName !== NORMAL) {
  64477. var txConOptOtherState = attachedTxInfo[stateName].conOpt;
  64478. updateElOnState(stateName, textContent, txConOptOtherState, retrieveStyleOptionOnState(txConOptNormal, txConOptOtherState, stateName), null);
  64479. }
  64480. }
  64481. txConStlOptNormal ? textContent.dirty() : textContent.markRedraw();
  64482. }
  64483. }
  64484. }
  64485. function processTxInfo(elOption, state, attachedTxInfo) {
  64486. var stateOpt = !state ? elOption : retrieveStateOption(elOption, state);
  64487. var styleOpt = !state ? elOption.style : retrieveStyleOptionOnState(elOption, stateOpt, EMPHASIS);
  64488. var elType = elOption.type;
  64489. var txCfg = stateOpt ? stateOpt.textConfig : null;
  64490. var txConOptNormal = elOption.textContent;
  64491. var txConOpt = !txConOptNormal ? null : !state ? txConOptNormal : retrieveStateOption(txConOptNormal, state);
  64492. if (styleOpt && ( // Because emphasis style has little info to detect legacy,
  64493. // if normal is legacy, emphasis is trade as legacy.
  64494. attachedTxInfo.isLegacy || isEC4CompatibleStyle(styleOpt, elType, !!txCfg, !!txConOpt))) {
  64495. attachedTxInfo.isLegacy = true;
  64496. var convertResult = convertFromEC4CompatibleStyle(styleOpt, elType, !state); // Explicitly specified `textConfig` and `textContent` has higher priority than
  64497. // the ones generated by legacy style. Otherwise if users use them and `api.style`
  64498. // at the same time, they not both work and hardly to known why.
  64499. if (!txCfg && convertResult.textConfig) {
  64500. txCfg = convertResult.textConfig;
  64501. }
  64502. if (!txConOpt && convertResult.textContent) {
  64503. txConOpt = convertResult.textContent;
  64504. }
  64505. }
  64506. if (!state && txConOpt) {
  64507. var txConOptNormal_1 = txConOpt; // `textContent: {type: 'text'}`, the "type" is easy to be missing. So we tolerate it.
  64508. !txConOptNormal_1.type && (txConOptNormal_1.type = 'text');
  64509. if ("development" !== 'production') {
  64510. // Do not tolerate incorrcet type for forward compat.
  64511. assert(txConOptNormal_1.type === 'text', 'textContent.type must be "text"');
  64512. }
  64513. }
  64514. var info = !state ? attachedTxInfo.normal : attachedTxInfo[state];
  64515. info.cfg = txCfg;
  64516. info.conOpt = txConOpt;
  64517. }
  64518. function retrieveStateOption(elOption, state) {
  64519. return !state ? elOption : elOption ? elOption[state] : null;
  64520. }
  64521. function retrieveStyleOptionOnState(stateOptionNormal, stateOption, state) {
  64522. var style = stateOption && stateOption.style;
  64523. if (style == null && state === EMPHASIS && stateOptionNormal) {
  64524. style = stateOptionNormal.styleEmphasis;
  64525. }
  64526. return style;
  64527. } // Usage:
  64528. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates
  64529. // that the existing children will not be removed, and enables the feature
  64530. // that update some of the props of some of the children simply by construct
  64531. // the returned children of `renderItem` like:
  64532. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  64533. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  64534. // by child.name. But that might be lower performance.
  64535. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  64536. // replaced totally.
  64537. // (4) If `!elOption.children`, following the "merge" principle, nothing will
  64538. // happen.
  64539. // (5) If `elOption.$mergeChildren` is not `false` neither `'byName'` and the
  64540. // `el` is a group, and if any of the new child is null, it means to remove
  64541. // the element at the same index, if exists. On the other hand, if the new
  64542. // child is and empty object `{}`, it means to keep the element not changed.
  64543. //
  64544. // For implementation simpleness, do not provide a direct way to remove single
  64545. // child (otherwise the total indices of the children array have to be modified).
  64546. // User can remove a single child by setting its `ignore` to `true`.
  64547. function mergeChildren(api, el, dataIndex, elOption, seriesModel) {
  64548. var newChildren = elOption.children;
  64549. var newLen = newChildren ? newChildren.length : 0;
  64550. var mergeChildren = elOption.$mergeChildren; // `diffChildrenByName` has been deprecated.
  64551. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  64552. var notMerge = mergeChildren === false; // For better performance on roam update, only enter if necessary.
  64553. if (!newLen && !byName && !notMerge) {
  64554. return;
  64555. }
  64556. if (byName) {
  64557. diffGroupChildren({
  64558. api: api,
  64559. oldChildren: el.children() || [],
  64560. newChildren: newChildren || [],
  64561. dataIndex: dataIndex,
  64562. seriesModel: seriesModel,
  64563. group: el
  64564. });
  64565. return;
  64566. }
  64567. notMerge && el.removeAll(); // Mapping children of a group simply by index, which
  64568. // might be better performance.
  64569. var index = 0;
  64570. for (; index < newLen; index++) {
  64571. var newChild = newChildren[index];
  64572. var oldChild = el.childAt(index);
  64573. if (newChild) {
  64574. if (newChild.ignore == null) {
  64575. // The old child is set to be ignored if null (see comments
  64576. // below). So we need to set ignore to be false back.
  64577. newChild.ignore = false;
  64578. }
  64579. doCreateOrUpdateEl(api, oldChild, dataIndex, newChild, seriesModel, el);
  64580. } else {
  64581. if ("development" !== 'production') {
  64582. assert(oldChild, 'renderItem should not return a group containing elements' + ' as null/undefined/{} if they do not exist before.');
  64583. } // If the new element option is null, it means to remove the old
  64584. // element. But we cannot really remove the element from the group
  64585. // directly, because the element order may not be stable when this
  64586. // element is added back. So we set the element to be ignored.
  64587. oldChild.ignore = true;
  64588. }
  64589. }
  64590. for (var i = el.childCount() - 1; i >= index; i--) {
  64591. var child = el.childAt(i);
  64592. removeChildFromGroup(el, child, seriesModel);
  64593. }
  64594. }
  64595. function removeChildFromGroup(group, child, seriesModel) {
  64596. // Do not support leave elements that are not mentioned in the latest
  64597. // `renderItem` return. Otherwise users may not have a clear and simple
  64598. // concept that how to control all of the elements.
  64599. child && applyLeaveTransition(child, customInnerStore(group).option, seriesModel);
  64600. }
  64601. function diffGroupChildren(context) {
  64602. new DataDiffer(context.oldChildren, context.newChildren, getKey, getKey, context).add(processAddUpdate).update(processAddUpdate).remove(processRemove).execute();
  64603. }
  64604. function getKey(item, idx) {
  64605. var name = item && item.name;
  64606. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  64607. }
  64608. function processAddUpdate(newIndex, oldIndex) {
  64609. var context = this.context;
  64610. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  64611. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  64612. doCreateOrUpdateEl(context.api, child, context.dataIndex, childOption, context.seriesModel, context.group);
  64613. }
  64614. function processRemove(oldIndex) {
  64615. var context = this.context;
  64616. var child = context.oldChildren[oldIndex];
  64617. child && applyLeaveTransition(child, customInnerStore(child).option, context.seriesModel);
  64618. }
  64619. /**
  64620. * @return SVG Path data.
  64621. */
  64622. function getPathData(shape) {
  64623. // "d" follows the SVG convention.
  64624. return shape && (shape.pathData || shape.d);
  64625. }
  64626. function hasOwnPathData(shape) {
  64627. return shape && (hasOwn(shape, 'pathData') || hasOwn(shape, 'd'));
  64628. }
  64629. function install$r(registers) {
  64630. registers.registerChartView(CustomChartView);
  64631. registers.registerSeriesModel(CustomSeriesModel);
  64632. }
  64633. var inner$a = makeInner();
  64634. var clone$3 = clone;
  64635. var bind$1 = bind;
  64636. /**
  64637. * Base axis pointer class in 2D.
  64638. */
  64639. var BaseAxisPointer =
  64640. /** @class */
  64641. function () {
  64642. function BaseAxisPointer() {
  64643. this._dragging = false;
  64644. /**
  64645. * In px, arbitrary value. Do not set too small,
  64646. * no animation is ok for most cases.
  64647. */
  64648. this.animationThreshold = 15;
  64649. }
  64650. /**
  64651. * @implement
  64652. */
  64653. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  64654. var value = axisPointerModel.get('value');
  64655. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  64656. // be replaced when user calling setOption in not merge mode.
  64657. this._axisModel = axisModel;
  64658. this._axisPointerModel = axisPointerModel;
  64659. this._api = api; // Optimize: `render` will be called repeatedly during mouse move.
  64660. // So it is power consuming if performing `render` each time,
  64661. // especially on mobile device.
  64662. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  64663. return;
  64664. }
  64665. this._lastValue = value;
  64666. this._lastStatus = status;
  64667. var group = this._group;
  64668. var handle = this._handle;
  64669. if (!status || status === 'hide') {
  64670. // Do not clear here, for animation better.
  64671. group && group.hide();
  64672. handle && handle.hide();
  64673. return;
  64674. }
  64675. group && group.show();
  64676. handle && handle.show(); // Otherwise status is 'show'
  64677. var elOption = {};
  64678. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  64679. var graphicKey = elOption.graphicKey;
  64680. if (graphicKey !== this._lastGraphicKey) {
  64681. this.clear(api);
  64682. }
  64683. this._lastGraphicKey = graphicKey;
  64684. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  64685. if (!group) {
  64686. group = this._group = new Group();
  64687. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  64688. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  64689. api.getZr().add(group);
  64690. } else {
  64691. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  64692. this.updatePointerEl(group, elOption, doUpdateProps);
  64693. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  64694. }
  64695. updateMandatoryProps(group, axisPointerModel, true);
  64696. this._renderHandle(value);
  64697. };
  64698. /**
  64699. * @implement
  64700. */
  64701. BaseAxisPointer.prototype.remove = function (api) {
  64702. this.clear(api);
  64703. };
  64704. /**
  64705. * @implement
  64706. */
  64707. BaseAxisPointer.prototype.dispose = function (api) {
  64708. this.clear(api);
  64709. };
  64710. /**
  64711. * @protected
  64712. */
  64713. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  64714. var animation = axisPointerModel.get('animation');
  64715. var axis = axisModel.axis;
  64716. var isCategoryAxis = axis.type === 'category';
  64717. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  64718. if (!useSnap && !isCategoryAxis) {
  64719. return false;
  64720. }
  64721. if (animation === 'auto' || animation == null) {
  64722. var animationThreshold = this.animationThreshold;
  64723. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  64724. return true;
  64725. } // It is important to auto animation when snap used. Consider if there is
  64726. // a dataZoom, animation will be disabled when too many points exist, while
  64727. // it will be enabled for better visual effect when little points exist.
  64728. if (useSnap) {
  64729. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  64730. var axisExtent = axis.getExtent(); // Approximate band width
  64731. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  64732. }
  64733. return false;
  64734. }
  64735. return animation === true;
  64736. };
  64737. /**
  64738. * add {pointer, label, graphicKey} to elOption
  64739. * @protected
  64740. */
  64741. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {// Should be implemenented by sub-class.
  64742. };
  64743. /**
  64744. * @protected
  64745. */
  64746. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  64747. var pointerOption = elOption.pointer;
  64748. if (pointerOption) {
  64749. var pointerEl = inner$a(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  64750. group.add(pointerEl);
  64751. }
  64752. };
  64753. /**
  64754. * @protected
  64755. */
  64756. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  64757. if (elOption.label) {
  64758. var labelEl = inner$a(group).labelEl = new ZRText(clone$3(elOption.label));
  64759. group.add(labelEl);
  64760. updateLabelShowHide(labelEl, axisPointerModel);
  64761. }
  64762. };
  64763. /**
  64764. * @protected
  64765. */
  64766. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  64767. var pointerEl = inner$a(group).pointerEl;
  64768. if (pointerEl && elOption.pointer) {
  64769. pointerEl.setStyle(elOption.pointer.style);
  64770. updateProps(pointerEl, {
  64771. shape: elOption.pointer.shape
  64772. });
  64773. }
  64774. };
  64775. /**
  64776. * @protected
  64777. */
  64778. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  64779. var labelEl = inner$a(group).labelEl;
  64780. if (labelEl) {
  64781. labelEl.setStyle(elOption.label.style);
  64782. updateProps(labelEl, {
  64783. // Consider text length change in vertical axis, animation should
  64784. // be used on shape, otherwise the effect will be weird.
  64785. // TODOTODO
  64786. // shape: elOption.label.shape,
  64787. x: elOption.label.x,
  64788. y: elOption.label.y
  64789. });
  64790. updateLabelShowHide(labelEl, axisPointerModel);
  64791. }
  64792. };
  64793. /**
  64794. * @private
  64795. */
  64796. BaseAxisPointer.prototype._renderHandle = function (value) {
  64797. if (this._dragging || !this.updateHandleTransform) {
  64798. return;
  64799. }
  64800. var axisPointerModel = this._axisPointerModel;
  64801. var zr = this._api.getZr();
  64802. var handle = this._handle;
  64803. var handleModel = axisPointerModel.getModel('handle');
  64804. var status = axisPointerModel.get('status');
  64805. if (!handleModel.get('show') || !status || status === 'hide') {
  64806. handle && zr.remove(handle);
  64807. this._handle = null;
  64808. return;
  64809. }
  64810. var isInit;
  64811. if (!this._handle) {
  64812. isInit = true;
  64813. handle = this._handle = createIcon(handleModel.get('icon'), {
  64814. cursor: 'move',
  64815. draggable: true,
  64816. onmousemove: function (e) {
  64817. // For mobile device, prevent screen slider on the button.
  64818. stop(e.event);
  64819. },
  64820. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  64821. drift: bind$1(this._onHandleDragMove, this),
  64822. ondragend: bind$1(this._onHandleDragEnd, this)
  64823. });
  64824. zr.add(handle);
  64825. }
  64826. updateMandatoryProps(handle, axisPointerModel, false); // update style
  64827. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'])); // update position
  64828. var handleSize = handleModel.get('size');
  64829. if (!isArray(handleSize)) {
  64830. handleSize = [handleSize, handleSize];
  64831. }
  64832. handle.scaleX = handleSize[0] / 2;
  64833. handle.scaleY = handleSize[1] / 2;
  64834. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  64835. this._moveHandleToValue(value, isInit);
  64836. };
  64837. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  64838. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  64839. };
  64840. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  64841. var handle = this._handle;
  64842. if (!handle) {
  64843. return;
  64844. }
  64845. this._dragging = true; // Persistent for throttle.
  64846. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  64847. this._payloadInfo = trans;
  64848. handle.stopAnimation();
  64849. handle.attr(getHandleTransProps(trans));
  64850. inner$a(handle).lastProp = null;
  64851. this._doDispatchAxisPointer();
  64852. };
  64853. /**
  64854. * Throttled method.
  64855. */
  64856. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  64857. var handle = this._handle;
  64858. if (!handle) {
  64859. return;
  64860. }
  64861. var payloadInfo = this._payloadInfo;
  64862. var axisModel = this._axisModel;
  64863. this._api.dispatchAction({
  64864. type: 'updateAxisPointer',
  64865. x: payloadInfo.cursorPoint[0],
  64866. y: payloadInfo.cursorPoint[1],
  64867. tooltipOption: payloadInfo.tooltipOption,
  64868. axesInfo: [{
  64869. axisDim: axisModel.axis.dim,
  64870. axisIndex: axisModel.componentIndex
  64871. }]
  64872. });
  64873. };
  64874. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  64875. this._dragging = false;
  64876. var handle = this._handle;
  64877. if (!handle) {
  64878. return;
  64879. }
  64880. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  64881. // axisPointer. So move handle to align the exact value position when
  64882. // drag ended.
  64883. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  64884. // button, and will be hidden after finger left handle button.
  64885. this._api.dispatchAction({
  64886. type: 'hideTip'
  64887. });
  64888. };
  64889. /**
  64890. * @private
  64891. */
  64892. BaseAxisPointer.prototype.clear = function (api) {
  64893. this._lastValue = null;
  64894. this._lastStatus = null;
  64895. var zr = api.getZr();
  64896. var group = this._group;
  64897. var handle = this._handle;
  64898. if (zr && group) {
  64899. this._lastGraphicKey = null;
  64900. group && zr.remove(group);
  64901. handle && zr.remove(handle);
  64902. this._group = null;
  64903. this._handle = null;
  64904. this._payloadInfo = null;
  64905. }
  64906. clear(this, '_doDispatchAxisPointer');
  64907. };
  64908. /**
  64909. * @protected
  64910. */
  64911. BaseAxisPointer.prototype.doClear = function () {// Implemented by sub-class if necessary.
  64912. };
  64913. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  64914. xDimIndex = xDimIndex || 0;
  64915. return {
  64916. x: xy[xDimIndex],
  64917. y: xy[1 - xDimIndex],
  64918. width: wh[xDimIndex],
  64919. height: wh[1 - xDimIndex]
  64920. };
  64921. };
  64922. return BaseAxisPointer;
  64923. }();
  64924. function updateProps$1(animationModel, moveAnimation, el, props) {
  64925. // Animation optimize.
  64926. if (!propsEqual(inner$a(el).lastProp, props)) {
  64927. inner$a(el).lastProp = props;
  64928. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  64929. }
  64930. }
  64931. function propsEqual(lastProps, newProps) {
  64932. if (isObject(lastProps) && isObject(newProps)) {
  64933. var equals_1 = true;
  64934. each(newProps, function (item, key) {
  64935. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  64936. });
  64937. return !!equals_1;
  64938. } else {
  64939. return lastProps === newProps;
  64940. }
  64941. }
  64942. function updateLabelShowHide(labelEl, axisPointerModel) {
  64943. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  64944. }
  64945. function getHandleTransProps(trans) {
  64946. return {
  64947. x: trans.x || 0,
  64948. y: trans.y || 0,
  64949. rotation: trans.rotation || 0
  64950. };
  64951. }
  64952. function updateMandatoryProps(group, axisPointerModel, silent) {
  64953. var z = axisPointerModel.get('z');
  64954. var zlevel = axisPointerModel.get('zlevel');
  64955. group && group.traverse(function (el) {
  64956. if (el.type !== 'group') {
  64957. z != null && (el.z = z);
  64958. zlevel != null && (el.zlevel = zlevel);
  64959. el.silent = silent;
  64960. }
  64961. });
  64962. }
  64963. function buildElStyle(axisPointerModel) {
  64964. var axisPointerType = axisPointerModel.get('type');
  64965. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  64966. var style;
  64967. if (axisPointerType === 'line') {
  64968. style = styleModel.getLineStyle();
  64969. style.fill = null;
  64970. } else if (axisPointerType === 'shadow') {
  64971. style = styleModel.getAreaStyle();
  64972. style.stroke = null;
  64973. }
  64974. return style;
  64975. }
  64976. /**
  64977. * @param {Function} labelPos {align, verticalAlign, position}
  64978. */
  64979. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  64980. var value = axisPointerModel.get('value');
  64981. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  64982. precision: axisPointerModel.get(['label', 'precision']),
  64983. formatter: axisPointerModel.get(['label', 'formatter'])
  64984. });
  64985. var labelModel = axisPointerModel.getModel('label');
  64986. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  64987. var font = labelModel.getFont();
  64988. var textRect = getBoundingRect(text, font);
  64989. var position = labelPos.position;
  64990. var width = textRect.width + paddings[1] + paddings[3];
  64991. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  64992. var align = labelPos.align;
  64993. align === 'right' && (position[0] -= width);
  64994. align === 'center' && (position[0] -= width / 2);
  64995. var verticalAlign = labelPos.verticalAlign;
  64996. verticalAlign === 'bottom' && (position[1] -= height);
  64997. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  64998. confineInContainer(position, width, height, api);
  64999. var bgColor = labelModel.get('backgroundColor');
  65000. if (!bgColor || bgColor === 'auto') {
  65001. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  65002. }
  65003. elOption.label = {
  65004. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  65005. x: position[0],
  65006. y: position[1],
  65007. style: createTextStyle(labelModel, {
  65008. text: text,
  65009. font: font,
  65010. fill: labelModel.getTextColor(),
  65011. padding: paddings,
  65012. backgroundColor: bgColor
  65013. }),
  65014. // Label should be over axisPointer.
  65015. z2: 10
  65016. };
  65017. } // Do not overflow ec container
  65018. function confineInContainer(position, width, height, api) {
  65019. var viewWidth = api.getWidth();
  65020. var viewHeight = api.getHeight();
  65021. position[0] = Math.min(position[0] + width, viewWidth) - width;
  65022. position[1] = Math.min(position[1] + height, viewHeight) - height;
  65023. position[0] = Math.max(position[0], 0);
  65024. position[1] = Math.max(position[1], 0);
  65025. }
  65026. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  65027. value = axis.scale.parse(value);
  65028. var text = axis.scale.getLabel({
  65029. value: value
  65030. }, {
  65031. // If `precision` is set, width can be fixed (like '12.00500'), which
  65032. // helps to debounce when when moving label.
  65033. precision: opt.precision
  65034. });
  65035. var formatter = opt.formatter;
  65036. if (formatter) {
  65037. var params_1 = {
  65038. value: getAxisRawValue(axis, {
  65039. value: value
  65040. }),
  65041. axisDimension: axis.dim,
  65042. axisIndex: axis.index,
  65043. seriesData: []
  65044. };
  65045. each(seriesDataIndices, function (idxItem) {
  65046. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  65047. var dataIndex = idxItem.dataIndexInside;
  65048. var dataParams = series && series.getDataParams(dataIndex);
  65049. dataParams && params_1.seriesData.push(dataParams);
  65050. });
  65051. if (isString(formatter)) {
  65052. text = formatter.replace('{value}', text);
  65053. } else if (isFunction(formatter)) {
  65054. text = formatter(params_1);
  65055. }
  65056. }
  65057. return text;
  65058. }
  65059. function getTransformedPosition(axis, value, layoutInfo) {
  65060. var transform = create$1();
  65061. rotate(transform, transform, layoutInfo.rotation);
  65062. translate(transform, transform, layoutInfo.position);
  65063. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  65064. }
  65065. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  65066. // @ts-ignore
  65067. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  65068. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  65069. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  65070. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  65071. align: textLayout.textAlign,
  65072. verticalAlign: textLayout.textVerticalAlign
  65073. });
  65074. }
  65075. function makeLineShape(p1, p2, xDimIndex) {
  65076. xDimIndex = xDimIndex || 0;
  65077. return {
  65078. x1: p1[xDimIndex],
  65079. y1: p1[1 - xDimIndex],
  65080. x2: p2[xDimIndex],
  65081. y2: p2[1 - xDimIndex]
  65082. };
  65083. }
  65084. function makeRectShape(xy, wh, xDimIndex) {
  65085. xDimIndex = xDimIndex || 0;
  65086. return {
  65087. x: xy[xDimIndex],
  65088. y: xy[1 - xDimIndex],
  65089. width: wh[xDimIndex],
  65090. height: wh[1 - xDimIndex]
  65091. };
  65092. }
  65093. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  65094. return {
  65095. cx: cx,
  65096. cy: cy,
  65097. r0: r0,
  65098. r: r,
  65099. startAngle: startAngle,
  65100. endAngle: endAngle,
  65101. clockwise: true
  65102. };
  65103. }
  65104. var CartesianAxisPointer =
  65105. /** @class */
  65106. function (_super) {
  65107. __extends(CartesianAxisPointer, _super);
  65108. function CartesianAxisPointer() {
  65109. return _super !== null && _super.apply(this, arguments) || this;
  65110. }
  65111. /**
  65112. * @override
  65113. */
  65114. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  65115. var axis = axisModel.axis;
  65116. var grid = axis.grid;
  65117. var axisPointerType = axisPointerModel.get('type');
  65118. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  65119. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  65120. if (axisPointerType && axisPointerType !== 'none') {
  65121. var elStyle = buildElStyle(axisPointerModel);
  65122. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  65123. pointerOption.style = elStyle;
  65124. elOption.graphicKey = pointerOption.type;
  65125. elOption.pointer = pointerOption;
  65126. }
  65127. var layoutInfo = layout$1(grid.model, axisModel);
  65128. buildCartesianSingleLabelElOption( // @ts-ignore
  65129. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  65130. };
  65131. /**
  65132. * @override
  65133. */
  65134. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  65135. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  65136. labelInside: false
  65137. }); // @ts-ignore
  65138. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  65139. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  65140. return {
  65141. x: pos[0],
  65142. y: pos[1],
  65143. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  65144. };
  65145. };
  65146. /**
  65147. * @override
  65148. */
  65149. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  65150. var axis = axisModel.axis;
  65151. var grid = axis.grid;
  65152. var axisExtent = axis.getGlobalExtent(true);
  65153. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  65154. var dimIndex = axis.dim === 'x' ? 0 : 1;
  65155. var currPosition = [transform.x, transform.y];
  65156. currPosition[dimIndex] += delta[dimIndex];
  65157. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  65158. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  65159. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  65160. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  65161. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  65162. var tooltipOptions = [{
  65163. verticalAlign: 'middle'
  65164. }, {
  65165. align: 'center'
  65166. }];
  65167. return {
  65168. x: currPosition[0],
  65169. y: currPosition[1],
  65170. rotation: transform.rotation,
  65171. cursorPoint: cursorPoint,
  65172. tooltipOption: tooltipOptions[dimIndex]
  65173. };
  65174. };
  65175. return CartesianAxisPointer;
  65176. }(BaseAxisPointer);
  65177. function getCartesian(grid, axis) {
  65178. var opt = {};
  65179. opt[axis.dim + 'AxisIndex'] = axis.index;
  65180. return grid.getCartesian(opt);
  65181. }
  65182. var pointerShapeBuilder = {
  65183. line: function (axis, pixelValue, otherExtent) {
  65184. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  65185. return {
  65186. type: 'Line',
  65187. subPixelOptimize: true,
  65188. shape: targetShape
  65189. };
  65190. },
  65191. shadow: function (axis, pixelValue, otherExtent) {
  65192. var bandWidth = Math.max(1, axis.getBandWidth());
  65193. var span = otherExtent[1] - otherExtent[0];
  65194. return {
  65195. type: 'Rect',
  65196. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  65197. };
  65198. }
  65199. };
  65200. function getAxisDimIndex(axis) {
  65201. return axis.dim === 'x' ? 0 : 1;
  65202. }
  65203. var AxisPointerModel =
  65204. /** @class */
  65205. function (_super) {
  65206. __extends(AxisPointerModel, _super);
  65207. function AxisPointerModel() {
  65208. var _this = _super !== null && _super.apply(this, arguments) || this;
  65209. _this.type = AxisPointerModel.type;
  65210. return _this;
  65211. }
  65212. AxisPointerModel.type = 'axisPointer';
  65213. AxisPointerModel.defaultOption = {
  65214. // 'auto' means that show when triggered by tooltip or handle.
  65215. show: 'auto',
  65216. // zlevel: 0,
  65217. z: 50,
  65218. type: 'line',
  65219. // axispointer triggered by tootip determine snap automatically,
  65220. // see `modelHelper`.
  65221. snap: false,
  65222. triggerTooltip: true,
  65223. value: null,
  65224. status: null,
  65225. link: [],
  65226. // Do not set 'auto' here, otherwise global animation: false
  65227. // will not effect at this axispointer.
  65228. animation: null,
  65229. animationDurationUpdate: 200,
  65230. lineStyle: {
  65231. color: '#B9BEC9',
  65232. width: 1,
  65233. type: 'dashed'
  65234. },
  65235. shadowStyle: {
  65236. color: 'rgba(210,219,238,0.2)'
  65237. },
  65238. label: {
  65239. show: true,
  65240. formatter: null,
  65241. precision: 'auto',
  65242. margin: 3,
  65243. color: '#fff',
  65244. padding: [5, 7, 5, 7],
  65245. backgroundColor: 'auto',
  65246. borderColor: null,
  65247. borderWidth: 0,
  65248. borderRadius: 3
  65249. },
  65250. handle: {
  65251. show: false,
  65252. // eslint-disable-next-line
  65253. icon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z',
  65254. size: 45,
  65255. // handle margin is from symbol center to axis, which is stable when circular move.
  65256. margin: 50,
  65257. // color: '#1b8bbd'
  65258. // color: '#2f4554'
  65259. color: '#333',
  65260. shadowBlur: 3,
  65261. shadowColor: '#aaa',
  65262. shadowOffsetX: 0,
  65263. shadowOffsetY: 2,
  65264. // For mobile performance
  65265. throttle: 40
  65266. }
  65267. };
  65268. return AxisPointerModel;
  65269. }(ComponentModel);
  65270. var inner$b = makeInner();
  65271. var each$7 = each;
  65272. /**
  65273. * @param {string} key
  65274. * @param {module:echarts/ExtensionAPI} api
  65275. * @param {Function} handler
  65276. * param: {string} currTrigger
  65277. * param: {Array.<number>} point
  65278. */
  65279. function register(key, api, handler) {
  65280. if (env.node) {
  65281. return;
  65282. }
  65283. var zr = api.getZr();
  65284. inner$b(zr).records || (inner$b(zr).records = {});
  65285. initGlobalListeners(zr, api);
  65286. var record = inner$b(zr).records[key] || (inner$b(zr).records[key] = {});
  65287. record.handler = handler;
  65288. }
  65289. function initGlobalListeners(zr, api) {
  65290. if (inner$b(zr).initialized) {
  65291. return;
  65292. }
  65293. inner$b(zr).initialized = true;
  65294. useHandler('click', curry(doEnter, 'click'));
  65295. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  65296. useHandler('globalout', onLeave);
  65297. function useHandler(eventType, cb) {
  65298. zr.on(eventType, function (e) {
  65299. var dis = makeDispatchAction(api);
  65300. each$7(inner$b(zr).records, function (record) {
  65301. record && cb(record, e, dis.dispatchAction);
  65302. });
  65303. dispatchTooltipFinally(dis.pendings, api);
  65304. });
  65305. }
  65306. }
  65307. function dispatchTooltipFinally(pendings, api) {
  65308. var showLen = pendings.showTip.length;
  65309. var hideLen = pendings.hideTip.length;
  65310. var actuallyPayload;
  65311. if (showLen) {
  65312. actuallyPayload = pendings.showTip[showLen - 1];
  65313. } else if (hideLen) {
  65314. actuallyPayload = pendings.hideTip[hideLen - 1];
  65315. }
  65316. if (actuallyPayload) {
  65317. actuallyPayload.dispatchAction = null;
  65318. api.dispatchAction(actuallyPayload);
  65319. }
  65320. }
  65321. function onLeave(record, e, dispatchAction) {
  65322. record.handler('leave', null, dispatchAction);
  65323. }
  65324. function doEnter(currTrigger, record, e, dispatchAction) {
  65325. record.handler(currTrigger, e, dispatchAction);
  65326. }
  65327. function makeDispatchAction(api) {
  65328. var pendings = {
  65329. showTip: [],
  65330. hideTip: []
  65331. }; // FIXME
  65332. // better approach?
  65333. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  65334. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  65335. // So we have to add "final stage" to merge those dispatched actions.
  65336. var dispatchAction = function (payload) {
  65337. var pendingList = pendings[payload.type];
  65338. if (pendingList) {
  65339. pendingList.push(payload);
  65340. } else {
  65341. payload.dispatchAction = dispatchAction;
  65342. api.dispatchAction(payload);
  65343. }
  65344. };
  65345. return {
  65346. dispatchAction: dispatchAction,
  65347. pendings: pendings
  65348. };
  65349. }
  65350. function unregister(key, api) {
  65351. if (env.node) {
  65352. return;
  65353. }
  65354. var zr = api.getZr();
  65355. var record = (inner$b(zr).records || {})[key];
  65356. if (record) {
  65357. inner$b(zr).records[key] = null;
  65358. }
  65359. }
  65360. var AxisPointerView =
  65361. /** @class */
  65362. function (_super) {
  65363. __extends(AxisPointerView, _super);
  65364. function AxisPointerView() {
  65365. var _this = _super !== null && _super.apply(this, arguments) || this;
  65366. _this.type = AxisPointerView.type;
  65367. return _this;
  65368. }
  65369. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  65370. var globalTooltipModel = ecModel.getComponent('tooltip');
  65371. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  65372. // AxisPointerView to be independent to Tooltip.
  65373. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  65374. // If 'none', it is not controlled by mouse totally.
  65375. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  65376. dispatchAction({
  65377. type: 'updateAxisPointer',
  65378. currTrigger: currTrigger,
  65379. x: e && e.offsetX,
  65380. y: e && e.offsetY
  65381. });
  65382. }
  65383. });
  65384. };
  65385. AxisPointerView.prototype.remove = function (ecModel, api) {
  65386. unregister('axisPointer', api);
  65387. };
  65388. AxisPointerView.prototype.dispose = function (ecModel, api) {
  65389. unregister('axisPointer', api);
  65390. };
  65391. AxisPointerView.type = 'axisPointer';
  65392. return AxisPointerView;
  65393. }(ComponentView);
  65394. /**
  65395. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  65396. * @param ecModel
  65397. * @return {point: [x, y], el: ...} point Will not be null.
  65398. */
  65399. function findPointFromSeries(finder, ecModel) {
  65400. var point = [];
  65401. var seriesIndex = finder.seriesIndex;
  65402. var seriesModel;
  65403. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  65404. return {
  65405. point: []
  65406. };
  65407. }
  65408. var data = seriesModel.getData();
  65409. var dataIndex = queryDataIndex(data, finder);
  65410. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  65411. return {
  65412. point: []
  65413. };
  65414. }
  65415. var el = data.getItemGraphicEl(dataIndex);
  65416. var coordSys = seriesModel.coordinateSystem;
  65417. if (seriesModel.getTooltipPosition) {
  65418. point = seriesModel.getTooltipPosition(dataIndex) || [];
  65419. } else if (coordSys && coordSys.dataToPoint) {
  65420. if (finder.isStacked) {
  65421. var baseAxis = coordSys.getBaseAxis();
  65422. var valueAxis = coordSys.getOtherAxis(baseAxis);
  65423. var valueAxisDim = valueAxis.dim;
  65424. var baseAxisDim = baseAxis.dim;
  65425. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  65426. var baseDim = data.mapDimension(baseAxisDim);
  65427. var stackedData = [];
  65428. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  65429. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  65430. point = coordSys.dataToPoint(stackedData) || [];
  65431. } else {
  65432. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  65433. return data.mapDimension(dim);
  65434. }), dataIndex)) || [];
  65435. }
  65436. } else if (el) {
  65437. // Use graphic bounding rect
  65438. var rect = el.getBoundingRect().clone();
  65439. rect.applyTransform(el.transform);
  65440. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  65441. }
  65442. return {
  65443. point: point,
  65444. el: el
  65445. };
  65446. }
  65447. var inner$c = makeInner();
  65448. /**
  65449. * Basic logic: check all axis, if they do not demand show/highlight,
  65450. * then hide/downplay them.
  65451. *
  65452. * @return content of event obj for echarts.connect.
  65453. */
  65454. function axisTrigger(payload, ecModel, api) {
  65455. var currTrigger = payload.currTrigger;
  65456. var point = [payload.x, payload.y];
  65457. var finder = payload;
  65458. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  65459. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  65460. // See #6121. But we are not able to reproduce it yet.
  65461. if (!coordSysAxesInfo) {
  65462. return;
  65463. }
  65464. if (illegalPoint(point)) {
  65465. // Used in the default behavior of `connection`: use the sample seriesIndex
  65466. // and dataIndex. And also used in the tooltipView trigger.
  65467. point = findPointFromSeries({
  65468. seriesIndex: finder.seriesIndex,
  65469. // Do not use dataIndexInside from other ec instance.
  65470. // FIXME: auto detect it?
  65471. dataIndex: finder.dataIndex
  65472. }, ecModel).point;
  65473. }
  65474. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  65475. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  65476. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  65477. // and dataIndex.
  65478. var inputAxesInfo = finder.axesInfo;
  65479. var axesInfo = coordSysAxesInfo.axesInfo;
  65480. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  65481. var outputPayload = {};
  65482. var showValueMap = {};
  65483. var dataByCoordSys = {
  65484. list: [],
  65485. map: {}
  65486. };
  65487. var updaters = {
  65488. showPointer: curry(showPointer, showValueMap),
  65489. showTooltip: curry(showTooltip, dataByCoordSys)
  65490. }; // Process for triggered axes.
  65491. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  65492. // If a point given, it must be contained by the coordinate system.
  65493. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  65494. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  65495. var axis = axisInfo.axis;
  65496. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  65497. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  65498. var val = inputAxisInfo && inputAxisInfo.value;
  65499. if (val == null && !isIllegalPoint) {
  65500. val = axis.pointToData(point);
  65501. }
  65502. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  65503. }
  65504. });
  65505. }); // Process for linked axes.
  65506. var linkTriggers = {};
  65507. each(axesInfo, function (tarAxisInfo, tarKey) {
  65508. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  65509. if (linkGroup && !showValueMap[tarKey]) {
  65510. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  65511. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  65512. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  65513. var val = srcValItem.value;
  65514. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  65515. linkTriggers[tarAxisInfo.key] = val;
  65516. }
  65517. });
  65518. }
  65519. });
  65520. each(linkTriggers, function (val, tarKey) {
  65521. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  65522. });
  65523. updateModelActually(showValueMap, axesInfo, outputPayload);
  65524. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  65525. dispatchHighDownActually(axesInfo, dispatchAction, api);
  65526. return outputPayload;
  65527. }
  65528. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  65529. var axis = axisInfo.axis;
  65530. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  65531. return;
  65532. }
  65533. if (!axisInfo.involveSeries) {
  65534. updaters.showPointer(axisInfo, newValue);
  65535. return;
  65536. } // Heavy calculation. So put it after axis.containData checking.
  65537. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  65538. var payloadBatch = payloadInfo.payloadBatch;
  65539. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  65540. // By default use the first involved series data as a sample to connect.
  65541. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  65542. extend(outputFinder, payloadBatch[0]);
  65543. } // If no linkSource input, this process is for collecting link
  65544. // target, where snap should not be accepted.
  65545. if (!noSnap && axisInfo.snap) {
  65546. if (axis.containData(snapToValue) && snapToValue != null) {
  65547. newValue = snapToValue;
  65548. }
  65549. }
  65550. updaters.showPointer(axisInfo, newValue, payloadBatch); // Tooltip should always be snapToValue, otherwise there will be
  65551. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  65552. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  65553. }
  65554. function buildPayloadsBySeries(value, axisInfo) {
  65555. var axis = axisInfo.axis;
  65556. var dim = axis.dim;
  65557. var snapToValue = value;
  65558. var payloadBatch = [];
  65559. var minDist = Number.MAX_VALUE;
  65560. var minDiff = -1;
  65561. each(axisInfo.seriesModels, function (series, idx) {
  65562. var dataDim = series.getData().mapDimensionsAll(dim);
  65563. var seriesNestestValue;
  65564. var dataIndices;
  65565. if (series.getAxisTooltipData) {
  65566. var result = series.getAxisTooltipData(dataDim, value, axis);
  65567. dataIndices = result.dataIndices;
  65568. seriesNestestValue = result.nestestValue;
  65569. } else {
  65570. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  65571. // when data length is not same.
  65572. // false,
  65573. axis.type === 'category' ? 0.5 : null);
  65574. if (!dataIndices.length) {
  65575. return;
  65576. }
  65577. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  65578. }
  65579. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  65580. return;
  65581. }
  65582. var diff = value - seriesNestestValue;
  65583. var dist = Math.abs(diff); // Consider category case
  65584. if (dist <= minDist) {
  65585. if (dist < minDist || diff >= 0 && minDiff < 0) {
  65586. minDist = dist;
  65587. minDiff = diff;
  65588. snapToValue = seriesNestestValue;
  65589. payloadBatch.length = 0;
  65590. }
  65591. each(dataIndices, function (dataIndex) {
  65592. payloadBatch.push({
  65593. seriesIndex: series.seriesIndex,
  65594. dataIndexInside: dataIndex,
  65595. dataIndex: series.getData().getRawIndex(dataIndex)
  65596. });
  65597. });
  65598. }
  65599. });
  65600. return {
  65601. payloadBatch: payloadBatch,
  65602. snapToValue: snapToValue
  65603. };
  65604. }
  65605. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  65606. showValueMap[axisInfo.key] = {
  65607. value: value,
  65608. payloadBatch: payloadBatch
  65609. };
  65610. }
  65611. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  65612. var payloadBatch = payloadInfo.payloadBatch;
  65613. var axis = axisInfo.axis;
  65614. var axisModel = axis.model;
  65615. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  65616. // whose length will be used to judge whether dispatch action.
  65617. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  65618. return;
  65619. }
  65620. var coordSysModel = axisInfo.coordSys.model;
  65621. var coordSysKey = makeKey(coordSysModel);
  65622. var coordSysItem = dataByCoordSys.map[coordSysKey];
  65623. if (!coordSysItem) {
  65624. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  65625. coordSysId: coordSysModel.id,
  65626. coordSysIndex: coordSysModel.componentIndex,
  65627. coordSysType: coordSysModel.type,
  65628. coordSysMainType: coordSysModel.mainType,
  65629. dataByAxis: []
  65630. };
  65631. dataByCoordSys.list.push(coordSysItem);
  65632. }
  65633. coordSysItem.dataByAxis.push({
  65634. axisDim: axis.dim,
  65635. axisIndex: axisModel.componentIndex,
  65636. axisType: axisModel.type,
  65637. axisId: axisModel.id,
  65638. value: value,
  65639. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  65640. // depends that all models have been updated. So it should not be performed
  65641. // here. Considering axisPointerModel used here is volatile, which is hard
  65642. // to be retrieve in TooltipView, we prepare parameters here.
  65643. valueLabelOpt: {
  65644. precision: axisPointerModel.get(['label', 'precision']),
  65645. formatter: axisPointerModel.get(['label', 'formatter'])
  65646. },
  65647. seriesDataIndices: payloadBatch.slice()
  65648. });
  65649. }
  65650. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  65651. var outputAxesInfo = outputPayload.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  65652. each(axesInfo, function (axisInfo, key) {
  65653. var option = axisInfo.axisPointerModel.option;
  65654. var valItem = showValueMap[key];
  65655. if (valItem) {
  65656. !axisInfo.useHandle && (option.status = 'show');
  65657. option.value = valItem.value; // For label formatter param and highlight.
  65658. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  65659. } // When always show (e.g., handle used), remain
  65660. // original value and status.
  65661. else {
  65662. // If hide, value still need to be set, consider
  65663. // click legend to toggle axis blank.
  65664. !axisInfo.useHandle && (option.status = 'hide');
  65665. } // If status is 'hide', should be no info in payload.
  65666. option.status === 'show' && outputAxesInfo.push({
  65667. axisDim: axisInfo.axis.dim,
  65668. axisIndex: axisInfo.axis.model.componentIndex,
  65669. value: option.value
  65670. });
  65671. });
  65672. }
  65673. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  65674. // Basic logic: If no showTip required, hideTip will be dispatched.
  65675. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  65676. dispatchAction({
  65677. type: 'hideTip'
  65678. });
  65679. return;
  65680. } // In most case only one axis (or event one series is used). It is
  65681. // convenient to fetch payload.seriesIndex and payload.dataIndex
  65682. // directly. So put the first seriesIndex and dataIndex of the first
  65683. // axis on the payload.
  65684. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  65685. dispatchAction({
  65686. type: 'showTip',
  65687. escapeConnect: true,
  65688. x: point[0],
  65689. y: point[1],
  65690. tooltipOption: payload.tooltipOption,
  65691. position: payload.position,
  65692. dataIndexInside: sampleItem.dataIndexInside,
  65693. dataIndex: sampleItem.dataIndex,
  65694. seriesIndex: sampleItem.seriesIndex,
  65695. dataByCoordSys: dataByCoordSys.list
  65696. });
  65697. }
  65698. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  65699. // FIXME
  65700. // highlight status modification should be a stage of main process?
  65701. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  65702. var zr = api.getZr();
  65703. var highDownKey = 'axisPointerLastHighlights';
  65704. var lastHighlights = inner$c(zr)[highDownKey] || {};
  65705. var newHighlights = inner$c(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  65706. // Build hash map and remove duplicate incidentally.
  65707. each(axesInfo, function (axisInfo, key) {
  65708. var option = axisInfo.axisPointerModel.option;
  65709. option.status === 'show' && each(option.seriesDataIndices, function (batchItem) {
  65710. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  65711. newHighlights[key] = batchItem;
  65712. });
  65713. }); // Diff.
  65714. var toHighlight = [];
  65715. var toDownplay = [];
  65716. each(lastHighlights, function (batchItem, key) {
  65717. !newHighlights[key] && toDownplay.push(batchItem);
  65718. });
  65719. each(newHighlights, function (batchItem, key) {
  65720. !lastHighlights[key] && toHighlight.push(batchItem);
  65721. });
  65722. toDownplay.length && api.dispatchAction({
  65723. type: 'downplay',
  65724. escapeConnect: true,
  65725. // Not blur others when highlight in axisPointer.
  65726. notBlur: true,
  65727. batch: toDownplay
  65728. });
  65729. toHighlight.length && api.dispatchAction({
  65730. type: 'highlight',
  65731. escapeConnect: true,
  65732. // Not blur others when highlight in axisPointer.
  65733. notBlur: true,
  65734. batch: toHighlight
  65735. });
  65736. }
  65737. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  65738. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  65739. var inputAxisInfo = inputAxesInfo[i];
  65740. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  65741. return inputAxisInfo;
  65742. }
  65743. }
  65744. }
  65745. function makeMapperParam(axisInfo) {
  65746. var axisModel = axisInfo.axis.model;
  65747. var item = {};
  65748. var dim = item.axisDim = axisInfo.axis.dim;
  65749. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  65750. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  65751. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  65752. return item;
  65753. }
  65754. function illegalPoint(point) {
  65755. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  65756. }
  65757. function install$s(registers) {
  65758. // CartesianAxisPointer is not supposed to be required here. But consider
  65759. // echarts.simple.js and online build tooltip, which only require gridSimple,
  65760. // CartesianAxisPointer should be able to required somewhere.
  65761. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  65762. registers.registerComponentModel(AxisPointerModel);
  65763. registers.registerComponentView(AxisPointerView);
  65764. registers.registerPreprocessor(function (option) {
  65765. // Always has a global axisPointerModel for default setting.
  65766. if (option) {
  65767. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  65768. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  65769. // is not set, remain null/undefined, otherwise it will
  65770. // override existent link setting.
  65771. if (link && !isArray(link)) {
  65772. option.axisPointer.link = [link];
  65773. }
  65774. }
  65775. }); // This process should proformed after coordinate systems created
  65776. // and series data processed. So put it on statistic processing stage.
  65777. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  65778. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  65779. // allAxesInfo should be updated when setOption performed.
  65780. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  65781. }); // Broadcast to all views.
  65782. registers.registerAction({
  65783. type: 'updateAxisPointer',
  65784. event: 'updateAxisPointer',
  65785. update: ':updateAxisPointer'
  65786. }, axisTrigger);
  65787. }
  65788. function install$t(registers) {
  65789. use(install$5);
  65790. use(install$s);
  65791. }
  65792. var PolarAxisPointer =
  65793. /** @class */
  65794. function (_super) {
  65795. __extends(PolarAxisPointer, _super);
  65796. function PolarAxisPointer() {
  65797. return _super !== null && _super.apply(this, arguments) || this;
  65798. }
  65799. /**
  65800. * @override
  65801. */
  65802. PolarAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  65803. var axis = axisModel.axis;
  65804. if (axis.dim === 'angle') {
  65805. this.animationThreshold = Math.PI / 18;
  65806. }
  65807. var polar = axis.polar;
  65808. var otherAxis = polar.getOtherAxis(axis);
  65809. var otherExtent = otherAxis.getExtent();
  65810. var coordValue = axis.dataToCoord(value);
  65811. var axisPointerType = axisPointerModel.get('type');
  65812. if (axisPointerType && axisPointerType !== 'none') {
  65813. var elStyle = buildElStyle(axisPointerModel);
  65814. var pointerOption = pointerShapeBuilder$1[axisPointerType](axis, polar, coordValue, otherExtent);
  65815. pointerOption.style = elStyle;
  65816. elOption.graphicKey = pointerOption.type;
  65817. elOption.pointer = pointerOption;
  65818. }
  65819. var labelMargin = axisPointerModel.get(['label', 'margin']);
  65820. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  65821. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  65822. };
  65823. return PolarAxisPointer;
  65824. }(BaseAxisPointer);
  65825. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  65826. var axis = axisModel.axis;
  65827. var coord = axis.dataToCoord(value);
  65828. var axisAngle = polar.getAngleAxis().getExtent()[0];
  65829. axisAngle = axisAngle / 180 * Math.PI;
  65830. var radiusExtent = polar.getRadiusAxis().getExtent();
  65831. var position;
  65832. var align;
  65833. var verticalAlign;
  65834. if (axis.dim === 'radius') {
  65835. var transform = create$1();
  65836. rotate(transform, transform, axisAngle);
  65837. translate(transform, transform, [polar.cx, polar.cy]);
  65838. position = applyTransform$1([coord, -labelMargin], transform);
  65839. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0; // @ts-ignore
  65840. var labelLayout = AxisBuilder.innerTextLayout(axisAngle, labelRotation * Math.PI / 180, -1);
  65841. align = labelLayout.textAlign;
  65842. verticalAlign = labelLayout.textVerticalAlign;
  65843. } else {
  65844. // angle axis
  65845. var r = radiusExtent[1];
  65846. position = polar.coordToPoint([r + labelMargin, coord]);
  65847. var cx = polar.cx;
  65848. var cy = polar.cy;
  65849. align = Math.abs(position[0] - cx) / r < 0.3 ? 'center' : position[0] > cx ? 'left' : 'right';
  65850. verticalAlign = Math.abs(position[1] - cy) / r < 0.3 ? 'middle' : position[1] > cy ? 'top' : 'bottom';
  65851. }
  65852. return {
  65853. position: position,
  65854. align: align,
  65855. verticalAlign: verticalAlign
  65856. };
  65857. }
  65858. var pointerShapeBuilder$1 = {
  65859. line: function (axis, polar, coordValue, otherExtent) {
  65860. return axis.dim === 'angle' ? {
  65861. type: 'Line',
  65862. shape: makeLineShape(polar.coordToPoint([otherExtent[0], coordValue]), polar.coordToPoint([otherExtent[1], coordValue]))
  65863. } : {
  65864. type: 'Circle',
  65865. shape: {
  65866. cx: polar.cx,
  65867. cy: polar.cy,
  65868. r: coordValue
  65869. }
  65870. };
  65871. },
  65872. shadow: function (axis, polar, coordValue, otherExtent) {
  65873. var bandWidth = Math.max(1, axis.getBandWidth());
  65874. var radian = Math.PI / 180;
  65875. return axis.dim === 'angle' ? {
  65876. type: 'Sector',
  65877. shape: makeSectorShape(polar.cx, polar.cy, otherExtent[0], otherExtent[1], // In ECharts y is negative if angle is positive
  65878. (-coordValue - bandWidth / 2) * radian, (-coordValue + bandWidth / 2) * radian)
  65879. } : {
  65880. type: 'Sector',
  65881. shape: makeSectorShape(polar.cx, polar.cy, coordValue - bandWidth / 2, coordValue + bandWidth / 2, 0, Math.PI * 2)
  65882. };
  65883. }
  65884. };
  65885. var PolarModel =
  65886. /** @class */
  65887. function (_super) {
  65888. __extends(PolarModel, _super);
  65889. function PolarModel() {
  65890. var _this = _super !== null && _super.apply(this, arguments) || this;
  65891. _this.type = PolarModel.type;
  65892. return _this;
  65893. }
  65894. PolarModel.prototype.findAxisModel = function (axisType) {
  65895. var foundAxisModel;
  65896. var ecModel = this.ecModel;
  65897. ecModel.eachComponent(axisType, function (axisModel) {
  65898. if (axisModel.getCoordSysModel() === this) {
  65899. foundAxisModel = axisModel;
  65900. }
  65901. }, this);
  65902. return foundAxisModel;
  65903. };
  65904. PolarModel.type = 'polar';
  65905. PolarModel.dependencies = ['radiusAxis', 'angleAxis'];
  65906. PolarModel.defaultOption = {
  65907. // zlevel: 0,
  65908. z: 0,
  65909. center: ['50%', '50%'],
  65910. radius: '80%'
  65911. };
  65912. return PolarModel;
  65913. }(ComponentModel);
  65914. var PolarAxisModel =
  65915. /** @class */
  65916. function (_super) {
  65917. __extends(PolarAxisModel, _super);
  65918. function PolarAxisModel() {
  65919. return _super !== null && _super.apply(this, arguments) || this;
  65920. }
  65921. PolarAxisModel.prototype.getCoordSysModel = function () {
  65922. return this.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  65923. };
  65924. PolarAxisModel.type = 'polarAxis';
  65925. return PolarAxisModel;
  65926. }(ComponentModel);
  65927. mixin(PolarAxisModel, AxisModelCommonMixin);
  65928. var AngleAxisModel =
  65929. /** @class */
  65930. function (_super) {
  65931. __extends(AngleAxisModel, _super);
  65932. function AngleAxisModel() {
  65933. var _this = _super !== null && _super.apply(this, arguments) || this;
  65934. _this.type = AngleAxisModel.type;
  65935. return _this;
  65936. }
  65937. AngleAxisModel.type = 'angleAxis';
  65938. return AngleAxisModel;
  65939. }(PolarAxisModel);
  65940. var RadiusAxisModel =
  65941. /** @class */
  65942. function (_super) {
  65943. __extends(RadiusAxisModel, _super);
  65944. function RadiusAxisModel() {
  65945. var _this = _super !== null && _super.apply(this, arguments) || this;
  65946. _this.type = RadiusAxisModel.type;
  65947. return _this;
  65948. }
  65949. RadiusAxisModel.type = 'radiusAxis';
  65950. return RadiusAxisModel;
  65951. }(PolarAxisModel);
  65952. var RadiusAxis =
  65953. /** @class */
  65954. function (_super) {
  65955. __extends(RadiusAxis, _super);
  65956. function RadiusAxis(scale, radiusExtent) {
  65957. return _super.call(this, 'radius', scale, radiusExtent) || this;
  65958. }
  65959. RadiusAxis.prototype.pointToData = function (point, clamp) {
  65960. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65961. };
  65962. return RadiusAxis;
  65963. }(Axis);
  65964. RadiusAxis.prototype.dataToRadius = Axis.prototype.dataToCoord;
  65965. RadiusAxis.prototype.radiusToData = Axis.prototype.coordToData;
  65966. var inner$d = makeInner();
  65967. var AngleAxis =
  65968. /** @class */
  65969. function (_super) {
  65970. __extends(AngleAxis, _super);
  65971. function AngleAxis(scale, angleExtent) {
  65972. return _super.call(this, 'angle', scale, angleExtent || [0, 360]) || this;
  65973. }
  65974. AngleAxis.prototype.pointToData = function (point, clamp) {
  65975. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  65976. };
  65977. /**
  65978. * Only be called in category axis.
  65979. * Angle axis uses text height to decide interval
  65980. *
  65981. * @override
  65982. * @return {number} Auto interval for cateogry axis tick and label
  65983. */
  65984. AngleAxis.prototype.calculateCategoryInterval = function () {
  65985. var axis = this;
  65986. var labelModel = axis.getLabelModel();
  65987. var ordinalScale = axis.scale;
  65988. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  65989. // avoid generating a long array by `getTicks`
  65990. // in large category data case.
  65991. var tickCount = ordinalScale.count();
  65992. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  65993. return 0;
  65994. }
  65995. var tickValue = ordinalExtent[0];
  65996. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  65997. var unitH = Math.abs(unitSpan); // Not precise, just use height as text width
  65998. // and each distance from axis line yet.
  65999. var rect = getBoundingRect(tickValue == null ? '' : tickValue + '', labelModel.getFont(), 'center', 'top');
  66000. var maxH = Math.max(rect.height, 7);
  66001. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  66002. isNaN(dh) && (dh = Infinity);
  66003. var interval = Math.max(0, Math.floor(dh));
  66004. var cache = inner$d(axis.model);
  66005. var lastAutoInterval = cache.lastAutoInterval;
  66006. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  66007. // otherwise the calculated interval might jitter when the zoom
  66008. // window size is close to the interval-changing size.
  66009. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  66010. // point is not the same when zooming in or zooming out.
  66011. && lastAutoInterval > interval) {
  66012. interval = lastAutoInterval;
  66013. } // Only update cache if cache not used, otherwise the
  66014. // changing of interval is too insensitive.
  66015. else {
  66016. cache.lastTickCount = tickCount;
  66017. cache.lastAutoInterval = interval;
  66018. }
  66019. return interval;
  66020. };
  66021. return AngleAxis;
  66022. }(Axis);
  66023. AngleAxis.prototype.dataToAngle = Axis.prototype.dataToCoord;
  66024. AngleAxis.prototype.angleToData = Axis.prototype.coordToData;
  66025. var polarDimensions = ['radius', 'angle'];
  66026. var Polar =
  66027. /** @class */
  66028. function () {
  66029. function Polar(name) {
  66030. this.dimensions = polarDimensions;
  66031. this.type = 'polar';
  66032. /**
  66033. * x of polar center
  66034. */
  66035. this.cx = 0;
  66036. /**
  66037. * y of polar center
  66038. */
  66039. this.cy = 0;
  66040. this._radiusAxis = new RadiusAxis();
  66041. this._angleAxis = new AngleAxis();
  66042. this.axisPointerEnabled = true;
  66043. this.name = name || '';
  66044. this._radiusAxis.polar = this._angleAxis.polar = this;
  66045. }
  66046. /**
  66047. * If contain coord
  66048. */
  66049. Polar.prototype.containPoint = function (point) {
  66050. var coord = this.pointToCoord(point);
  66051. return this._radiusAxis.contain(coord[0]) && this._angleAxis.contain(coord[1]);
  66052. };
  66053. /**
  66054. * If contain data
  66055. */
  66056. Polar.prototype.containData = function (data) {
  66057. return this._radiusAxis.containData(data[0]) && this._angleAxis.containData(data[1]);
  66058. };
  66059. Polar.prototype.getAxis = function (dim) {
  66060. var key = '_' + dim + 'Axis';
  66061. return this[key];
  66062. };
  66063. Polar.prototype.getAxes = function () {
  66064. return [this._radiusAxis, this._angleAxis];
  66065. };
  66066. /**
  66067. * Get axes by type of scale
  66068. */
  66069. Polar.prototype.getAxesByScale = function (scaleType) {
  66070. var axes = [];
  66071. var angleAxis = this._angleAxis;
  66072. var radiusAxis = this._radiusAxis;
  66073. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  66074. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  66075. return axes;
  66076. };
  66077. Polar.prototype.getAngleAxis = function () {
  66078. return this._angleAxis;
  66079. };
  66080. Polar.prototype.getRadiusAxis = function () {
  66081. return this._radiusAxis;
  66082. };
  66083. Polar.prototype.getOtherAxis = function (axis) {
  66084. var angleAxis = this._angleAxis;
  66085. return axis === angleAxis ? this._radiusAxis : angleAxis;
  66086. };
  66087. /**
  66088. * Base axis will be used on stacking.
  66089. *
  66090. */
  66091. Polar.prototype.getBaseAxis = function () {
  66092. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAngleAxis();
  66093. };
  66094. Polar.prototype.getTooltipAxes = function (dim) {
  66095. var baseAxis = dim != null && dim !== 'auto' ? this.getAxis(dim) : this.getBaseAxis();
  66096. return {
  66097. baseAxes: [baseAxis],
  66098. otherAxes: [this.getOtherAxis(baseAxis)]
  66099. };
  66100. };
  66101. /**
  66102. * Convert a single data item to (x, y) point.
  66103. * Parameter data is an array which the first element is radius and the second is angle
  66104. */
  66105. Polar.prototype.dataToPoint = function (data, clamp) {
  66106. return this.coordToPoint([this._radiusAxis.dataToRadius(data[0], clamp), this._angleAxis.dataToAngle(data[1], clamp)]);
  66107. };
  66108. /**
  66109. * Convert a (x, y) point to data
  66110. */
  66111. Polar.prototype.pointToData = function (point, clamp) {
  66112. var coord = this.pointToCoord(point);
  66113. return [this._radiusAxis.radiusToData(coord[0], clamp), this._angleAxis.angleToData(coord[1], clamp)];
  66114. };
  66115. /**
  66116. * Convert a (x, y) point to (radius, angle) coord
  66117. */
  66118. Polar.prototype.pointToCoord = function (point) {
  66119. var dx = point[0] - this.cx;
  66120. var dy = point[1] - this.cy;
  66121. var angleAxis = this.getAngleAxis();
  66122. var extent = angleAxis.getExtent();
  66123. var minAngle = Math.min(extent[0], extent[1]);
  66124. var maxAngle = Math.max(extent[0], extent[1]); // Fix fixed extent in polarCreator
  66125. // FIXME
  66126. angleAxis.inverse ? minAngle = maxAngle - 360 : maxAngle = minAngle + 360;
  66127. var radius = Math.sqrt(dx * dx + dy * dy);
  66128. dx /= radius;
  66129. dy /= radius;
  66130. var radian = Math.atan2(-dy, dx) / Math.PI * 180; // move to angleExtent
  66131. var dir = radian < minAngle ? 1 : -1;
  66132. while (radian < minAngle || radian > maxAngle) {
  66133. radian += dir * 360;
  66134. }
  66135. return [radius, radian];
  66136. };
  66137. /**
  66138. * Convert a (radius, angle) coord to (x, y) point
  66139. */
  66140. Polar.prototype.coordToPoint = function (coord) {
  66141. var radius = coord[0];
  66142. var radian = coord[1] / 180 * Math.PI;
  66143. var x = Math.cos(radian) * radius + this.cx; // Inverse the y
  66144. var y = -Math.sin(radian) * radius + this.cy;
  66145. return [x, y];
  66146. };
  66147. /**
  66148. * Get ring area of cartesian.
  66149. * Area will have a contain function to determine if a point is in the coordinate system.
  66150. */
  66151. Polar.prototype.getArea = function () {
  66152. var angleAxis = this.getAngleAxis();
  66153. var radiusAxis = this.getRadiusAxis();
  66154. var radiusExtent = radiusAxis.getExtent().slice();
  66155. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  66156. var angleExtent = angleAxis.getExtent();
  66157. var RADIAN = Math.PI / 180;
  66158. return {
  66159. cx: this.cx,
  66160. cy: this.cy,
  66161. r0: radiusExtent[0],
  66162. r: radiusExtent[1],
  66163. startAngle: -angleExtent[0] * RADIAN,
  66164. endAngle: -angleExtent[1] * RADIAN,
  66165. clockwise: angleAxis.inverse,
  66166. contain: function (x, y) {
  66167. // It's a ring shape.
  66168. // Start angle and end angle don't matter
  66169. var dx = x - this.cx;
  66170. var dy = y - this.cy; // minus a tiny value 1e-4 to avoid being clipped unexpectedly
  66171. var d2 = dx * dx + dy * dy - 1e-4;
  66172. var r = this.r;
  66173. var r0 = this.r0;
  66174. return d2 <= r * r && d2 >= r0 * r0;
  66175. }
  66176. };
  66177. };
  66178. Polar.prototype.convertToPixel = function (ecModel, finder, value) {
  66179. var coordSys = getCoordSys$2(finder);
  66180. return coordSys === this ? this.dataToPoint(value) : null;
  66181. };
  66182. Polar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  66183. var coordSys = getCoordSys$2(finder);
  66184. return coordSys === this ? this.pointToData(pixel) : null;
  66185. };
  66186. return Polar;
  66187. }();
  66188. function getCoordSys$2(finder) {
  66189. var seriesModel = finder.seriesModel;
  66190. var polarModel = finder.polarModel;
  66191. return polarModel && polarModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  66192. }
  66193. /**
  66194. * Resize method bound to the polar
  66195. */
  66196. function resizePolar(polar, polarModel, api) {
  66197. var center = polarModel.get('center');
  66198. var width = api.getWidth();
  66199. var height = api.getHeight();
  66200. polar.cx = parsePercent$1(center[0], width);
  66201. polar.cy = parsePercent$1(center[1], height);
  66202. var radiusAxis = polar.getRadiusAxis();
  66203. var size = Math.min(width, height) / 2;
  66204. var radius = polarModel.get('radius');
  66205. if (radius == null) {
  66206. radius = [0, '100%'];
  66207. } else if (!isArray(radius)) {
  66208. // r0 = 0
  66209. radius = [0, radius];
  66210. }
  66211. var parsedRadius = [parsePercent$1(radius[0], size), parsePercent$1(radius[1], size)];
  66212. radiusAxis.inverse ? radiusAxis.setExtent(parsedRadius[1], parsedRadius[0]) : radiusAxis.setExtent(parsedRadius[0], parsedRadius[1]);
  66213. }
  66214. /**
  66215. * Update polar
  66216. */
  66217. function updatePolarScale(ecModel, api) {
  66218. var polar = this;
  66219. var angleAxis = polar.getAngleAxis();
  66220. var radiusAxis = polar.getRadiusAxis(); // Reset scale
  66221. angleAxis.scale.setExtent(Infinity, -Infinity);
  66222. radiusAxis.scale.setExtent(Infinity, -Infinity);
  66223. ecModel.eachSeries(function (seriesModel) {
  66224. if (seriesModel.coordinateSystem === polar) {
  66225. var data_1 = seriesModel.getData();
  66226. each(getDataDimensionsOnAxis(data_1, 'radius'), function (dim) {
  66227. radiusAxis.scale.unionExtentFromData(data_1, dim);
  66228. });
  66229. each(getDataDimensionsOnAxis(data_1, 'angle'), function (dim) {
  66230. angleAxis.scale.unionExtentFromData(data_1, dim);
  66231. });
  66232. }
  66233. });
  66234. niceScaleExtent(angleAxis.scale, angleAxis.model);
  66235. niceScaleExtent(radiusAxis.scale, radiusAxis.model); // Fix extent of category angle axis
  66236. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  66237. var extent = angleAxis.getExtent();
  66238. var diff = 360 / angleAxis.scale.count();
  66239. angleAxis.inverse ? extent[1] += diff : extent[1] -= diff;
  66240. angleAxis.setExtent(extent[0], extent[1]);
  66241. }
  66242. }
  66243. function isAngleAxisModel(axisModel) {
  66244. return axisModel.mainType === 'angleAxis';
  66245. }
  66246. /**
  66247. * Set common axis properties
  66248. */
  66249. function setAxis(axis, axisModel) {
  66250. axis.type = axisModel.get('type');
  66251. axis.scale = createScaleByModel(axisModel);
  66252. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  66253. axis.inverse = axisModel.get('inverse');
  66254. if (isAngleAxisModel(axisModel)) {
  66255. axis.inverse = axis.inverse !== axisModel.get('clockwise');
  66256. var startAngle = axisModel.get('startAngle');
  66257. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  66258. } // Inject axis instance
  66259. axisModel.axis = axis;
  66260. axis.model = axisModel;
  66261. }
  66262. var polarCreator = {
  66263. dimensions: polarDimensions,
  66264. create: function (ecModel, api) {
  66265. var polarList = [];
  66266. ecModel.eachComponent('polar', function (polarModel, idx) {
  66267. var polar = new Polar(idx + ''); // Inject resize and update method
  66268. polar.update = updatePolarScale;
  66269. var radiusAxis = polar.getRadiusAxis();
  66270. var angleAxis = polar.getAngleAxis();
  66271. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  66272. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  66273. setAxis(radiusAxis, radiusAxisModel);
  66274. setAxis(angleAxis, angleAxisModel);
  66275. resizePolar(polar, polarModel, api);
  66276. polarList.push(polar);
  66277. polarModel.coordinateSystem = polar;
  66278. polar.model = polarModel;
  66279. }); // Inject coordinateSystem to series
  66280. ecModel.eachSeries(function (seriesModel) {
  66281. if (seriesModel.get('coordinateSystem') === 'polar') {
  66282. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  66283. if ("development" !== 'production') {
  66284. if (!polarModel) {
  66285. throw new Error('Polar "' + retrieve(seriesModel.get('polarIndex'), seriesModel.get('polarId'), 0) + '" not found');
  66286. }
  66287. }
  66288. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  66289. }
  66290. });
  66291. return polarList;
  66292. }
  66293. };
  66294. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea'];
  66295. function getAxisLineShape(polar, rExtent, angle) {
  66296. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  66297. var start = polar.coordToPoint([rExtent[0], angle]);
  66298. var end = polar.coordToPoint([rExtent[1], angle]);
  66299. return {
  66300. x1: start[0],
  66301. y1: start[1],
  66302. x2: end[0],
  66303. y2: end[1]
  66304. };
  66305. }
  66306. function getRadiusIdx(polar) {
  66307. var radiusAxis = polar.getRadiusAxis();
  66308. return radiusAxis.inverse ? 0 : 1;
  66309. } // Remove the last tick which will overlap the first tick
  66310. function fixAngleOverlap(list) {
  66311. var firstItem = list[0];
  66312. var lastItem = list[list.length - 1];
  66313. if (firstItem && lastItem && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4) {
  66314. list.pop();
  66315. }
  66316. }
  66317. var AngleAxisView =
  66318. /** @class */
  66319. function (_super) {
  66320. __extends(AngleAxisView, _super);
  66321. function AngleAxisView() {
  66322. var _this = _super !== null && _super.apply(this, arguments) || this;
  66323. _this.type = AngleAxisView.type;
  66324. _this.axisPointerClass = 'PolarAxisPointer';
  66325. return _this;
  66326. }
  66327. AngleAxisView.prototype.render = function (angleAxisModel, ecModel) {
  66328. this.group.removeAll();
  66329. if (!angleAxisModel.get('show')) {
  66330. return;
  66331. }
  66332. var angleAxis = angleAxisModel.axis;
  66333. var polar = angleAxis.polar;
  66334. var radiusExtent = polar.getRadiusAxis().getExtent();
  66335. var ticksAngles = angleAxis.getTicksCoords();
  66336. var minorTickAngles = angleAxis.getMinorTicksCoords();
  66337. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  66338. labelItem = clone(labelItem);
  66339. var scale = angleAxis.scale;
  66340. var tickValue = scale.type === 'ordinal' ? scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  66341. labelItem.coord = angleAxis.dataToCoord(tickValue);
  66342. return labelItem;
  66343. });
  66344. fixAngleOverlap(labels);
  66345. fixAngleOverlap(ticksAngles);
  66346. each(elementList$1, function (name) {
  66347. if (angleAxisModel.get([name, 'show']) && (!angleAxis.scale.isBlank() || name === 'axisLine')) {
  66348. angelAxisElementsBuilders[name](this.group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels);
  66349. }
  66350. }, this);
  66351. };
  66352. AngleAxisView.type = 'angleAxis';
  66353. return AngleAxisView;
  66354. }(AxisView);
  66355. var angelAxisElementsBuilders = {
  66356. axisLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66357. var lineStyleModel = angleAxisModel.getModel(['axisLine', 'lineStyle']); // extent id of the axis radius (r0 and r)
  66358. var rId = getRadiusIdx(polar);
  66359. var r0Id = rId ? 0 : 1;
  66360. var shape;
  66361. if (radiusExtent[r0Id] === 0) {
  66362. shape = new Circle({
  66363. shape: {
  66364. cx: polar.cx,
  66365. cy: polar.cy,
  66366. r: radiusExtent[rId]
  66367. },
  66368. style: lineStyleModel.getLineStyle(),
  66369. z2: 1,
  66370. silent: true
  66371. });
  66372. } else {
  66373. shape = new Ring({
  66374. shape: {
  66375. cx: polar.cx,
  66376. cy: polar.cy,
  66377. r: radiusExtent[rId],
  66378. r0: radiusExtent[r0Id]
  66379. },
  66380. style: lineStyleModel.getLineStyle(),
  66381. z2: 1,
  66382. silent: true
  66383. });
  66384. }
  66385. shape.style.fill = null;
  66386. group.add(shape);
  66387. },
  66388. axisTick: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66389. var tickModel = angleAxisModel.getModel('axisTick');
  66390. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  66391. var radius = radiusExtent[getRadiusIdx(polar)];
  66392. var lines = map(ticksAngles, function (tickAngleItem) {
  66393. return new Line({
  66394. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  66395. });
  66396. });
  66397. group.add(mergePath$1(lines, {
  66398. style: defaults(tickModel.getModel('lineStyle').getLineStyle(), {
  66399. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  66400. })
  66401. }));
  66402. },
  66403. minorTick: function (group, angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) {
  66404. if (!minorTickAngles.length) {
  66405. return;
  66406. }
  66407. var tickModel = angleAxisModel.getModel('axisTick');
  66408. var minorTickModel = angleAxisModel.getModel('minorTick');
  66409. var tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length');
  66410. var radius = radiusExtent[getRadiusIdx(polar)];
  66411. var lines = [];
  66412. for (var i = 0; i < minorTickAngles.length; i++) {
  66413. for (var k = 0; k < minorTickAngles[i].length; k++) {
  66414. lines.push(new Line({
  66415. shape: getAxisLineShape(polar, [radius, radius + tickLen], minorTickAngles[i][k].coord)
  66416. }));
  66417. }
  66418. }
  66419. group.add(mergePath$1(lines, {
  66420. style: defaults(minorTickModel.getModel('lineStyle').getLineStyle(), defaults(tickModel.getLineStyle(), {
  66421. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  66422. }))
  66423. }));
  66424. },
  66425. axisLabel: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) {
  66426. var rawCategoryData = angleAxisModel.getCategories(true);
  66427. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  66428. var labelMargin = commonLabelModel.get('margin');
  66429. var triggerEvent = angleAxisModel.get('triggerEvent'); // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  66430. each(labels, function (labelItem, idx) {
  66431. var labelModel = commonLabelModel;
  66432. var tickValue = labelItem.tickValue;
  66433. var r = radiusExtent[getRadiusIdx(polar)];
  66434. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  66435. var cx = polar.cx;
  66436. var cy = polar.cy;
  66437. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3 ? 'center' : p[0] > cx ? 'left' : 'right';
  66438. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3 ? 'middle' : p[1] > cy ? 'top' : 'bottom';
  66439. if (rawCategoryData && rawCategoryData[tickValue]) {
  66440. var rawCategoryItem = rawCategoryData[tickValue];
  66441. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  66442. labelModel = new Model(rawCategoryItem.textStyle, commonLabelModel, commonLabelModel.ecModel);
  66443. }
  66444. }
  66445. var textEl = new ZRText({
  66446. silent: AxisBuilder.isLabelSilent(angleAxisModel),
  66447. style: createTextStyle(labelModel, {
  66448. x: p[0],
  66449. y: p[1],
  66450. fill: labelModel.getTextColor() || angleAxisModel.get(['axisLine', 'lineStyle', 'color']),
  66451. text: labelItem.formattedLabel,
  66452. align: labelTextAlign,
  66453. verticalAlign: labelTextVerticalAlign
  66454. })
  66455. });
  66456. group.add(textEl); // Pack data for mouse event
  66457. if (triggerEvent) {
  66458. var eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel);
  66459. eventData.targetType = 'axisLabel';
  66460. eventData.value = labelItem.rawLabel;
  66461. getECData(textEl).eventData = eventData;
  66462. }
  66463. }, this);
  66464. },
  66465. splitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66466. var splitLineModel = angleAxisModel.getModel('splitLine');
  66467. var lineStyleModel = splitLineModel.getModel('lineStyle');
  66468. var lineColors = lineStyleModel.get('color');
  66469. var lineCount = 0;
  66470. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  66471. var splitLines = [];
  66472. for (var i = 0; i < ticksAngles.length; i++) {
  66473. var colorIndex = lineCount++ % lineColors.length;
  66474. splitLines[colorIndex] = splitLines[colorIndex] || [];
  66475. splitLines[colorIndex].push(new Line({
  66476. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  66477. }));
  66478. } // Simple optimization
  66479. // Batching the lines if color are the same
  66480. for (var i = 0; i < splitLines.length; i++) {
  66481. group.add(mergePath$1(splitLines[i], {
  66482. style: defaults({
  66483. stroke: lineColors[i % lineColors.length]
  66484. }, lineStyleModel.getLineStyle()),
  66485. silent: true,
  66486. z: angleAxisModel.get('z')
  66487. }));
  66488. }
  66489. },
  66490. minorSplitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66491. if (!minorTickAngles.length) {
  66492. return;
  66493. }
  66494. var minorSplitLineModel = angleAxisModel.getModel('minorSplitLine');
  66495. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  66496. var lines = [];
  66497. for (var i = 0; i < minorTickAngles.length; i++) {
  66498. for (var k = 0; k < minorTickAngles[i].length; k++) {
  66499. lines.push(new Line({
  66500. shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord)
  66501. }));
  66502. }
  66503. }
  66504. group.add(mergePath$1(lines, {
  66505. style: lineStyleModel.getLineStyle(),
  66506. silent: true,
  66507. z: angleAxisModel.get('z')
  66508. }));
  66509. },
  66510. splitArea: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66511. if (!ticksAngles.length) {
  66512. return;
  66513. }
  66514. var splitAreaModel = angleAxisModel.getModel('splitArea');
  66515. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66516. var areaColors = areaStyleModel.get('color');
  66517. var lineCount = 0;
  66518. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66519. var splitAreas = [];
  66520. var RADIAN = Math.PI / 180;
  66521. var prevAngle = -ticksAngles[0].coord * RADIAN;
  66522. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  66523. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  66524. var clockwise = angleAxisModel.get('clockwise');
  66525. for (var i = 1, len = ticksAngles.length; i <= len; i++) {
  66526. var coord = i === len ? ticksAngles[0].coord : ticksAngles[i].coord;
  66527. var colorIndex = lineCount++ % areaColors.length;
  66528. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66529. splitAreas[colorIndex].push(new Sector({
  66530. shape: {
  66531. cx: polar.cx,
  66532. cy: polar.cy,
  66533. r0: r0,
  66534. r: r1,
  66535. startAngle: prevAngle,
  66536. endAngle: -coord * RADIAN,
  66537. clockwise: clockwise
  66538. },
  66539. silent: true
  66540. }));
  66541. prevAngle = -coord * RADIAN;
  66542. } // Simple optimization
  66543. // Batching the lines if color are the same
  66544. for (var i = 0; i < splitAreas.length; i++) {
  66545. group.add(mergePath$1(splitAreas[i], {
  66546. style: defaults({
  66547. fill: areaColors[i % areaColors.length]
  66548. }, areaStyleModel.getAreaStyle()),
  66549. silent: true
  66550. }));
  66551. }
  66552. }
  66553. };
  66554. var axisBuilderAttrs$2 = ['axisLine', 'axisTickLabel', 'axisName'];
  66555. var selfBuilderAttrs$1 = ['splitLine', 'splitArea', 'minorSplitLine'];
  66556. var RadiusAxisView =
  66557. /** @class */
  66558. function (_super) {
  66559. __extends(RadiusAxisView, _super);
  66560. function RadiusAxisView() {
  66561. var _this = _super !== null && _super.apply(this, arguments) || this;
  66562. _this.type = RadiusAxisView.type;
  66563. _this.axisPointerClass = 'PolarAxisPointer';
  66564. return _this;
  66565. }
  66566. RadiusAxisView.prototype.render = function (radiusAxisModel, ecModel) {
  66567. this.group.removeAll();
  66568. if (!radiusAxisModel.get('show')) {
  66569. return;
  66570. }
  66571. var oldAxisGroup = this._axisGroup;
  66572. var newAxisGroup = this._axisGroup = new Group();
  66573. this.group.add(newAxisGroup);
  66574. var radiusAxis = radiusAxisModel.axis;
  66575. var polar = radiusAxis.polar;
  66576. var angleAxis = polar.getAngleAxis();
  66577. var ticksCoords = radiusAxis.getTicksCoords();
  66578. var minorTicksCoords = radiusAxis.getMinorTicksCoords();
  66579. var axisAngle = angleAxis.getExtent()[0];
  66580. var radiusExtent = radiusAxis.getExtent();
  66581. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  66582. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  66583. each(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  66584. newAxisGroup.add(axisBuilder.getGroup());
  66585. groupTransition(oldAxisGroup, newAxisGroup, radiusAxisModel);
  66586. each(selfBuilderAttrs$1, function (name) {
  66587. if (radiusAxisModel.get([name, 'show']) && !radiusAxis.scale.isBlank()) {
  66588. axisElementBuilders$1[name](this.group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords);
  66589. }
  66590. }, this);
  66591. };
  66592. RadiusAxisView.type = 'radiusAxis';
  66593. return RadiusAxisView;
  66594. }(AxisView);
  66595. var axisElementBuilders$1 = {
  66596. splitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66597. var splitLineModel = radiusAxisModel.getModel('splitLine');
  66598. var lineStyleModel = splitLineModel.getModel('lineStyle');
  66599. var lineColors = lineStyleModel.get('color');
  66600. var lineCount = 0;
  66601. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  66602. var splitLines = [];
  66603. for (var i = 0; i < ticksCoords.length; i++) {
  66604. var colorIndex = lineCount++ % lineColors.length;
  66605. splitLines[colorIndex] = splitLines[colorIndex] || [];
  66606. splitLines[colorIndex].push(new Circle({
  66607. shape: {
  66608. cx: polar.cx,
  66609. cy: polar.cy,
  66610. // ensure circle radius >= 0
  66611. r: Math.max(ticksCoords[i].coord, 0)
  66612. }
  66613. }));
  66614. } // Simple optimization
  66615. // Batching the lines if color are the same
  66616. for (var i = 0; i < splitLines.length; i++) {
  66617. group.add(mergePath$1(splitLines[i], {
  66618. style: defaults({
  66619. stroke: lineColors[i % lineColors.length],
  66620. fill: null
  66621. }, lineStyleModel.getLineStyle()),
  66622. silent: true
  66623. }));
  66624. }
  66625. },
  66626. minorSplitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) {
  66627. if (!minorTicksCoords.length) {
  66628. return;
  66629. }
  66630. var minorSplitLineModel = radiusAxisModel.getModel('minorSplitLine');
  66631. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  66632. var lines = [];
  66633. for (var i = 0; i < minorTicksCoords.length; i++) {
  66634. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  66635. lines.push(new Circle({
  66636. shape: {
  66637. cx: polar.cx,
  66638. cy: polar.cy,
  66639. r: minorTicksCoords[i][k].coord
  66640. }
  66641. }));
  66642. }
  66643. }
  66644. group.add(mergePath$1(lines, {
  66645. style: defaults({
  66646. fill: null
  66647. }, lineStyleModel.getLineStyle()),
  66648. silent: true
  66649. }));
  66650. },
  66651. splitArea: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66652. if (!ticksCoords.length) {
  66653. return;
  66654. }
  66655. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  66656. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66657. var areaColors = areaStyleModel.get('color');
  66658. var lineCount = 0;
  66659. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66660. var splitAreas = [];
  66661. var prevRadius = ticksCoords[0].coord;
  66662. for (var i = 1; i < ticksCoords.length; i++) {
  66663. var colorIndex = lineCount++ % areaColors.length;
  66664. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66665. splitAreas[colorIndex].push(new Sector({
  66666. shape: {
  66667. cx: polar.cx,
  66668. cy: polar.cy,
  66669. r0: prevRadius,
  66670. r: ticksCoords[i].coord,
  66671. startAngle: 0,
  66672. endAngle: Math.PI * 2
  66673. },
  66674. silent: true
  66675. }));
  66676. prevRadius = ticksCoords[i].coord;
  66677. } // Simple optimization
  66678. // Batching the lines if color are the same
  66679. for (var i = 0; i < splitAreas.length; i++) {
  66680. group.add(mergePath$1(splitAreas[i], {
  66681. style: defaults({
  66682. fill: areaColors[i % areaColors.length]
  66683. }, areaStyleModel.getAreaStyle()),
  66684. silent: true
  66685. }));
  66686. }
  66687. }
  66688. };
  66689. /**
  66690. * @inner
  66691. */
  66692. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  66693. return {
  66694. position: [polar.cx, polar.cy],
  66695. rotation: axisAngle / 180 * Math.PI,
  66696. labelDirection: -1,
  66697. tickDirection: -1,
  66698. nameDirection: 1,
  66699. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  66700. // Over splitLine and splitArea
  66701. z2: 1
  66702. };
  66703. }
  66704. function getSeriesStackId$1(seriesModel) {
  66705. return seriesModel.get('stack') || '__ec_stack_' + seriesModel.seriesIndex;
  66706. }
  66707. function getAxisKey$1(polar, axis) {
  66708. return axis.dim + polar.model.componentIndex;
  66709. }
  66710. function barLayoutPolar(seriesType, ecModel, api) {
  66711. var lastStackCoords = {};
  66712. var barWidthAndOffset = calRadialBar(filter(ecModel.getSeriesByType(seriesType), function (seriesModel) {
  66713. return !ecModel.isSeriesFiltered(seriesModel) && seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'polar';
  66714. }));
  66715. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  66716. // Check series coordinate, do layout for polar only
  66717. if (seriesModel.coordinateSystem.type !== 'polar') {
  66718. return;
  66719. }
  66720. var data = seriesModel.getData();
  66721. var polar = seriesModel.coordinateSystem;
  66722. var baseAxis = polar.getBaseAxis();
  66723. var axisKey = getAxisKey$1(polar, baseAxis);
  66724. var stackId = getSeriesStackId$1(seriesModel);
  66725. var columnLayoutInfo = barWidthAndOffset[axisKey][stackId];
  66726. var columnOffset = columnLayoutInfo.offset;
  66727. var columnWidth = columnLayoutInfo.width;
  66728. var valueAxis = polar.getOtherAxis(baseAxis);
  66729. var cx = seriesModel.coordinateSystem.cx;
  66730. var cy = seriesModel.coordinateSystem.cy;
  66731. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  66732. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  66733. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  66734. var valueDim = data.mapDimension(valueAxis.dim);
  66735. var baseDim = data.mapDimension(baseAxis.dim);
  66736. var stacked = isDimensionStacked(data, valueDim
  66737. /* , baseDim */
  66738. );
  66739. var clampLayout = baseAxis.dim !== 'radius' || !seriesModel.get('roundCap', true);
  66740. var valueAxisStart = valueAxis.dataToCoord(0);
  66741. for (var idx = 0, len = data.count(); idx < len; idx++) {
  66742. var value = data.get(valueDim, idx);
  66743. var baseValue = data.get(baseDim, idx);
  66744. var sign = value >= 0 ? 'p' : 'n';
  66745. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  66746. // stackResultDimension directly.
  66747. // Only ordinal axis can be stacked.
  66748. if (stacked) {
  66749. if (!lastStackCoords[stackId][baseValue]) {
  66750. lastStackCoords[stackId][baseValue] = {
  66751. p: valueAxisStart,
  66752. n: valueAxisStart // Negative stack
  66753. };
  66754. } // Should also consider #4243
  66755. baseCoord = lastStackCoords[stackId][baseValue][sign];
  66756. }
  66757. var r0 = void 0;
  66758. var r = void 0;
  66759. var startAngle = void 0;
  66760. var endAngle = void 0; // radial sector
  66761. if (valueAxis.dim === 'radius') {
  66762. var radiusSpan = valueAxis.dataToCoord(value) - valueAxisStart;
  66763. var angle = baseAxis.dataToCoord(baseValue);
  66764. if (Math.abs(radiusSpan) < barMinHeight) {
  66765. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  66766. }
  66767. r0 = baseCoord;
  66768. r = baseCoord + radiusSpan;
  66769. startAngle = angle - columnOffset;
  66770. endAngle = startAngle - columnWidth;
  66771. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  66772. } // tangential sector
  66773. else {
  66774. var angleSpan = valueAxis.dataToCoord(value, clampLayout) - valueAxisStart;
  66775. var radius = baseAxis.dataToCoord(baseValue);
  66776. if (Math.abs(angleSpan) < barMinAngle) {
  66777. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  66778. }
  66779. r0 = radius + columnOffset;
  66780. r = r0 + columnWidth;
  66781. startAngle = baseCoord;
  66782. endAngle = baseCoord + angleSpan; // if the previous stack is at the end of the ring,
  66783. // add a round to differentiate it from origin
  66784. // let extent = angleAxis.getExtent();
  66785. // let stackCoord = angle;
  66786. // if (stackCoord === extent[0] && value > 0) {
  66787. // stackCoord = extent[1];
  66788. // }
  66789. // else if (stackCoord === extent[1] && value < 0) {
  66790. // stackCoord = extent[0];
  66791. // }
  66792. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  66793. }
  66794. data.setItemLayout(idx, {
  66795. cx: cx,
  66796. cy: cy,
  66797. r0: r0,
  66798. r: r,
  66799. // Consider that positive angle is anti-clockwise,
  66800. // while positive radian of sector is clockwise
  66801. startAngle: -startAngle * Math.PI / 180,
  66802. endAngle: -endAngle * Math.PI / 180,
  66803. /**
  66804. * Keep the same logic with bar in catesion: use end value to
  66805. * control direction. Notice that if clockwise is true (by
  66806. * default), the sector will always draw clockwisely, no matter
  66807. * whether endAngle is greater or less than startAngle.
  66808. */
  66809. clockwise: startAngle >= endAngle
  66810. });
  66811. }
  66812. });
  66813. }
  66814. /**
  66815. * Calculate bar width and offset for radial bar charts
  66816. */
  66817. function calRadialBar(barSeries) {
  66818. // Columns info on each category axis. Key is polar name
  66819. var columnsMap = {};
  66820. each(barSeries, function (seriesModel, idx) {
  66821. var data = seriesModel.getData();
  66822. var polar = seriesModel.coordinateSystem;
  66823. var baseAxis = polar.getBaseAxis();
  66824. var axisKey = getAxisKey$1(polar, baseAxis);
  66825. var axisExtent = baseAxis.getExtent();
  66826. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  66827. var columnsOnAxis = columnsMap[axisKey] || {
  66828. bandWidth: bandWidth,
  66829. remainedWidth: bandWidth,
  66830. autoWidthCount: 0,
  66831. categoryGap: '20%',
  66832. gap: '30%',
  66833. stacks: {}
  66834. };
  66835. var stacks = columnsOnAxis.stacks;
  66836. columnsMap[axisKey] = columnsOnAxis;
  66837. var stackId = getSeriesStackId$1(seriesModel);
  66838. if (!stacks[stackId]) {
  66839. columnsOnAxis.autoWidthCount++;
  66840. }
  66841. stacks[stackId] = stacks[stackId] || {
  66842. width: 0,
  66843. maxWidth: 0
  66844. };
  66845. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  66846. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  66847. var barGap = seriesModel.get('barGap');
  66848. var barCategoryGap = seriesModel.get('barCategoryGap');
  66849. if (barWidth && !stacks[stackId].width) {
  66850. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  66851. stacks[stackId].width = barWidth;
  66852. columnsOnAxis.remainedWidth -= barWidth;
  66853. }
  66854. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  66855. barGap != null && (columnsOnAxis.gap = barGap);
  66856. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  66857. });
  66858. var result = {};
  66859. each(columnsMap, function (columnsOnAxis, coordSysName) {
  66860. result[coordSysName] = {};
  66861. var stacks = columnsOnAxis.stacks;
  66862. var bandWidth = columnsOnAxis.bandWidth;
  66863. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  66864. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  66865. var remainedWidth = columnsOnAxis.remainedWidth;
  66866. var autoWidthCount = columnsOnAxis.autoWidthCount;
  66867. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  66868. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  66869. each(stacks, function (column, stack) {
  66870. var maxWidth = column.maxWidth;
  66871. if (maxWidth && maxWidth < autoWidth) {
  66872. maxWidth = Math.min(maxWidth, remainedWidth);
  66873. if (column.width) {
  66874. maxWidth = Math.min(maxWidth, column.width);
  66875. }
  66876. remainedWidth -= maxWidth;
  66877. column.width = maxWidth;
  66878. autoWidthCount--;
  66879. }
  66880. }); // Recalculate width again
  66881. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  66882. autoWidth = Math.max(autoWidth, 0);
  66883. var widthSum = 0;
  66884. var lastColumn;
  66885. each(stacks, function (column, idx) {
  66886. if (!column.width) {
  66887. column.width = autoWidth;
  66888. }
  66889. lastColumn = column;
  66890. widthSum += column.width * (1 + barGapPercent);
  66891. });
  66892. if (lastColumn) {
  66893. widthSum -= lastColumn.width * barGapPercent;
  66894. }
  66895. var offset = -widthSum / 2;
  66896. each(stacks, function (column, stackId) {
  66897. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  66898. offset: offset,
  66899. width: column.width
  66900. };
  66901. offset += column.width * (1 + barGapPercent);
  66902. });
  66903. });
  66904. return result;
  66905. }
  66906. var angleAxisExtraOption = {
  66907. startAngle: 90,
  66908. clockwise: true,
  66909. splitNumber: 12,
  66910. axisLabel: {
  66911. rotate: 0
  66912. }
  66913. };
  66914. var radiusAxisExtraOption = {
  66915. splitNumber: 5
  66916. };
  66917. var PolarView =
  66918. /** @class */
  66919. function (_super) {
  66920. __extends(PolarView, _super);
  66921. function PolarView() {
  66922. var _this = _super !== null && _super.apply(this, arguments) || this;
  66923. _this.type = PolarView.type;
  66924. return _this;
  66925. }
  66926. PolarView.type = 'polar';
  66927. return PolarView;
  66928. }(ComponentView);
  66929. function install$u(registers) {
  66930. use(install$s);
  66931. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  66932. registers.registerCoordinateSystem('polar', polarCreator);
  66933. registers.registerComponentModel(PolarModel);
  66934. registers.registerComponentView(PolarView); // Model and view for angleAxis and radiusAxis
  66935. axisModelCreator(registers, 'angle', AngleAxisModel, angleAxisExtraOption);
  66936. axisModelCreator(registers, 'radius', RadiusAxisModel, radiusAxisExtraOption);
  66937. registers.registerComponentView(AngleAxisView);
  66938. registers.registerComponentView(RadiusAxisView);
  66939. registers.registerLayout(curry(barLayoutPolar, 'bar'));
  66940. }
  66941. function layout$2(axisModel, opt) {
  66942. opt = opt || {};
  66943. var single = axisModel.coordinateSystem;
  66944. var axis = axisModel.axis;
  66945. var layout = {};
  66946. var axisPosition = axis.position;
  66947. var orient = axis.orient;
  66948. var rect = single.getRect();
  66949. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  66950. var positionMap = {
  66951. horizontal: {
  66952. top: rectBound[2],
  66953. bottom: rectBound[3]
  66954. },
  66955. vertical: {
  66956. left: rectBound[0],
  66957. right: rectBound[1]
  66958. }
  66959. };
  66960. layout.position = [orient === 'vertical' ? positionMap.vertical[axisPosition] : rectBound[0], orient === 'horizontal' ? positionMap.horizontal[axisPosition] : rectBound[3]];
  66961. var r = {
  66962. horizontal: 0,
  66963. vertical: 1
  66964. };
  66965. layout.rotation = Math.PI / 2 * r[orient];
  66966. var directionMap = {
  66967. top: -1,
  66968. bottom: 1,
  66969. right: 1,
  66970. left: -1
  66971. };
  66972. layout.labelDirection = layout.tickDirection = layout.nameDirection = directionMap[axisPosition];
  66973. if (axisModel.get(['axisTick', 'inside'])) {
  66974. layout.tickDirection = -layout.tickDirection;
  66975. }
  66976. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  66977. layout.labelDirection = -layout.labelDirection;
  66978. }
  66979. var labelRotation = opt.rotate;
  66980. labelRotation == null && (labelRotation = axisModel.get(['axisLabel', 'rotate']));
  66981. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  66982. layout.z2 = 1;
  66983. return layout;
  66984. }
  66985. var axisBuilderAttrs$3 = ['axisLine', 'axisTickLabel', 'axisName'];
  66986. var selfBuilderAttrs$2 = ['splitArea', 'splitLine'];
  66987. var SingleAxisView =
  66988. /** @class */
  66989. function (_super) {
  66990. __extends(SingleAxisView, _super);
  66991. function SingleAxisView() {
  66992. var _this = _super !== null && _super.apply(this, arguments) || this;
  66993. _this.type = SingleAxisView.type;
  66994. _this.axisPointerClass = 'SingleAxisPointer';
  66995. return _this;
  66996. }
  66997. SingleAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  66998. var group = this.group;
  66999. group.removeAll();
  67000. var oldAxisGroup = this._axisGroup;
  67001. this._axisGroup = new Group();
  67002. var layout = layout$2(axisModel);
  67003. var axisBuilder = new AxisBuilder(axisModel, layout);
  67004. each(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  67005. group.add(this._axisGroup);
  67006. group.add(axisBuilder.getGroup());
  67007. each(selfBuilderAttrs$2, function (name) {
  67008. if (axisModel.get([name, 'show'])) {
  67009. axisElementBuilders$2[name](this, this.group, this._axisGroup, axisModel);
  67010. }
  67011. }, this);
  67012. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  67013. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  67014. };
  67015. SingleAxisView.prototype.remove = function () {
  67016. rectCoordAxisHandleRemove(this);
  67017. };
  67018. SingleAxisView.type = 'singleAxis';
  67019. return SingleAxisView;
  67020. }(AxisView);
  67021. var axisElementBuilders$2 = {
  67022. splitLine: function (axisView, group, axisGroup, axisModel) {
  67023. var axis = axisModel.axis;
  67024. if (axis.scale.isBlank()) {
  67025. return;
  67026. }
  67027. var splitLineModel = axisModel.getModel('splitLine');
  67028. var lineStyleModel = splitLineModel.getModel('lineStyle');
  67029. var lineColors = lineStyleModel.get('color');
  67030. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  67031. var lineWidth = lineStyleModel.get('width');
  67032. var gridRect = axisModel.coordinateSystem.getRect();
  67033. var isHorizontal = axis.isHorizontal();
  67034. var splitLines = [];
  67035. var lineCount = 0;
  67036. var ticksCoords = axis.getTicksCoords({
  67037. tickModel: splitLineModel
  67038. });
  67039. var p1 = [];
  67040. var p2 = [];
  67041. for (var i = 0; i < ticksCoords.length; ++i) {
  67042. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  67043. if (isHorizontal) {
  67044. p1[0] = tickCoord;
  67045. p1[1] = gridRect.y;
  67046. p2[0] = tickCoord;
  67047. p2[1] = gridRect.y + gridRect.height;
  67048. } else {
  67049. p1[0] = gridRect.x;
  67050. p1[1] = tickCoord;
  67051. p2[0] = gridRect.x + gridRect.width;
  67052. p2[1] = tickCoord;
  67053. }
  67054. var line = new Line({
  67055. shape: {
  67056. x1: p1[0],
  67057. y1: p1[1],
  67058. x2: p2[0],
  67059. y2: p2[1]
  67060. },
  67061. silent: true
  67062. });
  67063. subPixelOptimizeLine$1(line.shape, lineWidth);
  67064. var colorIndex = lineCount++ % lineColors.length;
  67065. splitLines[colorIndex] = splitLines[colorIndex] || [];
  67066. splitLines[colorIndex].push(line);
  67067. }
  67068. var lineStyle = lineStyleModel.getLineStyle(['color']);
  67069. for (var i = 0; i < splitLines.length; ++i) {
  67070. group.add(mergePath$1(splitLines[i], {
  67071. style: defaults({
  67072. stroke: lineColors[i % lineColors.length]
  67073. }, lineStyle),
  67074. silent: true
  67075. }));
  67076. }
  67077. },
  67078. splitArea: function (axisView, group, axisGroup, axisModel) {
  67079. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, axisModel);
  67080. }
  67081. };
  67082. var SingleAxisModel =
  67083. /** @class */
  67084. function (_super) {
  67085. __extends(SingleAxisModel, _super);
  67086. function SingleAxisModel() {
  67087. var _this = _super !== null && _super.apply(this, arguments) || this;
  67088. _this.type = SingleAxisModel.type;
  67089. return _this;
  67090. }
  67091. SingleAxisModel.prototype.getCoordSysModel = function () {
  67092. return this;
  67093. };
  67094. SingleAxisModel.type = 'singleAxis';
  67095. SingleAxisModel.layoutMode = 'box';
  67096. SingleAxisModel.defaultOption = {
  67097. left: '5%',
  67098. top: '5%',
  67099. right: '5%',
  67100. bottom: '5%',
  67101. type: 'value',
  67102. position: 'bottom',
  67103. orient: 'horizontal',
  67104. axisLine: {
  67105. show: true,
  67106. lineStyle: {
  67107. width: 1,
  67108. type: 'solid'
  67109. }
  67110. },
  67111. // Single coordinate system and single axis is the,
  67112. // which is used as the parent tooltip model.
  67113. // same model, so we set default tooltip show as true.
  67114. tooltip: {
  67115. show: true
  67116. },
  67117. axisTick: {
  67118. show: true,
  67119. length: 6,
  67120. lineStyle: {
  67121. width: 1
  67122. }
  67123. },
  67124. axisLabel: {
  67125. show: true,
  67126. interval: 'auto'
  67127. },
  67128. splitLine: {
  67129. show: true,
  67130. lineStyle: {
  67131. type: 'dashed',
  67132. opacity: 0.2
  67133. }
  67134. }
  67135. };
  67136. return SingleAxisModel;
  67137. }(ComponentModel);
  67138. mixin(SingleAxisModel, AxisModelCommonMixin.prototype);
  67139. var SingleAxis =
  67140. /** @class */
  67141. function (_super) {
  67142. __extends(SingleAxis, _super);
  67143. function SingleAxis(dim, scale, coordExtent, axisType, position) {
  67144. var _this = _super.call(this, dim, scale, coordExtent) || this;
  67145. _this.type = axisType || 'value';
  67146. _this.position = position || 'bottom';
  67147. return _this;
  67148. }
  67149. /**
  67150. * Judge the orient of the axis.
  67151. */
  67152. SingleAxis.prototype.isHorizontal = function () {
  67153. var position = this.position;
  67154. return position === 'top' || position === 'bottom';
  67155. };
  67156. SingleAxis.prototype.pointToData = function (point, clamp) {
  67157. return this.coordinateSystem.pointToData(point)[0];
  67158. };
  67159. return SingleAxis;
  67160. }(Axis);
  67161. var singleDimensions = ['single'];
  67162. /**
  67163. * Create a single coordinates system.
  67164. */
  67165. var Single =
  67166. /** @class */
  67167. function () {
  67168. function Single(axisModel, ecModel, api) {
  67169. this.type = 'single';
  67170. this.dimension = 'single';
  67171. /**
  67172. * Add it just for draw tooltip.
  67173. */
  67174. this.dimensions = singleDimensions;
  67175. this.axisPointerEnabled = true;
  67176. this.model = axisModel;
  67177. this._init(axisModel, ecModel, api);
  67178. }
  67179. /**
  67180. * Initialize single coordinate system.
  67181. */
  67182. Single.prototype._init = function (axisModel, ecModel, api) {
  67183. var dim = this.dimension;
  67184. var axis = new SingleAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisModel.get('position'));
  67185. var isCategory = axis.type === 'category';
  67186. axis.onBand = isCategory && axisModel.get('boundaryGap');
  67187. axis.inverse = axisModel.get('inverse');
  67188. axis.orient = axisModel.get('orient');
  67189. axisModel.axis = axis;
  67190. axis.model = axisModel;
  67191. axis.coordinateSystem = this;
  67192. this._axis = axis;
  67193. };
  67194. /**
  67195. * Update axis scale after data processed
  67196. */
  67197. Single.prototype.update = function (ecModel, api) {
  67198. ecModel.eachSeries(function (seriesModel) {
  67199. if (seriesModel.coordinateSystem === this) {
  67200. var data_1 = seriesModel.getData();
  67201. each(data_1.mapDimensionsAll(this.dimension), function (dim) {
  67202. this._axis.scale.unionExtentFromData(data_1, dim);
  67203. }, this);
  67204. niceScaleExtent(this._axis.scale, this._axis.model);
  67205. }
  67206. }, this);
  67207. };
  67208. /**
  67209. * Resize the single coordinate system.
  67210. */
  67211. Single.prototype.resize = function (axisModel, api) {
  67212. this._rect = getLayoutRect({
  67213. left: axisModel.get('left'),
  67214. top: axisModel.get('top'),
  67215. right: axisModel.get('right'),
  67216. bottom: axisModel.get('bottom'),
  67217. width: axisModel.get('width'),
  67218. height: axisModel.get('height')
  67219. }, {
  67220. width: api.getWidth(),
  67221. height: api.getHeight()
  67222. });
  67223. this._adjustAxis();
  67224. };
  67225. Single.prototype.getRect = function () {
  67226. return this._rect;
  67227. };
  67228. Single.prototype._adjustAxis = function () {
  67229. var rect = this._rect;
  67230. var axis = this._axis;
  67231. var isHorizontal = axis.isHorizontal();
  67232. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  67233. var idx = axis.inverse ? 1 : 0;
  67234. axis.setExtent(extent[idx], extent[1 - idx]);
  67235. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  67236. };
  67237. Single.prototype._updateAxisTransform = function (axis, coordBase) {
  67238. var axisExtent = axis.getExtent();
  67239. var extentSum = axisExtent[0] + axisExtent[1];
  67240. var isHorizontal = axis.isHorizontal();
  67241. axis.toGlobalCoord = isHorizontal ? function (coord) {
  67242. return coord + coordBase;
  67243. } : function (coord) {
  67244. return extentSum - coord + coordBase;
  67245. };
  67246. axis.toLocalCoord = isHorizontal ? function (coord) {
  67247. return coord - coordBase;
  67248. } : function (coord) {
  67249. return extentSum - coord + coordBase;
  67250. };
  67251. };
  67252. /**
  67253. * Get axis.
  67254. */
  67255. Single.prototype.getAxis = function () {
  67256. return this._axis;
  67257. };
  67258. /**
  67259. * Get axis, add it just for draw tooltip.
  67260. */
  67261. Single.prototype.getBaseAxis = function () {
  67262. return this._axis;
  67263. };
  67264. Single.prototype.getAxes = function () {
  67265. return [this._axis];
  67266. };
  67267. Single.prototype.getTooltipAxes = function () {
  67268. return {
  67269. baseAxes: [this.getAxis()],
  67270. // Empty otherAxes
  67271. otherAxes: []
  67272. };
  67273. };
  67274. /**
  67275. * If contain point.
  67276. */
  67277. Single.prototype.containPoint = function (point) {
  67278. var rect = this.getRect();
  67279. var axis = this.getAxis();
  67280. var orient = axis.orient;
  67281. if (orient === 'horizontal') {
  67282. return axis.contain(axis.toLocalCoord(point[0])) && point[1] >= rect.y && point[1] <= rect.y + rect.height;
  67283. } else {
  67284. return axis.contain(axis.toLocalCoord(point[1])) && point[0] >= rect.y && point[0] <= rect.y + rect.height;
  67285. }
  67286. };
  67287. Single.prototype.pointToData = function (point) {
  67288. var axis = this.getAxis();
  67289. return [axis.coordToData(axis.toLocalCoord(point[axis.orient === 'horizontal' ? 0 : 1]))];
  67290. };
  67291. /**
  67292. * Convert the series data to concrete point.
  67293. * Can be [val] | val
  67294. */
  67295. Single.prototype.dataToPoint = function (val) {
  67296. var axis = this.getAxis();
  67297. var rect = this.getRect();
  67298. var pt = [];
  67299. var idx = axis.orient === 'horizontal' ? 0 : 1;
  67300. if (val instanceof Array) {
  67301. val = val[0];
  67302. }
  67303. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  67304. pt[1 - idx] = idx === 0 ? rect.y + rect.height / 2 : rect.x + rect.width / 2;
  67305. return pt;
  67306. };
  67307. Single.prototype.convertToPixel = function (ecModel, finder, value) {
  67308. var coordSys = getCoordSys$3(finder);
  67309. return coordSys === this ? this.dataToPoint(value) : null;
  67310. };
  67311. Single.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  67312. var coordSys = getCoordSys$3(finder);
  67313. return coordSys === this ? this.pointToData(pixel) : null;
  67314. };
  67315. return Single;
  67316. }();
  67317. function getCoordSys$3(finder) {
  67318. var seriesModel = finder.seriesModel;
  67319. var singleModel = finder.singleAxisModel;
  67320. return singleModel && singleModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  67321. }
  67322. /**
  67323. * Create single coordinate system and inject it into seriesModel.
  67324. */
  67325. function create$2(ecModel, api) {
  67326. var singles = [];
  67327. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  67328. var single = new Single(axisModel, ecModel, api);
  67329. single.name = 'single_' + idx;
  67330. single.resize(axisModel, api);
  67331. axisModel.coordinateSystem = single;
  67332. singles.push(single);
  67333. });
  67334. ecModel.eachSeries(function (seriesModel) {
  67335. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  67336. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  67337. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  67338. }
  67339. });
  67340. return singles;
  67341. }
  67342. var singleCreator = {
  67343. create: create$2,
  67344. dimensions: singleDimensions
  67345. };
  67346. var XY = ['x', 'y'];
  67347. var WH = ['width', 'height'];
  67348. var SingleAxisPointer =
  67349. /** @class */
  67350. function (_super) {
  67351. __extends(SingleAxisPointer, _super);
  67352. function SingleAxisPointer() {
  67353. return _super !== null && _super.apply(this, arguments) || this;
  67354. }
  67355. /**
  67356. * @override
  67357. */
  67358. SingleAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  67359. var axis = axisModel.axis;
  67360. var coordSys = axis.coordinateSystem;
  67361. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  67362. var pixelValue = coordSys.dataToPoint(value)[0];
  67363. var axisPointerType = axisPointerModel.get('type');
  67364. if (axisPointerType && axisPointerType !== 'none') {
  67365. var elStyle = buildElStyle(axisPointerModel);
  67366. var pointerOption = pointerShapeBuilder$2[axisPointerType](axis, pixelValue, otherExtent);
  67367. pointerOption.style = elStyle;
  67368. elOption.graphicKey = pointerOption.type;
  67369. elOption.pointer = pointerOption;
  67370. }
  67371. var layoutInfo = layout$2(axisModel);
  67372. buildCartesianSingleLabelElOption( // @ts-ignore
  67373. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  67374. };
  67375. /**
  67376. * @override
  67377. */
  67378. SingleAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  67379. var layoutInfo = layout$2(axisModel, {
  67380. labelInside: false
  67381. }); // @ts-ignore
  67382. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  67383. var position = getTransformedPosition(axisModel.axis, value, layoutInfo);
  67384. return {
  67385. x: position[0],
  67386. y: position[1],
  67387. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  67388. };
  67389. };
  67390. /**
  67391. * @override
  67392. */
  67393. SingleAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  67394. var axis = axisModel.axis;
  67395. var coordSys = axis.coordinateSystem;
  67396. var dimIndex = getPointDimIndex(axis);
  67397. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  67398. var currPosition = [transform.x, transform.y];
  67399. currPosition[dimIndex] += delta[dimIndex];
  67400. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  67401. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  67402. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  67403. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  67404. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  67405. cursorPoint[dimIndex] = currPosition[dimIndex];
  67406. return {
  67407. x: currPosition[0],
  67408. y: currPosition[1],
  67409. rotation: transform.rotation,
  67410. cursorPoint: cursorPoint,
  67411. tooltipOption: {
  67412. verticalAlign: 'middle'
  67413. }
  67414. };
  67415. };
  67416. return SingleAxisPointer;
  67417. }(BaseAxisPointer);
  67418. var pointerShapeBuilder$2 = {
  67419. line: function (axis, pixelValue, otherExtent) {
  67420. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getPointDimIndex(axis));
  67421. return {
  67422. type: 'Line',
  67423. subPixelOptimize: true,
  67424. shape: targetShape
  67425. };
  67426. },
  67427. shadow: function (axis, pixelValue, otherExtent) {
  67428. var bandWidth = axis.getBandWidth();
  67429. var span = otherExtent[1] - otherExtent[0];
  67430. return {
  67431. type: 'Rect',
  67432. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getPointDimIndex(axis))
  67433. };
  67434. }
  67435. };
  67436. function getPointDimIndex(axis) {
  67437. return axis.isHorizontal() ? 0 : 1;
  67438. }
  67439. function getGlobalExtent(coordSys, dimIndex) {
  67440. var rect = coordSys.getRect();
  67441. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  67442. }
  67443. var SingleView =
  67444. /** @class */
  67445. function (_super) {
  67446. __extends(SingleView, _super);
  67447. function SingleView() {
  67448. var _this = _super !== null && _super.apply(this, arguments) || this;
  67449. _this.type = SingleView.type;
  67450. return _this;
  67451. }
  67452. SingleView.type = 'single';
  67453. return SingleView;
  67454. }(ComponentView);
  67455. function install$v(registers) {
  67456. use(install$s);
  67457. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  67458. registers.registerComponentView(SingleView); // Axis
  67459. registers.registerComponentView(SingleAxisView);
  67460. registers.registerComponentModel(SingleAxisModel);
  67461. axisModelCreator(registers, 'single', SingleAxisModel, SingleAxisModel.defaultOption);
  67462. registers.registerCoordinateSystem('single', singleCreator);
  67463. }
  67464. var CalendarModel =
  67465. /** @class */
  67466. function (_super) {
  67467. __extends(CalendarModel, _super);
  67468. function CalendarModel() {
  67469. var _this = _super !== null && _super.apply(this, arguments) || this;
  67470. _this.type = CalendarModel.type;
  67471. return _this;
  67472. }
  67473. /**
  67474. * @override
  67475. */
  67476. CalendarModel.prototype.init = function (option, parentModel, ecModel) {
  67477. var inputPositionParams = getLayoutParams(option);
  67478. _super.prototype.init.apply(this, arguments);
  67479. mergeAndNormalizeLayoutParams(option, inputPositionParams);
  67480. };
  67481. /**
  67482. * @override
  67483. */
  67484. CalendarModel.prototype.mergeOption = function (option) {
  67485. _super.prototype.mergeOption.apply(this, arguments);
  67486. mergeAndNormalizeLayoutParams(this.option, option);
  67487. };
  67488. CalendarModel.prototype.getCellSize = function () {
  67489. // Has been normalized
  67490. return this.option.cellSize;
  67491. };
  67492. CalendarModel.type = 'calendar';
  67493. CalendarModel.defaultOption = {
  67494. // zlevel: 0,
  67495. z: 2,
  67496. left: 80,
  67497. top: 60,
  67498. cellSize: 20,
  67499. // horizontal vertical
  67500. orient: 'horizontal',
  67501. // month separate line style
  67502. splitLine: {
  67503. show: true,
  67504. lineStyle: {
  67505. color: '#000',
  67506. width: 1,
  67507. type: 'solid'
  67508. }
  67509. },
  67510. // rect style temporarily unused emphasis
  67511. itemStyle: {
  67512. color: '#fff',
  67513. borderWidth: 1,
  67514. borderColor: '#ccc'
  67515. },
  67516. // week text style
  67517. dayLabel: {
  67518. show: true,
  67519. firstDay: 0,
  67520. // start end
  67521. position: 'start',
  67522. margin: '50%',
  67523. color: '#000'
  67524. },
  67525. // month text style
  67526. monthLabel: {
  67527. show: true,
  67528. // start end
  67529. position: 'start',
  67530. margin: 5,
  67531. // center or left
  67532. align: 'center',
  67533. formatter: null,
  67534. color: '#000'
  67535. },
  67536. // year text style
  67537. yearLabel: {
  67538. show: true,
  67539. // top bottom left right
  67540. position: null,
  67541. margin: 30,
  67542. formatter: null,
  67543. color: '#ccc',
  67544. fontFamily: 'sans-serif',
  67545. fontWeight: 'bolder',
  67546. fontSize: 20
  67547. }
  67548. };
  67549. return CalendarModel;
  67550. }(ComponentModel);
  67551. function mergeAndNormalizeLayoutParams(target, raw) {
  67552. // Normalize cellSize
  67553. var cellSize = target.cellSize;
  67554. var cellSizeArr;
  67555. if (!isArray(cellSize)) {
  67556. cellSizeArr = target.cellSize = [cellSize, cellSize];
  67557. } else {
  67558. cellSizeArr = cellSize;
  67559. }
  67560. if (cellSizeArr.length === 1) {
  67561. cellSizeArr[1] = cellSizeArr[0];
  67562. }
  67563. var ignoreSize = map([0, 1], function (hvIdx) {
  67564. // If user have set `width` or both `left` and `right`, cellSizeArr
  67565. // will be automatically set to 'auto', otherwise the default
  67566. // setting of cellSizeArr will make `width` setting not work.
  67567. if (sizeCalculable(raw, hvIdx)) {
  67568. cellSizeArr[hvIdx] = 'auto';
  67569. }
  67570. return cellSizeArr[hvIdx] != null && cellSizeArr[hvIdx] !== 'auto';
  67571. });
  67572. mergeLayoutParam(target, raw, {
  67573. type: 'box',
  67574. ignoreSize: ignoreSize
  67575. });
  67576. }
  67577. var CalendarView =
  67578. /** @class */
  67579. function (_super) {
  67580. __extends(CalendarView, _super);
  67581. function CalendarView() {
  67582. var _this = _super !== null && _super.apply(this, arguments) || this;
  67583. _this.type = CalendarView.type;
  67584. return _this;
  67585. }
  67586. CalendarView.prototype.render = function (calendarModel, ecModel, api) {
  67587. var group = this.group;
  67588. group.removeAll();
  67589. var coordSys = calendarModel.coordinateSystem; // range info
  67590. var rangeData = coordSys.getRangeInfo();
  67591. var orient = coordSys.getOrient(); // locale
  67592. var localeModel = ecModel.getLocaleModel();
  67593. this._renderDayRect(calendarModel, rangeData, group); // _renderLines must be called prior to following function
  67594. this._renderLines(calendarModel, rangeData, orient, group);
  67595. this._renderYearText(calendarModel, rangeData, orient, group);
  67596. this._renderMonthText(calendarModel, localeModel, orient, group);
  67597. this._renderWeekText(calendarModel, localeModel, rangeData, orient, group);
  67598. }; // render day rect
  67599. CalendarView.prototype._renderDayRect = function (calendarModel, rangeData, group) {
  67600. var coordSys = calendarModel.coordinateSystem;
  67601. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  67602. var sw = coordSys.getCellWidth();
  67603. var sh = coordSys.getCellHeight();
  67604. for (var i = rangeData.start.time; i <= rangeData.end.time; i = coordSys.getNextNDay(i, 1).time) {
  67605. var point = coordSys.dataToRect([i], false).tl; // every rect
  67606. var rect = new Rect({
  67607. shape: {
  67608. x: point[0],
  67609. y: point[1],
  67610. width: sw,
  67611. height: sh
  67612. },
  67613. cursor: 'default',
  67614. style: itemRectStyleModel
  67615. });
  67616. group.add(rect);
  67617. }
  67618. }; // render separate line
  67619. CalendarView.prototype._renderLines = function (calendarModel, rangeData, orient, group) {
  67620. var self = this;
  67621. var coordSys = calendarModel.coordinateSystem;
  67622. var lineStyleModel = calendarModel.getModel(['splitLine', 'lineStyle']).getLineStyle();
  67623. var show = calendarModel.get(['splitLine', 'show']);
  67624. var lineWidth = lineStyleModel.lineWidth;
  67625. this._tlpoints = [];
  67626. this._blpoints = [];
  67627. this._firstDayOfMonth = [];
  67628. this._firstDayPoints = [];
  67629. var firstDay = rangeData.start;
  67630. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  67631. addPoints(firstDay.formatedDate);
  67632. if (i === 0) {
  67633. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  67634. }
  67635. var date = firstDay.date;
  67636. date.setMonth(date.getMonth() + 1);
  67637. firstDay = coordSys.getDateInfo(date);
  67638. }
  67639. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  67640. function addPoints(date) {
  67641. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  67642. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  67643. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  67644. self._tlpoints.push(points[0]);
  67645. self._blpoints.push(points[points.length - 1]);
  67646. show && self._drawSplitline(points, lineStyleModel, group);
  67647. } // render top/left line
  67648. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group); // render bottom/right line
  67649. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  67650. }; // get points at both ends
  67651. CalendarView.prototype._getEdgesPoints = function (points, lineWidth, orient) {
  67652. var rs = [points[0].slice(), points[points.length - 1].slice()];
  67653. var idx = orient === 'horizontal' ? 0 : 1; // both ends of the line are extend half lineWidth
  67654. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  67655. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  67656. return rs;
  67657. }; // render split line
  67658. CalendarView.prototype._drawSplitline = function (points, lineStyle, group) {
  67659. var poyline = new Polyline({
  67660. z2: 20,
  67661. shape: {
  67662. points: points
  67663. },
  67664. style: lineStyle
  67665. });
  67666. group.add(poyline);
  67667. }; // render month line of one week points
  67668. CalendarView.prototype._getLinePointsOfOneWeek = function (calendarModel, date, orient) {
  67669. var coordSys = calendarModel.coordinateSystem;
  67670. var parsedDate = coordSys.getDateInfo(date);
  67671. var points = [];
  67672. for (var i = 0; i < 7; i++) {
  67673. var tmpD = coordSys.getNextNDay(parsedDate.time, i);
  67674. var point = coordSys.dataToRect([tmpD.time], false);
  67675. points[2 * tmpD.day] = point.tl;
  67676. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  67677. }
  67678. return points;
  67679. };
  67680. CalendarView.prototype._formatterLabel = function (formatter, params) {
  67681. if (isString(formatter) && formatter) {
  67682. return formatTplSimple(formatter, params);
  67683. }
  67684. if (isFunction(formatter)) {
  67685. return formatter(params);
  67686. }
  67687. return params.nameMap;
  67688. };
  67689. CalendarView.prototype._yearTextPositionControl = function (textEl, point, orient, position, margin) {
  67690. var x = point[0];
  67691. var y = point[1];
  67692. var aligns = ['center', 'bottom'];
  67693. if (position === 'bottom') {
  67694. y += margin;
  67695. aligns = ['center', 'top'];
  67696. } else if (position === 'left') {
  67697. x -= margin;
  67698. } else if (position === 'right') {
  67699. x += margin;
  67700. aligns = ['center', 'top'];
  67701. } else {
  67702. // top
  67703. y -= margin;
  67704. }
  67705. var rotate = 0;
  67706. if (position === 'left' || position === 'right') {
  67707. rotate = Math.PI / 2;
  67708. }
  67709. return {
  67710. rotation: rotate,
  67711. x: x,
  67712. y: y,
  67713. style: {
  67714. align: aligns[0],
  67715. verticalAlign: aligns[1]
  67716. }
  67717. };
  67718. }; // render year
  67719. CalendarView.prototype._renderYearText = function (calendarModel, rangeData, orient, group) {
  67720. var yearLabel = calendarModel.getModel('yearLabel');
  67721. if (!yearLabel.get('show')) {
  67722. return;
  67723. }
  67724. var margin = yearLabel.get('margin');
  67725. var pos = yearLabel.get('position');
  67726. if (!pos) {
  67727. pos = orient !== 'horizontal' ? 'top' : 'left';
  67728. }
  67729. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  67730. var xc = (points[0][0] + points[1][0]) / 2;
  67731. var yc = (points[0][1] + points[1][1]) / 2;
  67732. var idx = orient === 'horizontal' ? 0 : 1;
  67733. var posPoints = {
  67734. top: [xc, points[idx][1]],
  67735. bottom: [xc, points[1 - idx][1]],
  67736. left: [points[1 - idx][0], yc],
  67737. right: [points[idx][0], yc]
  67738. };
  67739. var name = rangeData.start.y;
  67740. if (+rangeData.end.y > +rangeData.start.y) {
  67741. name = name + '-' + rangeData.end.y;
  67742. }
  67743. var formatter = yearLabel.get('formatter');
  67744. var params = {
  67745. start: rangeData.start.y,
  67746. end: rangeData.end.y,
  67747. nameMap: name
  67748. };
  67749. var content = this._formatterLabel(formatter, params);
  67750. var yearText = new ZRText({
  67751. z2: 30,
  67752. style: createTextStyle(yearLabel, {
  67753. text: content
  67754. })
  67755. });
  67756. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  67757. group.add(yearText);
  67758. };
  67759. CalendarView.prototype._monthTextPositionControl = function (point, isCenter, orient, position, margin) {
  67760. var align = 'left';
  67761. var vAlign = 'top';
  67762. var x = point[0];
  67763. var y = point[1];
  67764. if (orient === 'horizontal') {
  67765. y = y + margin;
  67766. if (isCenter) {
  67767. align = 'center';
  67768. }
  67769. if (position === 'start') {
  67770. vAlign = 'bottom';
  67771. }
  67772. } else {
  67773. x = x + margin;
  67774. if (isCenter) {
  67775. vAlign = 'middle';
  67776. }
  67777. if (position === 'start') {
  67778. align = 'right';
  67779. }
  67780. }
  67781. return {
  67782. x: x,
  67783. y: y,
  67784. align: align,
  67785. verticalAlign: vAlign
  67786. };
  67787. }; // render month and year text
  67788. CalendarView.prototype._renderMonthText = function (calendarModel, localeModel, orient, group) {
  67789. var monthLabel = calendarModel.getModel('monthLabel');
  67790. if (!monthLabel.get('show')) {
  67791. return;
  67792. }
  67793. var nameMap = monthLabel.get('nameMap');
  67794. var margin = monthLabel.get('margin');
  67795. var pos = monthLabel.get('position');
  67796. var align = monthLabel.get('align');
  67797. var termPoints = [this._tlpoints, this._blpoints];
  67798. if (!nameMap || isString(nameMap)) {
  67799. if (nameMap) {
  67800. // case-sensitive
  67801. localeModel = getLocaleModel(nameMap) || localeModel;
  67802. } // PENDING
  67803. // for ZH locale, original form is `一月` but current form is `1月`
  67804. nameMap = localeModel.get(['time', 'monthAbbr']) || [];
  67805. }
  67806. var idx = pos === 'start' ? 0 : 1;
  67807. var axis = orient === 'horizontal' ? 0 : 1;
  67808. margin = pos === 'start' ? -margin : margin;
  67809. var isCenter = align === 'center';
  67810. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  67811. var tmp = termPoints[idx][i].slice();
  67812. var firstDay = this._firstDayOfMonth[i];
  67813. if (isCenter) {
  67814. var firstDayPoints = this._firstDayPoints[i];
  67815. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  67816. }
  67817. var formatter = monthLabel.get('formatter');
  67818. var name_1 = nameMap[+firstDay.m - 1];
  67819. var params = {
  67820. yyyy: firstDay.y,
  67821. yy: (firstDay.y + '').slice(2),
  67822. MM: firstDay.m,
  67823. M: +firstDay.m,
  67824. nameMap: name_1
  67825. };
  67826. var content = this._formatterLabel(formatter, params);
  67827. var monthText = new ZRText({
  67828. z2: 30,
  67829. style: extend(createTextStyle(monthLabel, {
  67830. text: content
  67831. }), this._monthTextPositionControl(tmp, isCenter, orient, pos, margin))
  67832. });
  67833. group.add(monthText);
  67834. }
  67835. };
  67836. CalendarView.prototype._weekTextPositionControl = function (point, orient, position, margin, cellSize) {
  67837. var align = 'center';
  67838. var vAlign = 'middle';
  67839. var x = point[0];
  67840. var y = point[1];
  67841. var isStart = position === 'start';
  67842. if (orient === 'horizontal') {
  67843. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  67844. align = isStart ? 'right' : 'left';
  67845. } else {
  67846. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  67847. vAlign = isStart ? 'bottom' : 'top';
  67848. }
  67849. return {
  67850. x: x,
  67851. y: y,
  67852. align: align,
  67853. verticalAlign: vAlign
  67854. };
  67855. }; // render weeks
  67856. CalendarView.prototype._renderWeekText = function (calendarModel, localeModel, rangeData, orient, group) {
  67857. var dayLabel = calendarModel.getModel('dayLabel');
  67858. if (!dayLabel.get('show')) {
  67859. return;
  67860. }
  67861. var coordSys = calendarModel.coordinateSystem;
  67862. var pos = dayLabel.get('position');
  67863. var nameMap = dayLabel.get('nameMap');
  67864. var margin = dayLabel.get('margin');
  67865. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  67866. if (!nameMap || isString(nameMap)) {
  67867. if (nameMap) {
  67868. // case-sensitive
  67869. localeModel = getLocaleModel(nameMap) || localeModel;
  67870. } // Use the first letter of `dayOfWeekAbbr` if `dayOfWeekShort` doesn't exist in the locale file
  67871. var dayOfWeekShort = localeModel.get(['time', 'dayOfWeekShort']);
  67872. nameMap = dayOfWeekShort || map(localeModel.get(['time', 'dayOfWeekAbbr']), function (val) {
  67873. return val[0];
  67874. });
  67875. }
  67876. var start = coordSys.getNextNDay(rangeData.end.time, 7 - rangeData.lweek).time;
  67877. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  67878. margin = parsePercent$1(margin, Math.min(cellSize[1], cellSize[0]));
  67879. if (pos === 'start') {
  67880. start = coordSys.getNextNDay(rangeData.start.time, -(7 + rangeData.fweek)).time;
  67881. margin = -margin;
  67882. }
  67883. for (var i = 0; i < 7; i++) {
  67884. var tmpD = coordSys.getNextNDay(start, i);
  67885. var point = coordSys.dataToRect([tmpD.time], false).center;
  67886. var day = i;
  67887. day = Math.abs((i + firstDayOfWeek) % 7);
  67888. var weekText = new ZRText({
  67889. z2: 30,
  67890. style: extend(createTextStyle(dayLabel, {
  67891. text: nameMap[day]
  67892. }), this._weekTextPositionControl(point, orient, pos, margin, cellSize))
  67893. });
  67894. group.add(weekText);
  67895. }
  67896. };
  67897. CalendarView.type = 'calendar';
  67898. return CalendarView;
  67899. }(ComponentView);
  67900. var PROXIMATE_ONE_DAY = 86400000;
  67901. var Calendar =
  67902. /** @class */
  67903. function () {
  67904. function Calendar(calendarModel, ecModel, api) {
  67905. this.type = 'calendar';
  67906. this.dimensions = Calendar.dimensions; // Required in createListFromData
  67907. this.getDimensionsInfo = Calendar.getDimensionsInfo;
  67908. this._model = calendarModel;
  67909. }
  67910. Calendar.getDimensionsInfo = function () {
  67911. return [{
  67912. name: 'time',
  67913. type: 'time'
  67914. }, 'value'];
  67915. };
  67916. Calendar.prototype.getRangeInfo = function () {
  67917. return this._rangeInfo;
  67918. };
  67919. Calendar.prototype.getModel = function () {
  67920. return this._model;
  67921. };
  67922. Calendar.prototype.getRect = function () {
  67923. return this._rect;
  67924. };
  67925. Calendar.prototype.getCellWidth = function () {
  67926. return this._sw;
  67927. };
  67928. Calendar.prototype.getCellHeight = function () {
  67929. return this._sh;
  67930. };
  67931. Calendar.prototype.getOrient = function () {
  67932. return this._orient;
  67933. };
  67934. /**
  67935. * getFirstDayOfWeek
  67936. *
  67937. * @example
  67938. * 0 : start at Sunday
  67939. * 1 : start at Monday
  67940. *
  67941. * @return {number}
  67942. */
  67943. Calendar.prototype.getFirstDayOfWeek = function () {
  67944. return this._firstDayOfWeek;
  67945. };
  67946. /**
  67947. * get date info
  67948. * }
  67949. */
  67950. Calendar.prototype.getDateInfo = function (date) {
  67951. date = parseDate(date);
  67952. var y = date.getFullYear();
  67953. var m = date.getMonth() + 1;
  67954. var mStr = m < 10 ? '0' + m : '' + m;
  67955. var d = date.getDate();
  67956. var dStr = d < 10 ? '0' + d : '' + d;
  67957. var day = date.getDay();
  67958. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  67959. return {
  67960. y: y + '',
  67961. m: mStr,
  67962. d: dStr,
  67963. day: day,
  67964. time: date.getTime(),
  67965. formatedDate: y + '-' + mStr + '-' + dStr,
  67966. date: date
  67967. };
  67968. };
  67969. Calendar.prototype.getNextNDay = function (date, n) {
  67970. n = n || 0;
  67971. if (n === 0) {
  67972. return this.getDateInfo(date);
  67973. }
  67974. date = new Date(this.getDateInfo(date).time);
  67975. date.setDate(date.getDate() + n);
  67976. return this.getDateInfo(date);
  67977. };
  67978. Calendar.prototype.update = function (ecModel, api) {
  67979. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  67980. this._orient = this._model.get('orient');
  67981. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  67982. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  67983. var weeks = this._rangeInfo.weeks || 1;
  67984. var whNames = ['width', 'height'];
  67985. var cellSize = this._model.getCellSize().slice();
  67986. var layoutParams = this._model.getBoxLayoutParams();
  67987. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  67988. each([0, 1], function (idx) {
  67989. if (cellSizeSpecified(cellSize, idx)) {
  67990. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  67991. }
  67992. });
  67993. var whGlobal = {
  67994. width: api.getWidth(),
  67995. height: api.getHeight()
  67996. };
  67997. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  67998. each([0, 1], function (idx) {
  67999. if (!cellSizeSpecified(cellSize, idx)) {
  68000. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  68001. }
  68002. });
  68003. function cellSizeSpecified(cellSize, idx) {
  68004. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  68005. } // Has been calculated out number.
  68006. this._sw = cellSize[0];
  68007. this._sh = cellSize[1];
  68008. };
  68009. /**
  68010. * Convert a time data(time, value) item to (x, y) point.
  68011. */
  68012. // TODO Clamp of calendar is not same with cartesian coordinate systems.
  68013. // It will return NaN if data exceeds.
  68014. Calendar.prototype.dataToPoint = function (data, clamp) {
  68015. isArray(data) && (data = data[0]);
  68016. clamp == null && (clamp = true);
  68017. var dayInfo = this.getDateInfo(data);
  68018. var range = this._rangeInfo;
  68019. var date = dayInfo.formatedDate; // if not in range return [NaN, NaN]
  68020. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY)) {
  68021. return [NaN, NaN];
  68022. }
  68023. var week = dayInfo.day;
  68024. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  68025. if (this._orient === 'vertical') {
  68026. return [this._rect.x + week * this._sw + this._sw / 2, this._rect.y + nthWeek * this._sh + this._sh / 2];
  68027. }
  68028. return [this._rect.x + nthWeek * this._sw + this._sw / 2, this._rect.y + week * this._sh + this._sh / 2];
  68029. };
  68030. /**
  68031. * Convert a (x, y) point to time data
  68032. */
  68033. Calendar.prototype.pointToData = function (point) {
  68034. var date = this.pointToDate(point);
  68035. return date && date.time;
  68036. };
  68037. /**
  68038. * Convert a time date item to (x, y) four point.
  68039. */
  68040. Calendar.prototype.dataToRect = function (data, clamp) {
  68041. var point = this.dataToPoint(data, clamp);
  68042. return {
  68043. contentShape: {
  68044. x: point[0] - (this._sw - this._lineWidth) / 2,
  68045. y: point[1] - (this._sh - this._lineWidth) / 2,
  68046. width: this._sw - this._lineWidth,
  68047. height: this._sh - this._lineWidth
  68048. },
  68049. center: point,
  68050. tl: [point[0] - this._sw / 2, point[1] - this._sh / 2],
  68051. tr: [point[0] + this._sw / 2, point[1] - this._sh / 2],
  68052. br: [point[0] + this._sw / 2, point[1] + this._sh / 2],
  68053. bl: [point[0] - this._sw / 2, point[1] + this._sh / 2]
  68054. };
  68055. };
  68056. /**
  68057. * Convert a (x, y) point to time date
  68058. *
  68059. * @param {Array} point point
  68060. * @return {Object} date
  68061. */
  68062. Calendar.prototype.pointToDate = function (point) {
  68063. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  68064. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  68065. var range = this._rangeInfo.range;
  68066. if (this._orient === 'vertical') {
  68067. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  68068. }
  68069. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  68070. };
  68071. Calendar.prototype.convertToPixel = function (ecModel, finder, value) {
  68072. var coordSys = getCoordSys$4(finder);
  68073. return coordSys === this ? coordSys.dataToPoint(value) : null;
  68074. };
  68075. Calendar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  68076. var coordSys = getCoordSys$4(finder);
  68077. return coordSys === this ? coordSys.pointToData(pixel) : null;
  68078. };
  68079. Calendar.prototype.containPoint = function (point) {
  68080. console.warn('Not implemented.');
  68081. return false;
  68082. };
  68083. /**
  68084. * initRange
  68085. * Normalize to an [start, end] array
  68086. */
  68087. Calendar.prototype._initRangeOption = function () {
  68088. var range = this._model.get('range');
  68089. var normalizedRange; // Convert [1990] to 1990
  68090. if (isArray(range) && range.length === 1) {
  68091. range = range[0];
  68092. }
  68093. if (!isArray(range)) {
  68094. var rangeStr = range.toString(); // One year.
  68095. if (/^\d{4}$/.test(rangeStr)) {
  68096. normalizedRange = [rangeStr + '-01-01', rangeStr + '-12-31'];
  68097. } // One month
  68098. if (/^\d{4}[\/|-]\d{1,2}$/.test(rangeStr)) {
  68099. var start = this.getDateInfo(rangeStr);
  68100. var firstDay = start.date;
  68101. firstDay.setMonth(firstDay.getMonth() + 1);
  68102. var end = this.getNextNDay(firstDay, -1);
  68103. normalizedRange = [start.formatedDate, end.formatedDate];
  68104. } // One day
  68105. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rangeStr)) {
  68106. normalizedRange = [rangeStr, rangeStr];
  68107. }
  68108. } else {
  68109. normalizedRange = range;
  68110. }
  68111. if (!normalizedRange) {
  68112. if ("development" !== 'production') {
  68113. logError('Invalid date range.');
  68114. } // Not handling it.
  68115. return range;
  68116. }
  68117. var tmp = this._getRangeInfo(normalizedRange);
  68118. if (tmp.start.time > tmp.end.time) {
  68119. normalizedRange.reverse();
  68120. }
  68121. return normalizedRange;
  68122. };
  68123. /**
  68124. * range info
  68125. *
  68126. * @private
  68127. * @param {Array} range range ['2017-01-01', '2017-07-08']
  68128. * If range[0] > range[1], they will not be reversed.
  68129. * @return {Object} obj
  68130. */
  68131. Calendar.prototype._getRangeInfo = function (range) {
  68132. var parsedRange = [this.getDateInfo(range[0]), this.getDateInfo(range[1])];
  68133. var reversed;
  68134. if (parsedRange[0].time > parsedRange[1].time) {
  68135. reversed = true;
  68136. parsedRange.reverse();
  68137. }
  68138. var allDay = Math.floor(parsedRange[1].time / PROXIMATE_ONE_DAY) - Math.floor(parsedRange[0].time / PROXIMATE_ONE_DAY) + 1; // Consider case1 (#11677 #10430):
  68139. // Set the system timezone as "UK", set the range to `['2016-07-01', '2016-12-31']`
  68140. // Consider case2:
  68141. // Firstly set system timezone as "Time Zone: America/Toronto",
  68142. // ```
  68143. // let first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  68144. // let second = new Date(1478412000000);
  68145. // let allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  68146. // ```
  68147. // will get wrong result because of DST. So we should fix it.
  68148. var date = new Date(parsedRange[0].time);
  68149. var startDateNum = date.getDate();
  68150. var endDateNum = parsedRange[1].date.getDate();
  68151. date.setDate(startDateNum + allDay - 1); // The bias can not over a month, so just compare date.
  68152. var dateNum = date.getDate();
  68153. if (dateNum !== endDateNum) {
  68154. var sign = date.getTime() - parsedRange[1].time > 0 ? 1 : -1;
  68155. while ((dateNum = date.getDate()) !== endDateNum && (date.getTime() - parsedRange[1].time) * sign > 0) {
  68156. allDay -= sign;
  68157. date.setDate(dateNum - sign);
  68158. }
  68159. }
  68160. var weeks = Math.floor((allDay + parsedRange[0].day + 6) / 7);
  68161. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  68162. reversed && parsedRange.reverse();
  68163. return {
  68164. range: [parsedRange[0].formatedDate, parsedRange[1].formatedDate],
  68165. start: parsedRange[0],
  68166. end: parsedRange[1],
  68167. allDay: allDay,
  68168. weeks: weeks,
  68169. // From 0.
  68170. nthWeek: nthWeek,
  68171. fweek: parsedRange[0].day,
  68172. lweek: parsedRange[1].day
  68173. };
  68174. };
  68175. /**
  68176. * get date by nthWeeks and week day in range
  68177. *
  68178. * @private
  68179. * @param {number} nthWeek the week
  68180. * @param {number} day the week day
  68181. * @param {Array} range [d1, d2]
  68182. * @return {Object}
  68183. */
  68184. Calendar.prototype._getDateByWeeksAndDay = function (nthWeek, day, range) {
  68185. var rangeInfo = this._getRangeInfo(range);
  68186. if (nthWeek > rangeInfo.weeks || nthWeek === 0 && day < rangeInfo.fweek || nthWeek === rangeInfo.weeks && day > rangeInfo.lweek) {
  68187. return null;
  68188. }
  68189. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  68190. var date = new Date(rangeInfo.start.time);
  68191. date.setDate(+rangeInfo.start.d + nthDay);
  68192. return this.getDateInfo(date);
  68193. };
  68194. Calendar.create = function (ecModel, api) {
  68195. var calendarList = [];
  68196. ecModel.eachComponent('calendar', function (calendarModel) {
  68197. var calendar = new Calendar(calendarModel, ecModel, api);
  68198. calendarList.push(calendar);
  68199. calendarModel.coordinateSystem = calendar;
  68200. });
  68201. ecModel.eachSeries(function (calendarSeries) {
  68202. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  68203. // Inject coordinate system
  68204. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  68205. }
  68206. });
  68207. return calendarList;
  68208. };
  68209. Calendar.dimensions = ['time', 'value'];
  68210. return Calendar;
  68211. }();
  68212. function getCoordSys$4(finder) {
  68213. var calendarModel = finder.calendarModel;
  68214. var seriesModel = finder.seriesModel;
  68215. var coordSys = calendarModel ? calendarModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem : null;
  68216. return coordSys;
  68217. }
  68218. function install$w(registers) {
  68219. registers.registerComponentModel(CalendarModel);
  68220. registers.registerComponentView(CalendarView);
  68221. registers.registerCoordinateSystem('calendar', Calendar);
  68222. }
  68223. function setKeyInfoToNewElOption(resultItem, newElOption) {
  68224. var existElOption = resultItem.existing; // Set id and type after id assigned.
  68225. newElOption.id = resultItem.keyInfo.id;
  68226. !newElOption.type && existElOption && (newElOption.type = existElOption.type); // Set parent id if not specified
  68227. if (newElOption.parentId == null) {
  68228. var newElParentOption = newElOption.parentOption;
  68229. if (newElParentOption) {
  68230. newElOption.parentId = newElParentOption.id;
  68231. } else if (existElOption) {
  68232. newElOption.parentId = existElOption.parentId;
  68233. }
  68234. } // Clear
  68235. newElOption.parentOption = null;
  68236. }
  68237. function isSetLoc(obj, props) {
  68238. var isSet;
  68239. each(props, function (prop) {
  68240. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  68241. });
  68242. return isSet;
  68243. }
  68244. function mergeNewElOptionToExist(existList, index, newElOption) {
  68245. // Update existing options, for `getOption` feature.
  68246. var newElOptCopy = extend({}, newElOption);
  68247. var existElOption = existList[index];
  68248. var $action = newElOption.$action || 'merge';
  68249. if ($action === 'merge') {
  68250. if (existElOption) {
  68251. if ("development" !== 'production') {
  68252. var newType = newElOption.type;
  68253. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  68254. } // We can ensure that newElOptCopy and existElOption are not
  68255. // the same object, so `merge` will not change newElOptCopy.
  68256. merge(existElOption, newElOptCopy, true); // Rigid body, use ignoreSize.
  68257. mergeLayoutParam(existElOption, newElOptCopy, {
  68258. ignoreSize: true
  68259. }); // Will be used in render.
  68260. copyLayoutParams(newElOption, existElOption); // Copy transition info to new option so it can be used in the transition.
  68261. // DO IT AFTER merge
  68262. copyTransitionInfo(newElOption, existElOption);
  68263. copyTransitionInfo(newElOption, existElOption, 'shape');
  68264. copyTransitionInfo(newElOption, existElOption, 'style');
  68265. copyTransitionInfo(newElOption, existElOption, 'extra'); // Copy clipPath
  68266. newElOption.clipPath = existElOption.clipPath;
  68267. } else {
  68268. existList[index] = newElOptCopy;
  68269. }
  68270. } else if ($action === 'replace') {
  68271. existList[index] = newElOptCopy;
  68272. } else if ($action === 'remove') {
  68273. // null will be cleaned later.
  68274. existElOption && (existList[index] = null);
  68275. }
  68276. }
  68277. var TRANSITION_PROPS_TO_COPY = ['transition', 'enterFrom', 'leaveTo'];
  68278. var ROOT_TRANSITION_PROPS_TO_COPY = TRANSITION_PROPS_TO_COPY.concat(['enterAnimation', 'updateAnimation', 'leaveAnimation']);
  68279. function copyTransitionInfo(target, source, targetProp) {
  68280. if (targetProp) {
  68281. if (!target[targetProp] && source[targetProp]) {
  68282. // TODO avoid creating this empty object when there is no transition configuration.
  68283. target[targetProp] = {};
  68284. }
  68285. target = target[targetProp];
  68286. source = source[targetProp];
  68287. }
  68288. if (!target || !source) {
  68289. return;
  68290. }
  68291. var props = targetProp ? TRANSITION_PROPS_TO_COPY : ROOT_TRANSITION_PROPS_TO_COPY;
  68292. for (var i = 0; i < props.length; i++) {
  68293. var prop = props[i];
  68294. if (target[prop] == null && source[prop] != null) {
  68295. target[prop] = source[prop];
  68296. }
  68297. }
  68298. }
  68299. function setLayoutInfoToExist(existItem, newElOption) {
  68300. if (!existItem) {
  68301. return;
  68302. }
  68303. existItem.hv = newElOption.hv = [// Rigid body, don't care about `width`.
  68304. isSetLoc(newElOption, ['left', 'right']), // Rigid body, don't care about `height`.
  68305. isSetLoc(newElOption, ['top', 'bottom'])]; // Give default group size. Otherwise layout error may occur.
  68306. if (existItem.type === 'group') {
  68307. var existingGroupOpt = existItem;
  68308. var newGroupOpt = newElOption;
  68309. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  68310. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  68311. }
  68312. }
  68313. var GraphicComponentModel =
  68314. /** @class */
  68315. function (_super) {
  68316. __extends(GraphicComponentModel, _super);
  68317. function GraphicComponentModel() {
  68318. var _this = _super !== null && _super.apply(this, arguments) || this;
  68319. _this.type = GraphicComponentModel.type;
  68320. _this.preventAutoZ = true;
  68321. return _this;
  68322. }
  68323. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  68324. // Prevent default merge to elements
  68325. var elements = this.option.elements;
  68326. this.option.elements = null;
  68327. _super.prototype.mergeOption.call(this, option, ecModel);
  68328. this.option.elements = elements;
  68329. };
  68330. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  68331. var thisOption = this.option;
  68332. var newList = (isInit ? thisOption : newOption).elements;
  68333. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  68334. var flattenedList = [];
  68335. this._flatten(newList, flattenedList, null);
  68336. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge'); // Clear elOptionsToUpdate
  68337. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  68338. each(mappingResult, function (resultItem, index) {
  68339. var newElOption = resultItem.newOption;
  68340. if ("development" !== 'production') {
  68341. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  68342. }
  68343. if (!newElOption) {
  68344. return;
  68345. }
  68346. elOptionsToUpdate.push(newElOption);
  68347. setKeyInfoToNewElOption(resultItem, newElOption);
  68348. mergeNewElOptionToExist(existList, index, newElOption);
  68349. setLayoutInfoToExist(existList[index], newElOption);
  68350. }, this); // Clean
  68351. thisOption.elements = filter(existList, function (item) {
  68352. // $action should be volatile, otherwise option gotten from
  68353. // `getOption` will contain unexpected $action.
  68354. item && delete item.$action;
  68355. return item != null;
  68356. });
  68357. };
  68358. /**
  68359. * Convert
  68360. * [{
  68361. * type: 'group',
  68362. * id: 'xx',
  68363. * children: [{type: 'circle'}, {type: 'polygon'}]
  68364. * }]
  68365. * to
  68366. * [
  68367. * {type: 'group', id: 'xx'},
  68368. * {type: 'circle', parentId: 'xx'},
  68369. * {type: 'polygon', parentId: 'xx'}
  68370. * ]
  68371. */
  68372. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  68373. each(optionList, function (option) {
  68374. if (!option) {
  68375. return;
  68376. }
  68377. if (parentOption) {
  68378. option.parentOption = parentOption;
  68379. }
  68380. result.push(option);
  68381. var children = option.children; // here we don't judge if option.type is `group`
  68382. // when new option doesn't provide `type`, it will cause that the children can't be updated.
  68383. if (children && children.length) {
  68384. this._flatten(children, result, option);
  68385. } // Deleting for JSON output, and for not affecting group creation.
  68386. delete option.children;
  68387. }, this);
  68388. }; // FIXME
  68389. // Pass to view using payload? setOption has a payload?
  68390. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  68391. var els = this._elOptionsToUpdate; // Clear to avoid render duplicately when zooming.
  68392. this._elOptionsToUpdate = null;
  68393. return els;
  68394. };
  68395. GraphicComponentModel.type = 'graphic';
  68396. GraphicComponentModel.defaultOption = {
  68397. elements: [] // parentId: null
  68398. };
  68399. return GraphicComponentModel;
  68400. }(ComponentModel);
  68401. var nonShapeGraphicElements = {
  68402. // Reserved but not supported in graphic component.
  68403. path: null,
  68404. compoundPath: null,
  68405. // Supported in graphic component.
  68406. group: Group,
  68407. image: ZRImage,
  68408. text: ZRText
  68409. };
  68410. var inner$e = makeInner(); // ------------------------
  68411. // View
  68412. // ------------------------
  68413. var GraphicComponentView =
  68414. /** @class */
  68415. function (_super) {
  68416. __extends(GraphicComponentView, _super);
  68417. function GraphicComponentView() {
  68418. var _this = _super !== null && _super.apply(this, arguments) || this;
  68419. _this.type = GraphicComponentView.type;
  68420. return _this;
  68421. }
  68422. GraphicComponentView.prototype.init = function () {
  68423. this._elMap = createHashMap();
  68424. };
  68425. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  68426. // Having leveraged between use cases and algorithm complexity, a very
  68427. // simple layout mechanism is used:
  68428. // The size(width/height) can be determined by itself or its parent (not
  68429. // implemented yet), but can not by its children. (Top-down travel)
  68430. // The location(x/y) can be determined by the bounding rect of itself
  68431. // (can including its descendants or not) and the size of its parent.
  68432. // (Bottom-up travel)
  68433. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  68434. // view will be reused.
  68435. if (graphicModel !== this._lastGraphicModel) {
  68436. this._clear();
  68437. }
  68438. this._lastGraphicModel = graphicModel;
  68439. this._updateElements(graphicModel);
  68440. this._relocate(graphicModel, api);
  68441. };
  68442. /**
  68443. * Update graphic elements.
  68444. */
  68445. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  68446. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  68447. if (!elOptionsToUpdate) {
  68448. return;
  68449. }
  68450. var elMap = this._elMap;
  68451. var rootGroup = this.group;
  68452. var globalZ = graphicModel.get('z');
  68453. var globalZLevel = graphicModel.get('zlevel'); // Top-down tranverse to assign graphic settings to each elements.
  68454. each(elOptionsToUpdate, function (elOption) {
  68455. var id = convertOptionIdName(elOption.id, null);
  68456. var elExisting = id != null ? elMap.get(id) : null;
  68457. var parentId = convertOptionIdName(elOption.parentId, null);
  68458. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  68459. var elType = elOption.type;
  68460. var elOptionStyle = elOption.style;
  68461. if (elType === 'text' && elOptionStyle) {
  68462. // In top/bottom mode, textVerticalAlign should not be used, which cause
  68463. // inaccurately locating.
  68464. if (elOption.hv && elOption.hv[1]) {
  68465. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  68466. }
  68467. }
  68468. var textContentOption = elOption.textContent;
  68469. var textConfig = elOption.textConfig;
  68470. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  68471. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  68472. if (!textConfig && convertResult.textConfig) {
  68473. textConfig = elOption.textConfig = convertResult.textConfig;
  68474. }
  68475. if (!textContentOption && convertResult.textContent) {
  68476. textContentOption = convertResult.textContent;
  68477. }
  68478. } // Remove unnecessary props to avoid potential problems.
  68479. var elOptionCleaned = getCleanedElOption(elOption); // For simple, do not support parent change, otherwise reorder is needed.
  68480. if ("development" !== 'production') {
  68481. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  68482. }
  68483. var $action = elOption.$action || 'merge';
  68484. var isMerge = $action === 'merge';
  68485. var isReplace = $action === 'replace';
  68486. if (isMerge) {
  68487. var isInit = !elExisting;
  68488. var el_1 = elExisting;
  68489. if (isInit) {
  68490. el_1 = createEl$1(id, targetElParent, elOption.type, elMap);
  68491. } else {
  68492. el_1 && (inner$e(el_1).isNew = false); // Stop and restore before update any other attributes.
  68493. stopPreviousKeyframeAnimationAndRestore(el_1);
  68494. }
  68495. if (el_1) {
  68496. applyUpdateTransition(el_1, elOptionCleaned, graphicModel, {
  68497. isInit: isInit
  68498. });
  68499. updateCommonAttrs(el_1, elOption, globalZ, globalZLevel);
  68500. }
  68501. } else if (isReplace) {
  68502. removeEl(elExisting, elOption, elMap, graphicModel);
  68503. var el_2 = createEl$1(id, targetElParent, elOption.type, elMap);
  68504. if (el_2) {
  68505. applyUpdateTransition(el_2, elOptionCleaned, graphicModel, {
  68506. isInit: true
  68507. });
  68508. updateCommonAttrs(el_2, elOption, globalZ, globalZLevel);
  68509. }
  68510. } else if ($action === 'remove') {
  68511. updateLeaveTo(elExisting, elOption);
  68512. removeEl(elExisting, elOption, elMap, graphicModel);
  68513. }
  68514. var el = elMap.get(id);
  68515. if (el && textContentOption) {
  68516. if (isMerge) {
  68517. var textContentExisting = el.getTextContent();
  68518. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  68519. } else if (isReplace) {
  68520. el.setTextContent(new ZRText(textContentOption));
  68521. }
  68522. }
  68523. if (el) {
  68524. var clipPathOption = elOption.clipPath;
  68525. if (clipPathOption) {
  68526. var clipPathType = clipPathOption.type;
  68527. var clipPath = void 0;
  68528. var isInit = false;
  68529. if (isMerge) {
  68530. var oldClipPath = el.getClipPath();
  68531. isInit = !oldClipPath || inner$e(oldClipPath).type !== clipPathType;
  68532. clipPath = isInit ? newEl(clipPathType) : oldClipPath;
  68533. } else if (isReplace) {
  68534. isInit = true;
  68535. clipPath = newEl(clipPathType);
  68536. }
  68537. el.setClipPath(clipPath);
  68538. applyUpdateTransition(clipPath, clipPathOption, graphicModel, {
  68539. isInit: isInit
  68540. });
  68541. applyKeyframeAnimation(clipPath, clipPathOption.keyframeAnimation, graphicModel);
  68542. }
  68543. var elInner = inner$e(el);
  68544. el.setTextConfig(textConfig);
  68545. elInner.option = elOption;
  68546. setEventData(el, graphicModel, elOption);
  68547. setTooltipConfig({
  68548. el: el,
  68549. componentModel: graphicModel,
  68550. itemName: el.name,
  68551. itemTooltipOption: elOption.tooltip
  68552. });
  68553. applyKeyframeAnimation(el, elOption.keyframeAnimation, graphicModel);
  68554. }
  68555. });
  68556. };
  68557. /**
  68558. * Locate graphic elements.
  68559. */
  68560. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  68561. var elOptions = graphicModel.option.elements;
  68562. var rootGroup = this.group;
  68563. var elMap = this._elMap;
  68564. var apiWidth = api.getWidth();
  68565. var apiHeight = api.getHeight();
  68566. var xy = ['x', 'y']; // Top-down to calculate percentage width/height of group
  68567. for (var i = 0; i < elOptions.length; i++) {
  68568. var elOption = elOptions[i];
  68569. var id = convertOptionIdName(elOption.id, null);
  68570. var el = id != null ? elMap.get(id) : null;
  68571. if (!el || !el.isGroup) {
  68572. continue;
  68573. }
  68574. var parentEl = el.parent;
  68575. var isParentRoot = parentEl === rootGroup; // Like 'position:absolut' in css, default 0.
  68576. var elInner = inner$e(el);
  68577. var parentElInner = inner$e(parentEl);
  68578. elInner.width = parsePercent$1(elInner.option.width, isParentRoot ? apiWidth : parentElInner.width) || 0;
  68579. elInner.height = parsePercent$1(elInner.option.height, isParentRoot ? apiHeight : parentElInner.height) || 0;
  68580. } // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  68581. for (var i = elOptions.length - 1; i >= 0; i--) {
  68582. var elOption = elOptions[i];
  68583. var id = convertOptionIdName(elOption.id, null);
  68584. var el = id != null ? elMap.get(id) : null;
  68585. if (!el) {
  68586. continue;
  68587. }
  68588. var parentEl = el.parent;
  68589. var parentElInner = inner$e(parentEl);
  68590. var containerInfo = parentEl === rootGroup ? {
  68591. width: apiWidth,
  68592. height: apiHeight
  68593. } : {
  68594. width: parentElInner.width,
  68595. height: parentElInner.height
  68596. }; // PENDING
  68597. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  68598. // does not include the rect of [0, 0, group.width, group.height], which
  68599. // is probably weird for users. Should we make a break change for it?
  68600. var layoutPos = {};
  68601. var layouted = positionElement(el, elOption, containerInfo, null, {
  68602. hv: elOption.hv,
  68603. boundingMode: elOption.bounding
  68604. }, layoutPos);
  68605. if (!inner$e(el).isNew && layouted) {
  68606. var transition = elOption.transition;
  68607. var animatePos = {};
  68608. for (var k = 0; k < xy.length; k++) {
  68609. var key = xy[k];
  68610. var val = layoutPos[key];
  68611. if (transition && (isTransitionAll(transition) || indexOf(transition, key) >= 0)) {
  68612. animatePos[key] = val;
  68613. } else {
  68614. el[key] = val;
  68615. }
  68616. }
  68617. updateProps(el, animatePos, graphicModel, 0);
  68618. } else {
  68619. el.attr(layoutPos);
  68620. }
  68621. }
  68622. };
  68623. /**
  68624. * Clear all elements.
  68625. */
  68626. GraphicComponentView.prototype._clear = function () {
  68627. var _this = this;
  68628. var elMap = this._elMap;
  68629. elMap.each(function (el) {
  68630. removeEl(el, inner$e(el).option, elMap, _this._lastGraphicModel);
  68631. });
  68632. this._elMap = createHashMap();
  68633. };
  68634. GraphicComponentView.prototype.dispose = function () {
  68635. this._clear();
  68636. };
  68637. GraphicComponentView.type = 'graphic';
  68638. return GraphicComponentView;
  68639. }(ComponentView);
  68640. function newEl(graphicType) {
  68641. if ("development" !== 'production') {
  68642. assert(graphicType, 'graphic type MUST be set');
  68643. }
  68644. var Clz = hasOwn(nonShapeGraphicElements, graphicType) // Those graphic elements are not shapes. They should not be
  68645. // overwritten by users, so do them first.
  68646. ? nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  68647. if ("development" !== 'production') {
  68648. assert(Clz, "graphic type " + graphicType + " can not be found");
  68649. }
  68650. var el = new Clz({});
  68651. inner$e(el).type = graphicType;
  68652. return el;
  68653. }
  68654. function createEl$1(id, targetElParent, graphicType, elMap) {
  68655. var el = newEl(graphicType);
  68656. targetElParent.add(el);
  68657. elMap.set(id, el);
  68658. inner$e(el).id = id;
  68659. inner$e(el).isNew = true;
  68660. return el;
  68661. }
  68662. function removeEl(elExisting, elOption, elMap, graphicModel) {
  68663. var existElParent = elExisting && elExisting.parent;
  68664. if (existElParent) {
  68665. elExisting.type === 'group' && elExisting.traverse(function (el) {
  68666. removeEl(el, elOption, elMap, graphicModel);
  68667. });
  68668. applyLeaveTransition(elExisting, elOption, graphicModel);
  68669. elMap.removeKey(inner$e(elExisting).id);
  68670. }
  68671. }
  68672. function updateCommonAttrs(el, elOption, defaultZ, defaultZlevel) {
  68673. if (!el.isGroup) {
  68674. each([['cursor', Displayable.prototype.cursor], // We should not support configure z and zlevel in the element level.
  68675. // But seems we didn't limit it previously. So here still use it to avoid breaking.
  68676. ['zlevel', defaultZlevel || 0], ['z', defaultZ || 0], // z2 must not be null/undefined, otherwise sort error may occur.
  68677. ['z2', 0]], function (item) {
  68678. var prop = item[0];
  68679. if (hasOwn(elOption, prop)) {
  68680. el[prop] = retrieve2(elOption[prop], item[1]);
  68681. } else if (el[prop] == null) {
  68682. el[prop] = item[1];
  68683. }
  68684. });
  68685. }
  68686. each(keys(elOption), function (key) {
  68687. // Assign event handlers.
  68688. // PENDING: should enumerate all event names or use pattern matching?
  68689. if (key.indexOf('on') === 0) {
  68690. var val = elOption[key];
  68691. el[key] = isFunction(val) ? val : null;
  68692. }
  68693. });
  68694. if (hasOwn(elOption, 'draggable')) {
  68695. el.draggable = elOption.draggable;
  68696. } // Other attributes
  68697. elOption.name != null && (el.name = elOption.name);
  68698. elOption.id != null && (el.id = elOption.id);
  68699. } // Remove unnecessary props to avoid potential problems.
  68700. function getCleanedElOption(elOption) {
  68701. elOption = extend({}, elOption);
  68702. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent', 'clipPath'].concat(LOCATION_PARAMS), function (name) {
  68703. delete elOption[name];
  68704. });
  68705. return elOption;
  68706. }
  68707. function setEventData(el, graphicModel, elOption) {
  68708. var eventData = getECData(el).eventData; // Simple optimize for large amount of elements that no need event.
  68709. if (!el.silent && !el.ignore && !eventData) {
  68710. eventData = getECData(el).eventData = {
  68711. componentType: 'graphic',
  68712. componentIndex: graphicModel.componentIndex,
  68713. name: el.name
  68714. };
  68715. } // `elOption.info` enables user to mount some info on
  68716. // elements and use them in event handlers.
  68717. if (eventData) {
  68718. eventData.info = elOption.info;
  68719. }
  68720. }
  68721. function install$x(registers) {
  68722. registers.registerComponentModel(GraphicComponentModel);
  68723. registers.registerComponentView(GraphicComponentView);
  68724. registers.registerPreprocessor(function (option) {
  68725. var graphicOption = option.graphic; // Convert
  68726. // {graphic: [{left: 10, type: 'circle'}, ...]}
  68727. // or
  68728. // {graphic: {left: 10, type: 'circle'}}
  68729. // to
  68730. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  68731. if (isArray(graphicOption)) {
  68732. if (!graphicOption[0] || !graphicOption[0].elements) {
  68733. option.graphic = [{
  68734. elements: graphicOption
  68735. }];
  68736. } else {
  68737. // Only one graphic instance can be instantiated. (We don't
  68738. // want that too many views are created in echarts._viewMap.)
  68739. option.graphic = [option.graphic[0]];
  68740. }
  68741. } else if (graphicOption && !graphicOption.elements) {
  68742. option.graphic = [{
  68743. elements: [graphicOption]
  68744. }];
  68745. }
  68746. });
  68747. }
  68748. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single']; // Supported coords.
  68749. // FIXME: polar has been broken (but rarely used).
  68750. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  68751. function isCoordSupported(seriesModel) {
  68752. var coordType = seriesModel.get('coordinateSystem');
  68753. return indexOf(SERIES_COORDS, coordType) >= 0;
  68754. }
  68755. function getAxisMainType(axisDim) {
  68756. if ("development" !== 'production') {
  68757. assert(axisDim);
  68758. }
  68759. return axisDim + 'Axis';
  68760. }
  68761. /**
  68762. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  68763. * This function finds all linked dataZoomModels start from the given payload.
  68764. */
  68765. function findEffectedDataZooms(ecModel, payload) {
  68766. // Key: `DataZoomAxisDimension`
  68767. var axisRecords = createHashMap();
  68768. var effectedModels = []; // Key: uid of dataZoomModel
  68769. var effectedModelMap = createHashMap(); // Find the dataZooms specified by payload.
  68770. ecModel.eachComponent({
  68771. mainType: 'dataZoom',
  68772. query: payload
  68773. }, function (dataZoomModel) {
  68774. if (!effectedModelMap.get(dataZoomModel.uid)) {
  68775. addToEffected(dataZoomModel);
  68776. }
  68777. }); // Start from the given dataZoomModels, travel the graph to find
  68778. // all of the linked dataZoom models.
  68779. var foundNewLink;
  68780. do {
  68781. foundNewLink = false;
  68782. ecModel.eachComponent('dataZoom', processSingle);
  68783. } while (foundNewLink);
  68784. function processSingle(dataZoomModel) {
  68785. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  68786. addToEffected(dataZoomModel);
  68787. foundNewLink = true;
  68788. }
  68789. }
  68790. function addToEffected(dataZoom) {
  68791. effectedModelMap.set(dataZoom.uid, true);
  68792. effectedModels.push(dataZoom);
  68793. markAxisControlled(dataZoom);
  68794. }
  68795. function isLinked(dataZoomModel) {
  68796. var isLink = false;
  68797. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68798. var axisIdxArr = axisRecords.get(axisDim);
  68799. if (axisIdxArr && axisIdxArr[axisIndex]) {
  68800. isLink = true;
  68801. }
  68802. });
  68803. return isLink;
  68804. }
  68805. function markAxisControlled(dataZoomModel) {
  68806. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68807. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  68808. });
  68809. }
  68810. return effectedModels;
  68811. }
  68812. /**
  68813. * Find the first target coordinate system.
  68814. * Available after model built.
  68815. *
  68816. * @return Like {
  68817. * grid: [
  68818. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  68819. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  68820. * ...
  68821. * ], // cartesians must not be null/undefined.
  68822. * polar: [
  68823. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  68824. * ...
  68825. * ], // polars must not be null/undefined.
  68826. * singleAxis: [
  68827. * {model: coord0, axisModels: [], coordIndex: 0}
  68828. * ]
  68829. * }
  68830. */
  68831. function collectReferCoordSysModelInfo(dataZoomModel) {
  68832. var ecModel = dataZoomModel.ecModel;
  68833. var coordSysInfoWrap = {
  68834. infoList: [],
  68835. infoMap: createHashMap()
  68836. };
  68837. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68838. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  68839. if (!axisModel) {
  68840. return;
  68841. }
  68842. var coordSysModel = axisModel.getCoordSysModel();
  68843. if (!coordSysModel) {
  68844. return;
  68845. }
  68846. var coordSysUid = coordSysModel.uid;
  68847. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  68848. if (!coordSysInfo) {
  68849. coordSysInfo = {
  68850. model: coordSysModel,
  68851. axisModels: []
  68852. };
  68853. coordSysInfoWrap.infoList.push(coordSysInfo);
  68854. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  68855. }
  68856. coordSysInfo.axisModels.push(axisModel);
  68857. });
  68858. return coordSysInfoWrap;
  68859. }
  68860. var DataZoomAxisInfo =
  68861. /** @class */
  68862. function () {
  68863. function DataZoomAxisInfo() {
  68864. this.indexList = [];
  68865. this.indexMap = [];
  68866. }
  68867. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  68868. // Remove duplication.
  68869. if (!this.indexMap[axisCmptIdx]) {
  68870. this.indexList.push(axisCmptIdx);
  68871. this.indexMap[axisCmptIdx] = true;
  68872. }
  68873. };
  68874. return DataZoomAxisInfo;
  68875. }();
  68876. var DataZoomModel =
  68877. /** @class */
  68878. function (_super) {
  68879. __extends(DataZoomModel, _super);
  68880. function DataZoomModel() {
  68881. var _this = _super !== null && _super.apply(this, arguments) || this;
  68882. _this.type = DataZoomModel.type;
  68883. _this._autoThrottle = true;
  68884. _this._noTarget = true;
  68885. /**
  68886. * It is `[rangeModeForMin, rangeModeForMax]`.
  68887. * The optional values for `rangeMode`:
  68888. * + `'value'` mode: the axis extent will always be determined by
  68889. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  68890. * how data like and how `axis.min` and `axis.max` are.
  68891. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  68892. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  68893. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  68894. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  68895. *
  68896. * For example, when users are using dynamic data (update data periodically via `setOption`),
  68897. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  68898. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  68899. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  68900. */
  68901. _this._rangePropMode = ['percent', 'percent'];
  68902. return _this;
  68903. }
  68904. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  68905. var inputRawOption = retrieveRawOption(option);
  68906. /**
  68907. * Suppose a "main process" start at the point that model prepared (that is,
  68908. * model initialized or merged or method called in `action`).
  68909. * We should keep the `main process` idempotent, that is, given a set of values
  68910. * on `option`, we get the same result.
  68911. *
  68912. * But sometimes, values on `option` will be updated for providing users
  68913. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  68914. * should not be the base/input of the `main process`.
  68915. *
  68916. * So in that case we should save and keep the input of the `main process`
  68917. * separately, called `settledOption`.
  68918. *
  68919. * For example, consider the case:
  68920. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  68921. * where the original input `option.startValue`, `option.endValue` are earsed by
  68922. * calculated value.
  68923. * (Step)2) click the legend to hide and show a series,
  68924. * where the new range is calculated by the earsed `startValue` and `endValue`,
  68925. * which brings incorrect result.
  68926. */
  68927. this.settledOption = inputRawOption;
  68928. this.mergeDefaultAndTheme(option, ecModel);
  68929. this._doInit(inputRawOption);
  68930. };
  68931. DataZoomModel.prototype.mergeOption = function (newOption) {
  68932. var inputRawOption = retrieveRawOption(newOption); // FIX #2591
  68933. merge(this.option, newOption, true);
  68934. merge(this.settledOption, inputRawOption, true);
  68935. this._doInit(inputRawOption);
  68936. };
  68937. DataZoomModel.prototype._doInit = function (inputRawOption) {
  68938. var thisOption = this.option;
  68939. this._setDefaultThrottle(inputRawOption);
  68940. this._updateRangeUse(inputRawOption);
  68941. var settledOption = this.settledOption;
  68942. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  68943. // start/end has higher priority over startValue/endValue if they
  68944. // both set, but we should make chart.setOption({endValue: 1000})
  68945. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  68946. if (this._rangePropMode[index] === 'value') {
  68947. thisOption[names[0]] = settledOption[names[0]] = null;
  68948. } // Otherwise do nothing and use the merge result.
  68949. }, this);
  68950. this._resetTarget();
  68951. };
  68952. DataZoomModel.prototype._resetTarget = function () {
  68953. var optionOrient = this.get('orient', true);
  68954. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  68955. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  68956. if (hasAxisSpecified) {
  68957. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  68958. } else {
  68959. this._orient = optionOrient || 'horizontal';
  68960. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  68961. }
  68962. this._noTarget = true;
  68963. targetAxisIndexMap.each(function (axisInfo) {
  68964. if (axisInfo.indexList.length) {
  68965. this._noTarget = false;
  68966. }
  68967. }, this);
  68968. };
  68969. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  68970. var hasAxisSpecified = false;
  68971. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  68972. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING); // When user set axisIndex as a empty array, we think that user specify axisIndex
  68973. // but do not want use auto mode. Because empty array may be encountered when
  68974. // some error occurred.
  68975. if (!refering.specified) {
  68976. return;
  68977. }
  68978. hasAxisSpecified = true;
  68979. var axisInfo = new DataZoomAxisInfo();
  68980. each(refering.models, function (axisModel) {
  68981. axisInfo.add(axisModel.componentIndex);
  68982. });
  68983. targetAxisIndexMap.set(axisDim, axisInfo);
  68984. }, this);
  68985. return hasAxisSpecified;
  68986. };
  68987. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  68988. var ecModel = this.ecModel;
  68989. var needAuto = true; // Find axis that parallel to dataZoom as default.
  68990. if (needAuto) {
  68991. var axisDim = orient === 'vertical' ? 'y' : 'x';
  68992. var axisModels = ecModel.findComponents({
  68993. mainType: axisDim + 'Axis'
  68994. });
  68995. setParallelAxis(axisModels, axisDim);
  68996. } // Find axis that parallel to dataZoom as default.
  68997. if (needAuto) {
  68998. var axisModels = ecModel.findComponents({
  68999. mainType: 'singleAxis',
  69000. filter: function (axisModel) {
  69001. return axisModel.get('orient', true) === orient;
  69002. }
  69003. });
  69004. setParallelAxis(axisModels, 'single');
  69005. }
  69006. function setParallelAxis(axisModels, axisDim) {
  69007. // At least use the first parallel axis as the target axis.
  69008. var axisModel = axisModels[0];
  69009. if (!axisModel) {
  69010. return;
  69011. }
  69012. var axisInfo = new DataZoomAxisInfo();
  69013. axisInfo.add(axisModel.componentIndex);
  69014. targetAxisIndexMap.set(axisDim, axisInfo);
  69015. needAuto = false; // Find parallel axes in the same grid.
  69016. if (axisDim === 'x' || axisDim === 'y') {
  69017. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  69018. gridModel_1 && each(axisModels, function (axModel) {
  69019. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  69020. axisInfo.add(axModel.componentIndex);
  69021. }
  69022. });
  69023. }
  69024. }
  69025. if (needAuto) {
  69026. // If no parallel axis, find the first category axis as default. (Also consider polar).
  69027. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  69028. if (!needAuto) {
  69029. return;
  69030. }
  69031. var axisModels = ecModel.findComponents({
  69032. mainType: getAxisMainType(axisDim),
  69033. filter: function (axisModel) {
  69034. return axisModel.get('type', true) === 'category';
  69035. }
  69036. });
  69037. if (axisModels[0]) {
  69038. var axisInfo = new DataZoomAxisInfo();
  69039. axisInfo.add(axisModels[0].componentIndex);
  69040. targetAxisIndexMap.set(axisDim, axisInfo);
  69041. needAuto = false;
  69042. }
  69043. }, this);
  69044. }
  69045. };
  69046. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  69047. var dim; // Find the first axis
  69048. this.eachTargetAxis(function (axisDim) {
  69049. !dim && (dim = axisDim);
  69050. }, this);
  69051. return dim === 'y' ? 'vertical' : 'horizontal';
  69052. };
  69053. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  69054. // When first time user set throttle, auto throttle ends.
  69055. if (inputRawOption.hasOwnProperty('throttle')) {
  69056. this._autoThrottle = false;
  69057. }
  69058. if (this._autoThrottle) {
  69059. var globalOption = this.ecModel.option;
  69060. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  69061. }
  69062. };
  69063. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  69064. var rangePropMode = this._rangePropMode;
  69065. var rangeModeInOption = this.get('rangeMode');
  69066. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69067. var percentSpecified = inputRawOption[names[0]] != null;
  69068. var valueSpecified = inputRawOption[names[1]] != null;
  69069. if (percentSpecified && !valueSpecified) {
  69070. rangePropMode[index] = 'percent';
  69071. } else if (!percentSpecified && valueSpecified) {
  69072. rangePropMode[index] = 'value';
  69073. } else if (rangeModeInOption) {
  69074. rangePropMode[index] = rangeModeInOption[index];
  69075. } else if (percentSpecified) {
  69076. // percentSpecified && valueSpecified
  69077. rangePropMode[index] = 'percent';
  69078. } // else remain its original setting.
  69079. });
  69080. };
  69081. DataZoomModel.prototype.noTarget = function () {
  69082. return this._noTarget;
  69083. };
  69084. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  69085. var firstAxisModel;
  69086. this.eachTargetAxis(function (axisDim, axisIndex) {
  69087. if (firstAxisModel == null) {
  69088. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  69089. }
  69090. }, this);
  69091. return firstAxisModel;
  69092. };
  69093. /**
  69094. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  69095. */
  69096. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  69097. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  69098. each(axisInfo.indexList, function (axisIndex) {
  69099. callback.call(context, axisDim, axisIndex);
  69100. });
  69101. });
  69102. };
  69103. /**
  69104. * @return If not found, return null/undefined.
  69105. */
  69106. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  69107. var axisModel = this.getAxisModel(axisDim, axisIndex);
  69108. if (axisModel) {
  69109. return axisModel.__dzAxisProxy;
  69110. }
  69111. };
  69112. /**
  69113. * @return If not found, return null/undefined.
  69114. */
  69115. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  69116. if ("development" !== 'production') {
  69117. assert(axisDim && axisIndex != null);
  69118. }
  69119. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  69120. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  69121. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  69122. }
  69123. };
  69124. /**
  69125. * If not specified, set to undefined.
  69126. */
  69127. DataZoomModel.prototype.setRawRange = function (opt) {
  69128. var thisOption = this.option;
  69129. var settledOption = this.settledOption;
  69130. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  69131. // Consider the pair <start, startValue>:
  69132. // If one has value and the other one is `null/undefined`, we both set them
  69133. // to `settledOption`. This strategy enables the feature to clear the original
  69134. // value in `settledOption` to `null/undefined`.
  69135. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  69136. // and keep `settledOption` with the original value. This strategy enables users to
  69137. // only set <end or endValue> but not set <start or startValue> when calling
  69138. // `dispatchAction`.
  69139. // The pair <end, endValue> is treated in the same way.
  69140. if (opt[names[0]] != null || opt[names[1]] != null) {
  69141. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  69142. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  69143. }
  69144. }, this);
  69145. this._updateRangeUse(opt);
  69146. };
  69147. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  69148. var option = this.option;
  69149. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  69150. option[name] = opt[name];
  69151. });
  69152. };
  69153. DataZoomModel.prototype.getPercentRange = function () {
  69154. var axisProxy = this.findRepresentativeAxisProxy();
  69155. if (axisProxy) {
  69156. return axisProxy.getDataPercentWindow();
  69157. }
  69158. };
  69159. /**
  69160. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  69161. *
  69162. * @return [startValue, endValue] value can only be '-' or finite number.
  69163. */
  69164. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  69165. if (axisDim == null && axisIndex == null) {
  69166. var axisProxy = this.findRepresentativeAxisProxy();
  69167. if (axisProxy) {
  69168. return axisProxy.getDataValueWindow();
  69169. }
  69170. } else {
  69171. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  69172. }
  69173. };
  69174. /**
  69175. * @param axisModel If axisModel given, find axisProxy
  69176. * corresponding to the axisModel
  69177. */
  69178. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  69179. if (axisModel) {
  69180. return axisModel.__dzAxisProxy;
  69181. } // Find the first hosted axisProxy
  69182. var firstProxy;
  69183. var axisDimList = this._targetAxisInfoMap.keys();
  69184. for (var i = 0; i < axisDimList.length; i++) {
  69185. var axisDim = axisDimList[i];
  69186. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  69187. for (var j = 0; j < axisInfo.indexList.length; j++) {
  69188. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  69189. if (proxy.hostedBy(this)) {
  69190. return proxy;
  69191. }
  69192. if (!firstProxy) {
  69193. firstProxy = proxy;
  69194. }
  69195. }
  69196. } // If no hosted proxy found, still need to return a proxy.
  69197. // This case always happens in toolbox dataZoom, where axes are all hosted by
  69198. // other dataZooms.
  69199. return firstProxy;
  69200. };
  69201. DataZoomModel.prototype.getRangePropMode = function () {
  69202. return this._rangePropMode.slice();
  69203. };
  69204. DataZoomModel.prototype.getOrient = function () {
  69205. if ("development" !== 'production') {
  69206. // Should not be called before initialized.
  69207. assert(this._orient);
  69208. }
  69209. return this._orient;
  69210. };
  69211. DataZoomModel.type = 'dataZoom';
  69212. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  69213. DataZoomModel.defaultOption = {
  69214. // zlevel: 0,
  69215. z: 4,
  69216. filterMode: 'filter',
  69217. start: 0,
  69218. end: 100
  69219. };
  69220. return DataZoomModel;
  69221. }(ComponentModel);
  69222. /**
  69223. * Retrieve those raw params from option, which will be cached separately,
  69224. * because they will be overwritten by normalized/calculated values in the main
  69225. * process.
  69226. */
  69227. function retrieveRawOption(option) {
  69228. var ret = {};
  69229. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  69230. option.hasOwnProperty(name) && (ret[name] = option[name]);
  69231. });
  69232. return ret;
  69233. }
  69234. var SelectDataZoomModel =
  69235. /** @class */
  69236. function (_super) {
  69237. __extends(SelectDataZoomModel, _super);
  69238. function SelectDataZoomModel() {
  69239. var _this = _super !== null && _super.apply(this, arguments) || this;
  69240. _this.type = SelectDataZoomModel.type;
  69241. return _this;
  69242. }
  69243. SelectDataZoomModel.type = 'dataZoom.select';
  69244. return SelectDataZoomModel;
  69245. }(DataZoomModel);
  69246. var DataZoomView =
  69247. /** @class */
  69248. function (_super) {
  69249. __extends(DataZoomView, _super);
  69250. function DataZoomView() {
  69251. var _this = _super !== null && _super.apply(this, arguments) || this;
  69252. _this.type = DataZoomView.type;
  69253. return _this;
  69254. }
  69255. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  69256. this.dataZoomModel = dataZoomModel;
  69257. this.ecModel = ecModel;
  69258. this.api = api;
  69259. };
  69260. DataZoomView.type = 'dataZoom';
  69261. return DataZoomView;
  69262. }(ComponentView);
  69263. var SelectDataZoomView =
  69264. /** @class */
  69265. function (_super) {
  69266. __extends(SelectDataZoomView, _super);
  69267. function SelectDataZoomView() {
  69268. var _this = _super !== null && _super.apply(this, arguments) || this;
  69269. _this.type = SelectDataZoomView.type;
  69270. return _this;
  69271. }
  69272. SelectDataZoomView.type = 'dataZoom.select';
  69273. return SelectDataZoomView;
  69274. }(DataZoomView);
  69275. var each$8 = each;
  69276. var asc$1 = asc;
  69277. /**
  69278. * Operate single axis.
  69279. * One axis can only operated by one axis operator.
  69280. * Different dataZoomModels may be defined to operate the same axis.
  69281. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  69282. * So dataZoomModels share one axisProxy in that case.
  69283. */
  69284. var AxisProxy =
  69285. /** @class */
  69286. function () {
  69287. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  69288. this._dimName = dimName;
  69289. this._axisIndex = axisIndex;
  69290. this.ecModel = ecModel;
  69291. this._dataZoomModel = dataZoomModel; // /**
  69292. // * @readOnly
  69293. // * @private
  69294. // */
  69295. // this.hasSeriesStacked;
  69296. }
  69297. /**
  69298. * Whether the axisProxy is hosted by dataZoomModel.
  69299. */
  69300. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  69301. return this._dataZoomModel === dataZoomModel;
  69302. };
  69303. /**
  69304. * @return Value can only be NaN or finite value.
  69305. */
  69306. AxisProxy.prototype.getDataValueWindow = function () {
  69307. return this._valueWindow.slice();
  69308. };
  69309. /**
  69310. * @return {Array.<number>}
  69311. */
  69312. AxisProxy.prototype.getDataPercentWindow = function () {
  69313. return this._percentWindow.slice();
  69314. };
  69315. AxisProxy.prototype.getTargetSeriesModels = function () {
  69316. var seriesModels = [];
  69317. this.ecModel.eachSeries(function (seriesModel) {
  69318. if (isCoordSupported(seriesModel)) {
  69319. var axisMainType = getAxisMainType(this._dimName);
  69320. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  69321. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  69322. seriesModels.push(seriesModel);
  69323. }
  69324. }
  69325. }, this);
  69326. return seriesModels;
  69327. };
  69328. AxisProxy.prototype.getAxisModel = function () {
  69329. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  69330. };
  69331. AxisProxy.prototype.getMinMaxSpan = function () {
  69332. return clone(this._minMaxSpan);
  69333. };
  69334. /**
  69335. * Only calculate by given range and this._dataExtent, do not change anything.
  69336. */
  69337. AxisProxy.prototype.calculateDataWindow = function (opt) {
  69338. var dataExtent = this._dataExtent;
  69339. var axisModel = this.getAxisModel();
  69340. var scale = axisModel.axis.scale;
  69341. var rangePropMode = this._dataZoomModel.getRangePropMode();
  69342. var percentExtent = [0, 100];
  69343. var percentWindow = [];
  69344. var valueWindow = [];
  69345. var hasPropModeValue;
  69346. each$8(['start', 'end'], function (prop, idx) {
  69347. var boundPercent = opt[prop];
  69348. var boundValue = opt[prop + 'Value']; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  69349. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  69350. // but not min/max of axis, which will be calculated by data window then).
  69351. // The former one is suitable for cases that a dataZoom component controls multiple
  69352. // axes with different unit or extent, and the latter one is suitable for accurate
  69353. // zoom by pixel (e.g., in dataZoomSelect).
  69354. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  69355. // only when setOption or dispatchAction, otherwise it remains its original value.
  69356. // (Why not only record `percentProp` and always map to `valueProp`? Because
  69357. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  69358. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  69359. // data extent. All of values that are overflow the `dataExtent` will be calculated
  69360. // to percent '100%').
  69361. if (rangePropMode[idx] === 'percent') {
  69362. boundPercent == null && (boundPercent = percentExtent[idx]); // Use scale.parse to math round for category or time axis.
  69363. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  69364. } else {
  69365. hasPropModeValue = true;
  69366. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue); // Calculating `percent` from `value` may be not accurate, because
  69367. // This calculation can not be inversed, because all of values that
  69368. // are overflow the `dataExtent` will be calculated to percent '100%'
  69369. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  69370. } // valueWindow[idx] = round(boundValue);
  69371. // percentWindow[idx] = round(boundPercent);
  69372. // fallback to extent start/end when parsed value or percent is invalid
  69373. valueWindow[idx] = boundValue == null || isNaN(boundValue) ? dataExtent[idx] : boundValue;
  69374. percentWindow[idx] = boundPercent == null || isNaN(boundPercent) ? percentExtent[idx] : boundPercent;
  69375. });
  69376. asc$1(valueWindow);
  69377. asc$1(percentWindow); // The windows from user calling of `dispatchAction` might be out of the extent,
  69378. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we don't restrict window
  69379. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  69380. // where API is able to initialize/modify the window size even though `zoomLock`
  69381. // specified.
  69382. var spans = this._minMaxSpan;
  69383. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  69384. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  69385. var suffix = toValue ? 'Span' : 'ValueSpan';
  69386. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  69387. for (var i = 0; i < 2; i++) {
  69388. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  69389. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  69390. }
  69391. }
  69392. return {
  69393. valueWindow: valueWindow,
  69394. percentWindow: percentWindow
  69395. };
  69396. };
  69397. /**
  69398. * Notice: reset should not be called before series.restoreData() is called,
  69399. * so it is recommended to be called in "process stage" but not "model init
  69400. * stage".
  69401. */
  69402. AxisProxy.prototype.reset = function (dataZoomModel) {
  69403. if (dataZoomModel !== this._dataZoomModel) {
  69404. return;
  69405. }
  69406. var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them.
  69407. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // `calculateDataWindow` uses min/maxSpan.
  69408. this._updateMinMaxSpan();
  69409. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  69410. this._valueWindow = dataWindow.valueWindow;
  69411. this._percentWindow = dataWindow.percentWindow; // Update axis setting then.
  69412. this._setAxisModel();
  69413. };
  69414. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  69415. if (dataZoomModel !== this._dataZoomModel) {
  69416. return;
  69417. }
  69418. var axisDim = this._dimName;
  69419. var seriesModels = this.getTargetSeriesModels();
  69420. var filterMode = dataZoomModel.get('filterMode');
  69421. var valueWindow = this._valueWindow;
  69422. if (filterMode === 'none') {
  69423. return;
  69424. } // FIXME
  69425. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  69426. // with NaN data, NaN will be filtered and stack will be wrong.
  69427. // So we need to force the mode to be set empty.
  69428. // In fect, it is not a big deal that do not support filterMode-'filter'
  69429. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  69430. // selection" some day, which might need "adapt to data extent on the
  69431. // otherAxis", which is disabled by filterMode-'empty'.
  69432. // But currently, stack has been fixed to based on value but not index,
  69433. // so this is not an issue any more.
  69434. // let otherAxisModel = this.getOtherAxisModel();
  69435. // if (dataZoomModel.get('$fromToolbox')
  69436. // && otherAxisModel
  69437. // && otherAxisModel.hasSeriesStacked
  69438. // ) {
  69439. // filterMode = 'empty';
  69440. // }
  69441. // TODO
  69442. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  69443. each$8(seriesModels, function (seriesModel) {
  69444. var seriesData = seriesModel.getData();
  69445. var dataDims = seriesData.mapDimensionsAll(axisDim);
  69446. if (!dataDims.length) {
  69447. return;
  69448. }
  69449. if (filterMode === 'weakFilter') {
  69450. var store_1 = seriesData.getStore();
  69451. var dataDimIndices_1 = map(dataDims, function (dim) {
  69452. return seriesData.getDimensionIndex(dim);
  69453. }, seriesData);
  69454. seriesData.filterSelf(function (dataIndex) {
  69455. var leftOut;
  69456. var rightOut;
  69457. var hasValue;
  69458. for (var i = 0; i < dataDims.length; i++) {
  69459. var value = store_1.get(dataDimIndices_1[i], dataIndex);
  69460. var thisHasValue = !isNaN(value);
  69461. var thisLeftOut = value < valueWindow[0];
  69462. var thisRightOut = value > valueWindow[1];
  69463. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  69464. return true;
  69465. }
  69466. thisHasValue && (hasValue = true);
  69467. thisLeftOut && (leftOut = true);
  69468. thisRightOut && (rightOut = true);
  69469. } // If both left out and right out, do not filter.
  69470. return hasValue && leftOut && rightOut;
  69471. });
  69472. } else {
  69473. each$8(dataDims, function (dim) {
  69474. if (filterMode === 'empty') {
  69475. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  69476. return !isInWindow(value) ? NaN : value;
  69477. }));
  69478. } else {
  69479. var range = {};
  69480. range[dim] = valueWindow; // console.time('select');
  69481. seriesData.selectRange(range); // console.timeEnd('select');
  69482. }
  69483. });
  69484. }
  69485. each$8(dataDims, function (dim) {
  69486. seriesData.setApproximateExtent(valueWindow, dim);
  69487. });
  69488. });
  69489. function isInWindow(value) {
  69490. return value >= valueWindow[0] && value <= valueWindow[1];
  69491. }
  69492. };
  69493. AxisProxy.prototype._updateMinMaxSpan = function () {
  69494. var minMaxSpan = this._minMaxSpan = {};
  69495. var dataZoomModel = this._dataZoomModel;
  69496. var dataExtent = this._dataExtent;
  69497. each$8(['min', 'max'], function (minMax) {
  69498. var percentSpan = dataZoomModel.get(minMax + 'Span');
  69499. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  69500. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan)); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  69501. if (valueSpan != null) {
  69502. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  69503. } else if (percentSpan != null) {
  69504. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  69505. }
  69506. minMaxSpan[minMax + 'Span'] = percentSpan;
  69507. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  69508. }, this);
  69509. };
  69510. AxisProxy.prototype._setAxisModel = function () {
  69511. var axisModel = this.getAxisModel();
  69512. var percentWindow = this._percentWindow;
  69513. var valueWindow = this._valueWindow;
  69514. if (!percentWindow) {
  69515. return;
  69516. } // [0, 500]: arbitrary value, guess axis extent.
  69517. var precision = getPixelPrecision(valueWindow, [0, 500]);
  69518. precision = Math.min(precision, 20); // For value axis, if min/max/scale are not set, we just use the extent obtained
  69519. // by series data, which may be a little different from the extent calculated by
  69520. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  69521. // little when zooming. So it will not be fixed until some users require it strongly.
  69522. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  69523. if (percentWindow[0] !== 0) {
  69524. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  69525. }
  69526. if (percentWindow[1] !== 100) {
  69527. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  69528. }
  69529. rawExtentInfo.freeze();
  69530. };
  69531. return AxisProxy;
  69532. }();
  69533. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  69534. var dataExtent = [Infinity, -Infinity];
  69535. each$8(seriesModels, function (seriesModel) {
  69536. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  69537. }); // It is important to get "consistent" extent when more then one axes is
  69538. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  69539. // when zooming. But it is difficult to know what is "consistent", considering
  69540. // axes have different type or even different meanings (For example, two
  69541. // time axes are used to compare data of the same date in different years).
  69542. // So basically dataZoom just obtains extent by series.data (in category axis
  69543. // extent can be obtained from axis.data).
  69544. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  69545. // consistent.
  69546. var axisModel = axisProxy.getAxisModel();
  69547. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  69548. return [rawExtentResult.min, rawExtentResult.max];
  69549. }
  69550. var dataZoomProcessor = {
  69551. // `dataZoomProcessor` will only be performed in needed series. Consider if
  69552. // there is a line series and a pie series, it is better not to update the
  69553. // line series if only pie series is needed to be updated.
  69554. getTargetSeries: function (ecModel) {
  69555. function eachAxisModel(cb) {
  69556. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69557. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  69558. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  69559. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  69560. });
  69561. });
  69562. } // FIXME: it brings side-effect to `getTargetSeries`.
  69563. // Prepare axis proxies.
  69564. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  69565. // dispose all last axis proxy, in case that some axis are deleted.
  69566. axisModel.__dzAxisProxy = null;
  69567. });
  69568. var proxyList = [];
  69569. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  69570. // Different dataZooms may constrol the same axis. In that case,
  69571. // an axisProxy serves both of them.
  69572. if (!axisModel.__dzAxisProxy) {
  69573. // Use the first dataZoomModel as the main model of axisProxy.
  69574. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  69575. proxyList.push(axisModel.__dzAxisProxy);
  69576. }
  69577. });
  69578. var seriesModelMap = createHashMap();
  69579. each(proxyList, function (axisProxy) {
  69580. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  69581. seriesModelMap.set(seriesModel.uid, seriesModel);
  69582. });
  69583. });
  69584. return seriesModelMap;
  69585. },
  69586. // Consider appendData, where filter should be performed. Because data process is
  69587. // in block mode currently, it is not need to worry about that the overallProgress
  69588. // execute every frame.
  69589. overallReset: function (ecModel, api) {
  69590. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69591. // We calculate window and reset axis here but not in model
  69592. // init stage and not after action dispatch handler, because
  69593. // reset should be called after seriesData.restoreData.
  69594. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  69595. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  69596. }); // Caution: data zoom filtering is order sensitive when using
  69597. // percent range and no min/max/scale set on axis.
  69598. // For example, we have dataZoom definition:
  69599. // [
  69600. // {xAxisIndex: 0, start: 30, end: 70},
  69601. // {yAxisIndex: 0, start: 20, end: 80}
  69602. // ]
  69603. // In this case, [20, 80] of y-dataZoom should be based on data
  69604. // that have filtered by x-dataZoom using range of [30, 70],
  69605. // but should not be based on full raw data. Thus sliding
  69606. // x-dataZoom will change both ranges of xAxis and yAxis,
  69607. // while sliding y-dataZoom will only change the range of yAxis.
  69608. // So we should filter x-axis after reset x-axis immediately,
  69609. // and then reset y-axis and filter y-axis.
  69610. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  69611. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  69612. });
  69613. });
  69614. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69615. // Fullfill all of the range props so that user
  69616. // is able to get them from chart.getOption().
  69617. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  69618. if (axisProxy) {
  69619. var percentRange = axisProxy.getDataPercentWindow();
  69620. var valueRange = axisProxy.getDataValueWindow();
  69621. dataZoomModel.setCalculatedRange({
  69622. start: percentRange[0],
  69623. end: percentRange[1],
  69624. startValue: valueRange[0],
  69625. endValue: valueRange[1]
  69626. });
  69627. }
  69628. });
  69629. }
  69630. };
  69631. function installDataZoomAction(registers) {
  69632. registers.registerAction('dataZoom', function (payload, ecModel) {
  69633. var effectedModels = findEffectedDataZooms(ecModel, payload);
  69634. each(effectedModels, function (dataZoomModel) {
  69635. dataZoomModel.setRawRange({
  69636. start: payload.start,
  69637. end: payload.end,
  69638. startValue: payload.startValue,
  69639. endValue: payload.endValue
  69640. });
  69641. });
  69642. });
  69643. }
  69644. var installed = false;
  69645. function installCommon(registers) {
  69646. if (installed) {
  69647. return;
  69648. }
  69649. installed = true;
  69650. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  69651. installDataZoomAction(registers);
  69652. registers.registerSubTypeDefaulter('dataZoom', function () {
  69653. // Default 'slider' when no type specified.
  69654. return 'slider';
  69655. });
  69656. }
  69657. function install$y(registers) {
  69658. registers.registerComponentModel(SelectDataZoomModel);
  69659. registers.registerComponentView(SelectDataZoomView);
  69660. installCommon(registers);
  69661. }
  69662. /*
  69663. * Licensed to the Apache Software Foundation (ASF) under one
  69664. * or more contributor license agreements. See the NOTICE file
  69665. * distributed with this work for additional information
  69666. * regarding copyright ownership. The ASF licenses this file
  69667. * to you under the Apache License, Version 2.0 (the
  69668. * "License"); you may not use this file except in compliance
  69669. * with the License. You may obtain a copy of the License at
  69670. *
  69671. * http://www.apache.org/licenses/LICENSE-2.0
  69672. *
  69673. * Unless required by applicable law or agreed to in writing,
  69674. * software distributed under the License is distributed on an
  69675. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69676. * KIND, either express or implied. See the License for the
  69677. * specific language governing permissions and limitations
  69678. * under the License.
  69679. */
  69680. /**
  69681. * AUTO-GENERATED FILE. DO NOT MODIFY.
  69682. */
  69683. var ToolboxFeature =
  69684. /** @class */
  69685. function () {
  69686. function ToolboxFeature() {}
  69687. return ToolboxFeature;
  69688. }();
  69689. var features = {};
  69690. function registerFeature(name, ctor) {
  69691. features[name] = ctor;
  69692. }
  69693. function getFeature(name) {
  69694. return features[name];
  69695. }
  69696. var ToolboxModel =
  69697. /** @class */
  69698. function (_super) {
  69699. __extends(ToolboxModel, _super);
  69700. function ToolboxModel() {
  69701. var _this = _super !== null && _super.apply(this, arguments) || this;
  69702. _this.type = ToolboxModel.type;
  69703. return _this;
  69704. }
  69705. ToolboxModel.prototype.optionUpdated = function () {
  69706. _super.prototype.optionUpdated.apply(this, arguments);
  69707. var ecModel = this.ecModel;
  69708. each(this.option.feature, function (featureOpt, featureName) {
  69709. var Feature = getFeature(featureName);
  69710. if (Feature) {
  69711. if (Feature.getDefaultOption) {
  69712. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  69713. }
  69714. merge(featureOpt, Feature.defaultOption);
  69715. }
  69716. });
  69717. };
  69718. ToolboxModel.type = 'toolbox';
  69719. ToolboxModel.layoutMode = {
  69720. type: 'box',
  69721. ignoreSize: true
  69722. };
  69723. ToolboxModel.defaultOption = {
  69724. show: true,
  69725. z: 6,
  69726. // zlevel: 0,
  69727. orient: 'horizontal',
  69728. left: 'right',
  69729. top: 'top',
  69730. // right
  69731. // bottom
  69732. backgroundColor: 'transparent',
  69733. borderColor: '#ccc',
  69734. borderRadius: 0,
  69735. borderWidth: 0,
  69736. padding: 5,
  69737. itemSize: 15,
  69738. itemGap: 8,
  69739. showTitle: true,
  69740. iconStyle: {
  69741. borderColor: '#666',
  69742. color: 'none'
  69743. },
  69744. emphasis: {
  69745. iconStyle: {
  69746. borderColor: '#3E98C5'
  69747. }
  69748. },
  69749. // textStyle: {},
  69750. // feature
  69751. tooltip: {
  69752. show: false,
  69753. position: 'bottom'
  69754. }
  69755. };
  69756. return ToolboxModel;
  69757. }(ComponentModel);
  69758. /**
  69759. * Layout list like component.
  69760. * It will box layout each items in group of component and then position the whole group in the viewport
  69761. * @param {module:zrender/group/Group} group
  69762. * @param {module:echarts/model/Component} componentModel
  69763. * @param {module:echarts/ExtensionAPI}
  69764. */
  69765. function layout$3(group, componentModel, api) {
  69766. var boxLayoutParams = componentModel.getBoxLayoutParams();
  69767. var padding = componentModel.get('padding');
  69768. var viewportSize = {
  69769. width: api.getWidth(),
  69770. height: api.getHeight()
  69771. };
  69772. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  69773. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  69774. positionElement(group, boxLayoutParams, viewportSize, padding);
  69775. }
  69776. function makeBackground(rect, componentModel) {
  69777. var padding = normalizeCssArray$1(componentModel.get('padding'));
  69778. var style = componentModel.getItemStyle(['color', 'opacity']);
  69779. style.fill = componentModel.get('backgroundColor');
  69780. rect = new Rect({
  69781. shape: {
  69782. x: rect.x - padding[3],
  69783. y: rect.y - padding[0],
  69784. width: rect.width + padding[1] + padding[3],
  69785. height: rect.height + padding[0] + padding[2],
  69786. r: componentModel.get('borderRadius')
  69787. },
  69788. style: style,
  69789. silent: true,
  69790. z2: -1
  69791. }); // FIXME
  69792. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  69793. // and background rect when setting like `left: 0`, `top: 0`.
  69794. // graphic.subPixelOptimizeRect(rect);
  69795. return rect;
  69796. }
  69797. var ToolboxView =
  69798. /** @class */
  69799. function (_super) {
  69800. __extends(ToolboxView, _super);
  69801. function ToolboxView() {
  69802. return _super !== null && _super.apply(this, arguments) || this;
  69803. }
  69804. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  69805. var group = this.group;
  69806. group.removeAll();
  69807. if (!toolboxModel.get('show')) {
  69808. return;
  69809. }
  69810. var itemSize = +toolboxModel.get('itemSize');
  69811. var isVertical = toolboxModel.get('orient') === 'vertical';
  69812. var featureOpts = toolboxModel.get('feature') || {};
  69813. var features = this._features || (this._features = {});
  69814. var featureNames = [];
  69815. each(featureOpts, function (opt, name) {
  69816. featureNames.push(name);
  69817. });
  69818. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(); // Keep for diff.
  69819. this._featureNames = featureNames;
  69820. function processFeature(newIndex, oldIndex) {
  69821. var featureName = featureNames[newIndex];
  69822. var oldName = featureNames[oldIndex];
  69823. var featureOpt = featureOpts[featureName];
  69824. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  69825. var feature; // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  69826. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  69827. featureOpt.title = payload.newTitle;
  69828. }
  69829. if (featureName && !oldName) {
  69830. // Create
  69831. if (isUserFeatureName(featureName)) {
  69832. feature = {
  69833. onclick: featureModel.option.onclick,
  69834. featureName: featureName
  69835. };
  69836. } else {
  69837. var Feature = getFeature(featureName);
  69838. if (!Feature) {
  69839. return;
  69840. }
  69841. feature = new Feature();
  69842. }
  69843. features[featureName] = feature;
  69844. } else {
  69845. feature = features[oldName]; // If feature does not exist.
  69846. if (!feature) {
  69847. return;
  69848. }
  69849. }
  69850. feature.uid = getUID('toolbox-feature');
  69851. feature.model = featureModel;
  69852. feature.ecModel = ecModel;
  69853. feature.api = api;
  69854. var isToolboxFeature = feature instanceof ToolboxFeature;
  69855. if (!featureName && oldName) {
  69856. isToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  69857. return;
  69858. }
  69859. if (!featureModel.get('show') || isToolboxFeature && feature.unusable) {
  69860. isToolboxFeature && feature.remove && feature.remove(ecModel, api);
  69861. return;
  69862. }
  69863. createIconPaths(featureModel, feature, featureName);
  69864. featureModel.setIconStatus = function (iconName, status) {
  69865. var option = this.option;
  69866. var iconPaths = this.iconPaths;
  69867. option.iconStatus = option.iconStatus || {};
  69868. option.iconStatus[iconName] = status;
  69869. if (iconPaths[iconName]) {
  69870. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  69871. }
  69872. };
  69873. if (feature instanceof ToolboxFeature) {
  69874. if (feature.render) {
  69875. feature.render(featureModel, ecModel, api, payload);
  69876. }
  69877. }
  69878. }
  69879. function createIconPaths(featureModel, feature, featureName) {
  69880. var iconStyleModel = featureModel.getModel('iconStyle');
  69881. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']); // If one feature has multiple icons, they are organized as
  69882. // {
  69883. // icon: {
  69884. // foo: '',
  69885. // bar: ''
  69886. // },
  69887. // title: {
  69888. // foo: '',
  69889. // bar: ''
  69890. // }
  69891. // }
  69892. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  69893. var titles = featureModel.get('title') || {};
  69894. var iconsMap;
  69895. var titlesMap;
  69896. if (isString(icons)) {
  69897. iconsMap = {};
  69898. iconsMap[featureName] = icons;
  69899. } else {
  69900. iconsMap = icons;
  69901. }
  69902. if (isString(titles)) {
  69903. titlesMap = {};
  69904. titlesMap[featureName] = titles;
  69905. } else {
  69906. titlesMap = titles;
  69907. }
  69908. var iconPaths = featureModel.iconPaths = {};
  69909. each(iconsMap, function (iconStr, iconName) {
  69910. var path = createIcon(iconStr, {}, {
  69911. x: -itemSize / 2,
  69912. y: -itemSize / 2,
  69913. width: itemSize,
  69914. height: itemSize
  69915. }); // TODO handling image
  69916. path.setStyle(iconStyleModel.getItemStyle());
  69917. var pathEmphasisState = path.ensureState('emphasis');
  69918. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle(); // Text position calculation
  69919. var textContent = new ZRText({
  69920. style: {
  69921. text: titlesMap[iconName],
  69922. align: iconStyleEmphasisModel.get('textAlign'),
  69923. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  69924. padding: iconStyleEmphasisModel.get('textPadding'),
  69925. fill: null
  69926. },
  69927. ignore: true
  69928. });
  69929. path.setTextContent(textContent);
  69930. setTooltipConfig({
  69931. el: path,
  69932. componentModel: toolboxModel,
  69933. itemName: iconName,
  69934. formatterParamsExtra: {
  69935. title: titlesMap[iconName]
  69936. }
  69937. });
  69938. path.__title = titlesMap[iconName];
  69939. path.on('mouseover', function () {
  69940. // Should not reuse above hoverStyle, which might be modified.
  69941. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  69942. var defaultTextPosition = isVertical ? toolboxModel.get('right') == null && toolboxModel.get('left') !== 'right' ? 'right' : 'left' : toolboxModel.get('bottom') == null && toolboxModel.get('top') !== 'bottom' ? 'bottom' : 'top';
  69943. textContent.setStyle({
  69944. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  69945. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  69946. });
  69947. path.setTextConfig({
  69948. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  69949. });
  69950. textContent.ignore = !toolboxModel.get('showTitle'); // Use enterEmphasis and leaveEmphasis provide by ec.
  69951. // There are flags managed by the echarts.
  69952. api.enterEmphasis(this);
  69953. }).on('mouseout', function () {
  69954. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  69955. api.leaveEmphasis(this);
  69956. }
  69957. textContent.hide();
  69958. });
  69959. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  69960. group.add(path);
  69961. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  69962. iconPaths[iconName] = path;
  69963. });
  69964. }
  69965. layout$3(group, toolboxModel, api); // Render background after group is layout
  69966. // FIXME
  69967. group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen
  69968. isVertical || group.eachChild(function (icon) {
  69969. var titleText = icon.__title; // const hoverStyle = icon.hoverStyle;
  69970. // TODO simplify code?
  69971. var emphasisState = icon.ensureState('emphasis');
  69972. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  69973. var textContent = icon.getTextContent();
  69974. var emphasisTextState = textContent && textContent.ensureState('emphasis'); // May be background element
  69975. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  69976. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  69977. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  69978. var offsetX = icon.x + group.x;
  69979. var offsetY = icon.y + group.y + itemSize;
  69980. var needPutOnTop = false;
  69981. if (offsetY + rect.height > api.getHeight()) {
  69982. emphasisTextConfig.position = 'top';
  69983. needPutOnTop = true;
  69984. }
  69985. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 10;
  69986. if (offsetX + rect.width / 2 > api.getWidth()) {
  69987. emphasisTextConfig.position = ['100%', topOffset];
  69988. emphasisTextStyle.align = 'right';
  69989. } else if (offsetX - rect.width / 2 < 0) {
  69990. emphasisTextConfig.position = [0, topOffset];
  69991. emphasisTextStyle.align = 'left';
  69992. }
  69993. }
  69994. });
  69995. };
  69996. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  69997. each(this._features, function (feature) {
  69998. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  69999. });
  70000. }; // updateLayout(toolboxModel, ecModel, api, payload) {
  70001. // zrUtil.each(this._features, function (feature) {
  70002. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  70003. // });
  70004. // },
  70005. ToolboxView.prototype.remove = function (ecModel, api) {
  70006. each(this._features, function (feature) {
  70007. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  70008. });
  70009. this.group.removeAll();
  70010. };
  70011. ToolboxView.prototype.dispose = function (ecModel, api) {
  70012. each(this._features, function (feature) {
  70013. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  70014. });
  70015. };
  70016. ToolboxView.type = 'toolbox';
  70017. return ToolboxView;
  70018. }(ComponentView);
  70019. function isUserFeatureName(featureName) {
  70020. return featureName.indexOf('my') === 0;
  70021. }
  70022. /* global window, document */
  70023. var SaveAsImage =
  70024. /** @class */
  70025. function (_super) {
  70026. __extends(SaveAsImage, _super);
  70027. function SaveAsImage() {
  70028. return _super !== null && _super.apply(this, arguments) || this;
  70029. }
  70030. SaveAsImage.prototype.onclick = function (ecModel, api) {
  70031. var model = this.model;
  70032. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  70033. var isSvg = api.getZr().painter.getType() === 'svg';
  70034. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  70035. var url = api.getConnectedDataURL({
  70036. type: type,
  70037. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  70038. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  70039. excludeComponents: model.get('excludeComponents'),
  70040. pixelRatio: model.get('pixelRatio')
  70041. });
  70042. var browser = env.browser; // Chrome, Firefox, New Edge
  70043. if (isFunction(MouseEvent) && (browser.newEdge || !browser.ie && !browser.edge)) {
  70044. var $a = document.createElement('a');
  70045. $a.download = title + '.' + type;
  70046. $a.target = '_blank';
  70047. $a.href = url;
  70048. var evt = new MouseEvent('click', {
  70049. // some micro front-end framework, window maybe is a Proxy
  70050. view: document.defaultView,
  70051. bubbles: true,
  70052. cancelable: false
  70053. });
  70054. $a.dispatchEvent(evt);
  70055. } // IE or old Edge
  70056. else {
  70057. // @ts-ignore
  70058. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  70059. var parts = url.split(','); // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  70060. var base64Encoded = parts[0].indexOf('base64') > -1;
  70061. var bstr = isSvg // should decode the svg data uri first
  70062. ? decodeURIComponent(parts[1]) : parts[1]; // only `atob` when the data uri is encoded with base64
  70063. // otherwise, like `svg` data uri exported by zrender,
  70064. // there will be an error, for it's not encoded with base64.
  70065. // (just a url-encoded string through `encodeURIComponent`)
  70066. base64Encoded && (bstr = window.atob(bstr));
  70067. var filename = title + '.' + type; // @ts-ignore
  70068. if (window.navigator.msSaveOrOpenBlob) {
  70069. var n = bstr.length;
  70070. var u8arr = new Uint8Array(n);
  70071. while (n--) {
  70072. u8arr[n] = bstr.charCodeAt(n);
  70073. }
  70074. var blob = new Blob([u8arr]); // @ts-ignore
  70075. window.navigator.msSaveOrOpenBlob(blob, filename);
  70076. } else {
  70077. var frame = document.createElement('iframe');
  70078. document.body.appendChild(frame);
  70079. var cw = frame.contentWindow;
  70080. var doc = cw.document;
  70081. doc.open('image/svg+xml', 'replace');
  70082. doc.write(bstr);
  70083. doc.close();
  70084. cw.focus();
  70085. doc.execCommand('SaveAs', true, filename);
  70086. document.body.removeChild(frame);
  70087. }
  70088. } else {
  70089. var lang = model.get('lang');
  70090. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  70091. var tab = window.open();
  70092. tab.document.write(html);
  70093. tab.document.title = title;
  70094. }
  70095. }
  70096. };
  70097. SaveAsImage.getDefaultOption = function (ecModel) {
  70098. var defaultOption = {
  70099. show: true,
  70100. icon: 'M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0',
  70101. title: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'title']),
  70102. type: 'png',
  70103. // Default use option.backgroundColor
  70104. // backgroundColor: '#fff',
  70105. connectedBackgroundColor: '#fff',
  70106. name: '',
  70107. excludeComponents: ['toolbox'],
  70108. // use current pixel ratio of device by default
  70109. // pixelRatio: 1,
  70110. lang: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'lang'])
  70111. };
  70112. return defaultOption;
  70113. };
  70114. return SaveAsImage;
  70115. }(ToolboxFeature);
  70116. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  70117. var radioTypes = [['line', 'bar'], ['stack']];
  70118. var MagicType =
  70119. /** @class */
  70120. function (_super) {
  70121. __extends(MagicType, _super);
  70122. function MagicType() {
  70123. return _super !== null && _super.apply(this, arguments) || this;
  70124. }
  70125. MagicType.prototype.getIcons = function () {
  70126. var model = this.model;
  70127. var availableIcons = model.get('icon');
  70128. var icons = {};
  70129. each(model.get('type'), function (type) {
  70130. if (availableIcons[type]) {
  70131. icons[type] = availableIcons[type];
  70132. }
  70133. });
  70134. return icons;
  70135. };
  70136. MagicType.getDefaultOption = function (ecModel) {
  70137. var defaultOption = {
  70138. show: true,
  70139. type: [],
  70140. // Icon group
  70141. icon: {
  70142. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  70143. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  70144. // eslint-disable-next-line
  70145. stack: 'M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z' // jshint ignore:line
  70146. },
  70147. // `line`, `bar`, `stack`, `tiled`
  70148. title: ecModel.getLocaleModel().get(['toolbox', 'magicType', 'title']),
  70149. option: {},
  70150. seriesIndex: {}
  70151. };
  70152. return defaultOption;
  70153. };
  70154. MagicType.prototype.onclick = function (ecModel, api, type) {
  70155. var model = this.model;
  70156. var seriesIndex = model.get(['seriesIndex', type]); // Not supported magicType
  70157. if (!seriesOptGenreator[type]) {
  70158. return;
  70159. }
  70160. var newOption = {
  70161. series: []
  70162. };
  70163. var generateNewSeriesTypes = function (seriesModel) {
  70164. var seriesType = seriesModel.subType;
  70165. var seriesId = seriesModel.id;
  70166. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  70167. if (newSeriesOpt) {
  70168. // PENDING If merge original option?
  70169. defaults(newSeriesOpt, seriesModel.option);
  70170. newOption.series.push(newSeriesOpt);
  70171. } // Modify boundaryGap
  70172. var coordSys = seriesModel.coordinateSystem;
  70173. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  70174. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  70175. if (categoryAxis) {
  70176. var axisDim = categoryAxis.dim;
  70177. var axisType = axisDim + 'Axis';
  70178. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  70179. var axisIndex = axisModel.componentIndex;
  70180. newOption[axisType] = newOption[axisType] || [];
  70181. for (var i = 0; i <= axisIndex; i++) {
  70182. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  70183. }
  70184. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  70185. }
  70186. }
  70187. };
  70188. each(radioTypes, function (radio) {
  70189. if (indexOf(radio, type) >= 0) {
  70190. each(radio, function (item) {
  70191. model.setIconStatus(item, 'normal');
  70192. });
  70193. }
  70194. });
  70195. model.setIconStatus(type, 'emphasis');
  70196. ecModel.eachComponent({
  70197. mainType: 'series',
  70198. query: seriesIndex == null ? null : {
  70199. seriesIndex: seriesIndex
  70200. }
  70201. }, generateNewSeriesTypes);
  70202. var newTitle;
  70203. var currentType = type; // Change title of stack
  70204. if (type === 'stack') {
  70205. // use titles in model instead of ecModel
  70206. // as stack and tiled appears in pair, just flip them
  70207. // no need of checking stack state
  70208. newTitle = merge({
  70209. stack: model.option.title.tiled,
  70210. tiled: model.option.title.stack
  70211. }, model.option.title);
  70212. if (model.get(['iconStatus', type]) !== 'emphasis') {
  70213. currentType = 'tiled';
  70214. }
  70215. }
  70216. api.dispatchAction({
  70217. type: 'changeMagicType',
  70218. currentType: currentType,
  70219. newOption: newOption,
  70220. newTitle: newTitle,
  70221. featureName: 'magicType'
  70222. });
  70223. };
  70224. return MagicType;
  70225. }(ToolboxFeature);
  70226. var seriesOptGenreator = {
  70227. 'line': function (seriesType, seriesId, seriesModel, model) {
  70228. if (seriesType === 'bar') {
  70229. return merge({
  70230. id: seriesId,
  70231. type: 'line',
  70232. // Preserve data related option
  70233. data: seriesModel.get('data'),
  70234. stack: seriesModel.get('stack'),
  70235. markPoint: seriesModel.get('markPoint'),
  70236. markLine: seriesModel.get('markLine')
  70237. }, model.get(['option', 'line']) || {}, true);
  70238. }
  70239. },
  70240. 'bar': function (seriesType, seriesId, seriesModel, model) {
  70241. if (seriesType === 'line') {
  70242. return merge({
  70243. id: seriesId,
  70244. type: 'bar',
  70245. // Preserve data related option
  70246. data: seriesModel.get('data'),
  70247. stack: seriesModel.get('stack'),
  70248. markPoint: seriesModel.get('markPoint'),
  70249. markLine: seriesModel.get('markLine')
  70250. }, model.get(['option', 'bar']) || {}, true);
  70251. }
  70252. },
  70253. 'stack': function (seriesType, seriesId, seriesModel, model) {
  70254. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  70255. if (seriesType === 'line' || seriesType === 'bar') {
  70256. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  70257. return merge({
  70258. id: seriesId,
  70259. stack: isStack ? '' : INNER_STACK_KEYWORD
  70260. }, model.get(['option', 'stack']) || {}, true);
  70261. }
  70262. }
  70263. }; // TODO: SELF REGISTERED.
  70264. registerAction({
  70265. type: 'changeMagicType',
  70266. event: 'magicTypeChanged',
  70267. update: 'prepareAndUpdate'
  70268. }, function (payload, ecModel) {
  70269. ecModel.mergeOption(payload.newOption);
  70270. });
  70271. /* global document */
  70272. var BLOCK_SPLITER = new Array(60).join('-');
  70273. var ITEM_SPLITER = '\t';
  70274. /**
  70275. * Group series into two types
  70276. * 1. on category axis, like line, bar
  70277. * 2. others, like scatter, pie
  70278. */
  70279. function groupSeries(ecModel) {
  70280. var seriesGroupByCategoryAxis = {};
  70281. var otherSeries = [];
  70282. var meta = [];
  70283. ecModel.eachRawSeries(function (seriesModel) {
  70284. var coordSys = seriesModel.coordinateSystem;
  70285. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  70286. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  70287. var baseAxis = coordSys.getBaseAxis();
  70288. if (baseAxis.type === 'category') {
  70289. var key = baseAxis.dim + '_' + baseAxis.index;
  70290. if (!seriesGroupByCategoryAxis[key]) {
  70291. seriesGroupByCategoryAxis[key] = {
  70292. categoryAxis: baseAxis,
  70293. valueAxis: coordSys.getOtherAxis(baseAxis),
  70294. series: []
  70295. };
  70296. meta.push({
  70297. axisDim: baseAxis.dim,
  70298. axisIndex: baseAxis.index
  70299. });
  70300. }
  70301. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  70302. } else {
  70303. otherSeries.push(seriesModel);
  70304. }
  70305. } else {
  70306. otherSeries.push(seriesModel);
  70307. }
  70308. });
  70309. return {
  70310. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  70311. other: otherSeries,
  70312. meta: meta
  70313. };
  70314. }
  70315. /**
  70316. * Assemble content of series on cateogory axis
  70317. * @inner
  70318. */
  70319. function assembleSeriesWithCategoryAxis(groups) {
  70320. var tables = [];
  70321. each(groups, function (group, key) {
  70322. var categoryAxis = group.categoryAxis;
  70323. var valueAxis = group.valueAxis;
  70324. var valueAxisDim = valueAxis.dim;
  70325. var headers = [' '].concat(map(group.series, function (series) {
  70326. return series.name;
  70327. })); // @ts-ignore TODO Polar
  70328. var columns = [categoryAxis.model.getCategories()];
  70329. each(group.series, function (series) {
  70330. var rawData = series.getRawData();
  70331. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  70332. return val;
  70333. }));
  70334. }); // Assemble table content
  70335. var lines = [headers.join(ITEM_SPLITER)];
  70336. for (var i = 0; i < columns[0].length; i++) {
  70337. var items = [];
  70338. for (var j = 0; j < columns.length; j++) {
  70339. items.push(columns[j][i]);
  70340. }
  70341. lines.push(items.join(ITEM_SPLITER));
  70342. }
  70343. tables.push(lines.join('\n'));
  70344. });
  70345. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  70346. }
  70347. /**
  70348. * Assemble content of other series
  70349. */
  70350. function assembleOtherSeries(series) {
  70351. return map(series, function (series) {
  70352. var data = series.getRawData();
  70353. var lines = [series.name];
  70354. var vals = [];
  70355. data.each(data.dimensions, function () {
  70356. var argLen = arguments.length;
  70357. var dataIndex = arguments[argLen - 1];
  70358. var name = data.getName(dataIndex);
  70359. for (var i = 0; i < argLen - 1; i++) {
  70360. vals[i] = arguments[i];
  70361. }
  70362. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  70363. });
  70364. return lines.join('\n');
  70365. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  70366. }
  70367. function getContentFromModel(ecModel) {
  70368. var result = groupSeries(ecModel);
  70369. return {
  70370. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  70371. return !!str.replace(/[\n\t\s]/g, '');
  70372. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  70373. meta: result.meta
  70374. };
  70375. }
  70376. function trim$1(str) {
  70377. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  70378. }
  70379. /**
  70380. * If a block is tsv format
  70381. */
  70382. function isTSVFormat(block) {
  70383. // Simple method to find out if a block is tsv format
  70384. var firstLine = block.slice(0, block.indexOf('\n'));
  70385. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  70386. return true;
  70387. }
  70388. }
  70389. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  70390. /**
  70391. * @param {string} tsv
  70392. * @return {Object}
  70393. */
  70394. function parseTSVContents(tsv) {
  70395. var tsvLines = tsv.split(/\n+/g);
  70396. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  70397. var categories = [];
  70398. var series = map(headers, function (header) {
  70399. return {
  70400. name: header,
  70401. data: []
  70402. };
  70403. });
  70404. for (var i = 0; i < tsvLines.length; i++) {
  70405. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  70406. categories.push(items.shift());
  70407. for (var j = 0; j < items.length; j++) {
  70408. series[j] && (series[j].data[i] = items[j]);
  70409. }
  70410. }
  70411. return {
  70412. series: series,
  70413. categories: categories
  70414. };
  70415. }
  70416. function parseListContents(str) {
  70417. var lines = str.split(/\n+/g);
  70418. var seriesName = trim$1(lines.shift());
  70419. var data = [];
  70420. for (var i = 0; i < lines.length; i++) {
  70421. // if line is empty, ignore it.
  70422. // there is a case that a user forgot to delete `\n`.
  70423. var line = trim$1(lines[i]);
  70424. if (!line) {
  70425. continue;
  70426. }
  70427. var items = line.split(itemSplitRegex);
  70428. var name_1 = '';
  70429. var value = void 0;
  70430. var hasName = false;
  70431. if (isNaN(items[0])) {
  70432. // First item is name
  70433. hasName = true;
  70434. name_1 = items[0];
  70435. items = items.slice(1);
  70436. data[i] = {
  70437. name: name_1,
  70438. value: []
  70439. };
  70440. value = data[i].value;
  70441. } else {
  70442. value = data[i] = [];
  70443. }
  70444. for (var j = 0; j < items.length; j++) {
  70445. value.push(+items[j]);
  70446. }
  70447. if (value.length === 1) {
  70448. hasName ? data[i].value = value[0] : data[i] = value[0];
  70449. }
  70450. }
  70451. return {
  70452. name: seriesName,
  70453. data: data
  70454. };
  70455. }
  70456. function parseContents(str, blockMetaList) {
  70457. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  70458. var newOption = {
  70459. series: []
  70460. };
  70461. each(blocks, function (block, idx) {
  70462. if (isTSVFormat(block)) {
  70463. var result = parseTSVContents(block);
  70464. var blockMeta = blockMetaList[idx];
  70465. var axisKey = blockMeta.axisDim + 'Axis';
  70466. if (blockMeta) {
  70467. newOption[axisKey] = newOption[axisKey] || [];
  70468. newOption[axisKey][blockMeta.axisIndex] = {
  70469. data: result.categories
  70470. };
  70471. newOption.series = newOption.series.concat(result.series);
  70472. }
  70473. } else {
  70474. var result = parseListContents(block);
  70475. newOption.series.push(result);
  70476. }
  70477. });
  70478. return newOption;
  70479. }
  70480. var DataView =
  70481. /** @class */
  70482. function (_super) {
  70483. __extends(DataView, _super);
  70484. function DataView() {
  70485. return _super !== null && _super.apply(this, arguments) || this;
  70486. }
  70487. DataView.prototype.onclick = function (ecModel, api) {
  70488. // FIXME: better way?
  70489. setTimeout(function () {
  70490. api.dispatchAction({
  70491. type: 'hideTip'
  70492. });
  70493. });
  70494. var container = api.getDom();
  70495. var model = this.model;
  70496. if (this._dom) {
  70497. container.removeChild(this._dom);
  70498. }
  70499. var root = document.createElement('div'); // use padding to avoid 5px whitespace
  70500. root.style.cssText = 'position:absolute;top:0;bottom:0;left:0;right:0;padding:5px';
  70501. root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements
  70502. var header = document.createElement('h4');
  70503. var lang = model.get('lang') || [];
  70504. header.innerHTML = lang[0] || model.get('title');
  70505. header.style.cssText = 'margin:10px 20px';
  70506. header.style.color = model.get('textColor');
  70507. var viewMain = document.createElement('div');
  70508. var textarea = document.createElement('textarea');
  70509. viewMain.style.cssText = 'overflow:auto';
  70510. var optionToContent = model.get('optionToContent');
  70511. var contentToOption = model.get('contentToOption');
  70512. var result = getContentFromModel(ecModel);
  70513. if (isFunction(optionToContent)) {
  70514. var htmlOrDom = optionToContent(api.getOption());
  70515. if (isString(htmlOrDom)) {
  70516. viewMain.innerHTML = htmlOrDom;
  70517. } else if (isDom(htmlOrDom)) {
  70518. viewMain.appendChild(htmlOrDom);
  70519. }
  70520. } else {
  70521. // Use default textarea
  70522. textarea.readOnly = model.get('readOnly');
  70523. var style = textarea.style; // eslint-disable-next-line max-len
  70524. style.cssText = 'display:block;width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;resize:none;box-sizing:border-box;outline:none';
  70525. style.color = model.get('textColor');
  70526. style.borderColor = model.get('textareaBorderColor');
  70527. style.backgroundColor = model.get('textareaColor');
  70528. textarea.value = result.value;
  70529. viewMain.appendChild(textarea);
  70530. }
  70531. var blockMetaList = result.meta;
  70532. var buttonContainer = document.createElement('div');
  70533. buttonContainer.style.cssText = 'position:absolute;bottom:5px;left:0;right:0'; // eslint-disable-next-line max-len
  70534. var buttonStyle = 'float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  70535. var closeButton = document.createElement('div');
  70536. var refreshButton = document.createElement('div');
  70537. buttonStyle += ';background-color:' + model.get('buttonColor');
  70538. buttonStyle += ';color:' + model.get('buttonTextColor');
  70539. var self = this;
  70540. function close() {
  70541. container.removeChild(root);
  70542. self._dom = null;
  70543. }
  70544. addEventListener(closeButton, 'click', close);
  70545. addEventListener(refreshButton, 'click', function () {
  70546. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  70547. if ("development" !== 'production') {
  70548. // eslint-disable-next-line
  70549. warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  70550. }
  70551. close();
  70552. return;
  70553. }
  70554. var newOption;
  70555. try {
  70556. if (isFunction(contentToOption)) {
  70557. newOption = contentToOption(viewMain, api.getOption());
  70558. } else {
  70559. newOption = parseContents(textarea.value, blockMetaList);
  70560. }
  70561. } catch (e) {
  70562. close();
  70563. throw new Error('Data view format error ' + e);
  70564. }
  70565. if (newOption) {
  70566. api.dispatchAction({
  70567. type: 'changeDataView',
  70568. newOption: newOption
  70569. });
  70570. }
  70571. close();
  70572. });
  70573. closeButton.innerHTML = lang[1];
  70574. refreshButton.innerHTML = lang[2];
  70575. refreshButton.style.cssText = closeButton.style.cssText = buttonStyle;
  70576. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  70577. buttonContainer.appendChild(closeButton);
  70578. root.appendChild(header);
  70579. root.appendChild(viewMain);
  70580. root.appendChild(buttonContainer);
  70581. viewMain.style.height = container.clientHeight - 80 + 'px';
  70582. container.appendChild(root);
  70583. this._dom = root;
  70584. };
  70585. DataView.prototype.remove = function (ecModel, api) {
  70586. this._dom && api.getDom().removeChild(this._dom);
  70587. };
  70588. DataView.prototype.dispose = function (ecModel, api) {
  70589. this.remove(ecModel, api);
  70590. };
  70591. DataView.getDefaultOption = function (ecModel) {
  70592. var defaultOption = {
  70593. show: true,
  70594. readOnly: false,
  70595. optionToContent: null,
  70596. contentToOption: null,
  70597. // eslint-disable-next-line
  70598. icon: 'M17.5,17.3H33 M17.5,17.3H33 M45.4,29.5h-28 M11.5,2v56H51V14.8L38.4,2H11.5z M38.4,2.2v12.7H51 M45.4,41.7h-28',
  70599. title: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'title']),
  70600. lang: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'lang']),
  70601. backgroundColor: '#fff',
  70602. textColor: '#000',
  70603. textareaColor: '#fff',
  70604. textareaBorderColor: '#333',
  70605. buttonColor: '#c23531',
  70606. buttonTextColor: '#fff'
  70607. };
  70608. return defaultOption;
  70609. };
  70610. return DataView;
  70611. }(ToolboxFeature);
  70612. /**
  70613. * @inner
  70614. */
  70615. function tryMergeDataOption(newData, originalData) {
  70616. return map(newData, function (newVal, idx) {
  70617. var original = originalData && originalData[idx];
  70618. if (isObject(original) && !isArray(original)) {
  70619. var newValIsObject = isObject(newVal) && !isArray(newVal);
  70620. if (!newValIsObject) {
  70621. newVal = {
  70622. value: newVal
  70623. };
  70624. } // original data has name but new data has no name
  70625. var shouldDeleteName = original.name != null && newVal.name == null; // Original data has option
  70626. newVal = defaults(newVal, original);
  70627. shouldDeleteName && delete newVal.name;
  70628. return newVal;
  70629. } else {
  70630. return newVal;
  70631. }
  70632. });
  70633. } // TODO: SELF REGISTERED.
  70634. registerAction({
  70635. type: 'changeDataView',
  70636. event: 'dataViewChanged',
  70637. update: 'prepareAndUpdate'
  70638. }, function (payload, ecModel) {
  70639. var newSeriesOptList = [];
  70640. each(payload.newOption.series, function (seriesOpt) {
  70641. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  70642. if (!seriesModel) {
  70643. // New created series
  70644. // Geuss the series type
  70645. newSeriesOptList.push(extend({
  70646. // Default is scatter
  70647. type: 'scatter'
  70648. }, seriesOpt));
  70649. } else {
  70650. var originalData = seriesModel.get('data');
  70651. newSeriesOptList.push({
  70652. name: seriesOpt.name,
  70653. data: tryMergeDataOption(seriesOpt.data, originalData)
  70654. });
  70655. }
  70656. });
  70657. ecModel.mergeOption(defaults({
  70658. series: newSeriesOptList
  70659. }, payload.newOption));
  70660. });
  70661. var each$9 = each;
  70662. var inner$f = makeInner();
  70663. /**
  70664. * @param ecModel
  70665. * @param newSnapshot key is dataZoomId
  70666. */
  70667. function push(ecModel, newSnapshot) {
  70668. var storedSnapshots = getStoreSnapshots(ecModel); // If previous dataZoom can not be found,
  70669. // complete an range with current range.
  70670. each$9(newSnapshot, function (batchItem, dataZoomId) {
  70671. var i = storedSnapshots.length - 1;
  70672. for (; i >= 0; i--) {
  70673. var snapshot = storedSnapshots[i];
  70674. if (snapshot[dataZoomId]) {
  70675. break;
  70676. }
  70677. }
  70678. if (i < 0) {
  70679. // No origin range set, create one by current range.
  70680. var dataZoomModel = ecModel.queryComponents({
  70681. mainType: 'dataZoom',
  70682. subType: 'select',
  70683. id: dataZoomId
  70684. })[0];
  70685. if (dataZoomModel) {
  70686. var percentRange = dataZoomModel.getPercentRange();
  70687. storedSnapshots[0][dataZoomId] = {
  70688. dataZoomId: dataZoomId,
  70689. start: percentRange[0],
  70690. end: percentRange[1]
  70691. };
  70692. }
  70693. }
  70694. });
  70695. storedSnapshots.push(newSnapshot);
  70696. }
  70697. function pop(ecModel) {
  70698. var storedSnapshots = getStoreSnapshots(ecModel);
  70699. var head = storedSnapshots[storedSnapshots.length - 1];
  70700. storedSnapshots.length > 1 && storedSnapshots.pop(); // Find top for all dataZoom.
  70701. var snapshot = {};
  70702. each$9(head, function (batchItem, dataZoomId) {
  70703. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  70704. batchItem = storedSnapshots[i][dataZoomId];
  70705. if (batchItem) {
  70706. snapshot[dataZoomId] = batchItem;
  70707. break;
  70708. }
  70709. }
  70710. });
  70711. return snapshot;
  70712. }
  70713. function clear$1(ecModel) {
  70714. inner$f(ecModel).snapshots = null;
  70715. }
  70716. function count(ecModel) {
  70717. return getStoreSnapshots(ecModel).length;
  70718. }
  70719. /**
  70720. * History length of each dataZoom may be different.
  70721. * this._history[0] is used to store origin range.
  70722. */
  70723. function getStoreSnapshots(ecModel) {
  70724. var store = inner$f(ecModel);
  70725. if (!store.snapshots) {
  70726. store.snapshots = [{}];
  70727. }
  70728. return store.snapshots;
  70729. }
  70730. var RestoreOption =
  70731. /** @class */
  70732. function (_super) {
  70733. __extends(RestoreOption, _super);
  70734. function RestoreOption() {
  70735. return _super !== null && _super.apply(this, arguments) || this;
  70736. }
  70737. RestoreOption.prototype.onclick = function (ecModel, api) {
  70738. clear$1(ecModel);
  70739. api.dispatchAction({
  70740. type: 'restore',
  70741. from: this.uid
  70742. });
  70743. };
  70744. RestoreOption.getDefaultOption = function (ecModel) {
  70745. var defaultOption = {
  70746. show: true,
  70747. // eslint-disable-next-line
  70748. icon: 'M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5',
  70749. title: ecModel.getLocaleModel().get(['toolbox', 'restore', 'title'])
  70750. };
  70751. return defaultOption;
  70752. };
  70753. return RestoreOption;
  70754. }(ToolboxFeature); // TODO: SELF REGISTERED.
  70755. registerAction({
  70756. type: 'restore',
  70757. event: 'restore',
  70758. update: 'prepareAndUpdate'
  70759. }, function (payload, ecModel) {
  70760. ecModel.resetOption('recreate');
  70761. });
  70762. // how to genarialize to more coordinate systems.
  70763. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  70764. var BrushTargetManager =
  70765. /** @class */
  70766. function () {
  70767. /**
  70768. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  70769. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  70770. * @param opt.include include coordinate system types.
  70771. */
  70772. function BrushTargetManager(finder, ecModel, opt) {
  70773. var _this = this;
  70774. this._targetInfoList = [];
  70775. var foundCpts = parseFinder$1(ecModel, finder);
  70776. each(targetInfoBuilders, function (builder, type) {
  70777. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  70778. builder(foundCpts, _this._targetInfoList);
  70779. }
  70780. });
  70781. }
  70782. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  70783. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  70784. (area.coordRanges || (area.coordRanges = [])).push(coordRange); // area.coordRange is the first of area.coordRanges
  70785. if (!area.coordRange) {
  70786. area.coordRange = coordRange; // In 'category' axis, coord to pixel is not reversible, so we can not
  70787. // rebuild range by coordRange accrately, which may bring trouble when
  70788. // brushing only one item. So we use __rangeOffset to rebuilding range
  70789. // by coordRange. And this it only used in brush component so it is no
  70790. // need to be adapted to coordRanges.
  70791. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  70792. area.__rangeOffset = {
  70793. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  70794. xyMinMax: result.xyMinMax
  70795. };
  70796. }
  70797. });
  70798. return areas;
  70799. };
  70800. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  70801. each(areas, function (area) {
  70802. var targetInfo = this.findTargetInfo(area, ecModel);
  70803. if (targetInfo && targetInfo !== true) {
  70804. each(targetInfo.coordSyses, function (coordSys) {
  70805. var result = coordConvert[area.brushType](1, coordSys, area.range, true);
  70806. cb(area, result.values, coordSys, ecModel);
  70807. });
  70808. }
  70809. }, this);
  70810. };
  70811. /**
  70812. * the `areas` is `BrushModel.areas`.
  70813. * Called in layout stage.
  70814. * convert `area.coordRange` to global range and set panelId to `area.range`.
  70815. */
  70816. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  70817. each(areas, function (area) {
  70818. var targetInfo = this.findTargetInfo(area, ecModel);
  70819. if ("development" !== 'production') {
  70820. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  70821. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  70822. }
  70823. area.range = area.range || []; // convert coordRange to global range and set panelId.
  70824. if (targetInfo && targetInfo !== true) {
  70825. area.panelId = targetInfo.panelId; // (1) area.range should always be calculate from coordRange but does
  70826. // not keep its original value, for the sake of the dataZoom scenario,
  70827. // where area.coordRange remains unchanged but area.range may be changed.
  70828. // (2) Only support converting one coordRange to pixel range in brush
  70829. // component. So do not consider `coordRanges`.
  70830. // (3) About __rangeOffset, see comment above.
  70831. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  70832. var rangeOffset = area.__rangeOffset;
  70833. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  70834. }
  70835. }, this);
  70836. };
  70837. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  70838. return map(this._targetInfoList, function (targetInfo) {
  70839. var rect = targetInfo.getPanelRect();
  70840. return {
  70841. panelId: targetInfo.panelId,
  70842. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  70843. clipPath: makeRectPanelClipPath(rect),
  70844. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  70845. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  70846. };
  70847. });
  70848. };
  70849. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  70850. // Check whether area is bound in coord, and series do not belong to that coord.
  70851. // If do not do this check, some brush (like lineX) will controll all axes.
  70852. var targetInfo = this.findTargetInfo(area, ecModel);
  70853. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  70854. };
  70855. /**
  70856. * If return Object, a coord found.
  70857. * If return true, global found.
  70858. * Otherwise nothing found.
  70859. */
  70860. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  70861. var targetInfoList = this._targetInfoList;
  70862. var foundCpts = parseFinder$1(ecModel, area);
  70863. for (var i = 0; i < targetInfoList.length; i++) {
  70864. var targetInfo = targetInfoList[i];
  70865. var areaPanelId = area.panelId;
  70866. if (areaPanelId) {
  70867. if (targetInfo.panelId === areaPanelId) {
  70868. return targetInfo;
  70869. }
  70870. } else {
  70871. for (var j = 0; j < targetInfoMatchers.length; j++) {
  70872. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  70873. return targetInfo;
  70874. }
  70875. }
  70876. }
  70877. }
  70878. return true;
  70879. };
  70880. return BrushTargetManager;
  70881. }();
  70882. function formatMinMax(minMax) {
  70883. minMax[0] > minMax[1] && minMax.reverse();
  70884. return minMax;
  70885. }
  70886. function parseFinder$1(ecModel, finder) {
  70887. return parseFinder(ecModel, finder, {
  70888. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  70889. });
  70890. }
  70891. var targetInfoBuilders = {
  70892. grid: function (foundCpts, targetInfoList) {
  70893. var xAxisModels = foundCpts.xAxisModels;
  70894. var yAxisModels = foundCpts.yAxisModels;
  70895. var gridModels = foundCpts.gridModels; // Remove duplicated.
  70896. var gridModelMap = createHashMap();
  70897. var xAxesHas = {};
  70898. var yAxesHas = {};
  70899. if (!xAxisModels && !yAxisModels && !gridModels) {
  70900. return;
  70901. }
  70902. each(xAxisModels, function (axisModel) {
  70903. var gridModel = axisModel.axis.grid.model;
  70904. gridModelMap.set(gridModel.id, gridModel);
  70905. xAxesHas[gridModel.id] = true;
  70906. });
  70907. each(yAxisModels, function (axisModel) {
  70908. var gridModel = axisModel.axis.grid.model;
  70909. gridModelMap.set(gridModel.id, gridModel);
  70910. yAxesHas[gridModel.id] = true;
  70911. });
  70912. each(gridModels, function (gridModel) {
  70913. gridModelMap.set(gridModel.id, gridModel);
  70914. xAxesHas[gridModel.id] = true;
  70915. yAxesHas[gridModel.id] = true;
  70916. });
  70917. gridModelMap.each(function (gridModel) {
  70918. var grid = gridModel.coordinateSystem;
  70919. var cartesians = [];
  70920. each(grid.getCartesians(), function (cartesian, index) {
  70921. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  70922. cartesians.push(cartesian);
  70923. }
  70924. });
  70925. targetInfoList.push({
  70926. panelId: 'grid--' + gridModel.id,
  70927. gridModel: gridModel,
  70928. coordSysModel: gridModel,
  70929. // Use the first one as the representitive coordSys.
  70930. coordSys: cartesians[0],
  70931. coordSyses: cartesians,
  70932. getPanelRect: panelRectBuilders.grid,
  70933. xAxisDeclared: xAxesHas[gridModel.id],
  70934. yAxisDeclared: yAxesHas[gridModel.id]
  70935. });
  70936. });
  70937. },
  70938. geo: function (foundCpts, targetInfoList) {
  70939. each(foundCpts.geoModels, function (geoModel) {
  70940. var coordSys = geoModel.coordinateSystem;
  70941. targetInfoList.push({
  70942. panelId: 'geo--' + geoModel.id,
  70943. geoModel: geoModel,
  70944. coordSysModel: geoModel,
  70945. coordSys: coordSys,
  70946. coordSyses: [coordSys],
  70947. getPanelRect: panelRectBuilders.geo
  70948. });
  70949. });
  70950. }
  70951. };
  70952. var targetInfoMatchers = [// grid
  70953. function (foundCpts, targetInfo) {
  70954. var xAxisModel = foundCpts.xAxisModel;
  70955. var yAxisModel = foundCpts.yAxisModel;
  70956. var gridModel = foundCpts.gridModel;
  70957. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  70958. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  70959. return gridModel && gridModel === targetInfo.gridModel;
  70960. }, // geo
  70961. function (foundCpts, targetInfo) {
  70962. var geoModel = foundCpts.geoModel;
  70963. return geoModel && geoModel === targetInfo.geoModel;
  70964. }];
  70965. var panelRectBuilders = {
  70966. grid: function () {
  70967. // grid is not Transformable.
  70968. return this.coordSys.master.getRect().clone();
  70969. },
  70970. geo: function () {
  70971. var coordSys = this.coordSys;
  70972. var rect = coordSys.getBoundingRect().clone(); // geo roam and zoom transform
  70973. rect.applyTransform(getTransform(coordSys));
  70974. return rect;
  70975. }
  70976. };
  70977. var coordConvert = {
  70978. lineX: curry(axisConvert, 0),
  70979. lineY: curry(axisConvert, 1),
  70980. rect: function (to, coordSys, rangeOrCoordRange, clamp) {
  70981. var xminymin = to ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
  70982. var xmaxymax = to ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
  70983. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  70984. return {
  70985. values: values,
  70986. xyMinMax: values
  70987. };
  70988. },
  70989. polygon: function (to, coordSys, rangeOrCoordRange, clamp) {
  70990. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  70991. var values = map(rangeOrCoordRange, function (item) {
  70992. var p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
  70993. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  70994. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  70995. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  70996. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  70997. return p;
  70998. });
  70999. return {
  71000. values: values,
  71001. xyMinMax: xyMinMax
  71002. };
  71003. }
  71004. };
  71005. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  71006. if ("development" !== 'production') {
  71007. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  71008. }
  71009. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  71010. var values = formatMinMax(map([0, 1], function (i) {
  71011. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  71012. }));
  71013. var xyMinMax = [];
  71014. xyMinMax[axisNameIndex] = values;
  71015. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  71016. return {
  71017. values: values,
  71018. xyMinMax: xyMinMax
  71019. };
  71020. }
  71021. var diffProcessor = {
  71022. lineX: curry(axisDiffProcessor, 0),
  71023. lineY: curry(axisDiffProcessor, 1),
  71024. rect: function (values, refer, scales) {
  71025. return [[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]], [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]];
  71026. },
  71027. polygon: function (values, refer, scales) {
  71028. return map(values, function (item, idx) {
  71029. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  71030. });
  71031. }
  71032. };
  71033. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  71034. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  71035. } // We have to process scale caused by dataZoom manually,
  71036. // although it might be not accurate.
  71037. // Return [0~1, 0~1]
  71038. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  71039. var sizeCurr = getSize$1(xyMinMaxCurr);
  71040. var sizeOrigin = getSize$1(xyMinMaxOrigin);
  71041. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  71042. isNaN(scales[0]) && (scales[0] = 1);
  71043. isNaN(scales[1]) && (scales[1] = 1);
  71044. return scales;
  71045. }
  71046. function getSize$1(xyMinMax) {
  71047. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  71048. }
  71049. var each$a = each;
  71050. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  71051. var DataZoomFeature =
  71052. /** @class */
  71053. function (_super) {
  71054. __extends(DataZoomFeature, _super);
  71055. function DataZoomFeature() {
  71056. return _super !== null && _super.apply(this, arguments) || this;
  71057. }
  71058. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  71059. if (!this._brushController) {
  71060. this._brushController = new BrushController(api.getZr());
  71061. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  71062. }
  71063. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  71064. updateBackBtnStatus(featureModel, ecModel);
  71065. };
  71066. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  71067. handlers$1[type].call(this);
  71068. };
  71069. DataZoomFeature.prototype.remove = function (ecModel, api) {
  71070. this._brushController && this._brushController.unmount();
  71071. };
  71072. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  71073. this._brushController && this._brushController.dispose();
  71074. };
  71075. DataZoomFeature.prototype._onBrush = function (eventParam) {
  71076. var areas = eventParam.areas;
  71077. if (!eventParam.isEnd || !areas.length) {
  71078. return;
  71079. }
  71080. var snapshot = {};
  71081. var ecModel = this.ecModel;
  71082. this._brushController.updateCovers([]); // remove cover
  71083. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  71084. include: ['grid']
  71085. });
  71086. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  71087. if (coordSys.type !== 'cartesian2d') {
  71088. return;
  71089. }
  71090. var brushType = area.brushType;
  71091. if (brushType === 'rect') {
  71092. setBatch('x', coordSys, coordRange[0]);
  71093. setBatch('y', coordSys, coordRange[1]);
  71094. } else {
  71095. setBatch({
  71096. lineX: 'x',
  71097. lineY: 'y'
  71098. }[brushType], coordSys, coordRange);
  71099. }
  71100. });
  71101. push(ecModel, snapshot);
  71102. this._dispatchZoomAction(snapshot);
  71103. function setBatch(dimName, coordSys, minMax) {
  71104. var axis = coordSys.getAxis(dimName);
  71105. var axisModel = axis.model;
  71106. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range.
  71107. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  71108. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  71109. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  71110. }
  71111. dataZoomModel && (snapshot[dataZoomModel.id] = {
  71112. dataZoomId: dataZoomModel.id,
  71113. startValue: minMax[0],
  71114. endValue: minMax[1]
  71115. });
  71116. }
  71117. function findDataZoom(dimName, axisModel, ecModel) {
  71118. var found;
  71119. ecModel.eachComponent({
  71120. mainType: 'dataZoom',
  71121. subType: 'select'
  71122. }, function (dzModel) {
  71123. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  71124. has && (found = dzModel);
  71125. });
  71126. return found;
  71127. }
  71128. };
  71129. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  71130. var batch = []; // Convert from hash map to array.
  71131. each$a(snapshot, function (batchItem, dataZoomId) {
  71132. batch.push(clone(batchItem));
  71133. });
  71134. batch.length && this.api.dispatchAction({
  71135. type: 'dataZoom',
  71136. from: this.uid,
  71137. batch: batch
  71138. });
  71139. };
  71140. DataZoomFeature.getDefaultOption = function (ecModel) {
  71141. var defaultOption = {
  71142. show: true,
  71143. filterMode: 'filter',
  71144. // Icon group
  71145. icon: {
  71146. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  71147. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  71148. },
  71149. // `zoom`, `back`
  71150. title: ecModel.getLocaleModel().get(['toolbox', 'dataZoom', 'title']),
  71151. brushStyle: {
  71152. borderWidth: 0,
  71153. color: 'rgba(210,219,238,0.2)'
  71154. }
  71155. };
  71156. return defaultOption;
  71157. };
  71158. return DataZoomFeature;
  71159. }(ToolboxFeature);
  71160. var handlers$1 = {
  71161. zoom: function () {
  71162. var nextActive = !this._isZoomActive;
  71163. this.api.dispatchAction({
  71164. type: 'takeGlobalCursor',
  71165. key: 'dataZoomSelect',
  71166. dataZoomSelectActive: nextActive
  71167. });
  71168. },
  71169. back: function () {
  71170. this._dispatchZoomAction(pop(this.ecModel));
  71171. }
  71172. };
  71173. function makeAxisFinder(dzFeatureModel) {
  71174. var setting = {
  71175. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  71176. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  71177. xAxisId: dzFeatureModel.get('xAxisId', true),
  71178. yAxisId: dzFeatureModel.get('yAxisId', true)
  71179. }; // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  71180. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  71181. // Some old cases set like this below to close yAxis control but leave xAxis control:
  71182. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  71183. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  71184. setting.xAxisIndex = 'all';
  71185. }
  71186. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  71187. setting.yAxisIndex = 'all';
  71188. }
  71189. return setting;
  71190. }
  71191. function updateBackBtnStatus(featureModel, ecModel) {
  71192. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  71193. }
  71194. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  71195. var zoomActive = view._isZoomActive;
  71196. if (payload && payload.type === 'takeGlobalCursor') {
  71197. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  71198. }
  71199. view._isZoomActive = zoomActive;
  71200. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  71201. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  71202. include: ['grid']
  71203. });
  71204. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  71205. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  71206. });
  71207. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  71208. brushType: 'auto',
  71209. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  71210. } : false);
  71211. }
  71212. registerInternalOptionCreator('dataZoom', function (ecModel) {
  71213. var toolboxModel = ecModel.getComponent('toolbox', 0);
  71214. var featureDataZoomPath = ['feature', 'dataZoom'];
  71215. if (!toolboxModel || toolboxModel.get(featureDataZoomPath) == null) {
  71216. return;
  71217. }
  71218. var dzFeatureModel = toolboxModel.getModel(featureDataZoomPath);
  71219. var dzOptions = [];
  71220. var finder = makeAxisFinder(dzFeatureModel);
  71221. var finderResult = parseFinder(ecModel, finder);
  71222. each$a(finderResult.xAxisModels, function (axisModel) {
  71223. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  71224. });
  71225. each$a(finderResult.yAxisModels, function (axisModel) {
  71226. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  71227. });
  71228. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  71229. var axisIndex = axisModel.componentIndex;
  71230. var newOpt = {
  71231. type: 'select',
  71232. $fromToolbox: true,
  71233. // Default to be filter
  71234. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  71235. // Id for merge mapping.
  71236. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  71237. };
  71238. newOpt[axisIndexPropName] = axisIndex;
  71239. dzOptions.push(newOpt);
  71240. }
  71241. return dzOptions;
  71242. });
  71243. function install$z(registers) {
  71244. registers.registerComponentModel(ToolboxModel);
  71245. registers.registerComponentView(ToolboxView);
  71246. registerFeature('saveAsImage', SaveAsImage);
  71247. registerFeature('magicType', MagicType);
  71248. registerFeature('dataView', DataView);
  71249. registerFeature('dataZoom', DataZoomFeature);
  71250. registerFeature('restore', RestoreOption);
  71251. use(install$y);
  71252. }
  71253. var TooltipModel =
  71254. /** @class */
  71255. function (_super) {
  71256. __extends(TooltipModel, _super);
  71257. function TooltipModel() {
  71258. var _this = _super !== null && _super.apply(this, arguments) || this;
  71259. _this.type = TooltipModel.type;
  71260. return _this;
  71261. }
  71262. TooltipModel.type = 'tooltip';
  71263. TooltipModel.dependencies = ['axisPointer'];
  71264. TooltipModel.defaultOption = {
  71265. // zlevel: 0,
  71266. z: 60,
  71267. show: true,
  71268. // tooltip main content
  71269. showContent: true,
  71270. // 'trigger' only works on coordinate system.
  71271. // 'item' | 'axis' | 'none'
  71272. trigger: 'item',
  71273. // 'click' | 'mousemove' | 'none'
  71274. triggerOn: 'mousemove|click',
  71275. alwaysShowContent: false,
  71276. displayMode: 'single',
  71277. renderMode: 'auto',
  71278. // whether restraint content inside viewRect.
  71279. // If renderMode: 'richText', default true.
  71280. // If renderMode: 'html', defaut false (for backward compat).
  71281. confine: null,
  71282. showDelay: 0,
  71283. hideDelay: 100,
  71284. // Animation transition time, unit is second
  71285. transitionDuration: 0.4,
  71286. enterable: false,
  71287. backgroundColor: '#fff',
  71288. // box shadow
  71289. shadowBlur: 10,
  71290. shadowColor: 'rgba(0, 0, 0, .2)',
  71291. shadowOffsetX: 1,
  71292. shadowOffsetY: 2,
  71293. // tooltip border radius, unit is px, default is 4
  71294. borderRadius: 4,
  71295. // tooltip border width, unit is px, default is 0 (no border)
  71296. borderWidth: 1,
  71297. // Tooltip inside padding, default is 5 for all direction
  71298. // Array is allowed to set up, right, bottom, left, same with css
  71299. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  71300. padding: null,
  71301. // Extra css text
  71302. extraCssText: '',
  71303. // axis indicator, trigger by axis
  71304. axisPointer: {
  71305. // default is line
  71306. // legal values: 'line' | 'shadow' | 'cross'
  71307. type: 'line',
  71308. // Valid when type is line, appoint tooltip line locate on which line. Optional
  71309. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  71310. // default is 'auto', chose the axis which type is category.
  71311. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  71312. axis: 'auto',
  71313. animation: 'auto',
  71314. animationDurationUpdate: 200,
  71315. animationEasingUpdate: 'exponentialOut',
  71316. crossStyle: {
  71317. color: '#999',
  71318. width: 1,
  71319. type: 'dashed',
  71320. // TODO formatter
  71321. textStyle: {}
  71322. } // lineStyle and shadowStyle should not be specified here,
  71323. // otherwise it will always override those styles on option.axisPointer.
  71324. },
  71325. textStyle: {
  71326. color: '#666',
  71327. fontSize: 14
  71328. }
  71329. };
  71330. return TooltipModel;
  71331. }(ComponentModel);
  71332. /* global document */
  71333. function shouldTooltipConfine(tooltipModel) {
  71334. var confineOption = tooltipModel.get('confine');
  71335. return confineOption != null ? !!confineOption // In richText mode, the outside part can not be visible.
  71336. : tooltipModel.get('renderMode') === 'richText';
  71337. }
  71338. function testStyle(styleProps) {
  71339. if (!env.domSupported) {
  71340. return;
  71341. }
  71342. var style = document.documentElement.style;
  71343. for (var i = 0, len = styleProps.length; i < len; i++) {
  71344. if (styleProps[i] in style) {
  71345. return styleProps[i];
  71346. }
  71347. }
  71348. }
  71349. var TRANSFORM_VENDOR = testStyle(['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  71350. var TRANSITION_VENDOR = testStyle(['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  71351. function toCSSVendorPrefix(styleVendor, styleProp) {
  71352. if (!styleVendor) {
  71353. return styleProp;
  71354. }
  71355. styleProp = toCamelCase(styleProp, true);
  71356. var idx = styleVendor.indexOf(styleProp);
  71357. styleVendor = idx === -1 ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp;
  71358. return styleVendor.toLowerCase();
  71359. }
  71360. function getComputedStyle(el, style) {
  71361. var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el);
  71362. return stl ? style ? stl[style] : stl : null;
  71363. }
  71364. /* global document, window */
  71365. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  71366. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform'); // eslint-disable-next-line
  71367. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  71368. function mirrorPos(pos) {
  71369. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  71370. return pos;
  71371. }
  71372. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  71373. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  71374. return '';
  71375. }
  71376. var backgroundColor = tooltipModel.get('backgroundColor');
  71377. var borderWidth = tooltipModel.get('borderWidth');
  71378. borderColor = convertToColorString(borderColor);
  71379. var arrowPos = mirrorPos(arrowPosition);
  71380. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  71381. var positionStyle = '';
  71382. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  71383. var rotateDeg;
  71384. if (indexOf(['left', 'right'], arrowPos) > -1) {
  71385. positionStyle += 'top:50%';
  71386. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  71387. } else {
  71388. positionStyle += 'left:50%';
  71389. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  71390. }
  71391. var rotateRadian = rotateDeg * Math.PI / 180;
  71392. var arrowWH = arrowSize + borderWidth;
  71393. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  71394. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  71395. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  71396. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  71397. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;z-index:-1;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  71398. return "<div style=\"" + styleCss.join('') + "\"></div>";
  71399. }
  71400. function assembleTransition(duration, onlyFade) {
  71401. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  71402. var transitionOption = " " + duration / 2 + "s " + transitionCurve;
  71403. var transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  71404. if (!onlyFade) {
  71405. transitionOption = " " + duration + "s " + transitionCurve;
  71406. transitionText += env.transformSupported ? "," + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption;
  71407. }
  71408. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  71409. }
  71410. function assembleTransform(x, y, toString) {
  71411. // If using float on style, the final width of the dom might
  71412. // keep changing slightly while mouse move. So `toFixed(0)` them.
  71413. var x0 = x.toFixed(0) + 'px';
  71414. var y0 = y.toFixed(0) + 'px'; // not support transform, use `left` and `top` instead.
  71415. if (!env.transformSupported) {
  71416. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  71417. } // support transform
  71418. var is3d = env.transform3dSupported;
  71419. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  71420. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  71421. }
  71422. /**
  71423. * @param {Object} textStyle
  71424. * @return {string}
  71425. * @inner
  71426. */
  71427. function assembleFont(textStyleModel) {
  71428. var cssText = [];
  71429. var fontSize = textStyleModel.get('fontSize');
  71430. var color = textStyleModel.getTextColor();
  71431. color && cssText.push('color:' + color);
  71432. cssText.push('font:' + textStyleModel.getFont());
  71433. fontSize // @ts-ignore, leave it to the tooltip refactor.
  71434. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  71435. var shadowColor = textStyleModel.get('textShadowColor');
  71436. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  71437. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  71438. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  71439. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  71440. each(['decoration', 'align'], function (name) {
  71441. var val = textStyleModel.get(name);
  71442. val && cssText.push('text-' + name + ':' + val);
  71443. });
  71444. return cssText.join(';');
  71445. }
  71446. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  71447. var cssText = [];
  71448. var transitionDuration = tooltipModel.get('transitionDuration');
  71449. var backgroundColor = tooltipModel.get('backgroundColor');
  71450. var shadowBlur = tooltipModel.get('shadowBlur');
  71451. var shadowColor = tooltipModel.get('shadowColor');
  71452. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  71453. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  71454. var textStyleModel = tooltipModel.getModel('textStyle');
  71455. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  71456. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  71457. cssText.push('box-shadow:' + boxShadow); // Animation transition. Do not animate when transitionDuration is 0.
  71458. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  71459. if (backgroundColor) {
  71460. cssText.push('background-color:' + backgroundColor);
  71461. } // Border style
  71462. each(['width', 'color', 'radius'], function (name) {
  71463. var borderName = 'border-' + name;
  71464. var camelCase = toCamelCase(borderName);
  71465. var val = tooltipModel.get(camelCase);
  71466. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  71467. }); // Text style
  71468. cssText.push(assembleFont(textStyleModel)); // Padding
  71469. if (padding != null) {
  71470. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  71471. }
  71472. return cssText.join(';') + ';';
  71473. } // If not able to make, do not modify the input `out`.
  71474. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  71475. var zrPainter = zr && zr.painter;
  71476. if (appendToBody) {
  71477. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  71478. if (zrViewportRoot) {
  71479. // Some APPs might use scale on body, so we support CSS transform here.
  71480. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  71481. }
  71482. } else {
  71483. out[0] = zrX;
  71484. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  71485. // the sibling of canvas root. So padding of ec container
  71486. // should be considered here.
  71487. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  71488. if (viewportRootOffset) {
  71489. out[0] += viewportRootOffset.offsetLeft;
  71490. out[1] += viewportRootOffset.offsetTop;
  71491. }
  71492. }
  71493. out[2] = out[0] / zr.getWidth();
  71494. out[3] = out[1] / zr.getHeight();
  71495. }
  71496. var TooltipHTMLContent =
  71497. /** @class */
  71498. function () {
  71499. function TooltipHTMLContent(container, api, opt) {
  71500. this._show = false;
  71501. this._styleCoord = [0, 0, 0, 0];
  71502. this._enterable = true;
  71503. this._alwaysShowContent = false;
  71504. this._firstShow = true;
  71505. this._longHide = true;
  71506. if (env.wxa) {
  71507. return null;
  71508. }
  71509. var el = document.createElement('div'); // TODO: TYPE
  71510. el.domBelongToZr = true;
  71511. this.el = el;
  71512. var zr = this._zr = api.getZr();
  71513. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  71514. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  71515. if (appendToBody) {
  71516. document.body.appendChild(el);
  71517. } else {
  71518. container.appendChild(el);
  71519. }
  71520. this._container = container; // FIXME
  71521. // Is it needed to trigger zr event manually if
  71522. // the browser do not support `pointer-events: none`.
  71523. var self = this;
  71524. el.onmouseenter = function () {
  71525. // clear the timeout in hideLater and keep showing tooltip
  71526. if (self._enterable) {
  71527. clearTimeout(self._hideTimeout);
  71528. self._show = true;
  71529. }
  71530. self._inContent = true;
  71531. };
  71532. el.onmousemove = function (e) {
  71533. e = e || window.event;
  71534. if (!self._enterable) {
  71535. // `pointer-events: none` is set to tooltip content div
  71536. // if `enterable` is set as `false`, and `el.onmousemove`
  71537. // can not be triggered. But in browser that do not
  71538. // support `pointer-events`, we need to do this:
  71539. // Try trigger zrender event to avoid mouse
  71540. // in and out shape too frequently
  71541. var handler = zr.handler;
  71542. var zrViewportRoot = zr.painter.getViewportRoot();
  71543. normalizeEvent(zrViewportRoot, e, true);
  71544. handler.dispatch('mousemove', e);
  71545. }
  71546. };
  71547. el.onmouseleave = function () {
  71548. // set `_inContent` to `false` before `hideLater`
  71549. self._inContent = false;
  71550. if (self._enterable) {
  71551. if (self._show) {
  71552. self.hideLater(self._hideDelay);
  71553. }
  71554. }
  71555. };
  71556. }
  71557. /**
  71558. * Update when tooltip is rendered
  71559. */
  71560. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  71561. // FIXME
  71562. // Move this logic to ec main?
  71563. var container = this._container;
  71564. var position = getComputedStyle(container, 'position');
  71565. var domStyle = container.style;
  71566. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  71567. domStyle.position = 'relative';
  71568. } // move tooltip if chart resized
  71569. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  71570. alwaysShowContent && this._moveIfResized(); // update alwaysShowContent
  71571. this._alwaysShowContent = alwaysShowContent; // update className
  71572. this.el.className = tooltipModel.get('className') || ''; // Hide the tooltip
  71573. // PENDING
  71574. // this.hide();
  71575. };
  71576. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  71577. clearTimeout(this._hideTimeout);
  71578. clearTimeout(this._longHideTimeout);
  71579. var el = this.el;
  71580. var style = el.style;
  71581. var styleCoord = this._styleCoord;
  71582. if (!el.innerHTML) {
  71583. style.display = 'none';
  71584. } else {
  71585. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide) // initial transform
  71586. + assembleTransform(styleCoord[0], styleCoord[1], true) + ("border-color:" + convertToColorString(nearPointColor) + ";") + (tooltipModel.get('extraCssText') || '') // If mouse occasionally move over the tooltip, a mouseout event will be
  71587. // triggered by canvas, and cause some unexpectable result like dragging
  71588. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  71589. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  71590. // scenario.
  71591. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  71592. }
  71593. this._show = true;
  71594. this._firstShow = false;
  71595. this._longHide = false;
  71596. };
  71597. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  71598. var el = this.el;
  71599. if (content == null) {
  71600. el.innerHTML = '';
  71601. return;
  71602. }
  71603. var arrow = '';
  71604. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  71605. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  71606. }
  71607. if (isString(content)) {
  71608. el.innerHTML = content + arrow;
  71609. } else if (content) {
  71610. // Clear previous
  71611. el.innerHTML = '';
  71612. if (!isArray(content)) {
  71613. content = [content];
  71614. }
  71615. for (var i = 0; i < content.length; i++) {
  71616. if (isDom(content[i]) && content[i].parentNode !== el) {
  71617. el.appendChild(content[i]);
  71618. }
  71619. } // no arrow if empty
  71620. if (arrow && el.childNodes.length) {
  71621. // no need to create a new parent element, but it's not supported by IE 10 and older.
  71622. // const arrowEl = document.createRange().createContextualFragment(arrow);
  71623. var arrowEl = document.createElement('div');
  71624. arrowEl.innerHTML = arrow;
  71625. el.appendChild(arrowEl);
  71626. }
  71627. }
  71628. };
  71629. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  71630. this._enterable = enterable;
  71631. };
  71632. TooltipHTMLContent.prototype.getSize = function () {
  71633. var el = this.el;
  71634. return [el.offsetWidth, el.offsetHeight];
  71635. };
  71636. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  71637. var styleCoord = this._styleCoord;
  71638. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  71639. if (styleCoord[0] != null && styleCoord[1] != null) {
  71640. var style_1 = this.el.style;
  71641. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  71642. each(transforms, function (transform) {
  71643. style_1[transform[0]] = transform[1];
  71644. });
  71645. }
  71646. };
  71647. /**
  71648. * when `alwaysShowContent` is true,
  71649. * move the tooltip after chart resized
  71650. */
  71651. TooltipHTMLContent.prototype._moveIfResized = function () {
  71652. // The ratio of left to width
  71653. var ratioX = this._styleCoord[2]; // The ratio of top to height
  71654. var ratioY = this._styleCoord[3];
  71655. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  71656. };
  71657. TooltipHTMLContent.prototype.hide = function () {
  71658. var _this = this;
  71659. var style = this.el.style;
  71660. style.visibility = 'hidden';
  71661. style.opacity = '0';
  71662. env.transform3dSupported && (style.willChange = '');
  71663. this._show = false;
  71664. this._longHideTimeout = setTimeout(function () {
  71665. return _this._longHide = true;
  71666. }, 500);
  71667. };
  71668. TooltipHTMLContent.prototype.hideLater = function (time) {
  71669. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  71670. if (time) {
  71671. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  71672. this._show = false;
  71673. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71674. } else {
  71675. this.hide();
  71676. }
  71677. }
  71678. };
  71679. TooltipHTMLContent.prototype.isShow = function () {
  71680. return this._show;
  71681. };
  71682. TooltipHTMLContent.prototype.dispose = function () {
  71683. this.el.parentNode.removeChild(this.el);
  71684. };
  71685. return TooltipHTMLContent;
  71686. }();
  71687. var TooltipRichContent =
  71688. /** @class */
  71689. function () {
  71690. function TooltipRichContent(api) {
  71691. this._show = false;
  71692. this._styleCoord = [0, 0, 0, 0];
  71693. this._alwaysShowContent = false;
  71694. this._enterable = true;
  71695. this._zr = api.getZr();
  71696. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  71697. }
  71698. /**
  71699. * Update when tooltip is rendered
  71700. */
  71701. TooltipRichContent.prototype.update = function (tooltipModel) {
  71702. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  71703. alwaysShowContent && this._moveIfResized(); // update alwaysShowContent
  71704. this._alwaysShowContent = alwaysShowContent;
  71705. };
  71706. TooltipRichContent.prototype.show = function () {
  71707. if (this._hideTimeout) {
  71708. clearTimeout(this._hideTimeout);
  71709. }
  71710. this.el.show();
  71711. this._show = true;
  71712. };
  71713. /**
  71714. * Set tooltip content
  71715. */
  71716. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  71717. var _this = this;
  71718. if (isObject(content)) {
  71719. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  71720. }
  71721. if (this.el) {
  71722. this._zr.remove(this.el);
  71723. }
  71724. var textStyleModel = tooltipModel.getModel('textStyle');
  71725. this.el = new ZRText({
  71726. style: {
  71727. rich: markupStyleCreator.richTextStyles,
  71728. text: content,
  71729. lineHeight: 22,
  71730. borderWidth: 1,
  71731. borderColor: borderColor,
  71732. textShadowColor: textStyleModel.get('textShadowColor'),
  71733. fill: tooltipModel.get(['textStyle', 'color']),
  71734. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  71735. verticalAlign: 'top',
  71736. align: 'left'
  71737. },
  71738. z: tooltipModel.get('z')
  71739. });
  71740. each(['backgroundColor', 'borderRadius', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'], function (propName) {
  71741. _this.el.style[propName] = tooltipModel.get(propName);
  71742. });
  71743. each(['textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'], function (propName) {
  71744. _this.el.style[propName] = textStyleModel.get(propName) || 0;
  71745. });
  71746. this._zr.add(this.el);
  71747. var self = this;
  71748. this.el.on('mouseover', function () {
  71749. // clear the timeout in hideLater and keep showing tooltip
  71750. if (self._enterable) {
  71751. clearTimeout(self._hideTimeout);
  71752. self._show = true;
  71753. }
  71754. self._inContent = true;
  71755. });
  71756. this.el.on('mouseout', function () {
  71757. if (self._enterable) {
  71758. if (self._show) {
  71759. self.hideLater(self._hideDelay);
  71760. }
  71761. }
  71762. self._inContent = false;
  71763. });
  71764. };
  71765. TooltipRichContent.prototype.setEnterable = function (enterable) {
  71766. this._enterable = enterable;
  71767. };
  71768. TooltipRichContent.prototype.getSize = function () {
  71769. var el = this.el;
  71770. var bounding = this.el.getBoundingRect(); // bounding rect does not include shadow. For renderMode richText,
  71771. // if overflow, it will be cut. So calculate them accurately.
  71772. var shadowOuterSize = calcShadowOuterSize(el.style);
  71773. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  71774. };
  71775. TooltipRichContent.prototype.moveTo = function (x, y) {
  71776. var el = this.el;
  71777. if (el) {
  71778. var styleCoord = this._styleCoord;
  71779. makeStyleCoord$1(styleCoord, this._zr, x, y);
  71780. x = styleCoord[0];
  71781. y = styleCoord[1];
  71782. var style = el.style;
  71783. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  71784. var shadowOuterSize = calcShadowOuterSize(style); // rich text x, y do not include border.
  71785. el.x = x + borderWidth + shadowOuterSize.left;
  71786. el.y = y + borderWidth + shadowOuterSize.top;
  71787. el.markRedraw();
  71788. }
  71789. };
  71790. /**
  71791. * when `alwaysShowContent` is true,
  71792. * move the tooltip after chart resized
  71793. */
  71794. TooltipRichContent.prototype._moveIfResized = function () {
  71795. // The ratio of left to width
  71796. var ratioX = this._styleCoord[2]; // The ratio of top to height
  71797. var ratioY = this._styleCoord[3];
  71798. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  71799. };
  71800. TooltipRichContent.prototype.hide = function () {
  71801. if (this.el) {
  71802. this.el.hide();
  71803. }
  71804. this._show = false;
  71805. };
  71806. TooltipRichContent.prototype.hideLater = function (time) {
  71807. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  71808. if (time) {
  71809. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  71810. this._show = false;
  71811. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71812. } else {
  71813. this.hide();
  71814. }
  71815. }
  71816. };
  71817. TooltipRichContent.prototype.isShow = function () {
  71818. return this._show;
  71819. };
  71820. TooltipRichContent.prototype.dispose = function () {
  71821. this._zr.remove(this.el);
  71822. };
  71823. return TooltipRichContent;
  71824. }();
  71825. function mathMaxWith0(val) {
  71826. return Math.max(0, val);
  71827. }
  71828. function calcShadowOuterSize(style) {
  71829. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  71830. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  71831. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  71832. return {
  71833. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  71834. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  71835. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  71836. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  71837. };
  71838. }
  71839. function makeStyleCoord$1(out, zr, zrX, zrY) {
  71840. out[0] = zrX;
  71841. out[1] = zrY;
  71842. out[2] = out[0] / zr.getWidth();
  71843. out[3] = out[1] / zr.getHeight();
  71844. }
  71845. var proxyRect = new Rect({
  71846. shape: {
  71847. x: -1,
  71848. y: -1,
  71849. width: 2,
  71850. height: 2
  71851. }
  71852. });
  71853. var TooltipView =
  71854. /** @class */
  71855. function (_super) {
  71856. __extends(TooltipView, _super);
  71857. function TooltipView() {
  71858. var _this = _super !== null && _super.apply(this, arguments) || this;
  71859. _this.type = TooltipView.type;
  71860. return _this;
  71861. }
  71862. TooltipView.prototype.init = function (ecModel, api) {
  71863. if (env.node || !api.getDom()) {
  71864. return;
  71865. }
  71866. var tooltipModel = ecModel.getComponent('tooltip');
  71867. var renderMode = this._renderMode = getTooltipRenderMode(tooltipModel.get('renderMode'));
  71868. this._tooltipContent = renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api.getDom(), api, {
  71869. appendToBody: tooltipModel.get('appendToBody', true)
  71870. });
  71871. };
  71872. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  71873. if (env.node || !api.getDom()) {
  71874. return;
  71875. } // Reset
  71876. this.group.removeAll();
  71877. this._tooltipModel = tooltipModel;
  71878. this._ecModel = ecModel;
  71879. this._api = api;
  71880. var tooltipContent = this._tooltipContent;
  71881. tooltipContent.update(tooltipModel);
  71882. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  71883. this._initGlobalListener();
  71884. this._keepShow(); // PENDING
  71885. // `mousemove` event will be triggered very frequently when the mouse moves fast,
  71886. // which causes that the `updatePosition` function was also called frequently.
  71887. // In Chrome with devtools open and Firefox, tooltip looks laggy and shakes. See #14695 #16101
  71888. // To avoid frequent triggering,
  71889. // consider throttling it in 50ms when transition is enabled
  71890. if (this._renderMode !== 'richText' && tooltipModel.get('transitionDuration')) {
  71891. createOrUpdate(this, '_updatePosition', 50, 'fixRate');
  71892. } else {
  71893. clear(this, '_updatePosition');
  71894. }
  71895. };
  71896. TooltipView.prototype._initGlobalListener = function () {
  71897. var tooltipModel = this._tooltipModel;
  71898. var triggerOn = tooltipModel.get('triggerOn');
  71899. register('itemTooltip', this._api, bind(function (currTrigger, e, dispatchAction) {
  71900. // If 'none', it is not controlled by mouse totally.
  71901. if (triggerOn !== 'none') {
  71902. if (triggerOn.indexOf(currTrigger) >= 0) {
  71903. this._tryShow(e, dispatchAction);
  71904. } else if (currTrigger === 'leave') {
  71905. this._hide(dispatchAction);
  71906. }
  71907. }
  71908. }, this));
  71909. };
  71910. TooltipView.prototype._keepShow = function () {
  71911. var tooltipModel = this._tooltipModel;
  71912. var ecModel = this._ecModel;
  71913. var api = this._api;
  71914. var triggerOn = tooltipModel.get('triggerOn'); // Try to keep the tooltip show when refreshing
  71915. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  71916. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  71917. // which is not expected.
  71918. && triggerOn !== 'none' && triggerOn !== 'click') {
  71919. var self_1 = this;
  71920. clearTimeout(this._refreshUpdateTimeout);
  71921. this._refreshUpdateTimeout = setTimeout(function () {
  71922. // Show tip next tick after other charts are rendered
  71923. // In case highlight action has wrong result
  71924. // FIXME
  71925. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  71926. x: self_1._lastX,
  71927. y: self_1._lastY,
  71928. dataByCoordSys: self_1._lastDataByCoordSys
  71929. });
  71930. });
  71931. }
  71932. };
  71933. /**
  71934. * Show tip manually by
  71935. * dispatchAction({
  71936. * type: 'showTip',
  71937. * x: 10,
  71938. * y: 10
  71939. * });
  71940. * Or
  71941. * dispatchAction({
  71942. * type: 'showTip',
  71943. * seriesIndex: 0,
  71944. * dataIndex or dataIndexInside or name
  71945. * });
  71946. *
  71947. * TODO Batch
  71948. */
  71949. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  71950. if (payload.from === this.uid || env.node || !api.getDom()) {
  71951. return;
  71952. }
  71953. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  71954. this._ticket = ''; // When triggered from axisPointer.
  71955. var dataByCoordSys = payload.dataByCoordSys;
  71956. var cmptRef = findComponentReference(payload, ecModel, api);
  71957. if (cmptRef) {
  71958. var rect = cmptRef.el.getBoundingRect().clone();
  71959. rect.applyTransform(cmptRef.el.transform);
  71960. this._tryShow({
  71961. offsetX: rect.x + rect.width / 2,
  71962. offsetY: rect.y + rect.height / 2,
  71963. target: cmptRef.el,
  71964. position: payload.position,
  71965. // When manully trigger, the mouse is not on the el, so we'd better to
  71966. // position tooltip on the bottom of the el and display arrow is possible.
  71967. positionDefault: 'bottom'
  71968. }, dispatchAction);
  71969. } else if (payload.tooltip && payload.x != null && payload.y != null) {
  71970. var el = proxyRect;
  71971. el.x = payload.x;
  71972. el.y = payload.y;
  71973. el.update();
  71974. getECData(el).tooltipConfig = {
  71975. name: null,
  71976. option: payload.tooltip
  71977. }; // Manually show tooltip while view is not using zrender elements.
  71978. this._tryShow({
  71979. offsetX: payload.x,
  71980. offsetY: payload.y,
  71981. target: el
  71982. }, dispatchAction);
  71983. } else if (dataByCoordSys) {
  71984. this._tryShow({
  71985. offsetX: payload.x,
  71986. offsetY: payload.y,
  71987. position: payload.position,
  71988. dataByCoordSys: dataByCoordSys,
  71989. tooltipOption: payload.tooltipOption
  71990. }, dispatchAction);
  71991. } else if (payload.seriesIndex != null) {
  71992. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  71993. return;
  71994. }
  71995. var pointInfo = findPointFromSeries(payload, ecModel);
  71996. var cx = pointInfo.point[0];
  71997. var cy = pointInfo.point[1];
  71998. if (cx != null && cy != null) {
  71999. this._tryShow({
  72000. offsetX: cx,
  72001. offsetY: cy,
  72002. target: pointInfo.el,
  72003. position: payload.position,
  72004. // When manully trigger, the mouse is not on the el, so we'd better to
  72005. // position tooltip on the bottom of the el and display arrow is possible.
  72006. positionDefault: 'bottom'
  72007. }, dispatchAction);
  72008. }
  72009. } else if (payload.x != null && payload.y != null) {
  72010. // FIXME
  72011. // should wrap dispatchAction like `axisPointer/globalListener` ?
  72012. api.dispatchAction({
  72013. type: 'updateAxisPointer',
  72014. x: payload.x,
  72015. y: payload.y
  72016. });
  72017. this._tryShow({
  72018. offsetX: payload.x,
  72019. offsetY: payload.y,
  72020. position: payload.position,
  72021. target: api.getZr().findHover(payload.x, payload.y).target
  72022. }, dispatchAction);
  72023. }
  72024. };
  72025. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  72026. var tooltipContent = this._tooltipContent;
  72027. if (this._tooltipModel) {
  72028. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  72029. }
  72030. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  72031. if (payload.from !== this.uid) {
  72032. this._hide(makeDispatchAction$1(payload, api));
  72033. }
  72034. }; // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  72035. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  72036. // and tooltip.
  72037. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  72038. var seriesIndex = payload.seriesIndex;
  72039. var dataIndex = payload.dataIndex; // @ts-ignore
  72040. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  72041. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  72042. return;
  72043. }
  72044. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  72045. if (!seriesModel) {
  72046. return;
  72047. }
  72048. var data = seriesModel.getData();
  72049. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model], this._tooltipModel);
  72050. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  72051. return;
  72052. }
  72053. api.dispatchAction({
  72054. type: 'updateAxisPointer',
  72055. seriesIndex: seriesIndex,
  72056. dataIndex: dataIndex,
  72057. position: payload.position
  72058. });
  72059. return true;
  72060. };
  72061. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  72062. var el = e.target;
  72063. var tooltipModel = this._tooltipModel;
  72064. if (!tooltipModel) {
  72065. return;
  72066. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  72067. this._lastX = e.offsetX;
  72068. this._lastY = e.offsetY;
  72069. var dataByCoordSys = e.dataByCoordSys;
  72070. if (dataByCoordSys && dataByCoordSys.length) {
  72071. this._showAxisTooltip(dataByCoordSys, e);
  72072. } else if (el) {
  72073. this._lastDataByCoordSys = null;
  72074. var seriesDispatcher_1;
  72075. var cmptDispatcher_1;
  72076. findEventDispatcher(el, function (target) {
  72077. // Always show item tooltip if mouse is on the element with dataIndex
  72078. if (getECData(target).dataIndex != null) {
  72079. seriesDispatcher_1 = target;
  72080. return true;
  72081. } // Tooltip provided directly. Like legend.
  72082. if (getECData(target).tooltipConfig != null) {
  72083. cmptDispatcher_1 = target;
  72084. return true;
  72085. }
  72086. }, true);
  72087. if (seriesDispatcher_1) {
  72088. this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction);
  72089. } else if (cmptDispatcher_1) {
  72090. this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction);
  72091. } else {
  72092. this._hide(dispatchAction);
  72093. }
  72094. } else {
  72095. this._lastDataByCoordSys = null;
  72096. this._hide(dispatchAction);
  72097. }
  72098. };
  72099. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  72100. // showDelay is used in this case: tooltip.enterable is set
  72101. // as true. User intent to move mouse into tooltip and click
  72102. // something. `showDelay` makes it easier to enter the content
  72103. // but tooltip do not move immediately.
  72104. var delay = tooltipModel.get('showDelay');
  72105. cb = bind(cb, this);
  72106. clearTimeout(this._showTimout);
  72107. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  72108. };
  72109. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  72110. var ecModel = this._ecModel;
  72111. var globalTooltipModel = this._tooltipModel;
  72112. var point = [e.offsetX, e.offsetY];
  72113. var singleTooltipModel = buildTooltipModel([e.tooltipOption], globalTooltipModel);
  72114. var renderMode = this._renderMode;
  72115. var cbParamsList = [];
  72116. var articleMarkup = createTooltipMarkup('section', {
  72117. blocks: [],
  72118. noHeader: true
  72119. }); // Only for legacy: `Serise['formatTooltip']` returns a string.
  72120. var markupTextArrLegacy = [];
  72121. var markupStyleCreator = new TooltipMarkupStyleCreator();
  72122. each(dataByCoordSys, function (itemCoordSys) {
  72123. each(itemCoordSys.dataByAxis, function (axisItem) {
  72124. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  72125. var axisValue = axisItem.value;
  72126. if (!axisModel || axisValue == null) {
  72127. return;
  72128. }
  72129. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  72130. var axisSectionMarkup = createTooltipMarkup('section', {
  72131. header: axisValueLabel,
  72132. noHeader: !trim(axisValueLabel),
  72133. sortBlocks: true,
  72134. blocks: []
  72135. });
  72136. articleMarkup.blocks.push(axisSectionMarkup);
  72137. each(axisItem.seriesDataIndices, function (idxItem) {
  72138. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  72139. var dataIndex = idxItem.dataIndexInside;
  72140. var cbParams = series.getDataParams(dataIndex); // Can't find data.
  72141. if (cbParams.dataIndex < 0) {
  72142. return;
  72143. }
  72144. cbParams.axisDim = axisItem.axisDim;
  72145. cbParams.axisIndex = axisItem.axisIndex;
  72146. cbParams.axisType = axisItem.axisType;
  72147. cbParams.axisId = axisItem.axisId;
  72148. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  72149. value: axisValue
  72150. });
  72151. cbParams.axisValueLabel = axisValueLabel; // Pre-create marker style for makers. Users can assemble richText
  72152. // text in `formatter` callback and use those markers style.
  72153. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  72154. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  72155. var frag = seriesTooltipResult.frag;
  72156. if (frag) {
  72157. var valueFormatter = buildTooltipModel([series], globalTooltipModel).get('valueFormatter');
  72158. axisSectionMarkup.blocks.push(valueFormatter ? extend({
  72159. valueFormatter: valueFormatter
  72160. }, frag) : frag);
  72161. }
  72162. if (seriesTooltipResult.text) {
  72163. markupTextArrLegacy.push(seriesTooltipResult.text);
  72164. }
  72165. cbParamsList.push(cbParams);
  72166. });
  72167. });
  72168. }); // In most cases, the second axis is displays upper on the first one.
  72169. // So we reverse it to look better.
  72170. articleMarkup.blocks.reverse();
  72171. markupTextArrLegacy.reverse();
  72172. var positionExpr = e.position;
  72173. var orderMode = singleTooltipModel.get('order');
  72174. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  72175. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  72176. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  72177. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  72178. this._showOrMove(singleTooltipModel, function () {
  72179. if (this._updateContentNotChangedOnAxis(dataByCoordSys, cbParamsList)) {
  72180. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  72181. } else {
  72182. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  72183. }
  72184. }); // Do not trigger events here, because this branch only be entered
  72185. // from dispatchAction.
  72186. };
  72187. TooltipView.prototype._showSeriesItemTooltip = function (e, dispatcher, dispatchAction) {
  72188. var ecModel = this._ecModel;
  72189. var ecData = getECData(dispatcher); // Use dataModel in element if possible
  72190. // Used when mouseover on a element like markPoint or edge
  72191. // In which case, the data is not main data in series.
  72192. var seriesIndex = ecData.seriesIndex;
  72193. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  72194. var dataModel = ecData.dataModel || seriesModel;
  72195. var dataIndex = ecData.dataIndex;
  72196. var dataType = ecData.dataType;
  72197. var data = dataModel.getData(dataType);
  72198. var renderMode = this._renderMode;
  72199. var positionDefault = e.positionDefault;
  72200. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model], this._tooltipModel, positionDefault ? {
  72201. position: positionDefault
  72202. } : null);
  72203. var tooltipTrigger = tooltipModel.get('trigger');
  72204. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  72205. return;
  72206. }
  72207. var params = dataModel.getDataParams(dataIndex, dataType);
  72208. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Pre-create marker style for makers. Users can assemble richText
  72209. // text in `formatter` callback and use those markers style.
  72210. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  72211. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  72212. var orderMode = tooltipModel.get('order');
  72213. var valueFormatter = tooltipModel.get('valueFormatter');
  72214. var frag = seriesTooltipResult.frag;
  72215. var markupText = frag ? buildTooltipMarkup(valueFormatter ? extend({
  72216. valueFormatter: valueFormatter
  72217. }, frag) : frag, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.text;
  72218. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  72219. this._showOrMove(tooltipModel, function () {
  72220. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  72221. }); // FIXME
  72222. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  72223. dispatchAction({
  72224. type: 'showTip',
  72225. dataIndexInside: dataIndex,
  72226. dataIndex: data.getRawIndex(dataIndex),
  72227. seriesIndex: seriesIndex,
  72228. from: this.uid
  72229. });
  72230. };
  72231. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  72232. var ecData = getECData(el);
  72233. var tooltipConfig = ecData.tooltipConfig;
  72234. var tooltipOpt = tooltipConfig.option || {};
  72235. if (isString(tooltipOpt)) {
  72236. var content = tooltipOpt;
  72237. tooltipOpt = {
  72238. content: content,
  72239. // Fixed formatter
  72240. formatter: content
  72241. };
  72242. }
  72243. var tooltipModelCascade = [tooltipOpt];
  72244. var cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex);
  72245. if (cmpt) {
  72246. tooltipModelCascade.push(cmpt);
  72247. } // In most cases, component tooltip formatter has different params with series tooltip formatter,
  72248. // so that they cannot share the same formatter. Since the global tooltip formatter is used for series
  72249. // by convention, we do not use it as the default formatter for component.
  72250. tooltipModelCascade.push({
  72251. formatter: tooltipOpt.content
  72252. });
  72253. var positionDefault = e.positionDefault;
  72254. var subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? {
  72255. position: positionDefault
  72256. } : null);
  72257. var defaultHtml = subTooltipModel.get('content');
  72258. var asyncTicket = Math.random() + ''; // PENDING: this case do not support richText style yet.
  72259. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Do not check whether `trigger` is 'none' here, because `trigger`
  72260. // only works on coordinate system. In fact, we have not found case
  72261. // that requires setting `trigger` nothing on component yet.
  72262. this._showOrMove(subTooltipModel, function () {
  72263. // Use formatterParams from element defined in component
  72264. // Avoid users modify it.
  72265. var formatterParams = clone(subTooltipModel.get('formatterParams') || {});
  72266. this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  72267. }); // If not dispatch showTip, tip may be hide triggered by axis.
  72268. dispatchAction({
  72269. type: 'showTip',
  72270. from: this.uid
  72271. });
  72272. };
  72273. TooltipView.prototype._showTooltipContent = function ( // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  72274. // Instead of top level tooltip.
  72275. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  72276. // Reset ticket
  72277. this._ticket = '';
  72278. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  72279. return;
  72280. }
  72281. var tooltipContent = this._tooltipContent;
  72282. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  72283. var formatter = tooltipModel.get('formatter');
  72284. positionExpr = positionExpr || tooltipModel.get('position');
  72285. var html = defaultHtml;
  72286. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  72287. var nearPointColor = nearPoint.color;
  72288. if (formatter) {
  72289. if (isString(formatter)) {
  72290. var useUTC = tooltipModel.ecModel.get('useUTC');
  72291. var params0 = isArray(params) ? params[0] : params;
  72292. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  72293. html = formatter;
  72294. if (isTimeAxis) {
  72295. html = format(params0.axisValue, html, useUTC);
  72296. }
  72297. html = formatTpl(html, params, true);
  72298. } else if (isFunction(formatter)) {
  72299. var callback = bind(function (cbTicket, html) {
  72300. if (cbTicket === this._ticket) {
  72301. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  72302. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  72303. }
  72304. }, this);
  72305. this._ticket = asyncTicket;
  72306. html = formatter(params, asyncTicket, callback);
  72307. } else {
  72308. html = formatter;
  72309. }
  72310. }
  72311. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  72312. tooltipContent.show(tooltipModel, nearPointColor);
  72313. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  72314. };
  72315. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  72316. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  72317. return {
  72318. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  72319. };
  72320. }
  72321. if (!isArray(tooltipDataParams)) {
  72322. return {
  72323. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  72324. };
  72325. }
  72326. };
  72327. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x, // Mouse x
  72328. y, // Mouse y
  72329. content, params, el) {
  72330. var viewWidth = this._api.getWidth();
  72331. var viewHeight = this._api.getHeight();
  72332. positionExpr = positionExpr || tooltipModel.get('position');
  72333. var contentSize = content.getSize();
  72334. var align = tooltipModel.get('align');
  72335. var vAlign = tooltipModel.get('verticalAlign');
  72336. var rect = el && el.getBoundingRect().clone();
  72337. el && rect.applyTransform(el.transform);
  72338. if (isFunction(positionExpr)) {
  72339. // Callback of position can be an array or a string specify the position
  72340. positionExpr = positionExpr([x, y], params, content.el, rect, {
  72341. viewSize: [viewWidth, viewHeight],
  72342. contentSize: contentSize.slice()
  72343. });
  72344. }
  72345. if (isArray(positionExpr)) {
  72346. x = parsePercent$1(positionExpr[0], viewWidth);
  72347. y = parsePercent$1(positionExpr[1], viewHeight);
  72348. } else if (isObject(positionExpr)) {
  72349. var boxLayoutPosition = positionExpr;
  72350. boxLayoutPosition.width = contentSize[0];
  72351. boxLayoutPosition.height = contentSize[1];
  72352. var layoutRect = getLayoutRect(boxLayoutPosition, {
  72353. width: viewWidth,
  72354. height: viewHeight
  72355. });
  72356. x = layoutRect.x;
  72357. y = layoutRect.y;
  72358. align = null; // When positionExpr is left/top/right/bottom,
  72359. // align and verticalAlign will not work.
  72360. vAlign = null;
  72361. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  72362. else if (isString(positionExpr) && el) {
  72363. var pos = calcTooltipPosition(positionExpr, rect, contentSize, tooltipModel.get('borderWidth'));
  72364. x = pos[0];
  72365. y = pos[1];
  72366. } else {
  72367. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  72368. x = pos[0];
  72369. y = pos[1];
  72370. }
  72371. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  72372. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  72373. if (shouldTooltipConfine(tooltipModel)) {
  72374. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  72375. x = pos[0];
  72376. y = pos[1];
  72377. }
  72378. content.moveTo(x, y);
  72379. }; // FIXME
  72380. // Should we remove this but leave this to user?
  72381. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys, cbParamsList) {
  72382. var lastCoordSys = this._lastDataByCoordSys;
  72383. var lastCbParamsList = this._cbParamsList;
  72384. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  72385. contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  72386. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  72387. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  72388. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  72389. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  72390. contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
  72391. var thisItem = thisDataByAxis[indexAxis] || {};
  72392. var lastIndices = lastItem.seriesDataIndices || [];
  72393. var newIndices = thisItem.seriesDataIndices || [];
  72394. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  72395. contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
  72396. var newIdxItem = newIndices[j];
  72397. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  72398. }); // check is cbParams data value changed
  72399. lastCbParamsList && each(lastItem.seriesDataIndices, function (idxItem) {
  72400. var seriesIdx = idxItem.seriesIndex;
  72401. var cbParams = cbParamsList[seriesIdx];
  72402. var lastCbParams = lastCbParamsList[seriesIdx];
  72403. if (cbParams && lastCbParams && lastCbParams.data !== cbParams.data) {
  72404. contentNotChanged = false;
  72405. }
  72406. });
  72407. });
  72408. });
  72409. this._lastDataByCoordSys = dataByCoordSys;
  72410. this._cbParamsList = cbParamsList;
  72411. return !!contentNotChanged;
  72412. };
  72413. TooltipView.prototype._hide = function (dispatchAction) {
  72414. // Do not directly hideLater here, because this behavior may be prevented
  72415. // in dispatchAction when showTip is dispatched.
  72416. // FIXME
  72417. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  72418. this._lastDataByCoordSys = null;
  72419. dispatchAction({
  72420. type: 'hideTip',
  72421. from: this.uid
  72422. });
  72423. };
  72424. TooltipView.prototype.dispose = function (ecModel, api) {
  72425. if (env.node || !api.getDom()) {
  72426. return;
  72427. }
  72428. clear(this, '_updatePosition');
  72429. this._tooltipContent.dispose();
  72430. unregister('itemTooltip', api);
  72431. };
  72432. TooltipView.type = 'tooltip';
  72433. return TooltipView;
  72434. }(ComponentView);
  72435. /**
  72436. * From top to bottom. (the last one should be globalTooltipModel);
  72437. */
  72438. function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) {
  72439. // Last is always tooltip model.
  72440. var ecModel = globalTooltipModel.ecModel;
  72441. var resultModel;
  72442. if (defaultTooltipOption) {
  72443. resultModel = new Model(defaultTooltipOption, ecModel, ecModel);
  72444. resultModel = new Model(globalTooltipModel.option, resultModel, ecModel);
  72445. } else {
  72446. resultModel = globalTooltipModel;
  72447. }
  72448. for (var i = modelCascade.length - 1; i >= 0; i--) {
  72449. var tooltipOpt = modelCascade[i];
  72450. if (tooltipOpt) {
  72451. if (tooltipOpt instanceof Model) {
  72452. tooltipOpt = tooltipOpt.get('tooltip', true);
  72453. } // In each data item tooltip can be simply write:
  72454. // {
  72455. // value: 10,
  72456. // tooltip: 'Something you need to know'
  72457. // }
  72458. if (isString(tooltipOpt)) {
  72459. tooltipOpt = {
  72460. formatter: tooltipOpt
  72461. };
  72462. }
  72463. if (tooltipOpt) {
  72464. resultModel = new Model(tooltipOpt, resultModel, ecModel);
  72465. }
  72466. }
  72467. }
  72468. return resultModel;
  72469. }
  72470. function makeDispatchAction$1(payload, api) {
  72471. return payload.dispatchAction || bind(api.dispatchAction, api);
  72472. }
  72473. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  72474. var size = content.getSize();
  72475. var width = size[0];
  72476. var height = size[1];
  72477. if (gapH != null) {
  72478. // Add extra 2 pixels for this case:
  72479. // At present the "values" in default tooltip are using CSS `float: right`.
  72480. // When the right edge of the tooltip box is on the right side of the
  72481. // viewport, the `float` layout might push the "values" to the second line.
  72482. if (x + width + gapH + 2 > viewWidth) {
  72483. x -= width + gapH;
  72484. } else {
  72485. x += gapH;
  72486. }
  72487. }
  72488. if (gapV != null) {
  72489. if (y + height + gapV > viewHeight) {
  72490. y -= height + gapV;
  72491. } else {
  72492. y += gapV;
  72493. }
  72494. }
  72495. return [x, y];
  72496. }
  72497. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  72498. var size = content.getSize();
  72499. var width = size[0];
  72500. var height = size[1];
  72501. x = Math.min(x + width, viewWidth) - width;
  72502. y = Math.min(y + height, viewHeight) - height;
  72503. x = Math.max(x, 0);
  72504. y = Math.max(y, 0);
  72505. return [x, y];
  72506. }
  72507. function calcTooltipPosition(position, rect, contentSize, borderWidth) {
  72508. var domWidth = contentSize[0];
  72509. var domHeight = contentSize[1];
  72510. var offset = Math.ceil(Math.SQRT2 * borderWidth) + 8;
  72511. var x = 0;
  72512. var y = 0;
  72513. var rectWidth = rect.width;
  72514. var rectHeight = rect.height;
  72515. switch (position) {
  72516. case 'inside':
  72517. x = rect.x + rectWidth / 2 - domWidth / 2;
  72518. y = rect.y + rectHeight / 2 - domHeight / 2;
  72519. break;
  72520. case 'top':
  72521. x = rect.x + rectWidth / 2 - domWidth / 2;
  72522. y = rect.y - domHeight - offset;
  72523. break;
  72524. case 'bottom':
  72525. x = rect.x + rectWidth / 2 - domWidth / 2;
  72526. y = rect.y + rectHeight + offset;
  72527. break;
  72528. case 'left':
  72529. x = rect.x - domWidth - offset;
  72530. y = rect.y + rectHeight / 2 - domHeight / 2;
  72531. break;
  72532. case 'right':
  72533. x = rect.x + rectWidth + offset;
  72534. y = rect.y + rectHeight / 2 - domHeight / 2;
  72535. }
  72536. return [x, y];
  72537. }
  72538. function isCenterAlign(align) {
  72539. return align === 'center' || align === 'middle';
  72540. }
  72541. /**
  72542. * Find target component by payload like:
  72543. * ```js
  72544. * { legendId: 'some_id', name: 'xxx' }
  72545. * { toolboxIndex: 1, name: 'xxx' }
  72546. * { geoName: 'some_name', name: 'xxx' }
  72547. * ```
  72548. * PENDING: at present only
  72549. *
  72550. * If not found, return null/undefined.
  72551. */
  72552. function findComponentReference(payload, ecModel, api) {
  72553. var queryOptionMap = preParseFinder(payload).queryOptionMap;
  72554. var componentMainType = queryOptionMap.keys()[0];
  72555. if (!componentMainType || componentMainType === 'series') {
  72556. return;
  72557. }
  72558. var queryResult = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), {
  72559. useDefault: false,
  72560. enableAll: false,
  72561. enableNone: false
  72562. });
  72563. var model = queryResult.models[0];
  72564. if (!model) {
  72565. return;
  72566. }
  72567. var view = api.getViewOfComponentModel(model);
  72568. var el;
  72569. view.group.traverse(function (subEl) {
  72570. var tooltipConfig = getECData(subEl).tooltipConfig;
  72571. if (tooltipConfig && tooltipConfig.name === payload.name) {
  72572. el = subEl;
  72573. return true; // stop
  72574. }
  72575. });
  72576. if (el) {
  72577. return {
  72578. componentMainType: componentMainType,
  72579. componentIndex: model.componentIndex,
  72580. el: el
  72581. };
  72582. }
  72583. }
  72584. function install$A(registers) {
  72585. use(install$s);
  72586. registers.registerComponentModel(TooltipModel);
  72587. registers.registerComponentView(TooltipView);
  72588. /**
  72589. * @action
  72590. * @property {string} type
  72591. * @property {number} seriesIndex
  72592. * @property {number} dataIndex
  72593. * @property {number} [x]
  72594. * @property {number} [y]
  72595. */
  72596. registers.registerAction({
  72597. type: 'showTip',
  72598. event: 'showTip',
  72599. update: 'tooltip:manuallyShowTip'
  72600. }, noop);
  72601. registers.registerAction({
  72602. type: 'hideTip',
  72603. event: 'hideTip',
  72604. update: 'tooltip:manuallyHideTip'
  72605. }, noop);
  72606. }
  72607. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  72608. function brushPreprocessor(option, isNew) {
  72609. var brushComponents = normalizeToArray(option ? option.brush : []);
  72610. if (!brushComponents.length) {
  72611. return;
  72612. }
  72613. var brushComponentSpecifiedBtns = [];
  72614. each(brushComponents, function (brushOpt) {
  72615. var tbs = brushOpt.hasOwnProperty('toolbox') ? brushOpt.toolbox : [];
  72616. if (tbs instanceof Array) {
  72617. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  72618. }
  72619. });
  72620. var toolbox = option && option.toolbox;
  72621. if (isArray(toolbox)) {
  72622. toolbox = toolbox[0];
  72623. }
  72624. if (!toolbox) {
  72625. toolbox = {
  72626. feature: {}
  72627. };
  72628. option.toolbox = [toolbox];
  72629. }
  72630. var toolboxFeature = toolbox.feature || (toolbox.feature = {});
  72631. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  72632. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  72633. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  72634. removeDuplicate(brushTypes);
  72635. if (isNew && !brushTypes.length) {
  72636. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  72637. }
  72638. }
  72639. function removeDuplicate(arr) {
  72640. var map = {};
  72641. each(arr, function (val) {
  72642. map[val] = 1;
  72643. });
  72644. arr.length = 0;
  72645. each(map, function (flag, val) {
  72646. arr.push(val);
  72647. });
  72648. }
  72649. var each$b = each;
  72650. function hasKeys(obj) {
  72651. if (obj) {
  72652. for (var name_1 in obj) {
  72653. if (obj.hasOwnProperty(name_1)) {
  72654. return true;
  72655. }
  72656. }
  72657. }
  72658. }
  72659. function createVisualMappings(option, stateList, supplementVisualOption) {
  72660. var visualMappings = {};
  72661. each$b(stateList, function (state) {
  72662. var mappings = visualMappings[state] = createMappings();
  72663. each$b(option[state], function (visualData, visualType) {
  72664. if (!VisualMapping.isValidType(visualType)) {
  72665. return;
  72666. }
  72667. var mappingOption = {
  72668. type: visualType,
  72669. visual: visualData
  72670. };
  72671. supplementVisualOption && supplementVisualOption(mappingOption, state);
  72672. mappings[visualType] = new VisualMapping(mappingOption); // Prepare a alpha for opacity, for some case that opacity
  72673. // is not supported, such as rendering using gradient color.
  72674. if (visualType === 'opacity') {
  72675. mappingOption = clone(mappingOption);
  72676. mappingOption.type = 'colorAlpha';
  72677. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  72678. }
  72679. });
  72680. });
  72681. return visualMappings;
  72682. function createMappings() {
  72683. var Creater = function () {}; // Make sure hidden fields will not be visited by
  72684. // object iteration (with hasOwnProperty checking).
  72685. Creater.prototype.__hidden = Creater.prototype;
  72686. var obj = new Creater();
  72687. return obj;
  72688. }
  72689. }
  72690. function replaceVisualOption(thisOption, newOption, keys) {
  72691. // Visual attributes merge is not supported, otherwise it
  72692. // brings overcomplicated merge logic. See #2853. So if
  72693. // newOption has anyone of these keys, all of these keys
  72694. // will be reset. Otherwise, all keys remain.
  72695. var has;
  72696. each(keys, function (key) {
  72697. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72698. has = true;
  72699. }
  72700. });
  72701. has && each(keys, function (key) {
  72702. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72703. thisOption[key] = clone(newOption[key]);
  72704. } else {
  72705. delete thisOption[key];
  72706. }
  72707. });
  72708. }
  72709. /**
  72710. * @param stateList
  72711. * @param visualMappings
  72712. * @param list
  72713. * @param getValueState param: valueOrIndex, return: state.
  72714. * @param scope Scope for getValueState
  72715. * @param dimension Concrete dimension, if used.
  72716. */
  72717. // ???! handle brush?
  72718. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  72719. var visualTypesMap = {};
  72720. each(stateList, function (state) {
  72721. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72722. visualTypesMap[state] = visualTypes;
  72723. });
  72724. var dataIndex;
  72725. function getVisual(key) {
  72726. return getItemVisualFromData(data, dataIndex, key);
  72727. }
  72728. function setVisual(key, value) {
  72729. setItemVisualFromData(data, dataIndex, key, value);
  72730. }
  72731. if (dimension == null) {
  72732. data.each(eachItem);
  72733. } else {
  72734. data.each([dimension], eachItem);
  72735. }
  72736. function eachItem(valueOrIndex, index) {
  72737. dataIndex = dimension == null ? valueOrIndex // First argument is index
  72738. : index;
  72739. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  72740. // @ts-ignore
  72741. if (rawDataItem && rawDataItem.visualMap === false) {
  72742. return;
  72743. }
  72744. var valueState = getValueState.call(scope, valueOrIndex);
  72745. var mappings = visualMappings[valueState];
  72746. var visualTypes = visualTypesMap[valueState];
  72747. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72748. var type = visualTypes[i];
  72749. mappings[type] && mappings[type].applyVisual(valueOrIndex, getVisual, setVisual);
  72750. }
  72751. }
  72752. }
  72753. /**
  72754. * @param data
  72755. * @param stateList
  72756. * @param visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  72757. * @param getValueState param: valueOrIndex, return: state.
  72758. * @param dim dimension or dimension index.
  72759. */
  72760. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  72761. var visualTypesMap = {};
  72762. each(stateList, function (state) {
  72763. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72764. visualTypesMap[state] = visualTypes;
  72765. });
  72766. return {
  72767. progress: function progress(params, data) {
  72768. var dimIndex;
  72769. if (dim != null) {
  72770. dimIndex = data.getDimensionIndex(dim);
  72771. }
  72772. function getVisual(key) {
  72773. return getItemVisualFromData(data, dataIndex, key);
  72774. }
  72775. function setVisual(key, value) {
  72776. setItemVisualFromData(data, dataIndex, key, value);
  72777. }
  72778. var dataIndex;
  72779. var store = data.getStore();
  72780. while ((dataIndex = params.next()) != null) {
  72781. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  72782. // @ts-ignore
  72783. if (rawDataItem && rawDataItem.visualMap === false) {
  72784. continue;
  72785. }
  72786. var value = dim != null ? store.get(dimIndex, dataIndex) : dataIndex;
  72787. var valueState = getValueState(value);
  72788. var mappings = visualMappings[valueState];
  72789. var visualTypes = visualTypesMap[valueState];
  72790. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72791. var type = visualTypes[i];
  72792. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  72793. }
  72794. }
  72795. }
  72796. };
  72797. }
  72798. function makeBrushCommonSelectorForSeries(area) {
  72799. var brushType = area.brushType; // Do not use function binding or curry for performance.
  72800. var selectors = {
  72801. point: function (itemLayout) {
  72802. return selector[brushType].point(itemLayout, selectors, area);
  72803. },
  72804. rect: function (itemLayout) {
  72805. return selector[brushType].rect(itemLayout, selectors, area);
  72806. }
  72807. };
  72808. return selectors;
  72809. }
  72810. var selector = {
  72811. lineX: getLineSelectors(0),
  72812. lineY: getLineSelectors(1),
  72813. rect: {
  72814. point: function (itemLayout, selectors, area) {
  72815. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  72816. },
  72817. rect: function (itemLayout, selectors, area) {
  72818. return itemLayout && area.boundingRect.intersect(itemLayout);
  72819. }
  72820. },
  72821. polygon: {
  72822. point: function (itemLayout, selectors, area) {
  72823. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]) && contain$2(area.range, itemLayout[0], itemLayout[1]);
  72824. },
  72825. rect: function (itemLayout, selectors, area) {
  72826. var points = area.range;
  72827. if (!itemLayout || points.length <= 1) {
  72828. return false;
  72829. }
  72830. var x = itemLayout.x;
  72831. var y = itemLayout.y;
  72832. var width = itemLayout.width;
  72833. var height = itemLayout.height;
  72834. var p = points[0];
  72835. if (contain$2(points, x, y) || contain$2(points, x + width, y) || contain$2(points, x, y + height) || contain$2(points, x + width, y + height) || BoundingRect.create(itemLayout).contain(p[0], p[1]) || linePolygonIntersect(x, y, x + width, y, points) || linePolygonIntersect(x, y, x, y + height, points) || linePolygonIntersect(x + width, y, x + width, y + height, points) || linePolygonIntersect(x, y + height, x + width, y + height, points)) {
  72836. return true;
  72837. }
  72838. }
  72839. }
  72840. };
  72841. function getLineSelectors(xyIndex) {
  72842. var xy = ['x', 'y'];
  72843. var wh = ['width', 'height'];
  72844. return {
  72845. point: function (itemLayout, selectors, area) {
  72846. if (itemLayout) {
  72847. var range = area.range;
  72848. var p = itemLayout[xyIndex];
  72849. return inLineRange(p, range);
  72850. }
  72851. },
  72852. rect: function (itemLayout, selectors, area) {
  72853. if (itemLayout) {
  72854. var range = area.range;
  72855. var layoutRange = [itemLayout[xy[xyIndex]], itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]];
  72856. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  72857. return inLineRange(layoutRange[0], range) || inLineRange(layoutRange[1], range) || inLineRange(range[0], layoutRange) || inLineRange(range[1], layoutRange);
  72858. }
  72859. }
  72860. };
  72861. }
  72862. function inLineRange(p, range) {
  72863. return range[0] <= p && p <= range[1];
  72864. }
  72865. var STATE_LIST = ['inBrush', 'outOfBrush'];
  72866. var DISPATCH_METHOD = '__ecBrushSelect';
  72867. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  72868. function layoutCovers(ecModel) {
  72869. ecModel.eachComponent({
  72870. mainType: 'brush'
  72871. }, function (brushModel) {
  72872. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  72873. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  72874. });
  72875. }
  72876. /**
  72877. * Register the visual encoding if this modules required.
  72878. */
  72879. function brushVisual(ecModel, api, payload) {
  72880. var brushSelected = [];
  72881. var throttleType;
  72882. var throttleDelay;
  72883. ecModel.eachComponent({
  72884. mainType: 'brush'
  72885. }, function (brushModel) {
  72886. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(payload.key === 'brush' ? payload.brushOption : {
  72887. brushType: false
  72888. });
  72889. });
  72890. layoutCovers(ecModel);
  72891. ecModel.eachComponent({
  72892. mainType: 'brush'
  72893. }, function (brushModel, brushIndex) {
  72894. var thisBrushSelected = {
  72895. brushId: brushModel.id,
  72896. brushIndex: brushIndex,
  72897. brushName: brushModel.name,
  72898. areas: clone(brushModel.areas),
  72899. selected: []
  72900. }; // Every brush component exists in event params, convenient
  72901. // for user to find by index.
  72902. brushSelected.push(thisBrushSelected);
  72903. var brushOption = brushModel.option;
  72904. var brushLink = brushOption.brushLink;
  72905. var linkedSeriesMap = [];
  72906. var selectedDataIndexForLink = [];
  72907. var rangeInfoBySeries = [];
  72908. var hasBrushExists = false;
  72909. if (!brushIndex) {
  72910. // Only the first throttle setting works.
  72911. throttleType = brushOption.throttleType;
  72912. throttleDelay = brushOption.throttleDelay;
  72913. } // Add boundingRect and selectors to range.
  72914. var areas = map(brushModel.areas, function (area) {
  72915. var builder = boundingRectBuilders[area.brushType];
  72916. var selectableArea = defaults({
  72917. boundingRect: builder ? builder(area) : void 0
  72918. }, area);
  72919. selectableArea.selectors = makeBrushCommonSelectorForSeries(selectableArea);
  72920. return selectableArea;
  72921. });
  72922. var visualMappings = createVisualMappings(brushModel.option, STATE_LIST, function (mappingOption) {
  72923. mappingOption.mappingMethod = 'fixed';
  72924. });
  72925. isArray(brushLink) && each(brushLink, function (seriesIndex) {
  72926. linkedSeriesMap[seriesIndex] = 1;
  72927. });
  72928. function linkOthers(seriesIndex) {
  72929. return brushLink === 'all' || !!linkedSeriesMap[seriesIndex];
  72930. } // If no supported brush or no brush on the series,
  72931. // all visuals should be in original state.
  72932. function brushed(rangeInfoList) {
  72933. return !!rangeInfoList.length;
  72934. }
  72935. /**
  72936. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  72937. *
  72938. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  72939. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  72940. * └!hasBrushExist┘ └nothing.
  72941. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  72942. * └!hasBrushExist┘ └nothing.
  72943. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  72944. * !brushed┘ └nothing.
  72945. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  72946. */
  72947. // Step A
  72948. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  72949. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  72950. seriesModel.subType === 'parallel' ? stepAParallel(seriesModel, seriesIndex) : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  72951. });
  72952. function stepAParallel(seriesModel, seriesIndex) {
  72953. var coordSys = seriesModel.coordinateSystem;
  72954. hasBrushExists = hasBrushExists || coordSys.hasAxisBrushed();
  72955. linkOthers(seriesIndex) && coordSys.eachActiveState(seriesModel.getData(), function (activeState, dataIndex) {
  72956. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  72957. });
  72958. }
  72959. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  72960. if (!seriesModel.brushSelector || brushModelNotControll(brushModel, seriesIndex)) {
  72961. return;
  72962. }
  72963. each(areas, function (area) {
  72964. if (brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)) {
  72965. rangeInfoList.push(area);
  72966. }
  72967. hasBrushExists = hasBrushExists || brushed(rangeInfoList);
  72968. });
  72969. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  72970. var data_1 = seriesModel.getData();
  72971. data_1.each(function (dataIndex) {
  72972. if (checkInRange(seriesModel, rangeInfoList, data_1, dataIndex)) {
  72973. selectedDataIndexForLink[dataIndex] = 1;
  72974. }
  72975. });
  72976. }
  72977. } // Step B
  72978. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  72979. var seriesBrushSelected = {
  72980. seriesId: seriesModel.id,
  72981. seriesIndex: seriesIndex,
  72982. seriesName: seriesModel.name,
  72983. dataIndex: []
  72984. }; // Every series exists in event params, convenient
  72985. // for user to find series by seriesIndex.
  72986. thisBrushSelected.selected.push(seriesBrushSelected);
  72987. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  72988. var data = seriesModel.getData();
  72989. var getValueState = linkOthers(seriesIndex) ? function (dataIndex) {
  72990. return selectedDataIndexForLink[dataIndex] ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  72991. } : function (dataIndex) {
  72992. return checkInRange(seriesModel, rangeInfoList, data, dataIndex) ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  72993. }; // If no supported brush or no brush, all visuals are in original state.
  72994. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList)) && applyVisual(STATE_LIST, visualMappings, data, getValueState);
  72995. });
  72996. });
  72997. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  72998. }
  72999. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  73000. // This event will not be triggered when `setOpion`, otherwise dead lock may
  73001. // triggered when do `setOption` in event listener, which we do not find
  73002. // satisfactory way to solve yet. Some considered resolutions:
  73003. // (a) Diff with prevoius selected data ant only trigger event when changed.
  73004. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  73005. // also detect value changes in selected data) might bring complexity or fragility.
  73006. // (b) Use spectial param like `silent` to suppress event triggering.
  73007. // But such kind of volatile param may be weird in `setOption`.
  73008. if (!payload) {
  73009. return;
  73010. }
  73011. var zr = api.getZr();
  73012. if (zr[DISPATCH_FLAG]) {
  73013. return;
  73014. }
  73015. if (!zr[DISPATCH_METHOD]) {
  73016. zr[DISPATCH_METHOD] = doDispatch;
  73017. }
  73018. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  73019. fn(api, brushSelected);
  73020. }
  73021. function doDispatch(api, brushSelected) {
  73022. if (!api.isDisposed()) {
  73023. var zr = api.getZr();
  73024. zr[DISPATCH_FLAG] = true;
  73025. api.dispatchAction({
  73026. type: 'brushSelect',
  73027. batch: brushSelected
  73028. });
  73029. zr[DISPATCH_FLAG] = false;
  73030. }
  73031. }
  73032. function checkInRange(seriesModel, rangeInfoList, data, dataIndex) {
  73033. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  73034. var area = rangeInfoList[i];
  73035. if (seriesModel.brushSelector(dataIndex, data, area.selectors, area)) {
  73036. return true;
  73037. }
  73038. }
  73039. }
  73040. function brushModelNotControll(brushModel, seriesIndex) {
  73041. var seriesIndices = brushModel.option.seriesIndex;
  73042. return seriesIndices != null && seriesIndices !== 'all' && (isArray(seriesIndices) ? indexOf(seriesIndices, seriesIndex) < 0 : seriesIndex !== seriesIndices);
  73043. }
  73044. var boundingRectBuilders = {
  73045. rect: function (area) {
  73046. return getBoundingRectFromMinMax(area.range);
  73047. },
  73048. polygon: function (area) {
  73049. var minMax;
  73050. var range = area.range;
  73051. for (var i = 0, len = range.length; i < len; i++) {
  73052. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  73053. var rg = range[i];
  73054. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  73055. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  73056. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  73057. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  73058. }
  73059. return minMax && getBoundingRectFromMinMax(minMax);
  73060. }
  73061. };
  73062. function getBoundingRectFromMinMax(minMax) {
  73063. return new BoundingRect(minMax[0][0], minMax[1][0], minMax[0][1] - minMax[0][0], minMax[1][1] - minMax[1][0]);
  73064. }
  73065. var BrushView =
  73066. /** @class */
  73067. function (_super) {
  73068. __extends(BrushView, _super);
  73069. function BrushView() {
  73070. var _this = _super !== null && _super.apply(this, arguments) || this;
  73071. _this.type = BrushView.type;
  73072. return _this;
  73073. }
  73074. BrushView.prototype.init = function (ecModel, api) {
  73075. this.ecModel = ecModel;
  73076. this.api = api;
  73077. this.model;
  73078. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this)).mount();
  73079. };
  73080. BrushView.prototype.render = function (brushModel, ecModel, api, payload) {
  73081. this.model = brushModel;
  73082. this._updateController(brushModel, ecModel, api, payload);
  73083. };
  73084. BrushView.prototype.updateTransform = function (brushModel, ecModel, api, payload) {
  73085. // PENDING: `updateTransform` is a little tricky, whose layout need
  73086. // to be calculate mandatorily and other stages will not be performed.
  73087. // Take care the correctness of the logic. See #11754 .
  73088. layoutCovers(ecModel);
  73089. this._updateController(brushModel, ecModel, api, payload);
  73090. };
  73091. BrushView.prototype.updateVisual = function (brushModel, ecModel, api, payload) {
  73092. this.updateTransform(brushModel, ecModel, api, payload);
  73093. };
  73094. BrushView.prototype.updateView = function (brushModel, ecModel, api, payload) {
  73095. this._updateController(brushModel, ecModel, api, payload);
  73096. };
  73097. BrushView.prototype._updateController = function (brushModel, ecModel, api, payload) {
  73098. // Do not update controller when drawing.
  73099. (!payload || payload.$from !== brushModel.id) && this._brushController.setPanels(brushModel.brushTargetManager.makePanelOpts(api)).enableBrush(brushModel.brushOption).updateCovers(brushModel.areas.slice());
  73100. }; // updateLayout: updateController,
  73101. // updateVisual: updateController,
  73102. BrushView.prototype.dispose = function () {
  73103. this._brushController.dispose();
  73104. };
  73105. BrushView.prototype._onBrush = function (eventParam) {
  73106. var modelId = this.model.id;
  73107. var areas = this.model.brushTargetManager.setOutputRanges(eventParam.areas, this.ecModel); // Action is not dispatched on drag end, because the drag end
  73108. // emits the same params with the last drag move event, and
  73109. // may have some delay when using touch pad, which makes
  73110. // animation not smooth (when using debounce).
  73111. (!eventParam.isEnd || eventParam.removeOnClick) && this.api.dispatchAction({
  73112. type: 'brush',
  73113. brushId: modelId,
  73114. areas: clone(areas),
  73115. $from: modelId
  73116. });
  73117. eventParam.isEnd && this.api.dispatchAction({
  73118. type: 'brushEnd',
  73119. brushId: modelId,
  73120. areas: clone(areas),
  73121. $from: modelId
  73122. });
  73123. };
  73124. BrushView.type = 'brush';
  73125. return BrushView;
  73126. }(ComponentView);
  73127. var DEFAULT_OUT_OF_BRUSH_COLOR = '#ddd';
  73128. var BrushModel =
  73129. /** @class */
  73130. function (_super) {
  73131. __extends(BrushModel, _super);
  73132. function BrushModel() {
  73133. var _this = _super !== null && _super.apply(this, arguments) || this;
  73134. _this.type = BrushModel.type;
  73135. /**
  73136. * @readOnly
  73137. */
  73138. _this.areas = [];
  73139. /**
  73140. * Current brush painting area settings.
  73141. * @readOnly
  73142. */
  73143. _this.brushOption = {};
  73144. return _this;
  73145. }
  73146. BrushModel.prototype.optionUpdated = function (newOption, isInit) {
  73147. var thisOption = this.option;
  73148. !isInit && replaceVisualOption(thisOption, newOption, ['inBrush', 'outOfBrush']);
  73149. var inBrush = thisOption.inBrush = thisOption.inBrush || {}; // Always give default visual, consider setOption at the second time.
  73150. thisOption.outOfBrush = thisOption.outOfBrush || {
  73151. color: DEFAULT_OUT_OF_BRUSH_COLOR
  73152. };
  73153. if (!inBrush.hasOwnProperty('liftZ')) {
  73154. // Bigger than the highlight z lift, otherwise it will
  73155. // be effected by the highlight z when brush.
  73156. inBrush.liftZ = 5;
  73157. }
  73158. };
  73159. /**
  73160. * If `areas` is null/undefined, range state remain.
  73161. */
  73162. BrushModel.prototype.setAreas = function (areas) {
  73163. if ("development" !== 'production') {
  73164. assert(isArray(areas));
  73165. each(areas, function (area) {
  73166. assert(area.brushType, 'Illegal areas');
  73167. });
  73168. } // If areas is null/undefined, range state remain.
  73169. // This helps user to dispatchAction({type: 'brush'}) with no areas
  73170. // set but just want to get the current brush select info from a `brush` event.
  73171. if (!areas) {
  73172. return;
  73173. }
  73174. this.areas = map(areas, function (area) {
  73175. return generateBrushOption(this.option, area);
  73176. }, this);
  73177. };
  73178. /**
  73179. * Set the current painting brush option.
  73180. */
  73181. BrushModel.prototype.setBrushOption = function (brushOption) {
  73182. this.brushOption = generateBrushOption(this.option, brushOption);
  73183. this.brushType = this.brushOption.brushType;
  73184. };
  73185. BrushModel.type = 'brush';
  73186. BrushModel.dependencies = ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'];
  73187. BrushModel.defaultOption = {
  73188. seriesIndex: 'all',
  73189. brushType: 'rect',
  73190. brushMode: 'single',
  73191. transformable: true,
  73192. brushStyle: {
  73193. borderWidth: 1,
  73194. color: 'rgba(210,219,238,0.3)',
  73195. borderColor: '#D2DBEE'
  73196. },
  73197. throttleType: 'fixRate',
  73198. throttleDelay: 0,
  73199. removeOnClick: true,
  73200. z: 10000
  73201. };
  73202. return BrushModel;
  73203. }(ComponentModel);
  73204. function generateBrushOption(option, brushOption) {
  73205. return merge({
  73206. brushType: option.brushType,
  73207. brushMode: option.brushMode,
  73208. transformable: option.transformable,
  73209. brushStyle: new Model(option.brushStyle).getItemStyle(),
  73210. removeOnClick: option.removeOnClick,
  73211. z: option.z
  73212. }, brushOption, true);
  73213. }
  73214. var ICON_TYPES = ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'];
  73215. var BrushFeature =
  73216. /** @class */
  73217. function (_super) {
  73218. __extends(BrushFeature, _super);
  73219. function BrushFeature() {
  73220. return _super !== null && _super.apply(this, arguments) || this;
  73221. }
  73222. BrushFeature.prototype.render = function (featureModel, ecModel, api) {
  73223. var brushType;
  73224. var brushMode;
  73225. var isBrushed;
  73226. ecModel.eachComponent({
  73227. mainType: 'brush'
  73228. }, function (brushModel) {
  73229. brushType = brushModel.brushType;
  73230. brushMode = brushModel.brushOption.brushMode || 'single';
  73231. isBrushed = isBrushed || !!brushModel.areas.length;
  73232. });
  73233. this._brushType = brushType;
  73234. this._brushMode = brushMode;
  73235. each(featureModel.get('type', true), function (type) {
  73236. featureModel.setIconStatus(type, (type === 'keep' ? brushMode === 'multiple' : type === 'clear' ? isBrushed : type === brushType) ? 'emphasis' : 'normal');
  73237. });
  73238. };
  73239. BrushFeature.prototype.updateView = function (featureModel, ecModel, api) {
  73240. this.render(featureModel, ecModel, api);
  73241. };
  73242. BrushFeature.prototype.getIcons = function () {
  73243. var model = this.model;
  73244. var availableIcons = model.get('icon', true);
  73245. var icons = {};
  73246. each(model.get('type', true), function (type) {
  73247. if (availableIcons[type]) {
  73248. icons[type] = availableIcons[type];
  73249. }
  73250. });
  73251. return icons;
  73252. };
  73253. BrushFeature.prototype.onclick = function (ecModel, api, type) {
  73254. var brushType = this._brushType;
  73255. var brushMode = this._brushMode;
  73256. if (type === 'clear') {
  73257. // Trigger parallel action firstly
  73258. api.dispatchAction({
  73259. type: 'axisAreaSelect',
  73260. intervals: []
  73261. });
  73262. api.dispatchAction({
  73263. type: 'brush',
  73264. command: 'clear',
  73265. // Clear all areas of all brush components.
  73266. areas: []
  73267. });
  73268. } else {
  73269. api.dispatchAction({
  73270. type: 'takeGlobalCursor',
  73271. key: 'brush',
  73272. brushOption: {
  73273. brushType: type === 'keep' ? brushType : brushType === type ? false : type,
  73274. brushMode: type === 'keep' ? brushMode === 'multiple' ? 'single' : 'multiple' : brushMode
  73275. }
  73276. });
  73277. }
  73278. };
  73279. BrushFeature.getDefaultOption = function (ecModel) {
  73280. var defaultOption = {
  73281. show: true,
  73282. type: ICON_TYPES.slice(),
  73283. icon: {
  73284. /* eslint-disable */
  73285. rect: 'M7.3,34.7 M0.4,10V-0.2h9.8 M89.6,10V-0.2h-9.8 M0.4,60v10.2h9.8 M89.6,60v10.2h-9.8 M12.3,22.4V10.5h13.1 M33.6,10.5h7.8 M49.1,10.5h7.8 M77.5,22.4V10.5h-13 M12.3,31.1v8.2 M77.7,31.1v8.2 M12.3,47.6v11.9h13.1 M33.6,59.5h7.6 M49.1,59.5 h7.7 M77.5,47.6v11.9h-13',
  73286. polygon: 'M55.2,34.9c1.7,0,3.1,1.4,3.1,3.1s-1.4,3.1-3.1,3.1 s-3.1-1.4-3.1-3.1S53.5,34.9,55.2,34.9z M50.4,51c1.7,0,3.1,1.4,3.1,3.1c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1 C47.3,52.4,48.7,51,50.4,51z M55.6,37.1l1.5-7.8 M60.1,13.5l1.6-8.7l-7.8,4 M59,19l-1,5.3 M24,16.1l6.4,4.9l6.4-3.3 M48.5,11.6 l-5.9,3.1 M19.1,12.8L9.7,5.1l1.1,7.7 M13.4,29.8l1,7.3l6.6,1.6 M11.6,18.4l1,6.1 M32.8,41.9 M26.6,40.4 M27.3,40.2l6.1,1.6 M49.9,52.1l-5.6-7.6l-4.9-1.2',
  73287. lineX: 'M15.2,30 M19.7,15.6V1.9H29 M34.8,1.9H40.4 M55.3,15.6V1.9H45.9 M19.7,44.4V58.1H29 M34.8,58.1H40.4 M55.3,44.4 V58.1H45.9 M12.5,20.3l-9.4,9.6l9.6,9.8 M3.1,29.9h16.5 M62.5,20.3l9.4,9.6L62.3,39.7 M71.9,29.9H55.4',
  73288. lineY: 'M38.8,7.7 M52.7,12h13.2v9 M65.9,26.6V32 M52.7,46.3h13.2v-9 M24.9,12H11.8v9 M11.8,26.6V32 M24.9,46.3H11.8v-9 M48.2,5.1l-9.3-9l-9.4,9.2 M38.9-3.9V12 M48.2,53.3l-9.3,9l-9.4-9.2 M38.9,62.3V46.4',
  73289. keep: 'M4,10.5V1h10.3 M20.7,1h6.1 M33,1h6.1 M55.4,10.5V1H45.2 M4,17.3v6.6 M55.6,17.3v6.6 M4,30.5V40h10.3 M20.7,40 h6.1 M33,40h6.1 M55.4,30.5V40H45.2 M21,18.9h62.9v48.6H21V18.9z',
  73290. clear: 'M22,14.7l30.9,31 M52.9,14.7L22,45.7 M4.7,16.8V4.2h13.1 M26,4.2h7.8 M41.6,4.2h7.8 M70.3,16.8V4.2H57.2 M4.7,25.9v8.6 M70.3,25.9v8.6 M4.7,43.2v12.6h13.1 M26,55.8h7.8 M41.6,55.8h7.8 M70.3,43.2v12.6H57.2' // jshint ignore:line
  73291. /* eslint-enable */
  73292. },
  73293. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  73294. title: ecModel.getLocaleModel().get(['toolbox', 'brush', 'title'])
  73295. };
  73296. return defaultOption;
  73297. };
  73298. return BrushFeature;
  73299. }(ToolboxFeature);
  73300. function install$B(registers) {
  73301. registers.registerComponentView(BrushView);
  73302. registers.registerComponentModel(BrushModel);
  73303. registers.registerPreprocessor(brushPreprocessor);
  73304. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, brushVisual);
  73305. registers.registerAction({
  73306. type: 'brush',
  73307. event: 'brush',
  73308. update: 'updateVisual'
  73309. }, function (payload, ecModel) {
  73310. ecModel.eachComponent({
  73311. mainType: 'brush',
  73312. query: payload
  73313. }, function (brushModel) {
  73314. brushModel.setAreas(payload.areas);
  73315. });
  73316. });
  73317. /**
  73318. * payload: {
  73319. * brushComponents: [
  73320. * {
  73321. * brushId,
  73322. * brushIndex,
  73323. * brushName,
  73324. * series: [
  73325. * {
  73326. * seriesId,
  73327. * seriesIndex,
  73328. * seriesName,
  73329. * rawIndices: [21, 34, ...]
  73330. * },
  73331. * ...
  73332. * ]
  73333. * },
  73334. * ...
  73335. * ]
  73336. * }
  73337. */
  73338. registers.registerAction({
  73339. type: 'brushSelect',
  73340. event: 'brushSelected',
  73341. update: 'none'
  73342. }, noop);
  73343. registers.registerAction({
  73344. type: 'brushEnd',
  73345. event: 'brushEnd',
  73346. update: 'none'
  73347. }, noop);
  73348. registerFeature('brush', BrushFeature);
  73349. }
  73350. var TitleModel =
  73351. /** @class */
  73352. function (_super) {
  73353. __extends(TitleModel, _super);
  73354. function TitleModel() {
  73355. var _this = _super !== null && _super.apply(this, arguments) || this;
  73356. _this.type = TitleModel.type;
  73357. _this.layoutMode = {
  73358. type: 'box',
  73359. ignoreSize: true
  73360. };
  73361. return _this;
  73362. }
  73363. TitleModel.type = 'title';
  73364. TitleModel.defaultOption = {
  73365. // zlevel: 0,
  73366. z: 6,
  73367. show: true,
  73368. text: '',
  73369. target: 'blank',
  73370. subtext: '',
  73371. subtarget: 'blank',
  73372. left: 0,
  73373. top: 0,
  73374. backgroundColor: 'rgba(0,0,0,0)',
  73375. borderColor: '#ccc',
  73376. borderWidth: 0,
  73377. padding: 5,
  73378. itemGap: 10,
  73379. textStyle: {
  73380. fontSize: 18,
  73381. fontWeight: 'bold',
  73382. color: '#464646'
  73383. },
  73384. subtextStyle: {
  73385. fontSize: 12,
  73386. color: '#6E7079'
  73387. }
  73388. };
  73389. return TitleModel;
  73390. }(ComponentModel); // View
  73391. var TitleView =
  73392. /** @class */
  73393. function (_super) {
  73394. __extends(TitleView, _super);
  73395. function TitleView() {
  73396. var _this = _super !== null && _super.apply(this, arguments) || this;
  73397. _this.type = TitleView.type;
  73398. return _this;
  73399. }
  73400. TitleView.prototype.render = function (titleModel, ecModel, api) {
  73401. this.group.removeAll();
  73402. if (!titleModel.get('show')) {
  73403. return;
  73404. }
  73405. var group = this.group;
  73406. var textStyleModel = titleModel.getModel('textStyle');
  73407. var subtextStyleModel = titleModel.getModel('subtextStyle');
  73408. var textAlign = titleModel.get('textAlign');
  73409. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  73410. var textEl = new ZRText({
  73411. style: createTextStyle(textStyleModel, {
  73412. text: titleModel.get('text'),
  73413. fill: textStyleModel.getTextColor()
  73414. }, {
  73415. disableBox: true
  73416. }),
  73417. z2: 10
  73418. });
  73419. var textRect = textEl.getBoundingRect();
  73420. var subText = titleModel.get('subtext');
  73421. var subTextEl = new ZRText({
  73422. style: createTextStyle(subtextStyleModel, {
  73423. text: subText,
  73424. fill: subtextStyleModel.getTextColor(),
  73425. y: textRect.height + titleModel.get('itemGap'),
  73426. verticalAlign: 'top'
  73427. }, {
  73428. disableBox: true
  73429. }),
  73430. z2: 10
  73431. });
  73432. var link = titleModel.get('link');
  73433. var sublink = titleModel.get('sublink');
  73434. var triggerEvent = titleModel.get('triggerEvent', true);
  73435. textEl.silent = !link && !triggerEvent;
  73436. subTextEl.silent = !sublink && !triggerEvent;
  73437. if (link) {
  73438. textEl.on('click', function () {
  73439. windowOpen(link, '_' + titleModel.get('target'));
  73440. });
  73441. }
  73442. if (sublink) {
  73443. subTextEl.on('click', function () {
  73444. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  73445. });
  73446. }
  73447. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  73448. componentType: 'title',
  73449. componentIndex: titleModel.componentIndex
  73450. } : null;
  73451. group.add(textEl);
  73452. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  73453. var groupRect = group.getBoundingRect();
  73454. var layoutOption = titleModel.getBoxLayoutParams();
  73455. layoutOption.width = groupRect.width;
  73456. layoutOption.height = groupRect.height;
  73457. var layoutRect = getLayoutRect(layoutOption, {
  73458. width: api.getWidth(),
  73459. height: api.getHeight()
  73460. }, titleModel.get('padding')); // Adjust text align based on position
  73461. if (!textAlign) {
  73462. // Align left if title is on the left. center and right is same
  73463. textAlign = titleModel.get('left') || titleModel.get('right'); // @ts-ignore
  73464. if (textAlign === 'middle') {
  73465. textAlign = 'center';
  73466. } // Adjust layout by text align
  73467. if (textAlign === 'right') {
  73468. layoutRect.x += layoutRect.width;
  73469. } else if (textAlign === 'center') {
  73470. layoutRect.x += layoutRect.width / 2;
  73471. }
  73472. }
  73473. if (!textVerticalAlign) {
  73474. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom'); // @ts-ignore
  73475. if (textVerticalAlign === 'center') {
  73476. textVerticalAlign = 'middle';
  73477. }
  73478. if (textVerticalAlign === 'bottom') {
  73479. layoutRect.y += layoutRect.height;
  73480. } else if (textVerticalAlign === 'middle') {
  73481. layoutRect.y += layoutRect.height / 2;
  73482. }
  73483. textVerticalAlign = textVerticalAlign || 'top';
  73484. }
  73485. group.x = layoutRect.x;
  73486. group.y = layoutRect.y;
  73487. group.markRedraw();
  73488. var alignStyle = {
  73489. align: textAlign,
  73490. verticalAlign: textVerticalAlign
  73491. };
  73492. textEl.setStyle(alignStyle);
  73493. subTextEl.setStyle(alignStyle); // Render background
  73494. // Get groupRect again because textAlign has been changed
  73495. groupRect = group.getBoundingRect();
  73496. var padding = layoutRect.margin;
  73497. var style = titleModel.getItemStyle(['color', 'opacity']);
  73498. style.fill = titleModel.get('backgroundColor');
  73499. var rect = new Rect({
  73500. shape: {
  73501. x: groupRect.x - padding[3],
  73502. y: groupRect.y - padding[0],
  73503. width: groupRect.width + padding[1] + padding[3],
  73504. height: groupRect.height + padding[0] + padding[2],
  73505. r: titleModel.get('borderRadius')
  73506. },
  73507. style: style,
  73508. subPixelOptimize: true,
  73509. silent: true
  73510. });
  73511. group.add(rect);
  73512. };
  73513. TitleView.type = 'title';
  73514. return TitleView;
  73515. }(ComponentView);
  73516. function install$C(registers) {
  73517. registers.registerComponentModel(TitleModel);
  73518. registers.registerComponentView(TitleView);
  73519. }
  73520. var TimelineModel =
  73521. /** @class */
  73522. function (_super) {
  73523. __extends(TimelineModel, _super);
  73524. function TimelineModel() {
  73525. var _this = _super !== null && _super.apply(this, arguments) || this;
  73526. _this.type = TimelineModel.type;
  73527. _this.layoutMode = 'box';
  73528. return _this;
  73529. }
  73530. /**
  73531. * @override
  73532. */
  73533. TimelineModel.prototype.init = function (option, parentModel, ecModel) {
  73534. this.mergeDefaultAndTheme(option, ecModel);
  73535. this._initData();
  73536. };
  73537. /**
  73538. * @override
  73539. */
  73540. TimelineModel.prototype.mergeOption = function (option) {
  73541. _super.prototype.mergeOption.apply(this, arguments);
  73542. this._initData();
  73543. };
  73544. TimelineModel.prototype.setCurrentIndex = function (currentIndex) {
  73545. if (currentIndex == null) {
  73546. currentIndex = this.option.currentIndex;
  73547. }
  73548. var count = this._data.count();
  73549. if (this.option.loop) {
  73550. currentIndex = (currentIndex % count + count) % count;
  73551. } else {
  73552. currentIndex >= count && (currentIndex = count - 1);
  73553. currentIndex < 0 && (currentIndex = 0);
  73554. }
  73555. this.option.currentIndex = currentIndex;
  73556. };
  73557. /**
  73558. * @return {number} currentIndex
  73559. */
  73560. TimelineModel.prototype.getCurrentIndex = function () {
  73561. return this.option.currentIndex;
  73562. };
  73563. /**
  73564. * @return {boolean}
  73565. */
  73566. TimelineModel.prototype.isIndexMax = function () {
  73567. return this.getCurrentIndex() >= this._data.count() - 1;
  73568. };
  73569. /**
  73570. * @param {boolean} state true: play, false: stop
  73571. */
  73572. TimelineModel.prototype.setPlayState = function (state) {
  73573. this.option.autoPlay = !!state;
  73574. };
  73575. /**
  73576. * @return {boolean} true: play, false: stop
  73577. */
  73578. TimelineModel.prototype.getPlayState = function () {
  73579. return !!this.option.autoPlay;
  73580. };
  73581. /**
  73582. * @private
  73583. */
  73584. TimelineModel.prototype._initData = function () {
  73585. var thisOption = this.option;
  73586. var dataArr = thisOption.data || [];
  73587. var axisType = thisOption.axisType;
  73588. var names = this._names = [];
  73589. var processedDataArr;
  73590. if (axisType === 'category') {
  73591. processedDataArr = [];
  73592. each(dataArr, function (item, index) {
  73593. var value = convertOptionIdName(getDataItemValue(item), '');
  73594. var newItem;
  73595. if (isObject(item)) {
  73596. newItem = clone(item);
  73597. newItem.value = index;
  73598. } else {
  73599. newItem = index;
  73600. }
  73601. processedDataArr.push(newItem);
  73602. names.push(value);
  73603. });
  73604. } else {
  73605. processedDataArr = dataArr;
  73606. }
  73607. var dimType = {
  73608. category: 'ordinal',
  73609. time: 'time',
  73610. value: 'number'
  73611. }[axisType] || 'number';
  73612. var data = this._data = new SeriesData([{
  73613. name: 'value',
  73614. type: dimType
  73615. }], this);
  73616. data.initData(processedDataArr, names);
  73617. };
  73618. TimelineModel.prototype.getData = function () {
  73619. return this._data;
  73620. };
  73621. /**
  73622. * @public
  73623. * @return {Array.<string>} categoreis
  73624. */
  73625. TimelineModel.prototype.getCategories = function () {
  73626. if (this.get('axisType') === 'category') {
  73627. return this._names.slice();
  73628. }
  73629. };
  73630. TimelineModel.type = 'timeline';
  73631. /**
  73632. * @protected
  73633. */
  73634. TimelineModel.defaultOption = {
  73635. // zlevel: 0, // 一级层叠
  73636. z: 4,
  73637. show: true,
  73638. axisType: 'time',
  73639. realtime: true,
  73640. left: '20%',
  73641. top: null,
  73642. right: '20%',
  73643. bottom: 0,
  73644. width: null,
  73645. height: 40,
  73646. padding: 5,
  73647. controlPosition: 'left',
  73648. autoPlay: false,
  73649. rewind: false,
  73650. loop: true,
  73651. playInterval: 2000,
  73652. currentIndex: 0,
  73653. itemStyle: {},
  73654. label: {
  73655. color: '#000'
  73656. },
  73657. data: []
  73658. };
  73659. return TimelineModel;
  73660. }(ComponentModel);
  73661. var SliderTimelineModel =
  73662. /** @class */
  73663. function (_super) {
  73664. __extends(SliderTimelineModel, _super);
  73665. function SliderTimelineModel() {
  73666. var _this = _super !== null && _super.apply(this, arguments) || this;
  73667. _this.type = SliderTimelineModel.type;
  73668. return _this;
  73669. }
  73670. SliderTimelineModel.type = 'timeline.slider';
  73671. /**
  73672. * @protected
  73673. */
  73674. SliderTimelineModel.defaultOption = inheritDefaultOption(TimelineModel.defaultOption, {
  73675. backgroundColor: 'rgba(0,0,0,0)',
  73676. borderColor: '#ccc',
  73677. borderWidth: 0,
  73678. orient: 'horizontal',
  73679. inverse: false,
  73680. tooltip: {
  73681. trigger: 'item' // data item may also have tootip attr.
  73682. },
  73683. symbol: 'circle',
  73684. symbolSize: 12,
  73685. lineStyle: {
  73686. show: true,
  73687. width: 2,
  73688. color: '#DAE1F5'
  73689. },
  73690. label: {
  73691. position: 'auto',
  73692. // When using number, label position is not
  73693. // restricted by viewRect.
  73694. // positive: right/bottom, negative: left/top
  73695. show: true,
  73696. interval: 'auto',
  73697. rotate: 0,
  73698. // formatter: null,
  73699. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73700. color: '#A4B1D7'
  73701. },
  73702. itemStyle: {
  73703. color: '#A4B1D7',
  73704. borderWidth: 1
  73705. },
  73706. checkpointStyle: {
  73707. symbol: 'circle',
  73708. symbolSize: 15,
  73709. color: '#316bf3',
  73710. borderColor: '#fff',
  73711. borderWidth: 2,
  73712. shadowBlur: 2,
  73713. shadowOffsetX: 1,
  73714. shadowOffsetY: 1,
  73715. shadowColor: 'rgba(0, 0, 0, 0.3)',
  73716. // borderColor: 'rgba(194,53,49, 0.5)',
  73717. animation: true,
  73718. animationDuration: 300,
  73719. animationEasing: 'quinticInOut'
  73720. },
  73721. controlStyle: {
  73722. show: true,
  73723. showPlayBtn: true,
  73724. showPrevBtn: true,
  73725. showNextBtn: true,
  73726. itemSize: 24,
  73727. itemGap: 12,
  73728. position: 'left',
  73729. playIcon: 'path://M31.6,53C17.5,53,6,41.5,6,27.4S17.5,1.8,31.6,1.8C45.7,1.8,57.2,13.3,57.2,27.4S45.7,53,31.6,53z M31.6,3.3 C18.4,3.3,7.5,14.1,7.5,27.4c0,13.3,10.8,24.1,24.1,24.1C44.9,51.5,55.7,40.7,55.7,27.4C55.7,14.1,44.9,3.3,31.6,3.3z M24.9,21.3 c0-2.2,1.6-3.1,3.5-2l10.5,6.1c1.899,1.1,1.899,2.9,0,4l-10.5,6.1c-1.9,1.1-3.5,0.2-3.5-2V21.3z',
  73730. stopIcon: 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z',
  73731. // eslint-disable-next-line max-len
  73732. nextIcon: 'M2,18.5A1.52,1.52,0,0,1,.92,18a1.49,1.49,0,0,1,0-2.12L7.81,9.36,1,3.11A1.5,1.5,0,1,1,3,.89l8,7.34a1.48,1.48,0,0,1,.49,1.09,1.51,1.51,0,0,1-.46,1.1L3,18.08A1.5,1.5,0,0,1,2,18.5Z',
  73733. // eslint-disable-next-line max-len
  73734. prevIcon: 'M10,.5A1.52,1.52,0,0,1,11.08,1a1.49,1.49,0,0,1,0,2.12L4.19,9.64,11,15.89a1.5,1.5,0,1,1-2,2.22L1,10.77A1.48,1.48,0,0,1,.5,9.68,1.51,1.51,0,0,1,1,8.58L9,.92A1.5,1.5,0,0,1,10,.5Z',
  73735. prevBtnSize: 18,
  73736. nextBtnSize: 18,
  73737. color: '#A4B1D7',
  73738. borderColor: '#A4B1D7',
  73739. borderWidth: 1
  73740. },
  73741. emphasis: {
  73742. label: {
  73743. show: true,
  73744. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73745. color: '#6f778d'
  73746. },
  73747. itemStyle: {
  73748. color: '#316BF3'
  73749. },
  73750. controlStyle: {
  73751. color: '#316BF3',
  73752. borderColor: '#316BF3',
  73753. borderWidth: 2
  73754. }
  73755. },
  73756. progress: {
  73757. lineStyle: {
  73758. color: '#316BF3'
  73759. },
  73760. itemStyle: {
  73761. color: '#316BF3'
  73762. },
  73763. label: {
  73764. color: '#6f778d'
  73765. }
  73766. },
  73767. data: []
  73768. });
  73769. return SliderTimelineModel;
  73770. }(TimelineModel);
  73771. mixin(SliderTimelineModel, DataFormatMixin.prototype);
  73772. var TimelineView =
  73773. /** @class */
  73774. function (_super) {
  73775. __extends(TimelineView, _super);
  73776. function TimelineView() {
  73777. var _this = _super !== null && _super.apply(this, arguments) || this;
  73778. _this.type = TimelineView.type;
  73779. return _this;
  73780. }
  73781. TimelineView.type = 'timeline';
  73782. return TimelineView;
  73783. }(ComponentView);
  73784. /**
  73785. * Extend axis 2d
  73786. */
  73787. var TimelineAxis =
  73788. /** @class */
  73789. function (_super) {
  73790. __extends(TimelineAxis, _super);
  73791. function TimelineAxis(dim, scale, coordExtent, axisType) {
  73792. var _this = _super.call(this, dim, scale, coordExtent) || this;
  73793. _this.type = axisType || 'value';
  73794. return _this;
  73795. }
  73796. /**
  73797. * @override
  73798. */
  73799. TimelineAxis.prototype.getLabelModel = function () {
  73800. // Force override
  73801. return this.model.getModel('label');
  73802. };
  73803. /**
  73804. * @override
  73805. */
  73806. TimelineAxis.prototype.isHorizontal = function () {
  73807. return this.model.get('orient') === 'horizontal';
  73808. };
  73809. return TimelineAxis;
  73810. }(Axis);
  73811. var PI$8 = Math.PI;
  73812. var labelDataIndexStore = makeInner();
  73813. var SliderTimelineView =
  73814. /** @class */
  73815. function (_super) {
  73816. __extends(SliderTimelineView, _super);
  73817. function SliderTimelineView() {
  73818. var _this = _super !== null && _super.apply(this, arguments) || this;
  73819. _this.type = SliderTimelineView.type;
  73820. return _this;
  73821. }
  73822. SliderTimelineView.prototype.init = function (ecModel, api) {
  73823. this.api = api;
  73824. };
  73825. /**
  73826. * @override
  73827. */
  73828. SliderTimelineView.prototype.render = function (timelineModel, ecModel, api) {
  73829. this.model = timelineModel;
  73830. this.api = api;
  73831. this.ecModel = ecModel;
  73832. this.group.removeAll();
  73833. if (timelineModel.get('show', true)) {
  73834. var layoutInfo_1 = this._layout(timelineModel, api);
  73835. var mainGroup_1 = this._createGroup('_mainGroup');
  73836. var labelGroup = this._createGroup('_labelGroup');
  73837. var axis_1 = this._axis = this._createAxis(layoutInfo_1, timelineModel);
  73838. timelineModel.formatTooltip = function (dataIndex) {
  73839. var name = axis_1.scale.getLabel({
  73840. value: dataIndex
  73841. });
  73842. return createTooltipMarkup('nameValue', {
  73843. noName: true,
  73844. value: name
  73845. });
  73846. };
  73847. each(['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'], function (name) {
  73848. this['_render' + name](layoutInfo_1, mainGroup_1, axis_1, timelineModel);
  73849. }, this);
  73850. this._renderAxisLabel(layoutInfo_1, labelGroup, axis_1, timelineModel);
  73851. this._position(layoutInfo_1, timelineModel);
  73852. }
  73853. this._doPlayStop();
  73854. this._updateTicksStatus();
  73855. };
  73856. /**
  73857. * @override
  73858. */
  73859. SliderTimelineView.prototype.remove = function () {
  73860. this._clearTimer();
  73861. this.group.removeAll();
  73862. };
  73863. /**
  73864. * @override
  73865. */
  73866. SliderTimelineView.prototype.dispose = function () {
  73867. this._clearTimer();
  73868. };
  73869. SliderTimelineView.prototype._layout = function (timelineModel, api) {
  73870. var labelPosOpt = timelineModel.get(['label', 'position']);
  73871. var orient = timelineModel.get('orient');
  73872. var viewRect = getViewRect$5(timelineModel, api);
  73873. var parsedLabelPos; // Auto label offset.
  73874. if (labelPosOpt == null || labelPosOpt === 'auto') {
  73875. parsedLabelPos = orient === 'horizontal' ? viewRect.y + viewRect.height / 2 < api.getHeight() / 2 ? '-' : '+' : viewRect.x + viewRect.width / 2 < api.getWidth() / 2 ? '+' : '-';
  73876. } else if (isString(labelPosOpt)) {
  73877. parsedLabelPos = {
  73878. horizontal: {
  73879. top: '-',
  73880. bottom: '+'
  73881. },
  73882. vertical: {
  73883. left: '-',
  73884. right: '+'
  73885. }
  73886. }[orient][labelPosOpt];
  73887. } else {
  73888. // is number
  73889. parsedLabelPos = labelPosOpt;
  73890. }
  73891. var labelAlignMap = {
  73892. horizontal: 'center',
  73893. vertical: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'left' : 'right'
  73894. };
  73895. var labelBaselineMap = {
  73896. horizontal: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'top' : 'bottom',
  73897. vertical: 'middle'
  73898. };
  73899. var rotationMap = {
  73900. horizontal: 0,
  73901. vertical: PI$8 / 2
  73902. }; // Position
  73903. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  73904. var controlModel = timelineModel.getModel('controlStyle');
  73905. var showControl = controlModel.get('show', true);
  73906. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  73907. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  73908. var sizePlusGap = controlSize + controlGap; // Special label rotate.
  73909. var labelRotation = timelineModel.get(['label', 'rotate']) || 0;
  73910. labelRotation = labelRotation * PI$8 / 180; // To radian.
  73911. var playPosition;
  73912. var prevBtnPosition;
  73913. var nextBtnPosition;
  73914. var controlPosition = controlModel.get('position', true);
  73915. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  73916. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  73917. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  73918. var xLeft = 0;
  73919. var xRight = mainLength; // position[0] means left, position[1] means middle.
  73920. if (controlPosition === 'left' || controlPosition === 'bottom') {
  73921. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  73922. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  73923. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73924. } else {
  73925. // 'top' 'right'
  73926. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73927. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  73928. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73929. }
  73930. var axisExtent = [xLeft, xRight];
  73931. if (timelineModel.get('inverse')) {
  73932. axisExtent.reverse();
  73933. }
  73934. return {
  73935. viewRect: viewRect,
  73936. mainLength: mainLength,
  73937. orient: orient,
  73938. rotation: rotationMap[orient],
  73939. labelRotation: labelRotation,
  73940. labelPosOpt: parsedLabelPos,
  73941. labelAlign: timelineModel.get(['label', 'align']) || labelAlignMap[orient],
  73942. labelBaseline: timelineModel.get(['label', 'verticalAlign']) || timelineModel.get(['label', 'baseline']) || labelBaselineMap[orient],
  73943. // Based on mainGroup.
  73944. playPosition: playPosition,
  73945. prevBtnPosition: prevBtnPosition,
  73946. nextBtnPosition: nextBtnPosition,
  73947. axisExtent: axisExtent,
  73948. controlSize: controlSize,
  73949. controlGap: controlGap
  73950. };
  73951. };
  73952. SliderTimelineView.prototype._position = function (layoutInfo, timelineModel) {
  73953. // Position is be called finally, because bounding rect is needed for
  73954. // adapt content to fill viewRect (auto adapt offset).
  73955. // Timeline may be not all in the viewRect when 'offset' is specified
  73956. // as a number, because it is more appropriate that label aligns at
  73957. // 'offset' but not the other edge defined by viewRect.
  73958. var mainGroup = this._mainGroup;
  73959. var labelGroup = this._labelGroup;
  73960. var viewRect = layoutInfo.viewRect;
  73961. if (layoutInfo.orient === 'vertical') {
  73962. // transform to horizontal, inverse rotate by left-top point.
  73963. var m = create$1();
  73964. var rotateOriginX = viewRect.x;
  73965. var rotateOriginY = viewRect.y + viewRect.height;
  73966. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  73967. rotate(m, m, -PI$8 / 2);
  73968. translate(m, m, [rotateOriginX, rotateOriginY]);
  73969. viewRect = viewRect.clone();
  73970. viewRect.applyTransform(m);
  73971. }
  73972. var viewBound = getBound(viewRect);
  73973. var mainBound = getBound(mainGroup.getBoundingRect());
  73974. var labelBound = getBound(labelGroup.getBoundingRect());
  73975. var mainPosition = [mainGroup.x, mainGroup.y];
  73976. var labelsPosition = [labelGroup.x, labelGroup.y];
  73977. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  73978. var labelPosOpt = layoutInfo.labelPosOpt;
  73979. if (labelPosOpt == null || isString(labelPosOpt)) {
  73980. // '+' or '-'
  73981. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  73982. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73983. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  73984. } else {
  73985. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  73986. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73987. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  73988. }
  73989. mainGroup.setPosition(mainPosition);
  73990. labelGroup.setPosition(labelsPosition);
  73991. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  73992. setOrigin(mainGroup);
  73993. setOrigin(labelGroup);
  73994. function setOrigin(targetGroup) {
  73995. targetGroup.originX = viewBound[0][0] - targetGroup.x;
  73996. targetGroup.originY = viewBound[1][0] - targetGroup.y;
  73997. }
  73998. function getBound(rect) {
  73999. // [[xmin, xmax], [ymin, ymax]]
  74000. return [[rect.x, rect.x + rect.width], [rect.y, rect.y + rect.height]];
  74001. }
  74002. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  74003. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  74004. }
  74005. };
  74006. SliderTimelineView.prototype._createAxis = function (layoutInfo, timelineModel) {
  74007. var data = timelineModel.getData();
  74008. var axisType = timelineModel.get('axisType');
  74009. var scale = createScaleByModel$1(timelineModel, axisType); // Customize scale. The `tickValue` is `dataIndex`.
  74010. scale.getTicks = function () {
  74011. return data.mapArray(['value'], function (value) {
  74012. return {
  74013. value: value
  74014. };
  74015. });
  74016. };
  74017. var dataExtent = data.getDataExtent('value');
  74018. scale.setExtent(dataExtent[0], dataExtent[1]);
  74019. scale.calcNiceTicks();
  74020. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  74021. axis.model = timelineModel;
  74022. return axis;
  74023. };
  74024. SliderTimelineView.prototype._createGroup = function (key) {
  74025. var newGroup = this[key] = new Group();
  74026. this.group.add(newGroup);
  74027. return newGroup;
  74028. };
  74029. SliderTimelineView.prototype._renderAxisLine = function (layoutInfo, group, axis, timelineModel) {
  74030. var axisExtent = axis.getExtent();
  74031. if (!timelineModel.get(['lineStyle', 'show'])) {
  74032. return;
  74033. }
  74034. var line = new Line({
  74035. shape: {
  74036. x1: axisExtent[0],
  74037. y1: 0,
  74038. x2: axisExtent[1],
  74039. y2: 0
  74040. },
  74041. style: extend({
  74042. lineCap: 'round'
  74043. }, timelineModel.getModel('lineStyle').getLineStyle()),
  74044. silent: true,
  74045. z2: 1
  74046. });
  74047. group.add(line);
  74048. var progressLine = this._progressLine = new Line({
  74049. shape: {
  74050. x1: axisExtent[0],
  74051. x2: this._currentPointer ? this._currentPointer.x : axisExtent[0],
  74052. y1: 0,
  74053. y2: 0
  74054. },
  74055. style: defaults({
  74056. lineCap: 'round',
  74057. lineWidth: line.style.lineWidth
  74058. }, timelineModel.getModel(['progress', 'lineStyle']).getLineStyle()),
  74059. silent: true,
  74060. z2: 1
  74061. });
  74062. group.add(progressLine);
  74063. };
  74064. SliderTimelineView.prototype._renderAxisTick = function (layoutInfo, group, axis, timelineModel) {
  74065. var _this = this;
  74066. var data = timelineModel.getData(); // Show all ticks, despite ignoring strategy.
  74067. var ticks = axis.scale.getTicks();
  74068. this._tickSymbols = []; // The value is dataIndex, see the customized scale.
  74069. each(ticks, function (tick) {
  74070. var tickCoord = axis.dataToCoord(tick.value);
  74071. var itemModel = data.getItemModel(tick.value);
  74072. var itemStyleModel = itemModel.getModel('itemStyle');
  74073. var hoverStyleModel = itemModel.getModel(['emphasis', 'itemStyle']);
  74074. var progressStyleModel = itemModel.getModel(['progress', 'itemStyle']);
  74075. var symbolOpt = {
  74076. x: tickCoord,
  74077. y: 0,
  74078. onclick: bind(_this._changeTimeline, _this, tick.value)
  74079. };
  74080. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  74081. el.ensureState('emphasis').style = hoverStyleModel.getItemStyle();
  74082. el.ensureState('progress').style = progressStyleModel.getItemStyle();
  74083. enableHoverEmphasis(el);
  74084. var ecData = getECData(el);
  74085. if (itemModel.get('tooltip')) {
  74086. ecData.dataIndex = tick.value;
  74087. ecData.dataModel = timelineModel;
  74088. } else {
  74089. ecData.dataIndex = ecData.dataModel = null;
  74090. }
  74091. _this._tickSymbols.push(el);
  74092. });
  74093. };
  74094. SliderTimelineView.prototype._renderAxisLabel = function (layoutInfo, group, axis, timelineModel) {
  74095. var _this = this;
  74096. var labelModel = axis.getLabelModel();
  74097. if (!labelModel.get('show')) {
  74098. return;
  74099. }
  74100. var data = timelineModel.getData();
  74101. var labels = axis.getViewLabels();
  74102. this._tickLabels = [];
  74103. each(labels, function (labelItem) {
  74104. // The tickValue is dataIndex, see the customized scale.
  74105. var dataIndex = labelItem.tickValue;
  74106. var itemModel = data.getItemModel(dataIndex);
  74107. var normalLabelModel = itemModel.getModel('label');
  74108. var hoverLabelModel = itemModel.getModel(['emphasis', 'label']);
  74109. var progressLabelModel = itemModel.getModel(['progress', 'label']);
  74110. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  74111. var textEl = new ZRText({
  74112. x: tickCoord,
  74113. y: 0,
  74114. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  74115. onclick: bind(_this._changeTimeline, _this, dataIndex),
  74116. silent: false,
  74117. style: createTextStyle(normalLabelModel, {
  74118. text: labelItem.formattedLabel,
  74119. align: layoutInfo.labelAlign,
  74120. verticalAlign: layoutInfo.labelBaseline
  74121. })
  74122. });
  74123. textEl.ensureState('emphasis').style = createTextStyle(hoverLabelModel);
  74124. textEl.ensureState('progress').style = createTextStyle(progressLabelModel);
  74125. group.add(textEl);
  74126. enableHoverEmphasis(textEl);
  74127. labelDataIndexStore(textEl).dataIndex = dataIndex;
  74128. _this._tickLabels.push(textEl);
  74129. });
  74130. };
  74131. SliderTimelineView.prototype._renderControl = function (layoutInfo, group, axis, timelineModel) {
  74132. var controlSize = layoutInfo.controlSize;
  74133. var rotation = layoutInfo.rotation;
  74134. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  74135. var hoverStyle = timelineModel.getModel(['emphasis', 'controlStyle']).getItemStyle();
  74136. var playState = timelineModel.getPlayState();
  74137. var inverse = timelineModel.get('inverse', true);
  74138. makeBtn(layoutInfo.nextBtnPosition, 'next', bind(this._changeTimeline, this, inverse ? '-' : '+'));
  74139. makeBtn(layoutInfo.prevBtnPosition, 'prev', bind(this._changeTimeline, this, inverse ? '+' : '-'));
  74140. makeBtn(layoutInfo.playPosition, playState ? 'stop' : 'play', bind(this._handlePlayClick, this, !playState), true);
  74141. function makeBtn(position, iconName, onclick, willRotate) {
  74142. if (!position) {
  74143. return;
  74144. }
  74145. var iconSize = parsePercent(retrieve2(timelineModel.get(['controlStyle', iconName + 'BtnSize']), controlSize), controlSize);
  74146. var rect = [0, -iconSize / 2, iconSize, iconSize];
  74147. var btn = makeControlIcon(timelineModel, iconName + 'Icon', rect, {
  74148. x: position[0],
  74149. y: position[1],
  74150. originX: controlSize / 2,
  74151. originY: 0,
  74152. rotation: willRotate ? -rotation : 0,
  74153. rectHover: true,
  74154. style: itemStyle,
  74155. onclick: onclick
  74156. });
  74157. btn.ensureState('emphasis').style = hoverStyle;
  74158. group.add(btn);
  74159. enableHoverEmphasis(btn);
  74160. }
  74161. };
  74162. SliderTimelineView.prototype._renderCurrentPointer = function (layoutInfo, group, axis, timelineModel) {
  74163. var data = timelineModel.getData();
  74164. var currentIndex = timelineModel.getCurrentIndex();
  74165. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  74166. var me = this;
  74167. var callback = {
  74168. onCreate: function (pointer) {
  74169. pointer.draggable = true;
  74170. pointer.drift = bind(me._handlePointerDrag, me);
  74171. pointer.ondragend = bind(me._handlePointerDragend, me);
  74172. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel, true);
  74173. },
  74174. onUpdate: function (pointer) {
  74175. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel);
  74176. }
  74177. }; // Reuse when exists, for animation and drag.
  74178. this._currentPointer = giveSymbol(pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback);
  74179. };
  74180. SliderTimelineView.prototype._handlePlayClick = function (nextState) {
  74181. this._clearTimer();
  74182. this.api.dispatchAction({
  74183. type: 'timelinePlayChange',
  74184. playState: nextState,
  74185. from: this.uid
  74186. });
  74187. };
  74188. SliderTimelineView.prototype._handlePointerDrag = function (dx, dy, e) {
  74189. this._clearTimer();
  74190. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  74191. };
  74192. SliderTimelineView.prototype._handlePointerDragend = function (e) {
  74193. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  74194. };
  74195. SliderTimelineView.prototype._pointerChangeTimeline = function (mousePos, trigger) {
  74196. var toCoord = this._toAxisCoord(mousePos)[0];
  74197. var axis = this._axis;
  74198. var axisExtent = asc(axis.getExtent().slice());
  74199. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  74200. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  74201. this._currentPointer.x = toCoord;
  74202. this._currentPointer.markRedraw();
  74203. var progressLine = this._progressLine;
  74204. if (progressLine) {
  74205. progressLine.shape.x2 = toCoord;
  74206. progressLine.dirty();
  74207. }
  74208. var targetDataIndex = this._findNearestTick(toCoord);
  74209. var timelineModel = this.model;
  74210. if (trigger || targetDataIndex !== timelineModel.getCurrentIndex() && timelineModel.get('realtime')) {
  74211. this._changeTimeline(targetDataIndex);
  74212. }
  74213. };
  74214. SliderTimelineView.prototype._doPlayStop = function () {
  74215. var _this = this;
  74216. this._clearTimer();
  74217. if (this.model.getPlayState()) {
  74218. this._timer = setTimeout(function () {
  74219. // Do not cache
  74220. var timelineModel = _this.model;
  74221. _this._changeTimeline(timelineModel.getCurrentIndex() + (timelineModel.get('rewind', true) ? -1 : 1));
  74222. }, this.model.get('playInterval'));
  74223. }
  74224. };
  74225. SliderTimelineView.prototype._toAxisCoord = function (vertex) {
  74226. var trans = this._mainGroup.getLocalTransform();
  74227. return applyTransform$1(vertex, trans, true);
  74228. };
  74229. SliderTimelineView.prototype._findNearestTick = function (axisCoord) {
  74230. var data = this.model.getData();
  74231. var dist = Infinity;
  74232. var targetDataIndex;
  74233. var axis = this._axis;
  74234. data.each(['value'], function (value, dataIndex) {
  74235. var coord = axis.dataToCoord(value);
  74236. var d = Math.abs(coord - axisCoord);
  74237. if (d < dist) {
  74238. dist = d;
  74239. targetDataIndex = dataIndex;
  74240. }
  74241. });
  74242. return targetDataIndex;
  74243. };
  74244. SliderTimelineView.prototype._clearTimer = function () {
  74245. if (this._timer) {
  74246. clearTimeout(this._timer);
  74247. this._timer = null;
  74248. }
  74249. };
  74250. SliderTimelineView.prototype._changeTimeline = function (nextIndex) {
  74251. var currentIndex = this.model.getCurrentIndex();
  74252. if (nextIndex === '+') {
  74253. nextIndex = currentIndex + 1;
  74254. } else if (nextIndex === '-') {
  74255. nextIndex = currentIndex - 1;
  74256. }
  74257. this.api.dispatchAction({
  74258. type: 'timelineChange',
  74259. currentIndex: nextIndex,
  74260. from: this.uid
  74261. });
  74262. };
  74263. SliderTimelineView.prototype._updateTicksStatus = function () {
  74264. var currentIndex = this.model.getCurrentIndex();
  74265. var tickSymbols = this._tickSymbols;
  74266. var tickLabels = this._tickLabels;
  74267. if (tickSymbols) {
  74268. for (var i = 0; i < tickSymbols.length; i++) {
  74269. tickSymbols && tickSymbols[i] && tickSymbols[i].toggleState('progress', i < currentIndex);
  74270. }
  74271. }
  74272. if (tickLabels) {
  74273. for (var i = 0; i < tickLabels.length; i++) {
  74274. tickLabels && tickLabels[i] && tickLabels[i].toggleState('progress', labelDataIndexStore(tickLabels[i]).dataIndex <= currentIndex);
  74275. }
  74276. }
  74277. };
  74278. SliderTimelineView.type = 'timeline.slider';
  74279. return SliderTimelineView;
  74280. }(TimelineView);
  74281. function createScaleByModel$1(model, axisType) {
  74282. axisType = axisType || model.get('type');
  74283. if (axisType) {
  74284. switch (axisType) {
  74285. // Buildin scale
  74286. case 'category':
  74287. return new OrdinalScale({
  74288. ordinalMeta: model.getCategories(),
  74289. extent: [Infinity, -Infinity]
  74290. });
  74291. case 'time':
  74292. return new TimeScale({
  74293. locale: model.ecModel.getLocaleModel(),
  74294. useUTC: model.ecModel.get('useUTC')
  74295. });
  74296. default:
  74297. // default to be value
  74298. return new IntervalScale();
  74299. }
  74300. }
  74301. }
  74302. function getViewRect$5(model, api) {
  74303. return getLayoutRect(model.getBoxLayoutParams(), {
  74304. width: api.getWidth(),
  74305. height: api.getHeight()
  74306. }, model.get('padding'));
  74307. }
  74308. function makeControlIcon(timelineModel, objPath, rect, opts) {
  74309. var style = opts.style;
  74310. var icon = createIcon(timelineModel.get(['controlStyle', objPath]), opts || {}, new BoundingRect(rect[0], rect[1], rect[2], rect[3])); // TODO createIcon won't use style in opt.
  74311. if (style) {
  74312. icon.setStyle(style);
  74313. }
  74314. return icon;
  74315. }
  74316. /**
  74317. * Create symbol or update symbol
  74318. * opt: basic position and event handlers
  74319. */
  74320. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  74321. var color = itemStyleModel.get('color');
  74322. if (!symbol) {
  74323. var symbolType = hostModel.get('symbol');
  74324. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  74325. symbol.setStyle('strokeNoScale', true);
  74326. group.add(symbol);
  74327. callback && callback.onCreate(symbol);
  74328. } else {
  74329. symbol.setColor(color);
  74330. group.add(symbol); // Group may be new, also need to add.
  74331. callback && callback.onUpdate(symbol);
  74332. } // Style
  74333. var itemStyle = itemStyleModel.getItemStyle(['color']);
  74334. symbol.setStyle(itemStyle); // Transform and events.
  74335. opt = merge({
  74336. rectHover: true,
  74337. z2: 100
  74338. }, opt, true);
  74339. var symbolSize = normalizeSymbolSize(hostModel.get('symbolSize'));
  74340. opt.scaleX = symbolSize[0] / 2;
  74341. opt.scaleY = symbolSize[1] / 2;
  74342. var symbolOffset = normalizeSymbolOffset(hostModel.get('symbolOffset'), symbolSize);
  74343. if (symbolOffset) {
  74344. opt.x = (opt.x || 0) + symbolOffset[0];
  74345. opt.y = (opt.y || 0) + symbolOffset[1];
  74346. }
  74347. var symbolRotate = hostModel.get('symbolRotate');
  74348. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  74349. symbol.attr(opt); // FIXME
  74350. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  74351. // getBoundingRect will return wrong result.
  74352. // (This is supposed to be resolved in zrender, but it is a little difficult to
  74353. // leverage performance and auto updateTransform)
  74354. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  74355. symbol.updateTransform();
  74356. return symbol;
  74357. }
  74358. function pointerMoveTo(pointer, progressLine, dataIndex, axis, timelineModel, noAnimation) {
  74359. if (pointer.dragging) {
  74360. return;
  74361. }
  74362. var pointerModel = timelineModel.getModel('checkpointStyle');
  74363. var toCoord = axis.dataToCoord(timelineModel.getData().get('value', dataIndex));
  74364. if (noAnimation || !pointerModel.get('animation', true)) {
  74365. pointer.attr({
  74366. x: toCoord,
  74367. y: 0
  74368. });
  74369. progressLine && progressLine.attr({
  74370. shape: {
  74371. x2: toCoord
  74372. }
  74373. });
  74374. } else {
  74375. var animationCfg = {
  74376. duration: pointerModel.get('animationDuration', true),
  74377. easing: pointerModel.get('animationEasing', true)
  74378. };
  74379. pointer.stopAnimation(null, true);
  74380. pointer.animateTo({
  74381. x: toCoord,
  74382. y: 0
  74383. }, animationCfg);
  74384. progressLine && progressLine.animateTo({
  74385. shape: {
  74386. x2: toCoord
  74387. }
  74388. }, animationCfg);
  74389. }
  74390. }
  74391. function installTimelineAction(registers) {
  74392. registers.registerAction({
  74393. type: 'timelineChange',
  74394. event: 'timelineChanged',
  74395. update: 'prepareAndUpdate'
  74396. }, function (payload, ecModel, api) {
  74397. var timelineModel = ecModel.getComponent('timeline');
  74398. if (timelineModel && payload.currentIndex != null) {
  74399. timelineModel.setCurrentIndex(payload.currentIndex);
  74400. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax() && timelineModel.getPlayState()) {
  74401. timelineModel.setPlayState(false); // The timeline has played to the end, trigger event
  74402. api.dispatchAction({
  74403. type: 'timelinePlayChange',
  74404. playState: false,
  74405. from: payload.from
  74406. });
  74407. }
  74408. } // Set normalized currentIndex to payload.
  74409. ecModel.resetOption('timeline', {
  74410. replaceMerge: timelineModel.get('replaceMerge', true)
  74411. });
  74412. return defaults({
  74413. currentIndex: timelineModel.option.currentIndex
  74414. }, payload);
  74415. });
  74416. registers.registerAction({
  74417. type: 'timelinePlayChange',
  74418. event: 'timelinePlayChanged',
  74419. update: 'update'
  74420. }, function (payload, ecModel) {
  74421. var timelineModel = ecModel.getComponent('timeline');
  74422. if (timelineModel && payload.playState != null) {
  74423. timelineModel.setPlayState(payload.playState);
  74424. }
  74425. });
  74426. }
  74427. function timelinePreprocessor(option) {
  74428. var timelineOpt = option && option.timeline;
  74429. if (!isArray(timelineOpt)) {
  74430. timelineOpt = timelineOpt ? [timelineOpt] : [];
  74431. }
  74432. each(timelineOpt, function (opt) {
  74433. if (!opt) {
  74434. return;
  74435. }
  74436. compatibleEC2(opt);
  74437. });
  74438. }
  74439. function compatibleEC2(opt) {
  74440. var type = opt.type;
  74441. var ec2Types = {
  74442. 'number': 'value',
  74443. 'time': 'time'
  74444. }; // Compatible with ec2
  74445. if (ec2Types[type]) {
  74446. opt.axisType = ec2Types[type];
  74447. delete opt.type;
  74448. }
  74449. transferItem(opt);
  74450. if (has(opt, 'controlPosition')) {
  74451. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  74452. if (!has(controlStyle, 'position')) {
  74453. controlStyle.position = opt.controlPosition;
  74454. }
  74455. if (controlStyle.position === 'none' && !has(controlStyle, 'show')) {
  74456. controlStyle.show = false;
  74457. delete controlStyle.position;
  74458. }
  74459. delete opt.controlPosition;
  74460. }
  74461. each(opt.data || [], function (dataItem) {
  74462. if (isObject(dataItem) && !isArray(dataItem)) {
  74463. if (!has(dataItem, 'value') && has(dataItem, 'name')) {
  74464. // In ec2, using name as value.
  74465. dataItem.value = dataItem.name;
  74466. }
  74467. transferItem(dataItem);
  74468. }
  74469. });
  74470. }
  74471. function transferItem(opt) {
  74472. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  74473. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {}); // Transfer label out
  74474. var label = opt.label || opt.label || {};
  74475. var labelNormal = label.normal || (label.normal = {});
  74476. var excludeLabelAttr = {
  74477. normal: 1,
  74478. emphasis: 1
  74479. };
  74480. each(label, function (value, name) {
  74481. if (!excludeLabelAttr[name] && !has(labelNormal, name)) {
  74482. labelNormal[name] = value;
  74483. }
  74484. });
  74485. if (itemStyleEmphasis.label && !has(label, 'emphasis')) {
  74486. label.emphasis = itemStyleEmphasis.label;
  74487. delete itemStyleEmphasis.label;
  74488. }
  74489. }
  74490. function has(obj, attr) {
  74491. return obj.hasOwnProperty(attr);
  74492. }
  74493. function install$D(registers) {
  74494. registers.registerComponentModel(SliderTimelineModel);
  74495. registers.registerComponentView(SliderTimelineView);
  74496. registers.registerSubTypeDefaulter('timeline', function () {
  74497. // Only slider now.
  74498. return 'slider';
  74499. });
  74500. installTimelineAction(registers);
  74501. registers.registerPreprocessor(timelinePreprocessor);
  74502. }
  74503. function checkMarkerInSeries(seriesOpts, markerType) {
  74504. if (!seriesOpts) {
  74505. return false;
  74506. }
  74507. var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [seriesOpts];
  74508. for (var idx = 0; idx < seriesOptArr.length; idx++) {
  74509. if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) {
  74510. return true;
  74511. }
  74512. }
  74513. return false;
  74514. }
  74515. function fillLabel(opt) {
  74516. defaultEmphasis(opt, 'label', ['show']);
  74517. } // { [componentType]: MarkerModel }
  74518. var inner$g = makeInner();
  74519. var MarkerModel =
  74520. /** @class */
  74521. function (_super) {
  74522. __extends(MarkerModel, _super);
  74523. function MarkerModel() {
  74524. var _this = _super !== null && _super.apply(this, arguments) || this;
  74525. _this.type = MarkerModel.type;
  74526. /**
  74527. * If marker model is created by self from series
  74528. */
  74529. _this.createdBySelf = false;
  74530. return _this;
  74531. }
  74532. /**
  74533. * @overrite
  74534. */
  74535. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  74536. if ("development" !== 'production') {
  74537. if (this.type === 'marker') {
  74538. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  74539. }
  74540. }
  74541. this.mergeDefaultAndTheme(option, ecModel);
  74542. this._mergeOption(option, ecModel, false, true);
  74543. };
  74544. MarkerModel.prototype.isAnimationEnabled = function () {
  74545. if (env.node) {
  74546. return false;
  74547. }
  74548. var hostSeries = this.__hostSeries;
  74549. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  74550. };
  74551. /**
  74552. * @overrite
  74553. */
  74554. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  74555. this._mergeOption(newOpt, ecModel, false, false);
  74556. };
  74557. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  74558. var componentType = this.mainType;
  74559. if (!createdBySelf) {
  74560. ecModel.eachSeries(function (seriesModel) {
  74561. // mainType can be markPoint, markLine, markArea
  74562. var markerOpt = seriesModel.get(this.mainType, true);
  74563. var markerModel = inner$g(seriesModel)[componentType];
  74564. if (!markerOpt || !markerOpt.data) {
  74565. inner$g(seriesModel)[componentType] = null;
  74566. return;
  74567. }
  74568. if (!markerModel) {
  74569. if (isInit) {
  74570. // Default label emphasis `position` and `show`
  74571. fillLabel(markerOpt);
  74572. }
  74573. each(markerOpt.data, function (item) {
  74574. // FIXME Overwrite fillLabel method ?
  74575. if (item instanceof Array) {
  74576. fillLabel(item[0]);
  74577. fillLabel(item[1]);
  74578. } else {
  74579. fillLabel(item);
  74580. }
  74581. });
  74582. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel); // markerModel = new ImplementedMarkerModel(
  74583. // markerOpt, this, ecModel
  74584. // );
  74585. extend(markerModel, {
  74586. mainType: this.mainType,
  74587. // Use the same series index and name
  74588. seriesIndex: seriesModel.seriesIndex,
  74589. name: seriesModel.name,
  74590. createdBySelf: true
  74591. });
  74592. markerModel.__hostSeries = seriesModel;
  74593. } else {
  74594. markerModel._mergeOption(markerOpt, ecModel, true);
  74595. }
  74596. inner$g(seriesModel)[componentType] = markerModel;
  74597. }, this);
  74598. }
  74599. };
  74600. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  74601. var data = this.getData();
  74602. var value = this.getRawValue(dataIndex);
  74603. var itemName = data.getName(dataIndex);
  74604. return createTooltipMarkup('section', {
  74605. header: this.name,
  74606. blocks: [createTooltipMarkup('nameValue', {
  74607. name: itemName,
  74608. value: value,
  74609. noName: !itemName,
  74610. noValue: value == null
  74611. })]
  74612. });
  74613. };
  74614. MarkerModel.prototype.getData = function () {
  74615. return this._data;
  74616. };
  74617. MarkerModel.prototype.setData = function (data) {
  74618. this._data = data;
  74619. };
  74620. MarkerModel.getMarkerModelFromSeries = function (seriesModel, // Support three types of markers. Strict check.
  74621. componentType) {
  74622. return inner$g(seriesModel)[componentType];
  74623. };
  74624. MarkerModel.type = 'marker';
  74625. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  74626. return MarkerModel;
  74627. }(ComponentModel);
  74628. mixin(MarkerModel, DataFormatMixin.prototype);
  74629. var MarkPointModel =
  74630. /** @class */
  74631. function (_super) {
  74632. __extends(MarkPointModel, _super);
  74633. function MarkPointModel() {
  74634. var _this = _super !== null && _super.apply(this, arguments) || this;
  74635. _this.type = MarkPointModel.type;
  74636. return _this;
  74637. }
  74638. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  74639. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  74640. };
  74641. MarkPointModel.type = 'markPoint';
  74642. MarkPointModel.defaultOption = {
  74643. // zlevel: 0,
  74644. z: 5,
  74645. symbol: 'pin',
  74646. symbolSize: 50,
  74647. // symbolRotate: 0,
  74648. // symbolOffset: [0, 0]
  74649. tooltip: {
  74650. trigger: 'item'
  74651. },
  74652. label: {
  74653. show: true,
  74654. position: 'inside'
  74655. },
  74656. itemStyle: {
  74657. borderWidth: 2
  74658. },
  74659. emphasis: {
  74660. label: {
  74661. show: true
  74662. }
  74663. }
  74664. };
  74665. return MarkPointModel;
  74666. }(MarkerModel);
  74667. function hasXOrY(item) {
  74668. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  74669. }
  74670. function hasXAndY(item) {
  74671. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  74672. }
  74673. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  74674. var coordArr = [];
  74675. var stacked = isDimensionStacked(data, targetDataDim
  74676. /* , otherDataDim */
  74677. );
  74678. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  74679. var value = numCalculate(data, calcDataDim, markerType);
  74680. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  74681. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  74682. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  74683. var coordArrValue = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision.
  74684. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  74685. precision = Math.min(precision, 20);
  74686. if (precision >= 0) {
  74687. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  74688. }
  74689. return [coordArr, coordArrValue];
  74690. } // TODO Specified percent
  74691. var markerTypeCalculator = {
  74692. min: curry(markerTypeCalculatorWithExtent, 'min'),
  74693. max: curry(markerTypeCalculatorWithExtent, 'max'),
  74694. average: curry(markerTypeCalculatorWithExtent, 'average'),
  74695. median: curry(markerTypeCalculatorWithExtent, 'median')
  74696. };
  74697. /**
  74698. * Transform markPoint data item to format used in List by do the following
  74699. * 1. Calculate statistic like `max`, `min`, `average`
  74700. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  74701. */
  74702. function dataTransform(seriesModel, item) {
  74703. if (!item) {
  74704. return;
  74705. }
  74706. var data = seriesModel.getData();
  74707. var coordSys = seriesModel.coordinateSystem;
  74708. var dims = coordSys && coordSys.dimensions; // 1. If not specify the position with pixel directly
  74709. // 2. If `coord` is not a data array. Which uses `xAxis`,
  74710. // `yAxis` to specify the coord on each dimension
  74711. // parseFloat first because item.x and item.y can be percent string like '20%'
  74712. if (!hasXAndY(item) && !isArray(item.coord) && isArray(dims)) {
  74713. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option
  74714. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  74715. item = clone(item);
  74716. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  74717. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  74718. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  74719. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  74720. item.coord = coordInfo[0]; // Force to use the value of calculated value.
  74721. // let item use the value without stack.
  74722. item.value = coordInfo[1];
  74723. } else {
  74724. // FIXME Only has one of xAxis and yAxis.
  74725. item.coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis];
  74726. }
  74727. } // x y is provided
  74728. if (item.coord == null || !isArray(dims)) {
  74729. item.coord = [];
  74730. } else {
  74731. // Each coord support max, min, average
  74732. var coord = item.coord;
  74733. for (var i = 0; i < 2; i++) {
  74734. if (markerTypeCalculator[coord[i]]) {
  74735. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  74736. }
  74737. }
  74738. }
  74739. return item;
  74740. }
  74741. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  74742. var ret = {};
  74743. if (item.valueIndex != null || item.valueDim != null) {
  74744. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  74745. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  74746. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  74747. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74748. } else {
  74749. ret.baseAxis = seriesModel.getBaseAxis();
  74750. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  74751. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74752. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  74753. }
  74754. return ret;
  74755. }
  74756. function dataDimToCoordDim(seriesModel, dataDim) {
  74757. var dimItem = seriesModel.getData().getDimensionInfo(dataDim);
  74758. return dimItem && dimItem.coordDim;
  74759. }
  74760. /**
  74761. * Filter data which is out of coordinateSystem range
  74762. * [dataFilter description]
  74763. */
  74764. function dataFilter$1( // Currently only polar and cartesian has containData.
  74765. coordSys, item) {
  74766. // Always return true if there is no coordSys
  74767. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  74768. }
  74769. function zoneFilter( // Currently only polar and cartesian has containData.
  74770. coordSys, item1, item2) {
  74771. // Always return true if there is no coordSys
  74772. return coordSys && coordSys.containZone && item1.coord && item2.coord && !hasXOrY(item1) && !hasXOrY(item2) ? coordSys.containZone(item1.coord, item2.coord) : true;
  74773. }
  74774. function createMarkerDimValueGetter(inCoordSys, dims) {
  74775. return inCoordSys ? function (item, dimName, dataIndex, dimIndex) {
  74776. var rawVal = dimIndex < 2 // x, y, radius, angle
  74777. ? item.coord && item.coord[dimIndex] : item.value;
  74778. return parseDataValue(rawVal, dims[dimIndex]);
  74779. } : function (item, dimName, dataIndex, dimIndex) {
  74780. return parseDataValue(item.value, dims[dimIndex]);
  74781. };
  74782. }
  74783. function numCalculate(data, valueDataDim, type) {
  74784. if (type === 'average') {
  74785. var sum_1 = 0;
  74786. var count_1 = 0;
  74787. data.each(valueDataDim, function (val, idx) {
  74788. if (!isNaN(val)) {
  74789. sum_1 += val;
  74790. count_1++;
  74791. }
  74792. });
  74793. return sum_1 / count_1;
  74794. } else if (type === 'median') {
  74795. return data.getMedian(valueDataDim);
  74796. } else {
  74797. // max & min
  74798. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  74799. }
  74800. }
  74801. var inner$h = makeInner();
  74802. var MarkerView =
  74803. /** @class */
  74804. function (_super) {
  74805. __extends(MarkerView, _super);
  74806. function MarkerView() {
  74807. var _this = _super !== null && _super.apply(this, arguments) || this;
  74808. _this.type = MarkerView.type;
  74809. return _this;
  74810. }
  74811. MarkerView.prototype.init = function () {
  74812. this.markerGroupMap = createHashMap();
  74813. };
  74814. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  74815. var _this = this;
  74816. var markerGroupMap = this.markerGroupMap;
  74817. markerGroupMap.each(function (item) {
  74818. inner$h(item).keep = false;
  74819. });
  74820. ecModel.eachSeries(function (seriesModel) {
  74821. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  74822. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  74823. });
  74824. markerGroupMap.each(function (item) {
  74825. !inner$h(item).keep && _this.group.remove(item.group);
  74826. });
  74827. };
  74828. MarkerView.prototype.markKeep = function (drawGroup) {
  74829. inner$h(drawGroup).keep = true;
  74830. };
  74831. MarkerView.prototype.toggleBlurSeries = function (seriesModelList, isBlur) {
  74832. var _this = this;
  74833. each(seriesModelList, function (seriesModel) {
  74834. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  74835. if (markerModel) {
  74836. var data = markerModel.getData();
  74837. data.eachItemGraphicEl(function (el) {
  74838. if (el) {
  74839. isBlur ? enterBlur(el) : leaveBlur(el);
  74840. }
  74841. });
  74842. }
  74843. });
  74844. };
  74845. MarkerView.type = 'marker';
  74846. return MarkerView;
  74847. }(ComponentView);
  74848. function updateMarkerLayout(mpData, seriesModel, api) {
  74849. var coordSys = seriesModel.coordinateSystem;
  74850. mpData.each(function (idx) {
  74851. var itemModel = mpData.getItemModel(idx);
  74852. var point;
  74853. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74854. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74855. if (!isNaN(xPx) && !isNaN(yPx)) {
  74856. point = [xPx, yPx];
  74857. } // Chart like bar may have there own marker positioning logic
  74858. else if (seriesModel.getMarkerPosition) {
  74859. // Use the getMarkerPosition
  74860. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  74861. } else if (coordSys) {
  74862. var x = mpData.get(coordSys.dimensions[0], idx);
  74863. var y = mpData.get(coordSys.dimensions[1], idx);
  74864. point = coordSys.dataToPoint([x, y]);
  74865. } // Use x, y if has any
  74866. if (!isNaN(xPx)) {
  74867. point[0] = xPx;
  74868. }
  74869. if (!isNaN(yPx)) {
  74870. point[1] = yPx;
  74871. }
  74872. mpData.setItemLayout(idx, point);
  74873. });
  74874. }
  74875. var MarkPointView =
  74876. /** @class */
  74877. function (_super) {
  74878. __extends(MarkPointView, _super);
  74879. function MarkPointView() {
  74880. var _this = _super !== null && _super.apply(this, arguments) || this;
  74881. _this.type = MarkPointView.type;
  74882. return _this;
  74883. }
  74884. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  74885. ecModel.eachSeries(function (seriesModel) {
  74886. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  74887. if (mpModel) {
  74888. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74889. this.markerGroupMap.get(seriesModel.id).updateLayout();
  74890. }
  74891. }, this);
  74892. };
  74893. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  74894. var coordSys = seriesModel.coordinateSystem;
  74895. var seriesId = seriesModel.id;
  74896. var seriesData = seriesModel.getData();
  74897. var symbolDrawMap = this.markerGroupMap;
  74898. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  74899. var mpData = createData(coordSys, seriesModel, mpModel); // FIXME
  74900. mpModel.setData(mpData);
  74901. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  74902. mpData.each(function (idx) {
  74903. var itemModel = mpData.getItemModel(idx);
  74904. var symbol = itemModel.getShallow('symbol');
  74905. var symbolSize = itemModel.getShallow('symbolSize');
  74906. var symbolRotate = itemModel.getShallow('symbolRotate');
  74907. var symbolOffset = itemModel.getShallow('symbolOffset');
  74908. var symbolKeepAspect = itemModel.getShallow('symbolKeepAspect'); // TODO: refactor needed: single data item should not support callback function
  74909. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate) || isFunction(symbolOffset)) {
  74910. var rawIdx = mpModel.getRawValue(idx);
  74911. var dataParams = mpModel.getDataParams(idx);
  74912. if (isFunction(symbol)) {
  74913. symbol = symbol(rawIdx, dataParams);
  74914. }
  74915. if (isFunction(symbolSize)) {
  74916. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  74917. symbolSize = symbolSize(rawIdx, dataParams);
  74918. }
  74919. if (isFunction(symbolRotate)) {
  74920. symbolRotate = symbolRotate(rawIdx, dataParams);
  74921. }
  74922. if (isFunction(symbolOffset)) {
  74923. symbolOffset = symbolOffset(rawIdx, dataParams);
  74924. }
  74925. }
  74926. var style = itemModel.getModel('itemStyle').getItemStyle();
  74927. var color = getVisualFromData(seriesData, 'color');
  74928. if (!style.fill) {
  74929. style.fill = color;
  74930. }
  74931. mpData.setItemVisual(idx, {
  74932. symbol: symbol,
  74933. symbolSize: symbolSize,
  74934. symbolRotate: symbolRotate,
  74935. symbolOffset: symbolOffset,
  74936. symbolKeepAspect: symbolKeepAspect,
  74937. style: style
  74938. });
  74939. }); // TODO Text are wrong
  74940. symbolDraw.updateData(mpData);
  74941. this.group.add(symbolDraw.group); // Set host model for tooltip
  74942. // FIXME
  74943. mpData.eachItemGraphicEl(function (el) {
  74944. el.traverse(function (child) {
  74945. getECData(child).dataModel = mpModel;
  74946. });
  74947. });
  74948. this.markKeep(symbolDraw);
  74949. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  74950. };
  74951. MarkPointView.type = 'markPoint';
  74952. return MarkPointView;
  74953. }(MarkerView);
  74954. function createData(coordSys, seriesModel, mpModel) {
  74955. var coordDimsInfos;
  74956. if (coordSys) {
  74957. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  74958. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  74959. return extend(extend({}, info), {
  74960. name: coordDim,
  74961. // DON'T use ordinalMeta to parse and collect ordinal.
  74962. ordinalMeta: null
  74963. });
  74964. });
  74965. } else {
  74966. coordDimsInfos = [{
  74967. name: 'value',
  74968. type: 'float'
  74969. }];
  74970. }
  74971. var mpData = new SeriesData(coordDimsInfos, mpModel);
  74972. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  74973. if (coordSys) {
  74974. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  74975. }
  74976. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  74977. mpData.initData(dataOpt, null, dimValueGetter);
  74978. return mpData;
  74979. }
  74980. function install$E(registers) {
  74981. registers.registerComponentModel(MarkPointModel);
  74982. registers.registerComponentView(MarkPointView);
  74983. registers.registerPreprocessor(function (opt) {
  74984. if (checkMarkerInSeries(opt.series, 'markPoint')) {
  74985. // Make sure markPoint component is enabled
  74986. opt.markPoint = opt.markPoint || {};
  74987. }
  74988. });
  74989. }
  74990. var MarkLineModel =
  74991. /** @class */
  74992. function (_super) {
  74993. __extends(MarkLineModel, _super);
  74994. function MarkLineModel() {
  74995. var _this = _super !== null && _super.apply(this, arguments) || this;
  74996. _this.type = MarkLineModel.type;
  74997. return _this;
  74998. }
  74999. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  75000. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  75001. };
  75002. MarkLineModel.type = 'markLine';
  75003. MarkLineModel.defaultOption = {
  75004. // zlevel: 0,
  75005. z: 5,
  75006. symbol: ['circle', 'arrow'],
  75007. symbolSize: [8, 16],
  75008. // symbolRotate: 0,
  75009. symbolOffset: 0,
  75010. precision: 2,
  75011. tooltip: {
  75012. trigger: 'item'
  75013. },
  75014. label: {
  75015. show: true,
  75016. position: 'end',
  75017. distance: 5
  75018. },
  75019. lineStyle: {
  75020. type: 'dashed'
  75021. },
  75022. emphasis: {
  75023. label: {
  75024. show: true
  75025. },
  75026. lineStyle: {
  75027. width: 3
  75028. }
  75029. },
  75030. animationEasing: 'linear'
  75031. };
  75032. return MarkLineModel;
  75033. }(MarkerModel);
  75034. var inner$i = makeInner();
  75035. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  75036. var data = seriesModel.getData();
  75037. var itemArray;
  75038. if (!isArray(item)) {
  75039. // Special type markLine like 'min', 'max', 'average', 'median'
  75040. var mlType = item.type;
  75041. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median' // In case
  75042. // data: [{
  75043. // yAxis: 10
  75044. // }]
  75045. || item.xAxis != null || item.yAxis != null) {
  75046. var valueAxis = void 0;
  75047. var value = void 0;
  75048. if (item.yAxis != null || item.xAxis != null) {
  75049. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  75050. value = retrieve(item.yAxis, item.xAxis);
  75051. } else {
  75052. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  75053. valueAxis = axisInfo.valueAxis;
  75054. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  75055. value = numCalculate(data, valueDataDim, mlType);
  75056. }
  75057. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  75058. var baseIndex = 1 - valueIndex; // Normized to 2d data with start and end point
  75059. var mlFrom = clone(item);
  75060. var mlTo = {
  75061. coord: []
  75062. };
  75063. mlFrom.type = null;
  75064. mlFrom.coord = [];
  75065. mlFrom.coord[baseIndex] = -Infinity;
  75066. mlTo.coord[baseIndex] = Infinity;
  75067. var precision = mlModel.get('precision');
  75068. if (precision >= 0 && isNumber(value)) {
  75069. value = +value.toFixed(Math.min(precision, 20));
  75070. }
  75071. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  75072. itemArray = [mlFrom, mlTo, {
  75073. type: mlType,
  75074. valueIndex: item.valueIndex,
  75075. // Force to use the value of calculated value.
  75076. value: value
  75077. }];
  75078. } else {
  75079. // Invalid data
  75080. if ("development" !== 'production') {
  75081. logError('Invalid markLine data.');
  75082. }
  75083. itemArray = [];
  75084. }
  75085. } else {
  75086. itemArray = item;
  75087. }
  75088. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])]; // Avoid line data type is extended by from(to) data type
  75089. normalizedItem[2].type = normalizedItem[2].type || null; // Merge from option and to option into line option
  75090. merge(normalizedItem[2], normalizedItem[0]);
  75091. merge(normalizedItem[2], normalizedItem[1]);
  75092. return normalizedItem;
  75093. };
  75094. function isInfinity(val) {
  75095. return !isNaN(val) && !isFinite(val);
  75096. } // If a markLine has one dim
  75097. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  75098. var otherDimIndex = 1 - dimIndex;
  75099. var dimName = coordSys.dimensions[dimIndex];
  75100. return isInfinity(fromCoord[otherDimIndex]) && isInfinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  75101. }
  75102. function markLineFilter(coordSys, item) {
  75103. if (coordSys.type === 'cartesian2d') {
  75104. var fromCoord = item[0].coord;
  75105. var toCoord = item[1].coord; // In case
  75106. // {
  75107. // markLine: {
  75108. // data: [{ yAxis: 2 }]
  75109. // }
  75110. // }
  75111. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  75112. return true;
  75113. }
  75114. }
  75115. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  75116. }
  75117. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  75118. var coordSys = seriesModel.coordinateSystem;
  75119. var itemModel = data.getItemModel(idx);
  75120. var point;
  75121. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  75122. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  75123. if (!isNaN(xPx) && !isNaN(yPx)) {
  75124. point = [xPx, yPx];
  75125. } else {
  75126. // Chart like bar may have there own marker positioning logic
  75127. if (seriesModel.getMarkerPosition) {
  75128. // Use the getMarkerPosition
  75129. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  75130. } else {
  75131. var dims = coordSys.dimensions;
  75132. var x = data.get(dims[0], idx);
  75133. var y = data.get(dims[1], idx);
  75134. point = coordSys.dataToPoint([x, y]);
  75135. } // Expand line to the edge of grid if value on one axis is Inifnity
  75136. // In case
  75137. // markLine: {
  75138. // data: [{
  75139. // yAxis: 2
  75140. // // or
  75141. // type: 'average'
  75142. // }]
  75143. // }
  75144. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  75145. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  75146. var xAxis = coordSys.getAxis('x');
  75147. var yAxis = coordSys.getAxis('y');
  75148. var dims = coordSys.dimensions;
  75149. if (isInfinity(data.get(dims[0], idx))) {
  75150. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  75151. } else if (isInfinity(data.get(dims[1], idx))) {
  75152. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  75153. }
  75154. } // Use x, y if has any
  75155. if (!isNaN(xPx)) {
  75156. point[0] = xPx;
  75157. }
  75158. if (!isNaN(yPx)) {
  75159. point[1] = yPx;
  75160. }
  75161. }
  75162. data.setItemLayout(idx, point);
  75163. }
  75164. var MarkLineView =
  75165. /** @class */
  75166. function (_super) {
  75167. __extends(MarkLineView, _super);
  75168. function MarkLineView() {
  75169. var _this = _super !== null && _super.apply(this, arguments) || this;
  75170. _this.type = MarkLineView.type;
  75171. return _this;
  75172. }
  75173. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  75174. ecModel.eachSeries(function (seriesModel) {
  75175. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  75176. if (mlModel) {
  75177. var mlData_1 = mlModel.getData();
  75178. var fromData_1 = inner$i(mlModel).from;
  75179. var toData_1 = inner$i(mlModel).to; // Update visual and layout of from symbol and to symbol
  75180. fromData_1.each(function (idx) {
  75181. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  75182. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  75183. }); // Update layout of line
  75184. mlData_1.each(function (idx) {
  75185. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  75186. });
  75187. this.markerGroupMap.get(seriesModel.id).updateLayout();
  75188. }
  75189. }, this);
  75190. };
  75191. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  75192. var coordSys = seriesModel.coordinateSystem;
  75193. var seriesId = seriesModel.id;
  75194. var seriesData = seriesModel.getData();
  75195. var lineDrawMap = this.markerGroupMap;
  75196. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  75197. this.group.add(lineDraw.group);
  75198. var mlData = createList$1(coordSys, seriesModel, mlModel);
  75199. var fromData = mlData.from;
  75200. var toData = mlData.to;
  75201. var lineData = mlData.line;
  75202. inner$i(mlModel).from = fromData;
  75203. inner$i(mlModel).to = toData; // Line data for tooltip and formatter
  75204. mlModel.setData(lineData); // TODO
  75205. // Functionally, `symbolSize` & `symbolOffset` can also be 2D array now.
  75206. // But the related logic and type definition are not finished yet.
  75207. // Finish it if required
  75208. var symbolType = mlModel.get('symbol');
  75209. var symbolSize = mlModel.get('symbolSize');
  75210. var symbolRotate = mlModel.get('symbolRotate');
  75211. var symbolOffset = mlModel.get('symbolOffset'); // TODO: support callback function like markPoint
  75212. if (!isArray(symbolType)) {
  75213. symbolType = [symbolType, symbolType];
  75214. }
  75215. if (!isArray(symbolSize)) {
  75216. symbolSize = [symbolSize, symbolSize];
  75217. }
  75218. if (!isArray(symbolRotate)) {
  75219. symbolRotate = [symbolRotate, symbolRotate];
  75220. }
  75221. if (!isArray(symbolOffset)) {
  75222. symbolOffset = [symbolOffset, symbolOffset];
  75223. } // Update visual and layout of from symbol and to symbol
  75224. mlData.from.each(function (idx) {
  75225. updateDataVisualAndLayout(fromData, idx, true);
  75226. updateDataVisualAndLayout(toData, idx, false);
  75227. }); // Update visual and layout of line
  75228. lineData.each(function (idx) {
  75229. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle(); // lineData.setItemVisual(idx, {
  75230. // color: lineColor || fromData.getItemVisual(idx, 'color')
  75231. // });
  75232. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  75233. if (lineStyle.stroke == null) {
  75234. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  75235. }
  75236. lineData.setItemVisual(idx, {
  75237. fromSymbolKeepAspect: fromData.getItemVisual(idx, 'symbolKeepAspect'),
  75238. fromSymbolOffset: fromData.getItemVisual(idx, 'symbolOffset'),
  75239. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  75240. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  75241. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  75242. toSymbolKeepAspect: toData.getItemVisual(idx, 'symbolKeepAspect'),
  75243. toSymbolOffset: toData.getItemVisual(idx, 'symbolOffset'),
  75244. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  75245. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  75246. toSymbol: toData.getItemVisual(idx, 'symbol'),
  75247. style: lineStyle
  75248. });
  75249. });
  75250. lineDraw.updateData(lineData); // Set host model for tooltip
  75251. // FIXME
  75252. mlData.line.eachItemGraphicEl(function (el) {
  75253. getECData(el).dataModel = mlModel;
  75254. el.traverse(function (child) {
  75255. getECData(child).dataModel = mlModel;
  75256. });
  75257. });
  75258. function updateDataVisualAndLayout(data, idx, isFrom) {
  75259. var itemModel = data.getItemModel(idx);
  75260. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  75261. var style = itemModel.getModel('itemStyle').getItemStyle();
  75262. if (style.fill == null) {
  75263. style.fill = getVisualFromData(seriesData, 'color');
  75264. }
  75265. data.setItemVisual(idx, {
  75266. symbolKeepAspect: itemModel.get('symbolKeepAspect'),
  75267. // `0` should be considered as a valid value, so use `retrieve2` instead of `||`
  75268. symbolOffset: retrieve2(itemModel.get('symbolOffset', true), symbolOffset[isFrom ? 0 : 1]),
  75269. symbolRotate: retrieve2(itemModel.get('symbolRotate', true), symbolRotate[isFrom ? 0 : 1]),
  75270. // TODO: when 2d array is supported, it should ignore parent
  75271. symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]),
  75272. symbol: retrieve2(itemModel.get('symbol', true), symbolType[isFrom ? 0 : 1]),
  75273. style: style
  75274. });
  75275. }
  75276. this.markKeep(lineDraw);
  75277. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  75278. };
  75279. MarkLineView.type = 'markLine';
  75280. return MarkLineView;
  75281. }(MarkerView);
  75282. function createList$1(coordSys, seriesModel, mlModel) {
  75283. var coordDimsInfos;
  75284. if (coordSys) {
  75285. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75286. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75287. return extend(extend({}, info), {
  75288. name: coordDim,
  75289. // DON'T use ordinalMeta to parse and collect ordinal.
  75290. ordinalMeta: null
  75291. });
  75292. });
  75293. } else {
  75294. coordDimsInfos = [{
  75295. name: 'value',
  75296. type: 'float'
  75297. }];
  75298. }
  75299. var fromData = new SeriesData(coordDimsInfos, mlModel);
  75300. var toData = new SeriesData(coordDimsInfos, mlModel); // No dimensions
  75301. var lineData = new SeriesData([], mlModel);
  75302. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  75303. if (coordSys) {
  75304. optData = filter(optData, curry(markLineFilter, coordSys));
  75305. }
  75306. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  75307. fromData.initData(map(optData, function (item) {
  75308. return item[0];
  75309. }), null, dimValueGetter);
  75310. toData.initData(map(optData, function (item) {
  75311. return item[1];
  75312. }), null, dimValueGetter);
  75313. lineData.initData(map(optData, function (item) {
  75314. return item[2];
  75315. }));
  75316. lineData.hasItemOption = true;
  75317. return {
  75318. from: fromData,
  75319. to: toData,
  75320. line: lineData
  75321. };
  75322. }
  75323. function install$F(registers) {
  75324. registers.registerComponentModel(MarkLineModel);
  75325. registers.registerComponentView(MarkLineView);
  75326. registers.registerPreprocessor(function (opt) {
  75327. if (checkMarkerInSeries(opt.series, 'markLine')) {
  75328. // Make sure markLine component is enabled
  75329. opt.markLine = opt.markLine || {};
  75330. }
  75331. });
  75332. }
  75333. var MarkAreaModel =
  75334. /** @class */
  75335. function (_super) {
  75336. __extends(MarkAreaModel, _super);
  75337. function MarkAreaModel() {
  75338. var _this = _super !== null && _super.apply(this, arguments) || this;
  75339. _this.type = MarkAreaModel.type;
  75340. return _this;
  75341. }
  75342. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  75343. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  75344. };
  75345. MarkAreaModel.type = 'markArea';
  75346. MarkAreaModel.defaultOption = {
  75347. // zlevel: 0,
  75348. // PENDING
  75349. z: 1,
  75350. tooltip: {
  75351. trigger: 'item'
  75352. },
  75353. // markArea should fixed on the coordinate system
  75354. animation: false,
  75355. label: {
  75356. show: true,
  75357. position: 'top'
  75358. },
  75359. itemStyle: {
  75360. // color and borderColor default to use color from series
  75361. // color: 'auto'
  75362. // borderColor: 'auto'
  75363. borderWidth: 0
  75364. },
  75365. emphasis: {
  75366. label: {
  75367. show: true,
  75368. position: 'top'
  75369. }
  75370. }
  75371. };
  75372. return MarkAreaModel;
  75373. }(MarkerModel);
  75374. var inner$j = makeInner();
  75375. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  75376. // item may be null
  75377. var item0 = item[0];
  75378. var item1 = item[1];
  75379. if (!item0 || !item1) {
  75380. return;
  75381. }
  75382. var lt = dataTransform(seriesModel, item0);
  75383. var rb = dataTransform(seriesModel, item1); // FIXME make sure lt is less than rb
  75384. var ltCoord = lt.coord;
  75385. var rbCoord = rb.coord;
  75386. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  75387. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  75388. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  75389. rbCoord[1] = retrieve(rbCoord[1], Infinity); // Merge option into one
  75390. var result = mergeAll([{}, lt, rb]);
  75391. result.coord = [lt.coord, rb.coord];
  75392. result.x0 = lt.x;
  75393. result.y0 = lt.y;
  75394. result.x1 = rb.x;
  75395. result.y1 = rb.y;
  75396. return result;
  75397. };
  75398. function isInfinity$1(val) {
  75399. return !isNaN(val) && !isFinite(val);
  75400. } // If a markArea has one dim
  75401. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  75402. var otherDimIndex = 1 - dimIndex;
  75403. return isInfinity$1(fromCoord[otherDimIndex]) && isInfinity$1(toCoord[otherDimIndex]);
  75404. }
  75405. function markAreaFilter(coordSys, item) {
  75406. var fromCoord = item.coord[0];
  75407. var toCoord = item.coord[1];
  75408. var item0 = {
  75409. coord: fromCoord,
  75410. x: item.x0,
  75411. y: item.y0
  75412. };
  75413. var item1 = {
  75414. coord: toCoord,
  75415. x: item.x1,
  75416. y: item.y1
  75417. };
  75418. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  75419. // In case
  75420. // {
  75421. // markArea: {
  75422. // data: [{ yAxis: 2 }]
  75423. // }
  75424. // }
  75425. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  75426. return true;
  75427. } // Directly returning true may also do the work,
  75428. // because markArea will not be shown automatically
  75429. // when it's not included in coordinate system.
  75430. // But filtering ahead can avoid keeping rendering markArea
  75431. // when there are too many of them.
  75432. return zoneFilter(coordSys, item0, item1);
  75433. }
  75434. return dataFilter$1(coordSys, item0) || dataFilter$1(coordSys, item1);
  75435. } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  75436. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  75437. var coordSys = seriesModel.coordinateSystem;
  75438. var itemModel = data.getItemModel(idx);
  75439. var point;
  75440. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  75441. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  75442. if (!isNaN(xPx) && !isNaN(yPx)) {
  75443. point = [xPx, yPx];
  75444. } else {
  75445. // Chart like bar may have there own marker positioning logic
  75446. if (seriesModel.getMarkerPosition) {
  75447. // Consider the case that user input the right-bottom point first
  75448. // Pick the larger x and y as 'x1' and 'y1'
  75449. var pointValue0 = data.getValues(['x0', 'y0'], idx);
  75450. var pointValue1 = data.getValues(['x1', 'y1'], idx);
  75451. var clampPointValue0 = coordSys.clampData(pointValue0);
  75452. var clampPointValue1 = coordSys.clampData(pointValue1);
  75453. var pointValue = [];
  75454. if (dims[0] === 'x0') {
  75455. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue1[0] : pointValue0[0];
  75456. } else {
  75457. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue0[0] : pointValue1[0];
  75458. }
  75459. if (dims[1] === 'y0') {
  75460. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue1[1] : pointValue0[1];
  75461. } else {
  75462. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue0[1] : pointValue1[1];
  75463. } // Use the getMarkerPosition
  75464. point = seriesModel.getMarkerPosition(pointValue, dims, true);
  75465. } else {
  75466. var x = data.get(dims[0], idx);
  75467. var y = data.get(dims[1], idx);
  75468. var pt = [x, y];
  75469. coordSys.clampData && coordSys.clampData(pt, pt);
  75470. point = coordSys.dataToPoint(pt, true);
  75471. }
  75472. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  75473. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  75474. var xAxis = coordSys.getAxis('x');
  75475. var yAxis = coordSys.getAxis('y');
  75476. var x = data.get(dims[0], idx);
  75477. var y = data.get(dims[1], idx);
  75478. if (isInfinity$1(x)) {
  75479. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  75480. } else if (isInfinity$1(y)) {
  75481. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  75482. }
  75483. } // Use x, y if has any
  75484. if (!isNaN(xPx)) {
  75485. point[0] = xPx;
  75486. }
  75487. if (!isNaN(yPx)) {
  75488. point[1] = yPx;
  75489. }
  75490. }
  75491. return point;
  75492. }
  75493. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  75494. var MarkAreaView =
  75495. /** @class */
  75496. function (_super) {
  75497. __extends(MarkAreaView, _super);
  75498. function MarkAreaView() {
  75499. var _this = _super !== null && _super.apply(this, arguments) || this;
  75500. _this.type = MarkAreaView.type;
  75501. return _this;
  75502. }
  75503. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  75504. ecModel.eachSeries(function (seriesModel) {
  75505. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  75506. if (maModel) {
  75507. var areaData_1 = maModel.getData();
  75508. areaData_1.each(function (idx) {
  75509. var points = map(dimPermutations, function (dim) {
  75510. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  75511. }); // Layout
  75512. areaData_1.setItemLayout(idx, points);
  75513. var el = areaData_1.getItemGraphicEl(idx);
  75514. el.setShape('points', points);
  75515. });
  75516. }
  75517. }, this);
  75518. };
  75519. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  75520. var coordSys = seriesModel.coordinateSystem;
  75521. var seriesId = seriesModel.id;
  75522. var seriesData = seriesModel.getData();
  75523. var areaGroupMap = this.markerGroupMap;
  75524. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  75525. group: new Group()
  75526. });
  75527. this.group.add(polygonGroup.group);
  75528. this.markKeep(polygonGroup);
  75529. var areaData = createList$2(coordSys, seriesModel, maModel); // Line data for tooltip and formatter
  75530. maModel.setData(areaData); // Update visual and layout of line
  75531. areaData.each(function (idx) {
  75532. // Layout
  75533. var points = map(dimPermutations, function (dim) {
  75534. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75535. });
  75536. var xAxisScale = coordSys.getAxis('x').scale;
  75537. var yAxisScale = coordSys.getAxis('y').scale;
  75538. var xAxisExtent = xAxisScale.getExtent();
  75539. var yAxisExtent = yAxisScale.getExtent();
  75540. var xPointExtent = [xAxisScale.parse(areaData.get('x0', idx)), xAxisScale.parse(areaData.get('x1', idx))];
  75541. var yPointExtent = [yAxisScale.parse(areaData.get('y0', idx)), yAxisScale.parse(areaData.get('y1', idx))];
  75542. asc(xPointExtent);
  75543. asc(yPointExtent);
  75544. var overlapped = !(xAxisExtent[0] > xPointExtent[1] || xAxisExtent[1] < xPointExtent[0] || yAxisExtent[0] > yPointExtent[1] || yAxisExtent[1] < yPointExtent[0]); // If none of the area is inside coordSys, allClipped is set to be true
  75545. // in layout so that label will not be displayed. See #12591
  75546. var allClipped = !overlapped;
  75547. areaData.setItemLayout(idx, {
  75548. points: points,
  75549. allClipped: allClipped
  75550. });
  75551. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  75552. var color$1 = getVisualFromData(seriesData, 'color');
  75553. if (!style.fill) {
  75554. style.fill = color$1;
  75555. if (isString(style.fill)) {
  75556. style.fill = modifyAlpha(style.fill, 0.4);
  75557. }
  75558. }
  75559. if (!style.stroke) {
  75560. style.stroke = color$1;
  75561. } // Visual
  75562. areaData.setItemVisual(idx, 'style', style);
  75563. });
  75564. areaData.diff(inner$j(polygonGroup).data).add(function (idx) {
  75565. var layout = areaData.getItemLayout(idx);
  75566. if (!layout.allClipped) {
  75567. var polygon = new Polygon({
  75568. shape: {
  75569. points: layout.points
  75570. }
  75571. });
  75572. areaData.setItemGraphicEl(idx, polygon);
  75573. polygonGroup.group.add(polygon);
  75574. }
  75575. }).update(function (newIdx, oldIdx) {
  75576. var polygon = inner$j(polygonGroup).data.getItemGraphicEl(oldIdx);
  75577. var layout = areaData.getItemLayout(newIdx);
  75578. if (!layout.allClipped) {
  75579. if (polygon) {
  75580. updateProps(polygon, {
  75581. shape: {
  75582. points: layout.points
  75583. }
  75584. }, maModel, newIdx);
  75585. } else {
  75586. polygon = new Polygon({
  75587. shape: {
  75588. points: layout.points
  75589. }
  75590. });
  75591. }
  75592. areaData.setItemGraphicEl(newIdx, polygon);
  75593. polygonGroup.group.add(polygon);
  75594. } else if (polygon) {
  75595. polygonGroup.group.remove(polygon);
  75596. }
  75597. }).remove(function (idx) {
  75598. var polygon = inner$j(polygonGroup).data.getItemGraphicEl(idx);
  75599. polygonGroup.group.remove(polygon);
  75600. }).execute();
  75601. areaData.eachItemGraphicEl(function (polygon, idx) {
  75602. var itemModel = areaData.getItemModel(idx);
  75603. var style = areaData.getItemVisual(idx, 'style');
  75604. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  75605. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  75606. labelFetcher: maModel,
  75607. labelDataIndex: idx,
  75608. defaultText: areaData.getName(idx) || '',
  75609. inheritColor: isString(style.fill) ? modifyAlpha(style.fill, 1) : '#000'
  75610. });
  75611. setStatesStylesFromModel(polygon, itemModel);
  75612. toggleHoverEmphasis(polygon, null, null, itemModel.get(['emphasis', 'disabled']));
  75613. getECData(polygon).dataModel = maModel;
  75614. });
  75615. inner$j(polygonGroup).data = areaData;
  75616. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  75617. };
  75618. MarkAreaView.type = 'markArea';
  75619. return MarkAreaView;
  75620. }(MarkerView);
  75621. function createList$2(coordSys, seriesModel, maModel) {
  75622. var areaData;
  75623. var dataDims;
  75624. var dims = ['x0', 'y0', 'x1', 'y1'];
  75625. if (coordSys) {
  75626. var coordDimsInfos_1 = map(coordSys && coordSys.dimensions, function (coordDim) {
  75627. var data = seriesModel.getData();
  75628. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75629. return extend(extend({}, info), {
  75630. name: coordDim,
  75631. // DON'T use ordinalMeta to parse and collect ordinal.
  75632. ordinalMeta: null
  75633. });
  75634. });
  75635. dataDims = map(dims, function (dim, idx) {
  75636. return {
  75637. name: dim,
  75638. type: coordDimsInfos_1[idx % 2].type
  75639. };
  75640. });
  75641. areaData = new SeriesData(dataDims, maModel);
  75642. } else {
  75643. dataDims = [{
  75644. name: 'value',
  75645. type: 'float'
  75646. }];
  75647. areaData = new SeriesData(dataDims, maModel);
  75648. }
  75649. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  75650. if (coordSys) {
  75651. optData = filter(optData, curry(markAreaFilter, coordSys));
  75652. }
  75653. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  75654. // TODO should convert to ParsedValue?
  75655. var rawVal = item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  75656. return parseDataValue(rawVal, dataDims[dimIndex]);
  75657. } : function (item, dimName, dataIndex, dimIndex) {
  75658. return parseDataValue(item.value, dataDims[dimIndex]);
  75659. };
  75660. areaData.initData(optData, null, dimValueGetter);
  75661. areaData.hasItemOption = true;
  75662. return areaData;
  75663. }
  75664. function install$G(registers) {
  75665. registers.registerComponentModel(MarkAreaModel);
  75666. registers.registerComponentView(MarkAreaView);
  75667. registers.registerPreprocessor(function (opt) {
  75668. if (checkMarkerInSeries(opt.series, 'markArea')) {
  75669. // Make sure markArea component is enabled
  75670. opt.markArea = opt.markArea || {};
  75671. }
  75672. });
  75673. }
  75674. var getDefaultSelectorOptions = function (ecModel, type) {
  75675. if (type === 'all') {
  75676. return {
  75677. type: 'all',
  75678. title: ecModel.getLocaleModel().get(['legend', 'selector', 'all'])
  75679. };
  75680. } else if (type === 'inverse') {
  75681. return {
  75682. type: 'inverse',
  75683. title: ecModel.getLocaleModel().get(['legend', 'selector', 'inverse'])
  75684. };
  75685. }
  75686. };
  75687. var LegendModel =
  75688. /** @class */
  75689. function (_super) {
  75690. __extends(LegendModel, _super);
  75691. function LegendModel() {
  75692. var _this = _super !== null && _super.apply(this, arguments) || this;
  75693. _this.type = LegendModel.type;
  75694. _this.layoutMode = {
  75695. type: 'box',
  75696. // legend.width/height are maxWidth/maxHeight actually,
  75697. // whereas real width/height is calculated by its content.
  75698. // (Setting {left: 10, right: 10} does not make sense).
  75699. // So consider the case:
  75700. // `setOption({legend: {left: 10});`
  75701. // then `setOption({legend: {right: 10});`
  75702. // The previous `left` should be cleared by setting `ignoreSize`.
  75703. ignoreSize: true
  75704. };
  75705. return _this;
  75706. }
  75707. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  75708. this.mergeDefaultAndTheme(option, ecModel);
  75709. option.selected = option.selected || {};
  75710. this._updateSelector(option);
  75711. };
  75712. LegendModel.prototype.mergeOption = function (option, ecModel) {
  75713. _super.prototype.mergeOption.call(this, option, ecModel);
  75714. this._updateSelector(option);
  75715. };
  75716. LegendModel.prototype._updateSelector = function (option) {
  75717. var selector = option.selector;
  75718. var ecModel = this.ecModel;
  75719. if (selector === true) {
  75720. selector = option.selector = ['all', 'inverse'];
  75721. }
  75722. if (isArray(selector)) {
  75723. each(selector, function (item, index) {
  75724. isString(item) && (item = {
  75725. type: item
  75726. });
  75727. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  75728. });
  75729. }
  75730. };
  75731. LegendModel.prototype.optionUpdated = function () {
  75732. this._updateData(this.ecModel);
  75733. var legendData = this._data; // If selectedMode is single, try to select one
  75734. if (legendData[0] && this.get('selectedMode') === 'single') {
  75735. var hasSelected = false; // If has any selected in option.selected
  75736. for (var i = 0; i < legendData.length; i++) {
  75737. var name_1 = legendData[i].get('name');
  75738. if (this.isSelected(name_1)) {
  75739. // Force to unselect others
  75740. this.select(name_1);
  75741. hasSelected = true;
  75742. break;
  75743. }
  75744. } // Try select the first if selectedMode is single
  75745. !hasSelected && this.select(legendData[0].get('name'));
  75746. }
  75747. };
  75748. LegendModel.prototype._updateData = function (ecModel) {
  75749. var potentialData = [];
  75750. var availableNames = [];
  75751. ecModel.eachRawSeries(function (seriesModel) {
  75752. var seriesName = seriesModel.name;
  75753. availableNames.push(seriesName);
  75754. var isPotential;
  75755. if (seriesModel.legendVisualProvider) {
  75756. var provider = seriesModel.legendVisualProvider;
  75757. var names = provider.getAllNames();
  75758. if (!ecModel.isSeriesFiltered(seriesModel)) {
  75759. availableNames = availableNames.concat(names);
  75760. }
  75761. if (names.length) {
  75762. potentialData = potentialData.concat(names);
  75763. } else {
  75764. isPotential = true;
  75765. }
  75766. } else {
  75767. isPotential = true;
  75768. }
  75769. if (isPotential && isNameSpecified(seriesModel)) {
  75770. potentialData.push(seriesModel.name);
  75771. }
  75772. });
  75773. /**
  75774. * @type {Array.<string>}
  75775. * @private
  75776. */
  75777. this._availableNames = availableNames; // If legend.data is not specified in option, use availableNames as data,
  75778. // which is convenient for user preparing option.
  75779. var rawData = this.get('data') || potentialData;
  75780. var legendNameMap = createHashMap();
  75781. var legendData = map(rawData, function (dataItem) {
  75782. // Can be string or number
  75783. if (isString(dataItem) || isNumber(dataItem)) {
  75784. dataItem = {
  75785. name: dataItem
  75786. };
  75787. }
  75788. if (legendNameMap.get(dataItem.name)) {
  75789. // remove legend name duplicate
  75790. return null;
  75791. }
  75792. legendNameMap.set(dataItem.name, true);
  75793. return new Model(dataItem, this, this.ecModel);
  75794. }, this);
  75795. /**
  75796. * @type {Array.<module:echarts/model/Model>}
  75797. * @private
  75798. */
  75799. this._data = filter(legendData, function (item) {
  75800. return !!item;
  75801. });
  75802. };
  75803. LegendModel.prototype.getData = function () {
  75804. return this._data;
  75805. };
  75806. LegendModel.prototype.select = function (name) {
  75807. var selected = this.option.selected;
  75808. var selectedMode = this.get('selectedMode');
  75809. if (selectedMode === 'single') {
  75810. var data = this._data;
  75811. each(data, function (dataItem) {
  75812. selected[dataItem.get('name')] = false;
  75813. });
  75814. }
  75815. selected[name] = true;
  75816. };
  75817. LegendModel.prototype.unSelect = function (name) {
  75818. if (this.get('selectedMode') !== 'single') {
  75819. this.option.selected[name] = false;
  75820. }
  75821. };
  75822. LegendModel.prototype.toggleSelected = function (name) {
  75823. var selected = this.option.selected; // Default is true
  75824. if (!selected.hasOwnProperty(name)) {
  75825. selected[name] = true;
  75826. }
  75827. this[selected[name] ? 'unSelect' : 'select'](name);
  75828. };
  75829. LegendModel.prototype.allSelect = function () {
  75830. var data = this._data;
  75831. var selected = this.option.selected;
  75832. each(data, function (dataItem) {
  75833. selected[dataItem.get('name', true)] = true;
  75834. });
  75835. };
  75836. LegendModel.prototype.inverseSelect = function () {
  75837. var data = this._data;
  75838. var selected = this.option.selected;
  75839. each(data, function (dataItem) {
  75840. var name = dataItem.get('name', true); // Initially, default value is true
  75841. if (!selected.hasOwnProperty(name)) {
  75842. selected[name] = true;
  75843. }
  75844. selected[name] = !selected[name];
  75845. });
  75846. };
  75847. LegendModel.prototype.isSelected = function (name) {
  75848. var selected = this.option.selected;
  75849. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  75850. };
  75851. LegendModel.prototype.getOrient = function () {
  75852. return this.get('orient') === 'vertical' ? {
  75853. index: 1,
  75854. name: 'vertical'
  75855. } : {
  75856. index: 0,
  75857. name: 'horizontal'
  75858. };
  75859. };
  75860. LegendModel.type = 'legend.plain';
  75861. LegendModel.dependencies = ['series'];
  75862. LegendModel.defaultOption = {
  75863. // zlevel: 0,
  75864. z: 4,
  75865. show: true,
  75866. orient: 'horizontal',
  75867. left: 'center',
  75868. // right: 'center',
  75869. top: 0,
  75870. // bottom: null,
  75871. align: 'auto',
  75872. backgroundColor: 'rgba(0,0,0,0)',
  75873. borderColor: '#ccc',
  75874. borderRadius: 0,
  75875. borderWidth: 0,
  75876. padding: 5,
  75877. itemGap: 10,
  75878. itemWidth: 25,
  75879. itemHeight: 14,
  75880. symbolRotate: 'inherit',
  75881. symbolKeepAspect: true,
  75882. inactiveColor: '#ccc',
  75883. inactiveBorderColor: '#ccc',
  75884. inactiveBorderWidth: 'auto',
  75885. itemStyle: {
  75886. color: 'inherit',
  75887. opacity: 'inherit',
  75888. borderColor: 'inherit',
  75889. borderWidth: 'auto',
  75890. borderCap: 'inherit',
  75891. borderJoin: 'inherit',
  75892. borderDashOffset: 'inherit',
  75893. borderMiterLimit: 'inherit'
  75894. },
  75895. lineStyle: {
  75896. width: 'auto',
  75897. color: 'inherit',
  75898. inactiveColor: '#ccc',
  75899. inactiveWidth: 2,
  75900. opacity: 'inherit',
  75901. type: 'inherit',
  75902. cap: 'inherit',
  75903. join: 'inherit',
  75904. dashOffset: 'inherit',
  75905. miterLimit: 'inherit'
  75906. },
  75907. textStyle: {
  75908. color: '#333'
  75909. },
  75910. selectedMode: true,
  75911. selector: false,
  75912. selectorLabel: {
  75913. show: true,
  75914. borderRadius: 10,
  75915. padding: [3, 5, 3, 5],
  75916. fontSize: 12,
  75917. fontFamily: 'sans-serif',
  75918. color: '#666',
  75919. borderWidth: 1,
  75920. borderColor: '#666'
  75921. },
  75922. emphasis: {
  75923. selectorLabel: {
  75924. show: true,
  75925. color: '#eee',
  75926. backgroundColor: '#666'
  75927. }
  75928. },
  75929. selectorPosition: 'auto',
  75930. selectorItemGap: 7,
  75931. selectorButtonGap: 10,
  75932. tooltip: {
  75933. show: false
  75934. }
  75935. };
  75936. return LegendModel;
  75937. }(ComponentModel);
  75938. var curry$1 = curry;
  75939. var each$c = each;
  75940. var Group$2 = Group;
  75941. var LegendView =
  75942. /** @class */
  75943. function (_super) {
  75944. __extends(LegendView, _super);
  75945. function LegendView() {
  75946. var _this = _super !== null && _super.apply(this, arguments) || this;
  75947. _this.type = LegendView.type;
  75948. _this.newlineDisabled = false;
  75949. return _this;
  75950. }
  75951. LegendView.prototype.init = function () {
  75952. this.group.add(this._contentGroup = new Group$2());
  75953. this.group.add(this._selectorGroup = new Group$2());
  75954. this._isFirstRender = true;
  75955. };
  75956. /**
  75957. * @protected
  75958. */
  75959. LegendView.prototype.getContentGroup = function () {
  75960. return this._contentGroup;
  75961. };
  75962. /**
  75963. * @protected
  75964. */
  75965. LegendView.prototype.getSelectorGroup = function () {
  75966. return this._selectorGroup;
  75967. };
  75968. /**
  75969. * @override
  75970. */
  75971. LegendView.prototype.render = function (legendModel, ecModel, api) {
  75972. var isFirstRender = this._isFirstRender;
  75973. this._isFirstRender = false;
  75974. this.resetInner();
  75975. if (!legendModel.get('show', true)) {
  75976. return;
  75977. }
  75978. var itemAlign = legendModel.get('align');
  75979. var orient = legendModel.get('orient');
  75980. if (!itemAlign || itemAlign === 'auto') {
  75981. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  75982. } // selector has been normalized to an array in model
  75983. var selector = legendModel.get('selector', true);
  75984. var selectorPosition = legendModel.get('selectorPosition', true);
  75985. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  75986. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  75987. }
  75988. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  75989. var positionInfo = legendModel.getBoxLayoutParams();
  75990. var viewportSize = {
  75991. width: api.getWidth(),
  75992. height: api.getHeight()
  75993. };
  75994. var padding = legendModel.get('padding');
  75995. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  75996. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  75997. var layoutRect = getLayoutRect(defaults({
  75998. width: mainRect.width,
  75999. height: mainRect.height
  76000. }, positionInfo), viewportSize, padding);
  76001. this.group.x = layoutRect.x - mainRect.x;
  76002. this.group.y = layoutRect.y - mainRect.y;
  76003. this.group.markRedraw(); // Render background after group is layout.
  76004. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  76005. };
  76006. LegendView.prototype.resetInner = function () {
  76007. this.getContentGroup().removeAll();
  76008. this._backgroundEl && this.group.remove(this._backgroundEl);
  76009. this.getSelectorGroup().removeAll();
  76010. };
  76011. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76012. var contentGroup = this.getContentGroup();
  76013. var legendDrawnMap = createHashMap();
  76014. var selectMode = legendModel.get('selectedMode');
  76015. var excludeSeriesId = [];
  76016. ecModel.eachRawSeries(function (seriesModel) {
  76017. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  76018. });
  76019. each$c(legendModel.getData(), function (legendItemModel, dataIndex) {
  76020. var name = legendItemModel.get('name'); // Use empty string or \n as a newline string
  76021. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  76022. var g = new Group$2(); // @ts-ignore
  76023. g.newline = true;
  76024. contentGroup.add(g);
  76025. return;
  76026. } // Representitive series.
  76027. var seriesModel = ecModel.getSeriesByName(name)[0];
  76028. if (legendDrawnMap.get(name)) {
  76029. // Have been drawn
  76030. return;
  76031. } // Legend to control series.
  76032. if (seriesModel) {
  76033. var data = seriesModel.getData();
  76034. var lineVisualStyle = data.getVisual('legendLineStyle') || {};
  76035. var legendIcon = data.getVisual('legendIcon');
  76036. /**
  76037. * `data.getVisual('style')` may be the color from the register
  76038. * in series. For example, for line series,
  76039. */
  76040. var style = data.getVisual('style');
  76041. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode, api);
  76042. itemGroup.on('click', curry$1(dispatchSelectAction, name, null, api, excludeSeriesId)).on('mouseover', curry$1(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  76043. legendDrawnMap.set(name, true);
  76044. } else {
  76045. // Legend to control data. In pie and funnel.
  76046. ecModel.eachRawSeries(function (seriesModel) {
  76047. // In case multiple series has same data name
  76048. if (legendDrawnMap.get(name)) {
  76049. return;
  76050. }
  76051. if (seriesModel.legendVisualProvider) {
  76052. var provider = seriesModel.legendVisualProvider;
  76053. if (!provider.containName(name)) {
  76054. return;
  76055. }
  76056. var idx = provider.indexOfName(name);
  76057. var style = provider.getItemVisual(idx, 'style');
  76058. var legendIcon = provider.getItemVisual(idx, 'legendIcon');
  76059. var colorArr = parse(style.fill); // Color may be set to transparent in visualMap when data is out of range.
  76060. // Do not show nothing.
  76061. if (colorArr && colorArr[3] === 0) {
  76062. colorArr[3] = 0.2; // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  76063. style = extend(extend({}, style), {
  76064. fill: stringify(colorArr, 'rgba')
  76065. });
  76066. }
  76067. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode, api); // FIXME: consider different series has items with the same name.
  76068. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  76069. // more than one pie series.
  76070. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  76071. legendDrawnMap.set(name, true);
  76072. }
  76073. }, this);
  76074. }
  76075. if ("development" !== 'production') {
  76076. if (!legendDrawnMap.get(name)) {
  76077. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  76078. }
  76079. }
  76080. }, this);
  76081. if (selector) {
  76082. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  76083. }
  76084. };
  76085. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  76086. var selectorGroup = this.getSelectorGroup();
  76087. each$c(selector, function createSelectorButton(selectorItem) {
  76088. var type = selectorItem.type;
  76089. var labelText = new ZRText({
  76090. style: {
  76091. x: 0,
  76092. y: 0,
  76093. align: 'center',
  76094. verticalAlign: 'middle'
  76095. },
  76096. onclick: function () {
  76097. api.dispatchAction({
  76098. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  76099. });
  76100. }
  76101. });
  76102. selectorGroup.add(labelText);
  76103. var labelModel = legendModel.getModel('selectorLabel');
  76104. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  76105. setLabelStyle(labelText, {
  76106. normal: labelModel,
  76107. emphasis: emphasisLabelModel
  76108. }, {
  76109. defaultText: selectorItem.title
  76110. });
  76111. enableHoverEmphasis(labelText);
  76112. });
  76113. };
  76114. LegendView.prototype._createItem = function (seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, legendIcon, selectMode, api) {
  76115. var drawType = seriesModel.visualDrawType;
  76116. var itemWidth = legendModel.get('itemWidth');
  76117. var itemHeight = legendModel.get('itemHeight');
  76118. var isSelected = legendModel.isSelected(name);
  76119. var iconRotate = legendItemModel.get('symbolRotate');
  76120. var symbolKeepAspect = legendItemModel.get('symbolKeepAspect');
  76121. var legendIconType = legendItemModel.get('icon');
  76122. legendIcon = legendIconType || legendIcon || 'roundRect';
  76123. var style = getLegendStyle(legendIcon, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api);
  76124. var itemGroup = new Group$2();
  76125. var textStyleModel = legendItemModel.getModel('textStyle');
  76126. if (isFunction(seriesModel.getLegendIcon) && (!legendIconType || legendIconType === 'inherit')) {
  76127. // Series has specific way to define legend icon
  76128. itemGroup.add(seriesModel.getLegendIcon({
  76129. itemWidth: itemWidth,
  76130. itemHeight: itemHeight,
  76131. icon: legendIcon,
  76132. iconRotate: iconRotate,
  76133. itemStyle: style.itemStyle,
  76134. lineStyle: style.lineStyle,
  76135. symbolKeepAspect: symbolKeepAspect
  76136. }));
  76137. } else {
  76138. // Use default legend icon policy for most series
  76139. var rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate : 0; // No rotation for no icon
  76140. itemGroup.add(getDefaultLegendIcon({
  76141. itemWidth: itemWidth,
  76142. itemHeight: itemHeight,
  76143. icon: legendIcon,
  76144. iconRotate: rotate,
  76145. itemStyle: style.itemStyle,
  76146. lineStyle: style.lineStyle,
  76147. symbolKeepAspect: symbolKeepAspect
  76148. }));
  76149. }
  76150. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  76151. var textAlign = itemAlign;
  76152. var formatter = legendModel.get('formatter');
  76153. var content = name;
  76154. if (isString(formatter) && formatter) {
  76155. content = formatter.replace('{name}', name != null ? name : '');
  76156. } else if (isFunction(formatter)) {
  76157. content = formatter(name);
  76158. }
  76159. var inactiveColor = legendItemModel.get('inactiveColor');
  76160. itemGroup.add(new ZRText({
  76161. style: createTextStyle(textStyleModel, {
  76162. text: content,
  76163. x: textX,
  76164. y: itemHeight / 2,
  76165. fill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  76166. align: textAlign,
  76167. verticalAlign: 'middle'
  76168. })
  76169. })); // Add a invisible rect to increase the area of mouse hover
  76170. var hitRect = new Rect({
  76171. shape: itemGroup.getBoundingRect(),
  76172. invisible: true
  76173. });
  76174. var tooltipModel = legendItemModel.getModel('tooltip');
  76175. if (tooltipModel.get('show')) {
  76176. setTooltipConfig({
  76177. el: hitRect,
  76178. componentModel: legendModel,
  76179. itemName: name,
  76180. itemTooltipOption: tooltipModel.option
  76181. });
  76182. }
  76183. itemGroup.add(hitRect);
  76184. itemGroup.eachChild(function (child) {
  76185. child.silent = true;
  76186. });
  76187. hitRect.silent = !selectMode;
  76188. this.getContentGroup().add(itemGroup);
  76189. enableHoverEmphasis(itemGroup); // @ts-ignore
  76190. itemGroup.__legendDataIndex = dataIndex;
  76191. return itemGroup;
  76192. };
  76193. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76194. var contentGroup = this.getContentGroup();
  76195. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  76196. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  76197. var contentRect = contentGroup.getBoundingRect();
  76198. var contentPos = [-contentRect.x, -contentRect.y];
  76199. selectorGroup.markRedraw();
  76200. contentGroup.markRedraw();
  76201. if (selector) {
  76202. // Place buttons in selectorGroup
  76203. box( // Buttons in selectorGroup always layout horizontally
  76204. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  76205. var selectorRect = selectorGroup.getBoundingRect();
  76206. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76207. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76208. var orientIdx = legendModel.getOrient().index;
  76209. var wh = orientIdx === 0 ? 'width' : 'height';
  76210. var hw = orientIdx === 0 ? 'height' : 'width';
  76211. var yx = orientIdx === 0 ? 'y' : 'x';
  76212. if (selectorPosition === 'end') {
  76213. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  76214. } else {
  76215. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  76216. } // Always align selector to content as 'middle'
  76217. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  76218. selectorGroup.x = selectorPos[0];
  76219. selectorGroup.y = selectorPos[1];
  76220. contentGroup.x = contentPos[0];
  76221. contentGroup.y = contentPos[1];
  76222. var mainRect = {
  76223. x: 0,
  76224. y: 0
  76225. };
  76226. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  76227. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  76228. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  76229. return mainRect;
  76230. } else {
  76231. contentGroup.x = contentPos[0];
  76232. contentGroup.y = contentPos[1];
  76233. return this.group.getBoundingRect();
  76234. }
  76235. };
  76236. /**
  76237. * @protected
  76238. */
  76239. LegendView.prototype.remove = function () {
  76240. this.getContentGroup().removeAll();
  76241. this._isFirstRender = true;
  76242. };
  76243. LegendView.type = 'legend.plain';
  76244. return LegendView;
  76245. }(ComponentView);
  76246. function getLegendStyle(iconType, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api) {
  76247. /**
  76248. * Use series style if is inherit;
  76249. * elsewise, use legend style
  76250. */
  76251. function handleCommonProps(style, visualStyle) {
  76252. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  76253. if (style.lineWidth === 'auto') {
  76254. style.lineWidth = visualStyle.lineWidth > 0 ? 2 : 0;
  76255. }
  76256. each$c(style, function (propVal, propName) {
  76257. style[propName] === 'inherit' && (style[propName] = visualStyle[propName]);
  76258. });
  76259. } // itemStyle
  76260. var itemStyleModel = legendItemModel.getModel('itemStyle');
  76261. var itemStyle = itemStyleModel.getItemStyle();
  76262. var iconBrushType = iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke';
  76263. var decalStyle = itemStyleModel.getShallow('decal');
  76264. itemStyle.decal = !decalStyle || decalStyle === 'inherit' ? itemVisualStyle.decal : createOrUpdatePatternFromDecal(decalStyle, api);
  76265. if (itemStyle.fill === 'inherit') {
  76266. /**
  76267. * Series with visualDrawType as 'stroke' should have
  76268. * series stroke as legend fill
  76269. */
  76270. itemStyle.fill = itemVisualStyle[drawType];
  76271. }
  76272. if (itemStyle.stroke === 'inherit') {
  76273. /**
  76274. * icon type with "emptyXXX" should use fill color
  76275. * in visual style
  76276. */
  76277. itemStyle.stroke = itemVisualStyle[iconBrushType];
  76278. }
  76279. if (itemStyle.opacity === 'inherit') {
  76280. /**
  76281. * Use lineStyle.opacity if drawType is stroke
  76282. */
  76283. itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity;
  76284. }
  76285. handleCommonProps(itemStyle, itemVisualStyle); // lineStyle
  76286. var legendLineModel = legendItemModel.getModel('lineStyle');
  76287. var lineStyle = legendLineModel.getLineStyle();
  76288. handleCommonProps(lineStyle, lineVisualStyle); // Fix auto color to real color
  76289. itemStyle.fill === 'auto' && (itemStyle.fill = itemVisualStyle.fill);
  76290. itemStyle.stroke === 'auto' && (itemStyle.stroke = itemVisualStyle.fill);
  76291. lineStyle.stroke === 'auto' && (lineStyle.stroke = itemVisualStyle.fill);
  76292. if (!isSelected) {
  76293. var borderWidth = legendItemModel.get('inactiveBorderWidth');
  76294. /**
  76295. * Since stroke is set to be inactiveBorderColor, it may occur that
  76296. * there is no border in series but border in legend, so we need to
  76297. * use border only when series has border if is set to be auto
  76298. */
  76299. var visualHasBorder = itemStyle[iconBrushType];
  76300. itemStyle.lineWidth = borderWidth === 'auto' ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth;
  76301. itemStyle.fill = legendItemModel.get('inactiveColor');
  76302. itemStyle.stroke = legendItemModel.get('inactiveBorderColor');
  76303. lineStyle.stroke = legendLineModel.get('inactiveColor');
  76304. lineStyle.lineWidth = legendLineModel.get('inactiveWidth');
  76305. }
  76306. return {
  76307. itemStyle: itemStyle,
  76308. lineStyle: lineStyle
  76309. };
  76310. }
  76311. function getDefaultLegendIcon(opt) {
  76312. var symboType = opt.icon || 'roundRect';
  76313. var icon = createSymbol(symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect);
  76314. icon.setStyle(opt.itemStyle);
  76315. icon.rotation = (opt.iconRotate || 0) * Math.PI / 180;
  76316. icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  76317. if (symboType.indexOf('empty') > -1) {
  76318. icon.style.stroke = icon.style.fill;
  76319. icon.style.fill = '#fff';
  76320. icon.style.lineWidth = 2;
  76321. }
  76322. return icon;
  76323. }
  76324. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  76325. // downplay before unselect
  76326. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  76327. api.dispatchAction({
  76328. type: 'legendToggleSelect',
  76329. name: seriesName != null ? seriesName : dataName
  76330. }); // highlight after select
  76331. // TODO highlight immediately may cause animation loss.
  76332. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  76333. }
  76334. function isUseHoverLayer(api) {
  76335. var list = api.getZr().storage.getDisplayList();
  76336. var emphasisState;
  76337. var i = 0;
  76338. var len = list.length;
  76339. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  76340. i++;
  76341. }
  76342. return emphasisState && emphasisState.hoverLayer;
  76343. }
  76344. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  76345. // If element hover will move to a hoverLayer.
  76346. if (!isUseHoverLayer(api)) {
  76347. api.dispatchAction({
  76348. type: 'highlight',
  76349. seriesName: seriesName,
  76350. name: dataName,
  76351. excludeSeriesId: excludeSeriesId
  76352. });
  76353. }
  76354. }
  76355. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  76356. // If element hover will move to a hoverLayer.
  76357. if (!isUseHoverLayer(api)) {
  76358. api.dispatchAction({
  76359. type: 'downplay',
  76360. seriesName: seriesName,
  76361. name: dataName,
  76362. excludeSeriesId: excludeSeriesId
  76363. });
  76364. }
  76365. }
  76366. /*
  76367. * Licensed to the Apache Software Foundation (ASF) under one
  76368. * or more contributor license agreements. See the NOTICE file
  76369. * distributed with this work for additional information
  76370. * regarding copyright ownership. The ASF licenses this file
  76371. * to you under the Apache License, Version 2.0 (the
  76372. * "License"); you may not use this file except in compliance
  76373. * with the License. You may obtain a copy of the License at
  76374. *
  76375. * http://www.apache.org/licenses/LICENSE-2.0
  76376. *
  76377. * Unless required by applicable law or agreed to in writing,
  76378. * software distributed under the License is distributed on an
  76379. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76380. * KIND, either express or implied. See the License for the
  76381. * specific language governing permissions and limitations
  76382. * under the License.
  76383. */
  76384. /**
  76385. * AUTO-GENERATED FILE. DO NOT MODIFY.
  76386. */
  76387. /*
  76388. * Licensed to the Apache Software Foundation (ASF) under one
  76389. * or more contributor license agreements. See the NOTICE file
  76390. * distributed with this work for additional information
  76391. * regarding copyright ownership. The ASF licenses this file
  76392. * to you under the Apache License, Version 2.0 (the
  76393. * "License"); you may not use this file except in compliance
  76394. * with the License. You may obtain a copy of the License at
  76395. *
  76396. * http://www.apache.org/licenses/LICENSE-2.0
  76397. *
  76398. * Unless required by applicable law or agreed to in writing,
  76399. * software distributed under the License is distributed on an
  76400. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76401. * KIND, either express or implied. See the License for the
  76402. * specific language governing permissions and limitations
  76403. * under the License.
  76404. */
  76405. function legendFilter(ecModel) {
  76406. var legendModels = ecModel.findComponents({
  76407. mainType: 'legend'
  76408. });
  76409. if (legendModels && legendModels.length) {
  76410. ecModel.filterSeries(function (series) {
  76411. // If in any legend component the status is not selected.
  76412. // Because in legend series is assumed selected when it is not in the legend data.
  76413. for (var i = 0; i < legendModels.length; i++) {
  76414. if (!legendModels[i].isSelected(series.name)) {
  76415. return false;
  76416. }
  76417. }
  76418. return true;
  76419. });
  76420. }
  76421. }
  76422. function legendSelectActionHandler(methodName, payload, ecModel) {
  76423. var selectedMap = {};
  76424. var isToggleSelect = methodName === 'toggleSelected';
  76425. var isSelected; // Update all legend components
  76426. ecModel.eachComponent('legend', function (legendModel) {
  76427. if (isToggleSelect && isSelected != null) {
  76428. // Force other legend has same selected status
  76429. // Or the first is toggled to true and other are toggled to false
  76430. // In the case one legend has some item unSelected in option. And if other legend
  76431. // doesn't has the item, they will assume it is selected.
  76432. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  76433. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  76434. legendModel[methodName]();
  76435. } else {
  76436. legendModel[methodName](payload.name);
  76437. isSelected = legendModel.isSelected(payload.name);
  76438. }
  76439. var legendData = legendModel.getData();
  76440. each(legendData, function (model) {
  76441. var name = model.get('name'); // Wrap element
  76442. if (name === '\n' || name === '') {
  76443. return;
  76444. }
  76445. var isItemSelected = legendModel.isSelected(name);
  76446. if (selectedMap.hasOwnProperty(name)) {
  76447. // Unselected if any legend is unselected
  76448. selectedMap[name] = selectedMap[name] && isItemSelected;
  76449. } else {
  76450. selectedMap[name] = isItemSelected;
  76451. }
  76452. });
  76453. }); // Return the event explicitly
  76454. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  76455. selected: selectedMap
  76456. } : {
  76457. name: payload.name,
  76458. selected: selectedMap
  76459. };
  76460. }
  76461. function installLegendAction(registers) {
  76462. /**
  76463. * @event legendToggleSelect
  76464. * @type {Object}
  76465. * @property {string} type 'legendToggleSelect'
  76466. * @property {string} [from]
  76467. * @property {string} name Series name or data item name
  76468. */
  76469. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  76470. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  76471. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  76472. /**
  76473. * @event legendSelect
  76474. * @type {Object}
  76475. * @property {string} type 'legendSelect'
  76476. * @property {string} name Series name or data item name
  76477. */
  76478. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  76479. /**
  76480. * @event legendUnSelect
  76481. * @type {Object}
  76482. * @property {string} type 'legendUnSelect'
  76483. * @property {string} name Series name or data item name
  76484. */
  76485. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  76486. }
  76487. function install$H(registers) {
  76488. registers.registerComponentModel(LegendModel);
  76489. registers.registerComponentView(LegendView);
  76490. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  76491. registers.registerSubTypeDefaulter('legend', function () {
  76492. return 'plain';
  76493. });
  76494. installLegendAction(registers);
  76495. }
  76496. var ScrollableLegendModel =
  76497. /** @class */
  76498. function (_super) {
  76499. __extends(ScrollableLegendModel, _super);
  76500. function ScrollableLegendModel() {
  76501. var _this = _super !== null && _super.apply(this, arguments) || this;
  76502. _this.type = ScrollableLegendModel.type;
  76503. return _this;
  76504. }
  76505. /**
  76506. * @param {number} scrollDataIndex
  76507. */
  76508. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  76509. this.option.scrollDataIndex = scrollDataIndex;
  76510. };
  76511. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  76512. var inputPositionParams = getLayoutParams(option);
  76513. _super.prototype.init.call(this, option, parentModel, ecModel);
  76514. mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams);
  76515. };
  76516. /**
  76517. * @override
  76518. */
  76519. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  76520. _super.prototype.mergeOption.call(this, option, ecModel);
  76521. mergeAndNormalizeLayoutParams$1(this, this.option, option);
  76522. };
  76523. ScrollableLegendModel.type = 'legend.scroll';
  76524. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  76525. scrollDataIndex: 0,
  76526. pageButtonItemGap: 5,
  76527. pageButtonGap: null,
  76528. pageButtonPosition: 'end',
  76529. pageFormatter: '{current}/{total}',
  76530. pageIcons: {
  76531. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  76532. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  76533. },
  76534. pageIconColor: '#2f4554',
  76535. pageIconInactiveColor: '#aaa',
  76536. pageIconSize: 15,
  76537. pageTextStyle: {
  76538. color: '#333'
  76539. },
  76540. animationDurationUpdate: 800
  76541. });
  76542. return ScrollableLegendModel;
  76543. }(LegendModel);
  76544. function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) {
  76545. var orient = legendModel.getOrient();
  76546. var ignoreSize = [1, 1];
  76547. ignoreSize[orient.index] = 0;
  76548. mergeLayoutParam(target, raw, {
  76549. type: 'box',
  76550. ignoreSize: !!ignoreSize
  76551. });
  76552. }
  76553. var Group$3 = Group;
  76554. var WH$1 = ['width', 'height'];
  76555. var XY$1 = ['x', 'y'];
  76556. var ScrollableLegendView =
  76557. /** @class */
  76558. function (_super) {
  76559. __extends(ScrollableLegendView, _super);
  76560. function ScrollableLegendView() {
  76561. var _this = _super !== null && _super.apply(this, arguments) || this;
  76562. _this.type = ScrollableLegendView.type;
  76563. _this.newlineDisabled = true;
  76564. _this._currentIndex = 0;
  76565. return _this;
  76566. }
  76567. ScrollableLegendView.prototype.init = function () {
  76568. _super.prototype.init.call(this);
  76569. this.group.add(this._containerGroup = new Group$3());
  76570. this._containerGroup.add(this.getContentGroup());
  76571. this.group.add(this._controllerGroup = new Group$3());
  76572. };
  76573. /**
  76574. * @override
  76575. */
  76576. ScrollableLegendView.prototype.resetInner = function () {
  76577. _super.prototype.resetInner.call(this);
  76578. this._controllerGroup.removeAll();
  76579. this._containerGroup.removeClipPath();
  76580. this._containerGroup.__rectSize = null;
  76581. };
  76582. /**
  76583. * @override
  76584. */
  76585. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76586. var self = this; // Render content items.
  76587. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  76588. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  76589. // e.g., '3/12345' should not overlap with the control arrow button.
  76590. var pageIconSize = legendModel.get('pageIconSize', true);
  76591. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  76592. createPageButton('pagePrev', 0);
  76593. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  76594. controllerGroup.add(new ZRText({
  76595. name: 'pageText',
  76596. style: {
  76597. // Placeholder to calculate a proper layout.
  76598. text: 'xx/xx',
  76599. fill: pageTextStyleModel.getTextColor(),
  76600. font: pageTextStyleModel.getFont(),
  76601. verticalAlign: 'middle',
  76602. align: 'center'
  76603. },
  76604. silent: true
  76605. }));
  76606. createPageButton('pageNext', 1);
  76607. function createPageButton(name, iconIdx) {
  76608. var pageDataIndexName = name + 'DataIndex';
  76609. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  76610. // Buttons will be created in each render, so we do not need
  76611. // to worry about avoiding using legendModel kept in scope.
  76612. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  76613. }, {
  76614. x: -pageIconSizeArr[0] / 2,
  76615. y: -pageIconSizeArr[1] / 2,
  76616. width: pageIconSizeArr[0],
  76617. height: pageIconSizeArr[1]
  76618. });
  76619. icon.name = name;
  76620. controllerGroup.add(icon);
  76621. }
  76622. };
  76623. /**
  76624. * @override
  76625. */
  76626. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76627. var selectorGroup = this.getSelectorGroup();
  76628. var orientIdx = legendModel.getOrient().index;
  76629. var wh = WH$1[orientIdx];
  76630. var xy = XY$1[orientIdx];
  76631. var hw = WH$1[1 - orientIdx];
  76632. var yx = XY$1[1 - orientIdx];
  76633. selector && box( // Buttons in selectorGroup always layout horizontally
  76634. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  76635. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76636. var selectorRect = selectorGroup.getBoundingRect();
  76637. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76638. var processMaxSize = clone(maxSize);
  76639. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  76640. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  76641. if (selector) {
  76642. if (selectorPosition === 'end') {
  76643. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  76644. } else {
  76645. var offset = selectorRect[wh] + selectorButtonGap;
  76646. selectorPos[orientIdx] -= offset;
  76647. mainRect[xy] -= offset;
  76648. }
  76649. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  76650. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  76651. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  76652. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  76653. selectorGroup.x = selectorPos[0];
  76654. selectorGroup.y = selectorPos[1];
  76655. selectorGroup.markRedraw();
  76656. }
  76657. return mainRect;
  76658. };
  76659. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  76660. var contentGroup = this.getContentGroup();
  76661. var containerGroup = this._containerGroup;
  76662. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  76663. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  76664. box( // Buttons in controller are layout always horizontally.
  76665. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  76666. var contentRect = contentGroup.getBoundingRect();
  76667. var controllerRect = controllerGroup.getBoundingRect();
  76668. var showController = this._showController = contentRect[wh] > maxSize[wh]; // In case that the inner elements of contentGroup layout do not based on [0, 0]
  76669. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  76670. // If first rendering, `contentGroup.position` is [0, 0], which
  76671. // does not make sense and may cause unexepcted animation if adopted.
  76672. if (!isFirstRender) {
  76673. contentPos[orientIdx] = contentGroup[xy];
  76674. } // Layout container group based on 0.
  76675. var containerPos = [0, 0];
  76676. var controllerPos = [-controllerRect.x, -controllerRect.y];
  76677. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  76678. if (showController) {
  76679. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  76680. if (pageButtonPosition === 'end') {
  76681. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  76682. } // controller is on the left / top.
  76683. else {
  76684. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  76685. }
  76686. } // Always align controller to content as 'middle'.
  76687. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  76688. contentGroup.setPosition(contentPos);
  76689. containerGroup.setPosition(containerPos);
  76690. controllerGroup.setPosition(controllerPos); // Calculate `mainRect` and set `clipPath`.
  76691. // mainRect should not be calculated by `this.group.getBoundingRect()`
  76692. // for sake of the overflow.
  76693. var mainRect = {
  76694. x: 0,
  76695. y: 0
  76696. }; // Consider content may be overflow (should be clipped).
  76697. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  76698. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  76699. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  76700. containerGroup.__rectSize = maxSize[wh];
  76701. if (showController) {
  76702. var clipShape = {
  76703. x: 0,
  76704. y: 0
  76705. };
  76706. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  76707. clipShape[hw] = mainRect[hw];
  76708. containerGroup.setClipPath(new Rect({
  76709. shape: clipShape
  76710. })); // Consider content may be larger than container, container rect
  76711. // can not be obtained from `containerGroup.getBoundingRect()`.
  76712. containerGroup.__rectSize = clipShape[wh];
  76713. } else {
  76714. // Do not remove or ignore controller. Keep them set as placeholders.
  76715. controllerGroup.eachChild(function (child) {
  76716. child.attr({
  76717. invisible: true,
  76718. silent: true
  76719. });
  76720. });
  76721. } // Content translate animation.
  76722. var pageInfo = this._getPageInfo(legendModel);
  76723. pageInfo.pageIndex != null && updateProps(contentGroup, {
  76724. x: pageInfo.contentPosition[0],
  76725. y: pageInfo.contentPosition[1]
  76726. }, // When switch from "show controller" to "not show controller", view should be
  76727. // updated immediately without animation, otherwise causes weird effect.
  76728. showController ? legendModel : null);
  76729. this._updatePageInfoView(legendModel, pageInfo);
  76730. return mainRect;
  76731. };
  76732. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  76733. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  76734. scrollDataIndex != null && api.dispatchAction({
  76735. type: 'legendScroll',
  76736. scrollDataIndex: scrollDataIndex,
  76737. legendId: legendModel.id
  76738. });
  76739. };
  76740. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  76741. var controllerGroup = this._controllerGroup;
  76742. each(['pagePrev', 'pageNext'], function (name) {
  76743. var key = name + 'DataIndex';
  76744. var canJump = pageInfo[key] != null;
  76745. var icon = controllerGroup.childOfName(name);
  76746. if (icon) {
  76747. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  76748. icon.cursor = canJump ? 'pointer' : 'default';
  76749. }
  76750. });
  76751. var pageText = controllerGroup.childOfName('pageText');
  76752. var pageFormatter = legendModel.get('pageFormatter');
  76753. var pageIndex = pageInfo.pageIndex;
  76754. var current = pageIndex != null ? pageIndex + 1 : 0;
  76755. var total = pageInfo.pageCount;
  76756. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  76757. current: current,
  76758. total: total
  76759. }));
  76760. };
  76761. /**
  76762. * contentPosition: Array.<number>, null when data item not found.
  76763. * pageIndex: number, null when data item not found.
  76764. * pageCount: number, always be a number, can be 0.
  76765. * pagePrevDataIndex: number, null when no previous page.
  76766. * pageNextDataIndex: number, null when no next page.
  76767. * }
  76768. */
  76769. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  76770. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  76771. var contentGroup = this.getContentGroup();
  76772. var containerRectSize = this._containerGroup.__rectSize;
  76773. var orientIdx = legendModel.getOrient().index;
  76774. var wh = WH$1[orientIdx];
  76775. var xy = XY$1[orientIdx];
  76776. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  76777. var children = contentGroup.children();
  76778. var targetItem = children[targetItemIndex];
  76779. var itemCount = children.length;
  76780. var pCount = !itemCount ? 0 : 1;
  76781. var result = {
  76782. contentPosition: [contentGroup.x, contentGroup.y],
  76783. pageCount: pCount,
  76784. pageIndex: pCount - 1,
  76785. pagePrevDataIndex: null,
  76786. pageNextDataIndex: null
  76787. };
  76788. if (!targetItem) {
  76789. return result;
  76790. }
  76791. var targetItemInfo = getItemInfo(targetItem);
  76792. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  76793. // (1) Always align based on the left/top most item.
  76794. // (2) It is user-friendly that the last item shown in the
  76795. // current window is shown at the begining of next window.
  76796. // Otherwise if half of the last item is cut by the window,
  76797. // it will have no chance to display entirely.
  76798. // (3) Consider that item size probably be different, we
  76799. // have calculate pageIndex by size rather than item index,
  76800. // and we can not get page index directly by division.
  76801. // (4) The window is to narrow to contain more than
  76802. // one item, we should make sure that the page can be fliped.
  76803. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  76804. currItemInfo = getItemInfo(children[i]);
  76805. if ( // Half of the last item is out of the window.
  76806. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  76807. // can be started at the current item or the last item.
  76808. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  76809. if (winEndItemInfo.i > winStartItemInfo.i) {
  76810. winStartItemInfo = winEndItemInfo;
  76811. } else {
  76812. // e.g., when page size is smaller than item size.
  76813. winStartItemInfo = currItemInfo;
  76814. }
  76815. if (winStartItemInfo) {
  76816. if (result.pageNextDataIndex == null) {
  76817. result.pageNextDataIndex = winStartItemInfo.i;
  76818. }
  76819. ++result.pageCount;
  76820. }
  76821. }
  76822. winEndItemInfo = currItemInfo;
  76823. }
  76824. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  76825. currItemInfo = getItemInfo(children[i]);
  76826. if ( // If the the end item does not intersect with the window started
  76827. // from the current item, a page can be settled.
  76828. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  76829. winStartItemInfo.i < winEndItemInfo.i) {
  76830. winEndItemInfo = winStartItemInfo;
  76831. if (result.pagePrevDataIndex == null) {
  76832. result.pagePrevDataIndex = winStartItemInfo.i;
  76833. }
  76834. ++result.pageCount;
  76835. ++result.pageIndex;
  76836. }
  76837. winStartItemInfo = currItemInfo;
  76838. }
  76839. return result;
  76840. function getItemInfo(el) {
  76841. if (el) {
  76842. var itemRect = el.getBoundingRect();
  76843. var start = itemRect[xy] + el[xy];
  76844. return {
  76845. s: start,
  76846. e: start + itemRect[wh],
  76847. i: el.__legendDataIndex
  76848. };
  76849. }
  76850. }
  76851. function intersect(itemInfo, winStart) {
  76852. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  76853. }
  76854. };
  76855. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  76856. if (!this._showController) {
  76857. return 0;
  76858. }
  76859. var index;
  76860. var contentGroup = this.getContentGroup();
  76861. var defaultIndex;
  76862. contentGroup.eachChild(function (child, idx) {
  76863. var legendDataIdx = child.__legendDataIndex; // FIXME
  76864. // If the given targetDataIndex (from model) is illegal,
  76865. // we use defaultIndex. But the index on the legend model and
  76866. // action payload is still illegal. That case will not be
  76867. // changed until some scenario requires.
  76868. if (defaultIndex == null && legendDataIdx != null) {
  76869. defaultIndex = idx;
  76870. }
  76871. if (legendDataIdx === targetDataIndex) {
  76872. index = idx;
  76873. }
  76874. });
  76875. return index != null ? index : defaultIndex;
  76876. };
  76877. ScrollableLegendView.type = 'legend.scroll';
  76878. return ScrollableLegendView;
  76879. }(LegendView);
  76880. /*
  76881. * Licensed to the Apache Software Foundation (ASF) under one
  76882. * or more contributor license agreements. See the NOTICE file
  76883. * distributed with this work for additional information
  76884. * regarding copyright ownership. The ASF licenses this file
  76885. * to you under the Apache License, Version 2.0 (the
  76886. * "License"); you may not use this file except in compliance
  76887. * with the License. You may obtain a copy of the License at
  76888. *
  76889. * http://www.apache.org/licenses/LICENSE-2.0
  76890. *
  76891. * Unless required by applicable law or agreed to in writing,
  76892. * software distributed under the License is distributed on an
  76893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76894. * KIND, either express or implied. See the License for the
  76895. * specific language governing permissions and limitations
  76896. * under the License.
  76897. */
  76898. /**
  76899. * AUTO-GENERATED FILE. DO NOT MODIFY.
  76900. */
  76901. /*
  76902. * Licensed to the Apache Software Foundation (ASF) under one
  76903. * or more contributor license agreements. See the NOTICE file
  76904. * distributed with this work for additional information
  76905. * regarding copyright ownership. The ASF licenses this file
  76906. * to you under the Apache License, Version 2.0 (the
  76907. * "License"); you may not use this file except in compliance
  76908. * with the License. You may obtain a copy of the License at
  76909. *
  76910. * http://www.apache.org/licenses/LICENSE-2.0
  76911. *
  76912. * Unless required by applicable law or agreed to in writing,
  76913. * software distributed under the License is distributed on an
  76914. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76915. * KIND, either express or implied. See the License for the
  76916. * specific language governing permissions and limitations
  76917. * under the License.
  76918. */
  76919. function installScrollableLegendAction(registers) {
  76920. /**
  76921. * @event legendScroll
  76922. * @type {Object}
  76923. * @property {string} type 'legendScroll'
  76924. * @property {string} scrollDataIndex
  76925. */
  76926. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  76927. var scrollDataIndex = payload.scrollDataIndex;
  76928. scrollDataIndex != null && ecModel.eachComponent({
  76929. mainType: 'legend',
  76930. subType: 'scroll',
  76931. query: payload
  76932. }, function (legendModel) {
  76933. legendModel.setScrollDataIndex(scrollDataIndex);
  76934. });
  76935. });
  76936. }
  76937. function install$I(registers) {
  76938. use(install$H);
  76939. registers.registerComponentModel(ScrollableLegendModel);
  76940. registers.registerComponentView(ScrollableLegendView);
  76941. installScrollableLegendAction(registers);
  76942. }
  76943. function install$J(registers) {
  76944. use(install$H);
  76945. use(install$I);
  76946. }
  76947. var InsideZoomModel =
  76948. /** @class */
  76949. function (_super) {
  76950. __extends(InsideZoomModel, _super);
  76951. function InsideZoomModel() {
  76952. var _this = _super !== null && _super.apply(this, arguments) || this;
  76953. _this.type = InsideZoomModel.type;
  76954. return _this;
  76955. }
  76956. InsideZoomModel.type = 'dataZoom.inside';
  76957. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  76958. disabled: false,
  76959. zoomLock: false,
  76960. zoomOnMouseWheel: true,
  76961. moveOnMouseMove: true,
  76962. moveOnMouseWheel: false,
  76963. preventDefaultMouseMove: true
  76964. });
  76965. return InsideZoomModel;
  76966. }(DataZoomModel);
  76967. var inner$k = makeInner();
  76968. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  76969. inner$k(api).coordSysRecordMap.each(function (coordSysRecord) {
  76970. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  76971. if (dzInfo) {
  76972. dzInfo.getRange = getRange;
  76973. }
  76974. });
  76975. }
  76976. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  76977. var coordSysRecordMap = inner$k(api).coordSysRecordMap;
  76978. var coordSysKeyArr = coordSysRecordMap.keys();
  76979. for (var i = 0; i < coordSysKeyArr.length; i++) {
  76980. var coordSysKey = coordSysKeyArr[i];
  76981. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  76982. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  76983. if (dataZoomInfoMap) {
  76984. var dzUid = dataZoomModel.uid;
  76985. var dzInfo = dataZoomInfoMap.get(dzUid);
  76986. if (dzInfo) {
  76987. dataZoomInfoMap.removeKey(dzUid);
  76988. if (!dataZoomInfoMap.keys().length) {
  76989. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  76990. }
  76991. }
  76992. }
  76993. }
  76994. }
  76995. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  76996. if (coordSysRecord) {
  76997. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  76998. var controller = coordSysRecord.controller;
  76999. controller && controller.dispose();
  77000. }
  77001. }
  77002. function createCoordSysRecord(api, coordSysModel) {
  77003. // These init props will never change after record created.
  77004. var coordSysRecord = {
  77005. model: coordSysModel,
  77006. containsPoint: curry(containsPoint, coordSysModel),
  77007. dispatchAction: curry(dispatchAction$1, api),
  77008. dataZoomInfoMap: null,
  77009. controller: null
  77010. }; // Must not do anything depends on coordSysRecord outside the event handler here,
  77011. // because coordSysRecord not completed yet.
  77012. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  77013. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  77014. controller.on(eventName, function (event) {
  77015. var batch = [];
  77016. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  77017. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  77018. // moveOnMouseWheel, ...) enabled.
  77019. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  77020. return;
  77021. }
  77022. var method = (dzInfo.getRange || {})[eventName];
  77023. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  77024. !dzInfo.model.get('disabled', true) && range && batch.push({
  77025. dataZoomId: dzInfo.model.id,
  77026. start: range[0],
  77027. end: range[1]
  77028. });
  77029. });
  77030. batch.length && coordSysRecord.dispatchAction(batch);
  77031. });
  77032. });
  77033. return coordSysRecord;
  77034. }
  77035. /**
  77036. * This action will be throttled.
  77037. */
  77038. function dispatchAction$1(api, batch) {
  77039. if (!api.isDisposed()) {
  77040. api.dispatchAction({
  77041. type: 'dataZoom',
  77042. animation: {
  77043. easing: 'cubicOut',
  77044. duration: 100
  77045. },
  77046. batch: batch
  77047. });
  77048. }
  77049. }
  77050. function containsPoint(coordSysModel, e, x, y) {
  77051. return coordSysModel.coordinateSystem.containPoint([x, y]);
  77052. }
  77053. /**
  77054. * Merge roamController settings when multiple dataZooms share one roamController.
  77055. */
  77056. function mergeControllerParams(dataZoomInfoMap) {
  77057. var controlType; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  77058. // as string, it is probably revert to reserved word by compress tool. See #7411.
  77059. var prefix = 'type_';
  77060. var typePriority = {
  77061. 'type_true': 2,
  77062. 'type_move': 1,
  77063. 'type_false': 0,
  77064. 'type_undefined': -1
  77065. };
  77066. var preventDefaultMouseMove = true;
  77067. dataZoomInfoMap.each(function (dataZoomInfo) {
  77068. var dataZoomModel = dataZoomInfo.model;
  77069. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  77070. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  77071. controlType = oneType;
  77072. } // Prevent default move event by default. If one false, do not prevent. Otherwise
  77073. // users may be confused why it does not work when multiple insideZooms exist.
  77074. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  77075. });
  77076. return {
  77077. controlType: controlType,
  77078. opt: {
  77079. // RoamController will enable all of these functionalities,
  77080. // and the final behavior is determined by its event listener
  77081. // provided by each inside zoom.
  77082. zoomOnMouseWheel: true,
  77083. moveOnMouseMove: true,
  77084. moveOnMouseWheel: true,
  77085. preventDefaultMouseMove: !!preventDefaultMouseMove
  77086. }
  77087. };
  77088. }
  77089. function installDataZoomRoamProcessor(registers) {
  77090. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  77091. var apiInner = inner$k(api);
  77092. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  77093. coordSysRecordMap.each(function (coordSysRecord) {
  77094. // `coordSysRecordMap` always exists (because it holds the `roam controller`, which should
  77095. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  77096. coordSysRecord.dataZoomInfoMap = null;
  77097. });
  77098. ecModel.eachComponent({
  77099. mainType: 'dataZoom',
  77100. subType: 'inside'
  77101. }, function (dataZoomModel) {
  77102. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  77103. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  77104. var coordSysUid = dzCoordSysInfo.model.uid;
  77105. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  77106. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap()); // Notice these props might be changed each time for a single dataZoomModel.
  77107. dataZoomInfoMap.set(dataZoomModel.uid, {
  77108. dzReferCoordSysInfo: dzCoordSysInfo,
  77109. model: dataZoomModel,
  77110. getRange: null
  77111. });
  77112. });
  77113. }); // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  77114. // (2) Clear coord sys if not refered by any dataZoom.
  77115. coordSysRecordMap.each(function (coordSysRecord) {
  77116. var controller = coordSysRecord.controller;
  77117. var firstDzInfo;
  77118. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  77119. if (dataZoomInfoMap) {
  77120. var firstDzKey = dataZoomInfoMap.keys()[0];
  77121. if (firstDzKey != null) {
  77122. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  77123. }
  77124. }
  77125. if (!firstDzInfo) {
  77126. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  77127. return;
  77128. }
  77129. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  77130. controller.enable(controllerParams.controlType, controllerParams.opt);
  77131. controller.setPointerChecker(coordSysRecord.containsPoint);
  77132. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  77133. });
  77134. });
  77135. }
  77136. var InsideZoomView =
  77137. /** @class */
  77138. function (_super) {
  77139. __extends(InsideZoomView, _super);
  77140. function InsideZoomView() {
  77141. var _this = _super !== null && _super.apply(this, arguments) || this;
  77142. _this.type = 'dataZoom.inside';
  77143. return _this;
  77144. }
  77145. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  77146. _super.prototype.render.apply(this, arguments);
  77147. if (dataZoomModel.noTarget()) {
  77148. this._clear();
  77149. return;
  77150. } // Hence the `throttle` util ensures to preserve command order,
  77151. // here simply updating range all the time will not cause missing
  77152. // any of the the roam change.
  77153. this.range = dataZoomModel.getPercentRange(); // Reset controllers.
  77154. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  77155. pan: bind(getRangeHandlers.pan, this),
  77156. zoom: bind(getRangeHandlers.zoom, this),
  77157. scrollMove: bind(getRangeHandlers.scrollMove, this)
  77158. });
  77159. };
  77160. InsideZoomView.prototype.dispose = function () {
  77161. this._clear();
  77162. _super.prototype.dispose.apply(this, arguments);
  77163. };
  77164. InsideZoomView.prototype._clear = function () {
  77165. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  77166. this.range = null;
  77167. };
  77168. InsideZoomView.type = 'dataZoom.inside';
  77169. return InsideZoomView;
  77170. }(DataZoomView);
  77171. var getRangeHandlers = {
  77172. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  77173. var lastRange = this.range;
  77174. var range = lastRange.slice(); // Calculate transform by the first axis.
  77175. var axisModel = coordSysInfo.axisModels[0];
  77176. if (!axisModel) {
  77177. return;
  77178. }
  77179. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  77180. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  77181. var scale = Math.max(1 / e.scale, 0);
  77182. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  77183. range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range.
  77184. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  77185. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  77186. this.range = range;
  77187. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  77188. return range;
  77189. }
  77190. },
  77191. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  77192. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  77193. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  77194. }),
  77195. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  77196. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  77197. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  77198. })
  77199. };
  77200. function makeMover(getPercentDelta) {
  77201. return function (coordSysInfo, coordSysMainType, controller, e) {
  77202. var lastRange = this.range;
  77203. var range = lastRange.slice(); // Calculate transform by the first axis.
  77204. var axisModel = coordSysInfo.axisModels[0];
  77205. if (!axisModel) {
  77206. return;
  77207. }
  77208. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  77209. sliderMove(percentDelta, range, [0, 100], 'all');
  77210. this.range = range;
  77211. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  77212. return range;
  77213. }
  77214. };
  77215. }
  77216. var getDirectionInfo = {
  77217. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  77218. var axis = axisModel.axis;
  77219. var ret = {};
  77220. var rect = coordSysInfo.model.coordinateSystem.getRect();
  77221. oldPoint = oldPoint || [0, 0];
  77222. if (axis.dim === 'x') {
  77223. ret.pixel = newPoint[0] - oldPoint[0];
  77224. ret.pixelLength = rect.width;
  77225. ret.pixelStart = rect.x;
  77226. ret.signal = axis.inverse ? 1 : -1;
  77227. } else {
  77228. // axis.dim === 'y'
  77229. ret.pixel = newPoint[1] - oldPoint[1];
  77230. ret.pixelLength = rect.height;
  77231. ret.pixelStart = rect.y;
  77232. ret.signal = axis.inverse ? -1 : 1;
  77233. }
  77234. return ret;
  77235. },
  77236. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  77237. var axis = axisModel.axis;
  77238. var ret = {};
  77239. var polar = coordSysInfo.model.coordinateSystem;
  77240. var radiusExtent = polar.getRadiusAxis().getExtent();
  77241. var angleExtent = polar.getAngleAxis().getExtent();
  77242. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  77243. newPoint = polar.pointToCoord(newPoint);
  77244. if (axisModel.mainType === 'radiusAxis') {
  77245. ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  77246. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  77247. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  77248. ret.pixelStart = radiusExtent[0];
  77249. ret.signal = axis.inverse ? 1 : -1;
  77250. } else {
  77251. // 'angleAxis'
  77252. ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  77253. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  77254. ret.pixelLength = angleExtent[1] - angleExtent[0];
  77255. ret.pixelStart = angleExtent[0];
  77256. ret.signal = axis.inverse ? -1 : 1;
  77257. }
  77258. return ret;
  77259. },
  77260. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  77261. var axis = axisModel.axis;
  77262. var rect = coordSysInfo.model.coordinateSystem.getRect();
  77263. var ret = {};
  77264. oldPoint = oldPoint || [0, 0];
  77265. if (axis.orient === 'horizontal') {
  77266. ret.pixel = newPoint[0] - oldPoint[0];
  77267. ret.pixelLength = rect.width;
  77268. ret.pixelStart = rect.x;
  77269. ret.signal = axis.inverse ? 1 : -1;
  77270. } else {
  77271. // 'vertical'
  77272. ret.pixel = newPoint[1] - oldPoint[1];
  77273. ret.pixelLength = rect.height;
  77274. ret.pixelStart = rect.y;
  77275. ret.signal = axis.inverse ? -1 : 1;
  77276. }
  77277. return ret;
  77278. }
  77279. };
  77280. function install$K(registers) {
  77281. installCommon(registers);
  77282. registers.registerComponentModel(InsideZoomModel);
  77283. registers.registerComponentView(InsideZoomView);
  77284. installDataZoomRoamProcessor(registers);
  77285. }
  77286. var SliderZoomModel =
  77287. /** @class */
  77288. function (_super) {
  77289. __extends(SliderZoomModel, _super);
  77290. function SliderZoomModel() {
  77291. var _this = _super !== null && _super.apply(this, arguments) || this;
  77292. _this.type = SliderZoomModel.type;
  77293. return _this;
  77294. }
  77295. SliderZoomModel.type = 'dataZoom.slider';
  77296. SliderZoomModel.layoutMode = 'box';
  77297. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  77298. show: true,
  77299. // deault value can only be drived in view stage.
  77300. right: 'ph',
  77301. top: 'ph',
  77302. width: 'ph',
  77303. height: 'ph',
  77304. left: null,
  77305. bottom: null,
  77306. borderColor: '#d2dbee',
  77307. borderRadius: 3,
  77308. backgroundColor: 'rgba(47,69,84,0)',
  77309. // dataBackgroundColor: '#ddd',
  77310. dataBackground: {
  77311. lineStyle: {
  77312. color: '#d2dbee',
  77313. width: 0.5
  77314. },
  77315. areaStyle: {
  77316. color: '#d2dbee',
  77317. opacity: 0.2
  77318. }
  77319. },
  77320. selectedDataBackground: {
  77321. lineStyle: {
  77322. color: '#8fb0f7',
  77323. width: 0.5
  77324. },
  77325. areaStyle: {
  77326. color: '#8fb0f7',
  77327. opacity: 0.2
  77328. }
  77329. },
  77330. // Color of selected window.
  77331. fillerColor: 'rgba(135,175,274,0.2)',
  77332. handleIcon: 'path://M-9.35,34.56V42m0-40V9.5m-2,0h4a2,2,0,0,1,2,2v21a2,2,0,0,1-2,2h-4a2,2,0,0,1-2-2v-21A2,2,0,0,1-11.35,9.5Z',
  77333. // Percent of the slider height
  77334. handleSize: '100%',
  77335. handleStyle: {
  77336. color: '#fff',
  77337. borderColor: '#ACB8D1'
  77338. },
  77339. moveHandleSize: 7,
  77340. moveHandleIcon: 'path://M-320.9-50L-320.9-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-348-41-339-50-320.9-50z M-212.3-50L-212.3-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-239.4-41-230.4-50-212.3-50z M-103.7-50L-103.7-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-130.9-41-121.8-50-103.7-50z',
  77341. moveHandleStyle: {
  77342. color: '#D2DBEE',
  77343. opacity: 0.7
  77344. },
  77345. showDetail: true,
  77346. showDataShadow: 'auto',
  77347. realtime: true,
  77348. zoomLock: false,
  77349. textStyle: {
  77350. color: '#6E7079'
  77351. },
  77352. brushSelect: true,
  77353. brushStyle: {
  77354. color: 'rgba(135,175,274,0.15)'
  77355. },
  77356. emphasis: {
  77357. handleStyle: {
  77358. borderColor: '#8FB0F7'
  77359. },
  77360. moveHandleStyle: {
  77361. color: '#8FB0F7'
  77362. }
  77363. }
  77364. });
  77365. return SliderZoomModel;
  77366. }(DataZoomModel);
  77367. var Rect$2 = Rect; // Constants
  77368. var DEFAULT_LOCATION_EDGE_GAP = 7;
  77369. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  77370. var DEFAULT_FILLER_SIZE = 30;
  77371. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  77372. var HORIZONTAL = 'horizontal';
  77373. var VERTICAL = 'vertical';
  77374. var LABEL_GAP = 5;
  77375. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  77376. var REALTIME_ANIMATION_CONFIG = {
  77377. easing: 'cubicOut',
  77378. duration: 100,
  77379. delay: 0
  77380. };
  77381. var SliderZoomView =
  77382. /** @class */
  77383. function (_super) {
  77384. __extends(SliderZoomView, _super);
  77385. function SliderZoomView() {
  77386. var _this = _super !== null && _super.apply(this, arguments) || this;
  77387. _this.type = SliderZoomView.type;
  77388. _this._displayables = {};
  77389. return _this;
  77390. }
  77391. SliderZoomView.prototype.init = function (ecModel, api) {
  77392. this.api = api; // A unique handler for each dataZoom component
  77393. this._onBrush = bind(this._onBrush, this);
  77394. this._onBrushEnd = bind(this._onBrushEnd, this);
  77395. };
  77396. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  77397. _super.prototype.render.apply(this, arguments);
  77398. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  77399. this._orient = dataZoomModel.getOrient();
  77400. if (dataZoomModel.get('show') === false) {
  77401. this.group.removeAll();
  77402. return;
  77403. }
  77404. if (dataZoomModel.noTarget()) {
  77405. this._clear();
  77406. this.group.removeAll();
  77407. return;
  77408. } // Notice: this._resetInterval() should not be executed when payload.type
  77409. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  77410. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  77411. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  77412. this._buildView();
  77413. }
  77414. this._updateView();
  77415. };
  77416. SliderZoomView.prototype.dispose = function () {
  77417. this._clear();
  77418. _super.prototype.dispose.apply(this, arguments);
  77419. };
  77420. SliderZoomView.prototype._clear = function () {
  77421. clear(this, '_dispatchZoomAction');
  77422. var zr = this.api.getZr();
  77423. zr.off('mousemove', this._onBrush);
  77424. zr.off('mouseup', this._onBrushEnd);
  77425. };
  77426. SliderZoomView.prototype._buildView = function () {
  77427. var thisGroup = this.group;
  77428. thisGroup.removeAll();
  77429. this._brushing = false;
  77430. this._displayables.brushRect = null;
  77431. this._resetLocation();
  77432. this._resetInterval();
  77433. var barGroup = this._displayables.sliderGroup = new Group();
  77434. this._renderBackground();
  77435. this._renderHandle();
  77436. this._renderDataShadow();
  77437. thisGroup.add(barGroup);
  77438. this._positionGroup();
  77439. };
  77440. SliderZoomView.prototype._resetLocation = function () {
  77441. var dataZoomModel = this.dataZoomModel;
  77442. var api = this.api;
  77443. var showMoveHandle = dataZoomModel.get('brushSelect');
  77444. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0; // If some of x/y/width/height are not specified,
  77445. // auto-adapt according to target grid.
  77446. var coordRect = this._findCoordRect();
  77447. var ecSize = {
  77448. width: api.getWidth(),
  77449. height: api.getHeight()
  77450. }; // Default align by coordinate system rect.
  77451. var positionInfo = this._orient === HORIZONTAL ? {
  77452. // Why using 'right', because right should be used in vertical,
  77453. // and it is better to be consistent for dealing with position param merge.
  77454. right: ecSize.width - coordRect.x - coordRect.width,
  77455. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  77456. width: coordRect.width,
  77457. height: DEFAULT_FILLER_SIZE
  77458. } : {
  77459. right: DEFAULT_LOCATION_EDGE_GAP,
  77460. top: coordRect.y,
  77461. width: DEFAULT_FILLER_SIZE,
  77462. height: coordRect.height
  77463. }; // Do not write back to option and replace value 'ph', because
  77464. // the 'ph' value should be recalculated when resize.
  77465. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
  77466. each(['right', 'top', 'width', 'height'], function (name) {
  77467. if (layoutParams[name] === 'ph') {
  77468. layoutParams[name] = positionInfo[name];
  77469. }
  77470. });
  77471. var layoutRect = getLayoutRect(layoutParams, ecSize);
  77472. this._location = {
  77473. x: layoutRect.x,
  77474. y: layoutRect.y
  77475. };
  77476. this._size = [layoutRect.width, layoutRect.height];
  77477. this._orient === VERTICAL && this._size.reverse();
  77478. };
  77479. SliderZoomView.prototype._positionGroup = function () {
  77480. var thisGroup = this.group;
  77481. var location = this._location;
  77482. var orient = this._orient; // Just use the first axis to determine mapping.
  77483. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  77484. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  77485. var sliderGroup = this._displayables.sliderGroup;
  77486. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
  77487. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  77488. scaleY: otherAxisInverse ? 1 : -1,
  77489. scaleX: 1
  77490. } : orient === HORIZONTAL && inverse ? {
  77491. scaleY: otherAxisInverse ? 1 : -1,
  77492. scaleX: -1
  77493. } : orient === VERTICAL && !inverse ? {
  77494. scaleY: otherAxisInverse ? -1 : 1,
  77495. scaleX: 1,
  77496. rotation: Math.PI / 2
  77497. } // Don't use Math.PI, considering shadow direction.
  77498. : {
  77499. scaleY: otherAxisInverse ? -1 : 1,
  77500. scaleX: -1,
  77501. rotation: Math.PI / 2
  77502. }); // Position barGroup
  77503. var rect = thisGroup.getBoundingRect([sliderGroup]);
  77504. thisGroup.x = location.x - rect.x;
  77505. thisGroup.y = location.y - rect.y;
  77506. thisGroup.markRedraw();
  77507. };
  77508. SliderZoomView.prototype._getViewExtent = function () {
  77509. return [0, this._size[0]];
  77510. };
  77511. SliderZoomView.prototype._renderBackground = function () {
  77512. var dataZoomModel = this.dataZoomModel;
  77513. var size = this._size;
  77514. var barGroup = this._displayables.sliderGroup;
  77515. var brushSelect = dataZoomModel.get('brushSelect');
  77516. barGroup.add(new Rect$2({
  77517. silent: true,
  77518. shape: {
  77519. x: 0,
  77520. y: 0,
  77521. width: size[0],
  77522. height: size[1]
  77523. },
  77524. style: {
  77525. fill: dataZoomModel.get('backgroundColor')
  77526. },
  77527. z2: -40
  77528. })); // Click panel, over shadow, below handles.
  77529. var clickPanel = new Rect$2({
  77530. shape: {
  77531. x: 0,
  77532. y: 0,
  77533. width: size[0],
  77534. height: size[1]
  77535. },
  77536. style: {
  77537. fill: 'transparent'
  77538. },
  77539. z2: 0,
  77540. onclick: bind(this._onClickPanel, this)
  77541. });
  77542. var zr = this.api.getZr();
  77543. if (brushSelect) {
  77544. clickPanel.on('mousedown', this._onBrushStart, this);
  77545. clickPanel.cursor = 'crosshair';
  77546. zr.on('mousemove', this._onBrush);
  77547. zr.on('mouseup', this._onBrushEnd);
  77548. } else {
  77549. zr.off('mousemove', this._onBrush);
  77550. zr.off('mouseup', this._onBrushEnd);
  77551. }
  77552. barGroup.add(clickPanel);
  77553. };
  77554. SliderZoomView.prototype._renderDataShadow = function () {
  77555. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  77556. this._displayables.dataShadowSegs = [];
  77557. if (!info) {
  77558. return;
  77559. }
  77560. var size = this._size;
  77561. var oldSize = this._shadowSize || [];
  77562. var seriesModel = info.series;
  77563. var data = seriesModel.getRawData();
  77564. var candlestickDim = seriesModel.getShadowDim && seriesModel.getShadowDim();
  77565. var otherDim = candlestickDim && data.getDimensionInfo(candlestickDim) ? seriesModel.getShadowDim() // @see candlestick
  77566. : info.otherDim;
  77567. if (otherDim == null) {
  77568. return;
  77569. }
  77570. var polygonPts = this._shadowPolygonPts;
  77571. var polylinePts = this._shadowPolylinePts; // Not re-render if data doesn't change.
  77572. if (data !== this._shadowData || otherDim !== this._shadowDim || size[0] !== oldSize[0] || size[1] !== oldSize[1]) {
  77573. var otherDataExtent_1 = data.getDataExtent(otherDim); // Nice extent.
  77574. var otherOffset = (otherDataExtent_1[1] - otherDataExtent_1[0]) * 0.3;
  77575. otherDataExtent_1 = [otherDataExtent_1[0] - otherOffset, otherDataExtent_1[1] + otherOffset];
  77576. var otherShadowExtent_1 = [0, size[1]];
  77577. var thisShadowExtent = [0, size[0]];
  77578. var areaPoints_1 = [[size[0], 0], [0, 0]];
  77579. var linePoints_1 = [];
  77580. var step_1 = thisShadowExtent[1] / (data.count() - 1);
  77581. var thisCoord_1 = 0; // Optimize for large data shadow
  77582. var stride_1 = Math.round(data.count() / size[0]);
  77583. var lastIsEmpty_1;
  77584. data.each([otherDim], function (value, index) {
  77585. if (stride_1 > 0 && index % stride_1) {
  77586. thisCoord_1 += step_1;
  77587. return;
  77588. } // FIXME
  77589. // Should consider axis.min/axis.max when drawing dataShadow.
  77590. // FIXME
  77591. // 应该使用统一的空判断?还是在list里进行空判断?
  77592. var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
  77593. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent_1, otherShadowExtent_1, true); // Attempt to draw data shadow precisely when there are empty value.
  77594. if (isEmpty && !lastIsEmpty_1 && index) {
  77595. areaPoints_1.push([areaPoints_1[areaPoints_1.length - 1][0], 0]);
  77596. linePoints_1.push([linePoints_1[linePoints_1.length - 1][0], 0]);
  77597. } else if (!isEmpty && lastIsEmpty_1) {
  77598. areaPoints_1.push([thisCoord_1, 0]);
  77599. linePoints_1.push([thisCoord_1, 0]);
  77600. }
  77601. areaPoints_1.push([thisCoord_1, otherCoord]);
  77602. linePoints_1.push([thisCoord_1, otherCoord]);
  77603. thisCoord_1 += step_1;
  77604. lastIsEmpty_1 = isEmpty;
  77605. });
  77606. polygonPts = this._shadowPolygonPts = areaPoints_1;
  77607. polylinePts = this._shadowPolylinePts = linePoints_1;
  77608. }
  77609. this._shadowData = data;
  77610. this._shadowDim = otherDim;
  77611. this._shadowSize = [size[0], size[1]];
  77612. var dataZoomModel = this.dataZoomModel;
  77613. function createDataShadowGroup(isSelectedArea) {
  77614. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  77615. var group = new Group();
  77616. var polygon = new Polygon({
  77617. shape: {
  77618. points: polygonPts
  77619. },
  77620. segmentIgnoreThreshold: 1,
  77621. style: model.getModel('areaStyle').getAreaStyle(),
  77622. silent: true,
  77623. z2: -20
  77624. });
  77625. var polyline = new Polyline({
  77626. shape: {
  77627. points: polylinePts
  77628. },
  77629. segmentIgnoreThreshold: 1,
  77630. style: model.getModel('lineStyle').getLineStyle(),
  77631. silent: true,
  77632. z2: -19
  77633. });
  77634. group.add(polygon);
  77635. group.add(polyline);
  77636. return group;
  77637. } // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  77638. for (var i = 0; i < 3; i++) {
  77639. var group = createDataShadowGroup(i === 1);
  77640. this._displayables.sliderGroup.add(group);
  77641. this._displayables.dataShadowSegs.push(group);
  77642. }
  77643. };
  77644. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  77645. var dataZoomModel = this.dataZoomModel;
  77646. var showDataShadow = dataZoomModel.get('showDataShadow');
  77647. if (showDataShadow === false) {
  77648. return;
  77649. } // Find a representative series.
  77650. var result;
  77651. var ecModel = this.ecModel;
  77652. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  77653. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  77654. each(seriesModels, function (seriesModel) {
  77655. if (result) {
  77656. return;
  77657. }
  77658. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  77659. return;
  77660. }
  77661. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  77662. var otherDim = getOtherDim(axisDim);
  77663. var otherAxisInverse;
  77664. var coordSys = seriesModel.coordinateSystem;
  77665. if (otherDim != null && coordSys.getOtherAxis) {
  77666. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  77667. }
  77668. otherDim = seriesModel.getData().mapDimension(otherDim);
  77669. result = {
  77670. thisAxis: thisAxis,
  77671. series: seriesModel,
  77672. thisDim: axisDim,
  77673. otherDim: otherDim,
  77674. otherAxisInverse: otherAxisInverse
  77675. };
  77676. }, this);
  77677. }, this);
  77678. return result;
  77679. };
  77680. SliderZoomView.prototype._renderHandle = function () {
  77681. var thisGroup = this.group;
  77682. var displayables = this._displayables;
  77683. var handles = displayables.handles = [null, null];
  77684. var handleLabels = displayables.handleLabels = [null, null];
  77685. var sliderGroup = this._displayables.sliderGroup;
  77686. var size = this._size;
  77687. var dataZoomModel = this.dataZoomModel;
  77688. var api = this.api;
  77689. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  77690. var brushSelect = dataZoomModel.get('brushSelect');
  77691. var filler = displayables.filler = new Rect$2({
  77692. silent: brushSelect,
  77693. style: {
  77694. fill: dataZoomModel.get('fillerColor')
  77695. },
  77696. textConfig: {
  77697. position: 'inside'
  77698. }
  77699. });
  77700. sliderGroup.add(filler); // Frame border.
  77701. sliderGroup.add(new Rect$2({
  77702. silent: true,
  77703. subPixelOptimize: true,
  77704. shape: {
  77705. x: 0,
  77706. y: 0,
  77707. width: size[0],
  77708. height: size[1],
  77709. r: borderRadius
  77710. },
  77711. style: {
  77712. // deprecated option
  77713. stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'),
  77714. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  77715. fill: 'rgba(0,0,0,0)'
  77716. }
  77717. })); // Left and right handle to resize
  77718. each([0, 1], function (handleIndex) {
  77719. var iconStr = dataZoomModel.get('handleIcon');
  77720. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  77721. // Compatitable with the old icon parsers. Which can use a path string without path://
  77722. iconStr = 'path://' + iconStr;
  77723. if ("development" !== 'production') {
  77724. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  77725. }
  77726. }
  77727. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  77728. path.attr({
  77729. cursor: getCursor(this._orient),
  77730. draggable: true,
  77731. drift: bind(this._onDragMove, this, handleIndex),
  77732. ondragend: bind(this._onDragEnd, this),
  77733. onmouseover: bind(this._showDataInfo, this, true),
  77734. onmouseout: bind(this._showDataInfo, this, false),
  77735. z2: 5
  77736. });
  77737. var bRect = path.getBoundingRect();
  77738. var handleSize = dataZoomModel.get('handleSize');
  77739. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  77740. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  77741. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  77742. path.style.strokeNoScale = true;
  77743. path.rectHover = true;
  77744. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  77745. enableHoverEmphasis(path);
  77746. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  77747. // Compatitable with previous version
  77748. if (handleColor != null) {
  77749. path.style.fill = handleColor;
  77750. }
  77751. sliderGroup.add(handles[handleIndex] = path);
  77752. var textStyleModel = dataZoomModel.getModel('textStyle');
  77753. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  77754. silent: true,
  77755. invisible: true,
  77756. style: createTextStyle(textStyleModel, {
  77757. x: 0,
  77758. y: 0,
  77759. text: '',
  77760. verticalAlign: 'middle',
  77761. align: 'center',
  77762. fill: textStyleModel.getTextColor(),
  77763. font: textStyleModel.getFont()
  77764. }),
  77765. z2: 10
  77766. }));
  77767. }, this); // Handle to move. Only visible when brushSelect is set true.
  77768. var actualMoveZone = filler;
  77769. if (brushSelect) {
  77770. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  77771. var moveHandle_1 = displayables.moveHandle = new Rect({
  77772. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  77773. silent: true,
  77774. shape: {
  77775. r: [0, 0, 2, 2],
  77776. y: size[1] - 0.5,
  77777. height: moveHandleHeight
  77778. }
  77779. });
  77780. var iconSize = moveHandleHeight * 0.8;
  77781. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  77782. moveHandleIcon.silent = true;
  77783. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  77784. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  77785. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  77786. actualMoveZone = displayables.moveZone = new Rect({
  77787. invisible: true,
  77788. shape: {
  77789. y: size[1] - moveZoneExpandSize,
  77790. height: moveHandleHeight + moveZoneExpandSize
  77791. }
  77792. });
  77793. actualMoveZone.on('mouseover', function () {
  77794. api.enterEmphasis(moveHandle_1);
  77795. }).on('mouseout', function () {
  77796. api.leaveEmphasis(moveHandle_1);
  77797. });
  77798. sliderGroup.add(moveHandle_1);
  77799. sliderGroup.add(moveHandleIcon);
  77800. sliderGroup.add(actualMoveZone);
  77801. }
  77802. actualMoveZone.attr({
  77803. draggable: true,
  77804. cursor: getCursor(this._orient),
  77805. drift: bind(this._onDragMove, this, 'all'),
  77806. ondragstart: bind(this._showDataInfo, this, true),
  77807. ondragend: bind(this._onDragEnd, this),
  77808. onmouseover: bind(this._showDataInfo, this, true),
  77809. onmouseout: bind(this._showDataInfo, this, false)
  77810. });
  77811. };
  77812. SliderZoomView.prototype._resetInterval = function () {
  77813. var range = this._range = this.dataZoomModel.getPercentRange();
  77814. var viewExtent = this._getViewExtent();
  77815. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  77816. };
  77817. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  77818. var dataZoomModel = this.dataZoomModel;
  77819. var handleEnds = this._handleEnds;
  77820. var viewExtend = this._getViewExtent();
  77821. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  77822. var percentExtent = [0, 100];
  77823. sliderMove(delta, handleEnds, viewExtend, dataZoomModel.get('zoomLock') ? 'all' : handleIndex, minMaxSpan.minSpan != null ? linearMap(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null, minMaxSpan.maxSpan != null ? linearMap(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null);
  77824. var lastRange = this._range;
  77825. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  77826. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  77827. };
  77828. SliderZoomView.prototype._updateView = function (nonRealtime) {
  77829. var displaybles = this._displayables;
  77830. var handleEnds = this._handleEnds;
  77831. var handleInterval = asc(handleEnds.slice());
  77832. var size = this._size;
  77833. each([0, 1], function (handleIndex) {
  77834. // Handles
  77835. var handle = displaybles.handles[handleIndex];
  77836. var handleHeight = this._handleHeight;
  77837. handle.attr({
  77838. scaleX: handleHeight / 2,
  77839. scaleY: handleHeight / 2,
  77840. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  77841. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  77842. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  77843. y: size[1] / 2 - handleHeight / 2
  77844. });
  77845. }, this); // Filler
  77846. displaybles.filler.setShape({
  77847. x: handleInterval[0],
  77848. y: 0,
  77849. width: handleInterval[1] - handleInterval[0],
  77850. height: size[1]
  77851. });
  77852. var viewExtent = {
  77853. x: handleInterval[0],
  77854. width: handleInterval[1] - handleInterval[0]
  77855. }; // Move handle
  77856. if (displaybles.moveHandle) {
  77857. displaybles.moveHandle.setShape(viewExtent);
  77858. displaybles.moveZone.setShape(viewExtent); // Force update path on the invisible object
  77859. displaybles.moveZone.getBoundingRect();
  77860. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  77861. } // update clip path of shadow.
  77862. var dataShadowSegs = displaybles.dataShadowSegs;
  77863. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  77864. for (var i = 0; i < dataShadowSegs.length; i++) {
  77865. var segGroup = dataShadowSegs[i];
  77866. var clipPath = segGroup.getClipPath();
  77867. if (!clipPath) {
  77868. clipPath = new Rect();
  77869. segGroup.setClipPath(clipPath);
  77870. }
  77871. clipPath.setShape({
  77872. x: segIntervals[i],
  77873. y: 0,
  77874. width: segIntervals[i + 1] - segIntervals[i],
  77875. height: size[1]
  77876. });
  77877. }
  77878. this._updateDataInfo(nonRealtime);
  77879. };
  77880. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  77881. var dataZoomModel = this.dataZoomModel;
  77882. var displaybles = this._displayables;
  77883. var handleLabels = displaybles.handleLabels;
  77884. var orient = this._orient;
  77885. var labelTexts = ['', '']; // FIXME
  77886. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  77887. if (dataZoomModel.get('showDetail')) {
  77888. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  77889. if (axisProxy) {
  77890. var axis = axisProxy.getAxisModel().axis;
  77891. var range = this._range;
  77892. var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  77893. ? axisProxy.calculateDataWindow({
  77894. start: range[0],
  77895. end: range[1]
  77896. }).valueWindow : axisProxy.getDataValueWindow();
  77897. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  77898. }
  77899. }
  77900. var orderedHandleEnds = asc(this._handleEnds.slice());
  77901. setLabel.call(this, 0);
  77902. setLabel.call(this, 1);
  77903. function setLabel(handleIndex) {
  77904. // Label
  77905. // Text should not transform by barGroup.
  77906. // Ignore handlers transform
  77907. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  77908. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  77909. var offset = this._handleWidth / 2 + LABEL_GAP;
  77910. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  77911. handleLabels[handleIndex].setStyle({
  77912. x: textPoint[0],
  77913. y: textPoint[1],
  77914. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  77915. align: orient === HORIZONTAL ? direction : 'center',
  77916. text: labelTexts[handleIndex]
  77917. });
  77918. }
  77919. };
  77920. SliderZoomView.prototype._formatLabel = function (value, axis) {
  77921. var dataZoomModel = this.dataZoomModel;
  77922. var labelFormatter = dataZoomModel.get('labelFormatter');
  77923. var labelPrecision = dataZoomModel.get('labelPrecision');
  77924. if (labelPrecision == null || labelPrecision === 'auto') {
  77925. labelPrecision = axis.getPixelPrecision();
  77926. }
  77927. var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
  77928. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  77929. value: Math.round(value)
  77930. }) // param of toFixed should less then 20.
  77931. : value.toFixed(Math.min(labelPrecision, 20));
  77932. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  77933. };
  77934. /**
  77935. * @param showOrHide true: show, false: hide
  77936. */
  77937. SliderZoomView.prototype._showDataInfo = function (showOrHide) {
  77938. // Always show when drgging.
  77939. showOrHide = this._dragging || showOrHide;
  77940. var displayables = this._displayables;
  77941. var handleLabels = displayables.handleLabels;
  77942. handleLabels[0].attr('invisible', !showOrHide);
  77943. handleLabels[1].attr('invisible', !showOrHide); // Highlight move handle
  77944. displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  77945. };
  77946. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  77947. this._dragging = true; // For mobile device, prevent screen slider on the button.
  77948. stop(event.event); // Transform dx, dy to bar coordination.
  77949. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  77950. var vertex = applyTransform$1([dx, dy], barTransform, true);
  77951. var changed = this._updateInterval(handleIndex, vertex[0]);
  77952. var realtime = this.dataZoomModel.get('realtime');
  77953. this._updateView(!realtime); // Avoid dispatch dataZoom repeatly but range not changed,
  77954. // which cause bad visual effect when progressive enabled.
  77955. changed && realtime && this._dispatchZoomAction(true);
  77956. };
  77957. SliderZoomView.prototype._onDragEnd = function () {
  77958. this._dragging = false;
  77959. this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when
  77960. // drag end will cause the whole view rerender, which is unnecessary.
  77961. var realtime = this.dataZoomModel.get('realtime');
  77962. !realtime && this._dispatchZoomAction(false);
  77963. };
  77964. SliderZoomView.prototype._onClickPanel = function (e) {
  77965. var size = this._size;
  77966. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  77967. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  77968. return;
  77969. }
  77970. var handleEnds = this._handleEnds;
  77971. var center = (handleEnds[0] + handleEnds[1]) / 2;
  77972. var changed = this._updateInterval('all', localPoint[0] - center);
  77973. this._updateView();
  77974. changed && this._dispatchZoomAction(false);
  77975. };
  77976. SliderZoomView.prototype._onBrushStart = function (e) {
  77977. var x = e.offsetX;
  77978. var y = e.offsetY;
  77979. this._brushStart = new Point(x, y);
  77980. this._brushing = true;
  77981. this._brushStartTime = +new Date(); // this._updateBrushRect(x, y);
  77982. };
  77983. SliderZoomView.prototype._onBrushEnd = function (e) {
  77984. if (!this._brushing) {
  77985. return;
  77986. }
  77987. var brushRect = this._displayables.brushRect;
  77988. this._brushing = false;
  77989. if (!brushRect) {
  77990. return;
  77991. }
  77992. brushRect.attr('ignore', true);
  77993. var brushShape = brushRect.shape;
  77994. var brushEndTime = +new Date(); // console.log(brushEndTime - this._brushStartTime);
  77995. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  77996. // Will treat it as a click
  77997. return;
  77998. }
  77999. var viewExtend = this._getViewExtent();
  78000. var percentExtent = [0, 100];
  78001. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  78002. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  78003. this._updateView();
  78004. this._dispatchZoomAction(false);
  78005. };
  78006. SliderZoomView.prototype._onBrush = function (e) {
  78007. if (this._brushing) {
  78008. // For mobile device, prevent screen slider on the button.
  78009. stop(e.event);
  78010. this._updateBrushRect(e.offsetX, e.offsetY);
  78011. }
  78012. };
  78013. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  78014. var displayables = this._displayables;
  78015. var dataZoomModel = this.dataZoomModel;
  78016. var brushRect = displayables.brushRect;
  78017. if (!brushRect) {
  78018. brushRect = displayables.brushRect = new Rect$2({
  78019. silent: true,
  78020. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  78021. });
  78022. displayables.sliderGroup.add(brushRect);
  78023. }
  78024. brushRect.attr('ignore', false);
  78025. var brushStart = this._brushStart;
  78026. var sliderGroup = this._displayables.sliderGroup;
  78027. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  78028. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  78029. var size = this._size;
  78030. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  78031. brushRect.setShape({
  78032. x: startPoint[0],
  78033. y: 0,
  78034. width: endPoint[0] - startPoint[0],
  78035. height: size[1]
  78036. });
  78037. };
  78038. /**
  78039. * This action will be throttled.
  78040. */
  78041. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  78042. var range = this._range;
  78043. this.api.dispatchAction({
  78044. type: 'dataZoom',
  78045. from: this.uid,
  78046. dataZoomId: this.dataZoomModel.id,
  78047. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  78048. start: range[0],
  78049. end: range[1]
  78050. });
  78051. };
  78052. SliderZoomView.prototype._findCoordRect = function () {
  78053. // Find the grid corresponding to the first axis referred by dataZoom.
  78054. var rect;
  78055. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  78056. if (!rect && coordSysInfoList.length) {
  78057. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  78058. rect = coordSys.getRect && coordSys.getRect();
  78059. }
  78060. if (!rect) {
  78061. var width = this.api.getWidth();
  78062. var height = this.api.getHeight();
  78063. rect = {
  78064. x: width * 0.2,
  78065. y: height * 0.2,
  78066. width: width * 0.6,
  78067. height: height * 0.6
  78068. };
  78069. }
  78070. return rect;
  78071. };
  78072. SliderZoomView.type = 'dataZoom.slider';
  78073. return SliderZoomView;
  78074. }(DataZoomView);
  78075. function getOtherDim(thisDim) {
  78076. // FIXME
  78077. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  78078. var map = {
  78079. x: 'y',
  78080. y: 'x',
  78081. radius: 'angle',
  78082. angle: 'radius'
  78083. };
  78084. return map[thisDim];
  78085. }
  78086. function getCursor(orient) {
  78087. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  78088. }
  78089. function install$L(registers) {
  78090. registers.registerComponentModel(SliderZoomModel);
  78091. registers.registerComponentView(SliderZoomView);
  78092. installCommon(registers);
  78093. }
  78094. function install$M(registers) {
  78095. use(install$K);
  78096. use(install$L); // Do not install './dataZoomSelect',
  78097. // since it only work for toolbox dataZoom.
  78098. }
  78099. var visualDefault = {
  78100. /**
  78101. * @public
  78102. */
  78103. get: function (visualType, key, isCategory) {
  78104. var value = clone((defaultOption$1[visualType] || {})[key]);
  78105. return isCategory ? isArray(value) ? value[value.length - 1] : value : value;
  78106. }
  78107. };
  78108. var defaultOption$1 = {
  78109. color: {
  78110. active: ['#006edd', '#e0ffff'],
  78111. inactive: ['rgba(0,0,0,0)']
  78112. },
  78113. colorHue: {
  78114. active: [0, 360],
  78115. inactive: [0, 0]
  78116. },
  78117. colorSaturation: {
  78118. active: [0.3, 1],
  78119. inactive: [0, 0]
  78120. },
  78121. colorLightness: {
  78122. active: [0.9, 0.5],
  78123. inactive: [0, 0]
  78124. },
  78125. colorAlpha: {
  78126. active: [0.3, 1],
  78127. inactive: [0, 0]
  78128. },
  78129. opacity: {
  78130. active: [0.3, 1],
  78131. inactive: [0, 0]
  78132. },
  78133. symbol: {
  78134. active: ['circle', 'roundRect', 'diamond'],
  78135. inactive: ['none']
  78136. },
  78137. symbolSize: {
  78138. active: [10, 50],
  78139. inactive: [0, 0]
  78140. }
  78141. };
  78142. var mapVisual$1 = VisualMapping.mapVisual;
  78143. var eachVisual = VisualMapping.eachVisual;
  78144. var isArray$1 = isArray;
  78145. var each$d = each;
  78146. var asc$2 = asc;
  78147. var linearMap$1 = linearMap;
  78148. var VisualMapModel =
  78149. /** @class */
  78150. function (_super) {
  78151. __extends(VisualMapModel, _super);
  78152. function VisualMapModel() {
  78153. var _this = _super !== null && _super.apply(this, arguments) || this;
  78154. _this.type = VisualMapModel.type;
  78155. _this.stateList = ['inRange', 'outOfRange'];
  78156. _this.replacableOptionKeys = ['inRange', 'outOfRange', 'target', 'controller', 'color'];
  78157. _this.layoutMode = {
  78158. type: 'box',
  78159. ignoreSize: true
  78160. };
  78161. /**
  78162. * [lowerBound, upperBound]
  78163. */
  78164. _this.dataBound = [-Infinity, Infinity];
  78165. _this.targetVisuals = {};
  78166. _this.controllerVisuals = {};
  78167. return _this;
  78168. }
  78169. VisualMapModel.prototype.init = function (option, parentModel, ecModel) {
  78170. this.mergeDefaultAndTheme(option, ecModel);
  78171. };
  78172. /**
  78173. * @protected
  78174. */
  78175. VisualMapModel.prototype.optionUpdated = function (newOption, isInit) {
  78176. var thisOption = this.option;
  78177. !isInit && replaceVisualOption(thisOption, newOption, this.replacableOptionKeys);
  78178. this.textStyleModel = this.getModel('textStyle');
  78179. this.resetItemSize();
  78180. this.completeVisualOption();
  78181. };
  78182. /**
  78183. * @protected
  78184. */
  78185. VisualMapModel.prototype.resetVisual = function (supplementVisualOption) {
  78186. var stateList = this.stateList;
  78187. supplementVisualOption = bind(supplementVisualOption, this);
  78188. this.controllerVisuals = createVisualMappings(this.option.controller, stateList, supplementVisualOption);
  78189. this.targetVisuals = createVisualMappings(this.option.target, stateList, supplementVisualOption);
  78190. };
  78191. /**
  78192. * @public
  78193. */
  78194. VisualMapModel.prototype.getItemSymbol = function () {
  78195. return null;
  78196. };
  78197. /**
  78198. * @protected
  78199. * @return {Array.<number>} An array of series indices.
  78200. */
  78201. VisualMapModel.prototype.getTargetSeriesIndices = function () {
  78202. var optionSeriesIndex = this.option.seriesIndex;
  78203. var seriesIndices = [];
  78204. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  78205. this.ecModel.eachSeries(function (seriesModel, index) {
  78206. seriesIndices.push(index);
  78207. });
  78208. } else {
  78209. seriesIndices = normalizeToArray(optionSeriesIndex);
  78210. }
  78211. return seriesIndices;
  78212. };
  78213. /**
  78214. * @public
  78215. */
  78216. VisualMapModel.prototype.eachTargetSeries = function (callback, context) {
  78217. each(this.getTargetSeriesIndices(), function (seriesIndex) {
  78218. var seriesModel = this.ecModel.getSeriesByIndex(seriesIndex);
  78219. if (seriesModel) {
  78220. callback.call(context, seriesModel);
  78221. }
  78222. }, this);
  78223. };
  78224. /**
  78225. * @pubilc
  78226. */
  78227. VisualMapModel.prototype.isTargetSeries = function (seriesModel) {
  78228. var is = false;
  78229. this.eachTargetSeries(function (model) {
  78230. model === seriesModel && (is = true);
  78231. });
  78232. return is;
  78233. };
  78234. /**
  78235. * @example
  78236. * this.formatValueText(someVal); // format single numeric value to text.
  78237. * this.formatValueText(someVal, true); // format single category value to text.
  78238. * this.formatValueText([min, max]); // format numeric min-max to text.
  78239. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  78240. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  78241. *
  78242. * @param value Real value, or this.dataBound[0 or 1].
  78243. * @param isCategory Only available when value is number.
  78244. * @param edgeSymbols Open-close symbol when value is interval.
  78245. * @protected
  78246. */
  78247. VisualMapModel.prototype.formatValueText = function (value, isCategory, edgeSymbols) {
  78248. var option = this.option;
  78249. var precision = option.precision;
  78250. var dataBound = this.dataBound;
  78251. var formatter = option.formatter;
  78252. var isMinMax;
  78253. edgeSymbols = edgeSymbols || ['<', '>'];
  78254. if (isArray(value)) {
  78255. value = value.slice();
  78256. isMinMax = true;
  78257. }
  78258. var textValue = isCategory ? value // Value is string when isCategory
  78259. : isMinMax ? [toFixed(value[0]), toFixed(value[1])] : toFixed(value);
  78260. if (isString(formatter)) {
  78261. return formatter.replace('{value}', isMinMax ? textValue[0] : textValue).replace('{value2}', isMinMax ? textValue[1] : textValue);
  78262. } else if (isFunction(formatter)) {
  78263. return isMinMax ? formatter(value[0], value[1]) : formatter(value);
  78264. }
  78265. if (isMinMax) {
  78266. if (value[0] === dataBound[0]) {
  78267. return edgeSymbols[0] + ' ' + textValue[1];
  78268. } else if (value[1] === dataBound[1]) {
  78269. return edgeSymbols[1] + ' ' + textValue[0];
  78270. } else {
  78271. return textValue[0] + ' - ' + textValue[1];
  78272. }
  78273. } else {
  78274. // Format single value (includes category case).
  78275. return textValue;
  78276. }
  78277. function toFixed(val) {
  78278. return val === dataBound[0] ? 'min' : val === dataBound[1] ? 'max' : (+val).toFixed(Math.min(precision, 20));
  78279. }
  78280. };
  78281. /**
  78282. * @protected
  78283. */
  78284. VisualMapModel.prototype.resetExtent = function () {
  78285. var thisOption = this.option; // Can not calculate data extent by data here.
  78286. // Because series and data may be modified in processing stage.
  78287. // So we do not support the feature "auto min/max".
  78288. var extent = asc$2([thisOption.min, thisOption.max]);
  78289. this._dataExtent = extent;
  78290. };
  78291. /**
  78292. * PENDING:
  78293. * delete this method if no outer usage.
  78294. *
  78295. * Return Concrete dimension. If null/undefined is returned, no dimension is used.
  78296. */
  78297. // getDataDimension(data: SeriesData) {
  78298. // const optDim = this.option.dimension;
  78299. // if (optDim != null) {
  78300. // return data.getDimension(optDim);
  78301. // }
  78302. // const dimNames = data.dimensions;
  78303. // for (let i = dimNames.length - 1; i >= 0; i--) {
  78304. // const dimName = dimNames[i];
  78305. // const dimInfo = data.getDimensionInfo(dimName);
  78306. // if (!dimInfo.isCalculationCoord) {
  78307. // return dimName;
  78308. // }
  78309. // }
  78310. // }
  78311. VisualMapModel.prototype.getDataDimensionIndex = function (data) {
  78312. var optDim = this.option.dimension;
  78313. if (optDim != null) {
  78314. return data.getDimensionIndex(optDim);
  78315. }
  78316. var dimNames = data.dimensions;
  78317. for (var i = dimNames.length - 1; i >= 0; i--) {
  78318. var dimName = dimNames[i];
  78319. var dimInfo = data.getDimensionInfo(dimName);
  78320. if (!dimInfo.isCalculationCoord) {
  78321. return dimInfo.storeDimIndex;
  78322. }
  78323. }
  78324. };
  78325. VisualMapModel.prototype.getExtent = function () {
  78326. return this._dataExtent.slice();
  78327. };
  78328. VisualMapModel.prototype.completeVisualOption = function () {
  78329. var ecModel = this.ecModel;
  78330. var thisOption = this.option;
  78331. var base = {
  78332. inRange: thisOption.inRange,
  78333. outOfRange: thisOption.outOfRange
  78334. };
  78335. var target = thisOption.target || (thisOption.target = {});
  78336. var controller = thisOption.controller || (thisOption.controller = {});
  78337. merge(target, base); // Do not override
  78338. merge(controller, base); // Do not override
  78339. var isCategory = this.isCategory();
  78340. completeSingle.call(this, target);
  78341. completeSingle.call(this, controller);
  78342. completeInactive.call(this, target, 'inRange', 'outOfRange'); // completeInactive.call(this, target, 'outOfRange', 'inRange');
  78343. completeController.call(this, controller);
  78344. function completeSingle(base) {
  78345. // Compatible with ec2 dataRange.color.
  78346. // The mapping order of dataRange.color is: [high value, ..., low value]
  78347. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  78348. // Notice: ec2 has no inverse.
  78349. if (isArray$1(thisOption.color) // If there has been inRange: {symbol: ...}, adding color is a mistake.
  78350. // So adding color only when no inRange defined.
  78351. && !base.inRange) {
  78352. base.inRange = {
  78353. color: thisOption.color.slice().reverse()
  78354. };
  78355. } // Compatible with previous logic, always give a default color, otherwise
  78356. // simple config with no inRange and outOfRange will not work.
  78357. // Originally we use visualMap.color as the default color, but setOption at
  78358. // the second time the default color will be erased. So we change to use
  78359. // constant DEFAULT_COLOR.
  78360. // If user do not want the default color, set inRange: {color: null}.
  78361. base.inRange = base.inRange || {
  78362. color: ecModel.get('gradientColor')
  78363. };
  78364. }
  78365. function completeInactive(base, stateExist, stateAbsent) {
  78366. var optExist = base[stateExist];
  78367. var optAbsent = base[stateAbsent];
  78368. if (optExist && !optAbsent) {
  78369. optAbsent = base[stateAbsent] = {};
  78370. each$d(optExist, function (visualData, visualType) {
  78371. if (!VisualMapping.isValidType(visualType)) {
  78372. return;
  78373. }
  78374. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  78375. if (defa != null) {
  78376. optAbsent[visualType] = defa; // Compatibable with ec2:
  78377. // Only inactive color to rgba(0,0,0,0) can not
  78378. // make label transparent, so use opacity also.
  78379. if (visualType === 'color' && !optAbsent.hasOwnProperty('opacity') && !optAbsent.hasOwnProperty('colorAlpha')) {
  78380. optAbsent.opacity = [0, 0];
  78381. }
  78382. }
  78383. });
  78384. }
  78385. }
  78386. function completeController(controller) {
  78387. var symbolExists = (controller.inRange || {}).symbol || (controller.outOfRange || {}).symbol;
  78388. var symbolSizeExists = (controller.inRange || {}).symbolSize || (controller.outOfRange || {}).symbolSize;
  78389. var inactiveColor = this.get('inactiveColor');
  78390. var itemSymbol = this.getItemSymbol();
  78391. var defaultSymbol = itemSymbol || 'roundRect';
  78392. each$d(this.stateList, function (state) {
  78393. var itemSize = this.itemSize;
  78394. var visuals = controller[state]; // Set inactive color for controller if no other color
  78395. // attr (like colorAlpha) specified.
  78396. if (!visuals) {
  78397. visuals = controller[state] = {
  78398. color: isCategory ? inactiveColor : [inactiveColor]
  78399. };
  78400. } // Consistent symbol and symbolSize if not specified.
  78401. if (visuals.symbol == null) {
  78402. visuals.symbol = symbolExists && clone(symbolExists) || (isCategory ? defaultSymbol : [defaultSymbol]);
  78403. }
  78404. if (visuals.symbolSize == null) {
  78405. visuals.symbolSize = symbolSizeExists && clone(symbolSizeExists) || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  78406. } // Filter none
  78407. visuals.symbol = mapVisual$1(visuals.symbol, function (symbol) {
  78408. return symbol === 'none' ? defaultSymbol : symbol;
  78409. }); // Normalize symbolSize
  78410. var symbolSize = visuals.symbolSize;
  78411. if (symbolSize != null) {
  78412. var max_1 = -Infinity; // symbolSize can be object when categories defined.
  78413. eachVisual(symbolSize, function (value) {
  78414. value > max_1 && (max_1 = value);
  78415. });
  78416. visuals.symbolSize = mapVisual$1(symbolSize, function (value) {
  78417. return linearMap$1(value, [0, max_1], [0, itemSize[0]], true);
  78418. });
  78419. }
  78420. }, this);
  78421. }
  78422. };
  78423. VisualMapModel.prototype.resetItemSize = function () {
  78424. this.itemSize = [parseFloat(this.get('itemWidth')), parseFloat(this.get('itemHeight'))];
  78425. };
  78426. VisualMapModel.prototype.isCategory = function () {
  78427. return !!this.option.categories;
  78428. };
  78429. /**
  78430. * @public
  78431. * @abstract
  78432. */
  78433. VisualMapModel.prototype.setSelected = function (selected) {};
  78434. VisualMapModel.prototype.getSelected = function () {
  78435. return null;
  78436. };
  78437. /**
  78438. * @public
  78439. * @abstract
  78440. */
  78441. VisualMapModel.prototype.getValueState = function (value) {
  78442. return null;
  78443. };
  78444. /**
  78445. * FIXME
  78446. * Do not publish to thirt-part-dev temporarily
  78447. * util the interface is stable. (Should it return
  78448. * a function but not visual meta?)
  78449. *
  78450. * @pubilc
  78451. * @abstract
  78452. * @param getColorVisual
  78453. * params: value, valueState
  78454. * return: color
  78455. * @return {Object} visualMeta
  78456. * should includes {stops, outerColors}
  78457. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  78458. */
  78459. VisualMapModel.prototype.getVisualMeta = function (getColorVisual) {
  78460. return null;
  78461. };
  78462. VisualMapModel.type = 'visualMap';
  78463. VisualMapModel.dependencies = ['series'];
  78464. VisualMapModel.defaultOption = {
  78465. show: true,
  78466. // zlevel: 0,
  78467. z: 4,
  78468. seriesIndex: 'all',
  78469. min: 0,
  78470. max: 200,
  78471. left: 0,
  78472. right: null,
  78473. top: null,
  78474. bottom: 0,
  78475. itemWidth: null,
  78476. itemHeight: null,
  78477. inverse: false,
  78478. orient: 'vertical',
  78479. backgroundColor: 'rgba(0,0,0,0)',
  78480. borderColor: '#ccc',
  78481. contentColor: '#5793f3',
  78482. inactiveColor: '#aaa',
  78483. borderWidth: 0,
  78484. padding: 5,
  78485. // 接受数组分别设定上右下左边距,同css
  78486. textGap: 10,
  78487. precision: 0,
  78488. textStyle: {
  78489. color: '#333' // 值域文字颜色
  78490. }
  78491. };
  78492. return VisualMapModel;
  78493. }(ComponentModel);
  78494. var DEFAULT_BAR_BOUND = [20, 140];
  78495. var ContinuousModel =
  78496. /** @class */
  78497. function (_super) {
  78498. __extends(ContinuousModel, _super);
  78499. function ContinuousModel() {
  78500. var _this = _super !== null && _super.apply(this, arguments) || this;
  78501. _this.type = ContinuousModel.type;
  78502. return _this;
  78503. }
  78504. /**
  78505. * @override
  78506. */
  78507. ContinuousModel.prototype.optionUpdated = function (newOption, isInit) {
  78508. _super.prototype.optionUpdated.apply(this, arguments);
  78509. this.resetExtent();
  78510. this.resetVisual(function (mappingOption) {
  78511. mappingOption.mappingMethod = 'linear';
  78512. mappingOption.dataExtent = this.getExtent();
  78513. });
  78514. this._resetRange();
  78515. };
  78516. /**
  78517. * @protected
  78518. * @override
  78519. */
  78520. ContinuousModel.prototype.resetItemSize = function () {
  78521. _super.prototype.resetItemSize.apply(this, arguments);
  78522. var itemSize = this.itemSize;
  78523. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  78524. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  78525. };
  78526. /**
  78527. * @private
  78528. */
  78529. ContinuousModel.prototype._resetRange = function () {
  78530. var dataExtent = this.getExtent();
  78531. var range = this.option.range;
  78532. if (!range || range.auto) {
  78533. // `range` should always be array (so we don't use other
  78534. // value like 'auto') for user-friend. (consider getOption).
  78535. dataExtent.auto = 1;
  78536. this.option.range = dataExtent;
  78537. } else if (isArray(range)) {
  78538. if (range[0] > range[1]) {
  78539. range.reverse();
  78540. }
  78541. range[0] = Math.max(range[0], dataExtent[0]);
  78542. range[1] = Math.min(range[1], dataExtent[1]);
  78543. }
  78544. };
  78545. /**
  78546. * @protected
  78547. * @override
  78548. */
  78549. ContinuousModel.prototype.completeVisualOption = function () {
  78550. _super.prototype.completeVisualOption.apply(this, arguments);
  78551. each(this.stateList, function (state) {
  78552. var symbolSize = this.option.controller[state].symbolSize;
  78553. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  78554. symbolSize[0] = symbolSize[1] / 3; // For good looking.
  78555. }
  78556. }, this);
  78557. };
  78558. /**
  78559. * @override
  78560. */
  78561. ContinuousModel.prototype.setSelected = function (selected) {
  78562. this.option.range = selected.slice();
  78563. this._resetRange();
  78564. };
  78565. /**
  78566. * @public
  78567. */
  78568. ContinuousModel.prototype.getSelected = function () {
  78569. var dataExtent = this.getExtent();
  78570. var dataInterval = asc((this.get('range') || []).slice()); // Clamp
  78571. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  78572. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  78573. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  78574. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  78575. return dataInterval;
  78576. };
  78577. /**
  78578. * @override
  78579. */
  78580. ContinuousModel.prototype.getValueState = function (value) {
  78581. var range = this.option.range;
  78582. var dataExtent = this.getExtent(); // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  78583. // range[1] is processed likewise.
  78584. return (range[0] <= dataExtent[0] || range[0] <= value) && (range[1] >= dataExtent[1] || value <= range[1]) ? 'inRange' : 'outOfRange';
  78585. };
  78586. ContinuousModel.prototype.findTargetDataIndices = function (range) {
  78587. var result = [];
  78588. this.eachTargetSeries(function (seriesModel) {
  78589. var dataIndices = [];
  78590. var data = seriesModel.getData();
  78591. data.each(this.getDataDimensionIndex(data), function (value, dataIndex) {
  78592. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  78593. }, this);
  78594. result.push({
  78595. seriesId: seriesModel.id,
  78596. dataIndex: dataIndices
  78597. });
  78598. }, this);
  78599. return result;
  78600. };
  78601. /**
  78602. * @implement
  78603. */
  78604. ContinuousModel.prototype.getVisualMeta = function (getColorVisual) {
  78605. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  78606. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  78607. var stops = [];
  78608. function setStop(value, valueState) {
  78609. stops.push({
  78610. value: value,
  78611. color: getColorVisual(value, valueState)
  78612. });
  78613. } // Format to: outOfRange -- inRange -- outOfRange.
  78614. var iIdx = 0;
  78615. var oIdx = 0;
  78616. var iLen = iVals.length;
  78617. var oLen = oVals.length;
  78618. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  78619. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  78620. if (oVals[oIdx] < iVals[iIdx]) {
  78621. setStop(oVals[oIdx], 'outOfRange');
  78622. }
  78623. }
  78624. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  78625. // If range is full, value beyond min, max will be clamped.
  78626. // make a singularity
  78627. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  78628. setStop(iVals[iIdx], 'inRange');
  78629. }
  78630. for (var first = 1; oIdx < oLen; oIdx++) {
  78631. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  78632. // make a singularity
  78633. if (first) {
  78634. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  78635. first = 0;
  78636. }
  78637. setStop(oVals[oIdx], 'outOfRange');
  78638. }
  78639. }
  78640. var stopsLen = stops.length;
  78641. return {
  78642. stops: stops,
  78643. outerColors: [stopsLen ? stops[0].color : 'transparent', stopsLen ? stops[stopsLen - 1].color : 'transparent']
  78644. };
  78645. };
  78646. ContinuousModel.type = 'visualMap.continuous';
  78647. ContinuousModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  78648. align: 'auto',
  78649. calculable: false,
  78650. hoverLink: true,
  78651. realtime: true,
  78652. handleIcon: 'path://M-11.39,9.77h0a3.5,3.5,0,0,1-3.5,3.5h-22a3.5,3.5,0,0,1-3.5-3.5h0a3.5,3.5,0,0,1,3.5-3.5h22A3.5,3.5,0,0,1-11.39,9.77Z',
  78653. handleSize: '120%',
  78654. handleStyle: {
  78655. borderColor: '#fff',
  78656. borderWidth: 1
  78657. },
  78658. indicatorIcon: 'circle',
  78659. indicatorSize: '50%',
  78660. indicatorStyle: {
  78661. borderColor: '#fff',
  78662. borderWidth: 2,
  78663. shadowBlur: 2,
  78664. shadowOffsetX: 1,
  78665. shadowOffsetY: 1,
  78666. shadowColor: 'rgba(0,0,0,0.2)'
  78667. } // emphasis: {
  78668. // handleStyle: {
  78669. // shadowBlur: 3,
  78670. // shadowOffsetX: 1,
  78671. // shadowOffsetY: 1,
  78672. // shadowColor: 'rgba(0,0,0,0.2)'
  78673. // }
  78674. // }
  78675. });
  78676. return ContinuousModel;
  78677. }(VisualMapModel);
  78678. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  78679. if (dataExtent[0] === dataExtent[1]) {
  78680. return dataExtent.slice();
  78681. } // When using colorHue mapping, it is not linear color any more.
  78682. // Moreover, canvas gradient seems not to be accurate linear.
  78683. // FIXME
  78684. // Should be arbitrary value 100? or based on pixel size?
  78685. var count = 200;
  78686. var step = (dataExtent[1] - dataExtent[0]) / count;
  78687. var value = dataExtent[0];
  78688. var stopValues = [];
  78689. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  78690. stopValues.push(value);
  78691. value += step;
  78692. }
  78693. stopValues.push(dataExtent[1]);
  78694. return stopValues;
  78695. }
  78696. var VisualMapView =
  78697. /** @class */
  78698. function (_super) {
  78699. __extends(VisualMapView, _super);
  78700. function VisualMapView() {
  78701. var _this = _super !== null && _super.apply(this, arguments) || this;
  78702. _this.type = VisualMapView.type;
  78703. _this.autoPositionValues = {
  78704. left: 1,
  78705. right: 1,
  78706. top: 1,
  78707. bottom: 1
  78708. };
  78709. return _this;
  78710. }
  78711. VisualMapView.prototype.init = function (ecModel, api) {
  78712. this.ecModel = ecModel;
  78713. this.api = api;
  78714. };
  78715. /**
  78716. * @protected
  78717. */
  78718. VisualMapView.prototype.render = function (visualMapModel, ecModel, api, payload // TODO: TYPE
  78719. ) {
  78720. this.visualMapModel = visualMapModel;
  78721. if (visualMapModel.get('show') === false) {
  78722. this.group.removeAll();
  78723. return;
  78724. }
  78725. this.doRender(visualMapModel, ecModel, api, payload);
  78726. };
  78727. /**
  78728. * @protected
  78729. */
  78730. VisualMapView.prototype.renderBackground = function (group) {
  78731. var visualMapModel = this.visualMapModel;
  78732. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  78733. var rect = group.getBoundingRect();
  78734. group.add(new Rect({
  78735. z2: -1,
  78736. silent: true,
  78737. shape: {
  78738. x: rect.x - padding[3],
  78739. y: rect.y - padding[0],
  78740. width: rect.width + padding[3] + padding[1],
  78741. height: rect.height + padding[0] + padding[2]
  78742. },
  78743. style: {
  78744. fill: visualMapModel.get('backgroundColor'),
  78745. stroke: visualMapModel.get('borderColor'),
  78746. lineWidth: visualMapModel.get('borderWidth')
  78747. }
  78748. }));
  78749. };
  78750. /**
  78751. * @protected
  78752. * @param targetValue can be Infinity or -Infinity
  78753. * @param visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  78754. * @param opts
  78755. * @param opts.forceState Specify state, instead of using getValueState method.
  78756. * @param opts.convertOpacityToAlpha For color gradient in controller widget.
  78757. * @return {*} Visual value.
  78758. */
  78759. VisualMapView.prototype.getControllerVisual = function (targetValue, visualCluster, opts) {
  78760. opts = opts || {};
  78761. var forceState = opts.forceState;
  78762. var visualMapModel = this.visualMapModel;
  78763. var visualObj = {}; // Default values.
  78764. if (visualCluster === 'color') {
  78765. var defaultColor = visualMapModel.get('contentColor');
  78766. visualObj.color = defaultColor;
  78767. }
  78768. function getter(key) {
  78769. return visualObj[key];
  78770. }
  78771. function setter(key, value) {
  78772. visualObj[key] = value;
  78773. }
  78774. var mappings = visualMapModel.controllerVisuals[forceState || visualMapModel.getValueState(targetValue)];
  78775. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  78776. each(visualTypes, function (type) {
  78777. var visualMapping = mappings[type];
  78778. if (opts.convertOpacityToAlpha && type === 'opacity') {
  78779. type = 'colorAlpha';
  78780. visualMapping = mappings.__alphaForOpacity;
  78781. }
  78782. if (VisualMapping.dependsOn(type, visualCluster)) {
  78783. visualMapping && visualMapping.applyVisual(targetValue, getter, setter);
  78784. }
  78785. });
  78786. return visualObj[visualCluster];
  78787. };
  78788. VisualMapView.prototype.positionGroup = function (group) {
  78789. var model = this.visualMapModel;
  78790. var api = this.api;
  78791. positionElement(group, model.getBoxLayoutParams(), {
  78792. width: api.getWidth(),
  78793. height: api.getHeight()
  78794. });
  78795. };
  78796. VisualMapView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {};
  78797. VisualMapView.type = 'visualMap';
  78798. return VisualMapView;
  78799. }(ComponentView);
  78800. var paramsSet = [['left', 'right', 'width'], ['top', 'bottom', 'height']];
  78801. /**
  78802. * @param visualMapModel
  78803. * @param api
  78804. * @param itemSize always [short, long]
  78805. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  78806. */
  78807. function getItemAlign(visualMapModel, api, itemSize) {
  78808. var modelOption = visualMapModel.option;
  78809. var itemAlign = modelOption.align;
  78810. if (itemAlign != null && itemAlign !== 'auto') {
  78811. return itemAlign;
  78812. } // Auto decision align.
  78813. var ecSize = {
  78814. width: api.getWidth(),
  78815. height: api.getHeight()
  78816. };
  78817. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  78818. var reals = paramsSet[realIndex];
  78819. var fakeValue = [0, null, 10];
  78820. var layoutInput = {};
  78821. for (var i = 0; i < 3; i++) {
  78822. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  78823. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  78824. }
  78825. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  78826. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  78827. return reals[(rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5 < ecSize[rParam[1]] * 0.5 ? 0 : 1];
  78828. }
  78829. /**
  78830. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  78831. * dataIndexInside means filtered index.
  78832. */
  78833. // TODO: TYPE more specified payload types.
  78834. function makeHighDownBatch(batch, visualMapModel) {
  78835. each(batch || [], function (batchItem) {
  78836. if (batchItem.dataIndex != null) {
  78837. batchItem.dataIndexInside = batchItem.dataIndex;
  78838. batchItem.dataIndex = null;
  78839. }
  78840. batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : '');
  78841. });
  78842. return batch;
  78843. }
  78844. var linearMap$2 = linearMap;
  78845. var each$e = each;
  78846. var mathMin$a = Math.min;
  78847. var mathMax$a = Math.max; // Arbitrary value
  78848. var HOVER_LINK_SIZE = 12;
  78849. var HOVER_LINK_OUT = 6; // Notice:
  78850. // Any "interval" should be by the order of [low, high].
  78851. // "handle0" (handleIndex === 0) maps to
  78852. // low data value: this._dataInterval[0] and has low coord.
  78853. // "handle1" (handleIndex === 1) maps to
  78854. // high data value: this._dataInterval[1] and has high coord.
  78855. // The logic of transform is implemented in this._createBarGroup.
  78856. var ContinuousView =
  78857. /** @class */
  78858. function (_super) {
  78859. __extends(ContinuousView, _super);
  78860. function ContinuousView() {
  78861. var _this = _super !== null && _super.apply(this, arguments) || this;
  78862. _this.type = ContinuousView.type;
  78863. _this._shapes = {};
  78864. _this._dataInterval = [];
  78865. _this._handleEnds = [];
  78866. _this._hoverLinkDataIndices = [];
  78867. return _this;
  78868. }
  78869. ContinuousView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {
  78870. this._api = api;
  78871. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  78872. this._buildView();
  78873. }
  78874. };
  78875. ContinuousView.prototype._buildView = function () {
  78876. this.group.removeAll();
  78877. var visualMapModel = this.visualMapModel;
  78878. var thisGroup = this.group;
  78879. this._orient = visualMapModel.get('orient');
  78880. this._useHandle = visualMapModel.get('calculable');
  78881. this._resetInterval();
  78882. this._renderBar(thisGroup);
  78883. var dataRangeText = visualMapModel.get('text');
  78884. this._renderEndsText(thisGroup, dataRangeText, 0);
  78885. this._renderEndsText(thisGroup, dataRangeText, 1); // Do this for background size calculation.
  78886. this._updateView(true); // After updating view, inner shapes is built completely,
  78887. // and then background can be rendered.
  78888. this.renderBackground(thisGroup); // Real update view
  78889. this._updateView();
  78890. this._enableHoverLinkToSeries();
  78891. this._enableHoverLinkFromSeries();
  78892. this.positionGroup(thisGroup);
  78893. };
  78894. ContinuousView.prototype._renderEndsText = function (group, dataRangeText, endsIndex) {
  78895. if (!dataRangeText) {
  78896. return;
  78897. } // Compatible with ec2, text[0] map to high value, text[1] map low value.
  78898. var text = dataRangeText[1 - endsIndex];
  78899. text = text != null ? text + '' : '';
  78900. var visualMapModel = this.visualMapModel;
  78901. var textGap = visualMapModel.get('textGap');
  78902. var itemSize = visualMapModel.itemSize;
  78903. var barGroup = this._shapes.mainGroup;
  78904. var position = this._applyTransform([itemSize[0] / 2, endsIndex === 0 ? -textGap : itemSize[1] + textGap], barGroup);
  78905. var align = this._applyTransform(endsIndex === 0 ? 'bottom' : 'top', barGroup);
  78906. var orient = this._orient;
  78907. var textStyleModel = this.visualMapModel.textStyleModel;
  78908. this.group.add(new ZRText({
  78909. style: createTextStyle(textStyleModel, {
  78910. x: position[0],
  78911. y: position[1],
  78912. verticalAlign: orient === 'horizontal' ? 'middle' : align,
  78913. align: orient === 'horizontal' ? align : 'center',
  78914. text: text
  78915. })
  78916. }));
  78917. };
  78918. ContinuousView.prototype._renderBar = function (targetGroup) {
  78919. var visualMapModel = this.visualMapModel;
  78920. var shapes = this._shapes;
  78921. var itemSize = visualMapModel.itemSize;
  78922. var orient = this._orient;
  78923. var useHandle = this._useHandle;
  78924. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  78925. var mainGroup = shapes.mainGroup = this._createBarGroup(itemAlign);
  78926. var gradientBarGroup = new Group();
  78927. mainGroup.add(gradientBarGroup); // Bar
  78928. gradientBarGroup.add(shapes.outOfRange = createPolygon());
  78929. gradientBarGroup.add(shapes.inRange = createPolygon(null, useHandle ? getCursor$1(this._orient) : null, bind(this._dragHandle, this, 'all', false), bind(this._dragHandle, this, 'all', true))); // A border radius clip.
  78930. gradientBarGroup.setClipPath(new Rect({
  78931. shape: {
  78932. x: 0,
  78933. y: 0,
  78934. width: itemSize[0],
  78935. height: itemSize[1],
  78936. r: 3
  78937. }
  78938. }));
  78939. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  78940. var textSize = mathMax$a(textRect.width, textRect.height); // Handle
  78941. if (useHandle) {
  78942. shapes.handleThumbs = [];
  78943. shapes.handleLabels = [];
  78944. shapes.handleLabelPoints = [];
  78945. this._createHandle(visualMapModel, mainGroup, 0, itemSize, textSize, orient);
  78946. this._createHandle(visualMapModel, mainGroup, 1, itemSize, textSize, orient);
  78947. }
  78948. this._createIndicator(visualMapModel, mainGroup, itemSize, textSize, orient);
  78949. targetGroup.add(mainGroup);
  78950. };
  78951. ContinuousView.prototype._createHandle = function (visualMapModel, mainGroup, handleIndex, itemSize, textSize, orient) {
  78952. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  78953. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  78954. var handleSize = parsePercent(visualMapModel.get('handleSize'), itemSize[0]);
  78955. var handleThumb = createSymbol(visualMapModel.get('handleIcon'), -handleSize / 2, -handleSize / 2, handleSize, handleSize, null, true);
  78956. var cursor = getCursor$1(this._orient);
  78957. handleThumb.attr({
  78958. cursor: cursor,
  78959. draggable: true,
  78960. drift: onDrift,
  78961. ondragend: onDragEnd,
  78962. onmousemove: function (e) {
  78963. stop(e.event);
  78964. }
  78965. });
  78966. handleThumb.x = itemSize[0] / 2;
  78967. handleThumb.useStyle(visualMapModel.getModel('handleStyle').getItemStyle());
  78968. handleThumb.setStyle({
  78969. strokeNoScale: true,
  78970. strokeFirst: true
  78971. });
  78972. handleThumb.style.lineWidth *= 2;
  78973. handleThumb.ensureState('emphasis').style = visualMapModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  78974. setAsHighDownDispatcher(handleThumb, true);
  78975. mainGroup.add(handleThumb); // Text is always horizontal layout but should not be effected by
  78976. // transform (orient/inverse). So label is built separately but not
  78977. // use zrender/graphic/helper/RectText, and is located based on view
  78978. // group (according to handleLabelPoint) but not barGroup.
  78979. var textStyleModel = this.visualMapModel.textStyleModel;
  78980. var handleLabel = new ZRText({
  78981. cursor: cursor,
  78982. draggable: true,
  78983. drift: onDrift,
  78984. onmousemove: function (e) {
  78985. // For mobile device, prevent screen slider on the button.
  78986. stop(e.event);
  78987. },
  78988. ondragend: onDragEnd,
  78989. style: createTextStyle(textStyleModel, {
  78990. x: 0,
  78991. y: 0,
  78992. text: ''
  78993. })
  78994. });
  78995. handleLabel.ensureState('blur').style = {
  78996. opacity: 0.1
  78997. };
  78998. handleLabel.stateTransition = {
  78999. duration: 200
  79000. };
  79001. this.group.add(handleLabel);
  79002. var handleLabelPoint = [handleSize, 0];
  79003. var shapes = this._shapes;
  79004. shapes.handleThumbs[handleIndex] = handleThumb;
  79005. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  79006. shapes.handleLabels[handleIndex] = handleLabel;
  79007. };
  79008. ContinuousView.prototype._createIndicator = function (visualMapModel, mainGroup, itemSize, textSize, orient) {
  79009. var scale = parsePercent(visualMapModel.get('indicatorSize'), itemSize[0]);
  79010. var indicator = createSymbol(visualMapModel.get('indicatorIcon'), -scale / 2, -scale / 2, scale, scale, null, true);
  79011. indicator.attr({
  79012. cursor: 'move',
  79013. invisible: true,
  79014. silent: true,
  79015. x: itemSize[0] / 2
  79016. });
  79017. var indicatorStyle = visualMapModel.getModel('indicatorStyle').getItemStyle();
  79018. if (indicator instanceof ZRImage) {
  79019. var pathStyle = indicator.style;
  79020. indicator.useStyle(extend({
  79021. // TODO other properties like x, y ?
  79022. image: pathStyle.image,
  79023. x: pathStyle.x,
  79024. y: pathStyle.y,
  79025. width: pathStyle.width,
  79026. height: pathStyle.height
  79027. }, indicatorStyle));
  79028. } else {
  79029. indicator.useStyle(indicatorStyle);
  79030. }
  79031. mainGroup.add(indicator);
  79032. var textStyleModel = this.visualMapModel.textStyleModel;
  79033. var indicatorLabel = new ZRText({
  79034. silent: true,
  79035. invisible: true,
  79036. style: createTextStyle(textStyleModel, {
  79037. x: 0,
  79038. y: 0,
  79039. text: ''
  79040. })
  79041. });
  79042. this.group.add(indicatorLabel);
  79043. var indicatorLabelPoint = [(orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT) + itemSize[0] / 2, 0];
  79044. var shapes = this._shapes;
  79045. shapes.indicator = indicator;
  79046. shapes.indicatorLabel = indicatorLabel;
  79047. shapes.indicatorLabelPoint = indicatorLabelPoint;
  79048. this._firstShowIndicator = true;
  79049. };
  79050. ContinuousView.prototype._dragHandle = function (handleIndex, isEnd, // dx is event from ondragend if isEnd is true. It's not used
  79051. dx, dy) {
  79052. if (!this._useHandle) {
  79053. return;
  79054. }
  79055. this._dragging = !isEnd;
  79056. if (!isEnd) {
  79057. // Transform dx, dy to bar coordination.
  79058. var vertex = this._applyTransform([dx, dy], this._shapes.mainGroup, true);
  79059. this._updateInterval(handleIndex, vertex[1]);
  79060. this._hideIndicator(); // Considering realtime, update view should be executed
  79061. // before dispatch action.
  79062. this._updateView();
  79063. } // dragEnd do not dispatch action when realtime.
  79064. if (isEnd === !this.visualMapModel.get('realtime')) {
  79065. // jshint ignore:line
  79066. this.api.dispatchAction({
  79067. type: 'selectDataRange',
  79068. from: this.uid,
  79069. visualMapId: this.visualMapModel.id,
  79070. selected: this._dataInterval.slice()
  79071. });
  79072. }
  79073. if (isEnd) {
  79074. !this._hovering && this._clearHoverLinkToSeries();
  79075. } else if (useHoverLinkOnHandle(this.visualMapModel)) {
  79076. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  79077. }
  79078. };
  79079. ContinuousView.prototype._resetInterval = function () {
  79080. var visualMapModel = this.visualMapModel;
  79081. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  79082. var dataExtent = visualMapModel.getExtent();
  79083. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79084. this._handleEnds = [linearMap$2(dataInterval[0], dataExtent, sizeExtent, true), linearMap$2(dataInterval[1], dataExtent, sizeExtent, true)];
  79085. };
  79086. /**
  79087. * @private
  79088. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  79089. * @param {number} dx
  79090. * @param {number} dy
  79091. */
  79092. ContinuousView.prototype._updateInterval = function (handleIndex, delta) {
  79093. delta = delta || 0;
  79094. var visualMapModel = this.visualMapModel;
  79095. var handleEnds = this._handleEnds;
  79096. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79097. sliderMove(delta, handleEnds, sizeExtent, handleIndex, // cross is forbidden
  79098. 0);
  79099. var dataExtent = visualMapModel.getExtent(); // Update data interval.
  79100. this._dataInterval = [linearMap$2(handleEnds[0], sizeExtent, dataExtent, true), linearMap$2(handleEnds[1], sizeExtent, dataExtent, true)];
  79101. };
  79102. ContinuousView.prototype._updateView = function (forSketch) {
  79103. var visualMapModel = this.visualMapModel;
  79104. var dataExtent = visualMapModel.getExtent();
  79105. var shapes = this._shapes;
  79106. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  79107. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  79108. var visualInRange = this._createBarVisual(this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange');
  79109. var visualOutOfRange = this._createBarVisual(dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange');
  79110. shapes.inRange.setStyle({
  79111. fill: visualInRange.barColor // opacity: visualInRange.opacity
  79112. }).setShape('points', visualInRange.barPoints);
  79113. shapes.outOfRange.setStyle({
  79114. fill: visualOutOfRange.barColor // opacity: visualOutOfRange.opacity
  79115. }).setShape('points', visualOutOfRange.barPoints);
  79116. this._updateHandle(inRangeHandleEnds, visualInRange);
  79117. };
  79118. ContinuousView.prototype._createBarVisual = function (dataInterval, dataExtent, handleEnds, forceState) {
  79119. var opts = {
  79120. forceState: forceState,
  79121. convertOpacityToAlpha: true
  79122. };
  79123. var colorStops = this._makeColorGradient(dataInterval, opts);
  79124. var symbolSizes = [this.getControllerVisual(dataInterval[0], 'symbolSize', opts), this.getControllerVisual(dataInterval[1], 'symbolSize', opts)];
  79125. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  79126. return {
  79127. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  79128. barPoints: barPoints,
  79129. handlesColor: [colorStops[0].color, colorStops[colorStops.length - 1].color]
  79130. };
  79131. };
  79132. ContinuousView.prototype._makeColorGradient = function (dataInterval, opts) {
  79133. // Considering colorHue, which is not linear, so we have to sample
  79134. // to calculate gradient color stops, but not only calculate head
  79135. // and tail.
  79136. var sampleNumber = 100; // Arbitrary value.
  79137. var colorStops = [];
  79138. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  79139. colorStops.push({
  79140. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  79141. offset: 0
  79142. });
  79143. for (var i = 1; i < sampleNumber; i++) {
  79144. var currValue = dataInterval[0] + step * i;
  79145. if (currValue > dataInterval[1]) {
  79146. break;
  79147. }
  79148. colorStops.push({
  79149. color: this.getControllerVisual(currValue, 'color', opts),
  79150. offset: i / sampleNumber
  79151. });
  79152. }
  79153. colorStops.push({
  79154. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  79155. offset: 1
  79156. });
  79157. return colorStops;
  79158. };
  79159. ContinuousView.prototype._createBarPoints = function (handleEnds, symbolSizes) {
  79160. var itemSize = this.visualMapModel.itemSize;
  79161. return [[itemSize[0] - symbolSizes[0], handleEnds[0]], [itemSize[0], handleEnds[0]], [itemSize[0], handleEnds[1]], [itemSize[0] - symbolSizes[1], handleEnds[1]]];
  79162. };
  79163. ContinuousView.prototype._createBarGroup = function (itemAlign) {
  79164. var orient = this._orient;
  79165. var inverse = this.visualMapModel.get('inverse');
  79166. return new Group(orient === 'horizontal' && !inverse ? {
  79167. scaleX: itemAlign === 'bottom' ? 1 : -1,
  79168. rotation: Math.PI / 2
  79169. } : orient === 'horizontal' && inverse ? {
  79170. scaleX: itemAlign === 'bottom' ? -1 : 1,
  79171. rotation: -Math.PI / 2
  79172. } : orient === 'vertical' && !inverse ? {
  79173. scaleX: itemAlign === 'left' ? 1 : -1,
  79174. scaleY: -1
  79175. } : {
  79176. scaleX: itemAlign === 'left' ? 1 : -1
  79177. });
  79178. };
  79179. ContinuousView.prototype._updateHandle = function (handleEnds, visualInRange) {
  79180. if (!this._useHandle) {
  79181. return;
  79182. }
  79183. var shapes = this._shapes;
  79184. var visualMapModel = this.visualMapModel;
  79185. var handleThumbs = shapes.handleThumbs;
  79186. var handleLabels = shapes.handleLabels;
  79187. var itemSize = visualMapModel.itemSize;
  79188. var dataExtent = visualMapModel.getExtent();
  79189. each$e([0, 1], function (handleIndex) {
  79190. var handleThumb = handleThumbs[handleIndex];
  79191. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  79192. handleThumb.y = handleEnds[handleIndex];
  79193. var val = linearMap$2(handleEnds[handleIndex], [0, itemSize[1]], dataExtent, true);
  79194. var symbolSize = this.getControllerVisual(val, 'symbolSize');
  79195. handleThumb.scaleX = handleThumb.scaleY = symbolSize / itemSize[0];
  79196. handleThumb.x = itemSize[0] - symbolSize / 2; // Update handle label position.
  79197. var textPoint = applyTransform$1(shapes.handleLabelPoints[handleIndex], getTransform(handleThumb, this.group));
  79198. handleLabels[handleIndex].setStyle({
  79199. x: textPoint[0],
  79200. y: textPoint[1],
  79201. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  79202. verticalAlign: 'middle',
  79203. align: this._orient === 'vertical' ? this._applyTransform('left', shapes.mainGroup) : 'center'
  79204. });
  79205. }, this);
  79206. };
  79207. ContinuousView.prototype._showIndicator = function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  79208. var visualMapModel = this.visualMapModel;
  79209. var dataExtent = visualMapModel.getExtent();
  79210. var itemSize = visualMapModel.itemSize;
  79211. var sizeExtent = [0, itemSize[1]];
  79212. var shapes = this._shapes;
  79213. var indicator = shapes.indicator;
  79214. if (!indicator) {
  79215. return;
  79216. }
  79217. indicator.attr('invisible', false);
  79218. var opts = {
  79219. convertOpacityToAlpha: true
  79220. };
  79221. var color = this.getControllerVisual(cursorValue, 'color', opts);
  79222. var symbolSize = this.getControllerVisual(cursorValue, 'symbolSize');
  79223. var y = linearMap$2(cursorValue, dataExtent, sizeExtent, true);
  79224. var x = itemSize[0] - symbolSize / 2;
  79225. var oldIndicatorPos = {
  79226. x: indicator.x,
  79227. y: indicator.y
  79228. }; // Update handle label position.
  79229. indicator.y = y;
  79230. indicator.x = x;
  79231. var textPoint = applyTransform$1(shapes.indicatorLabelPoint, getTransform(indicator, this.group));
  79232. var indicatorLabel = shapes.indicatorLabel;
  79233. indicatorLabel.attr('invisible', false);
  79234. var align = this._applyTransform('left', shapes.mainGroup);
  79235. var orient = this._orient;
  79236. var isHorizontal = orient === 'horizontal';
  79237. indicatorLabel.setStyle({
  79238. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  79239. verticalAlign: isHorizontal ? align : 'middle',
  79240. align: isHorizontal ? 'center' : align
  79241. });
  79242. var indicatorNewProps = {
  79243. x: x,
  79244. y: y,
  79245. style: {
  79246. fill: color
  79247. }
  79248. };
  79249. var labelNewProps = {
  79250. style: {
  79251. x: textPoint[0],
  79252. y: textPoint[1]
  79253. }
  79254. };
  79255. if (visualMapModel.ecModel.isAnimationEnabled() && !this._firstShowIndicator) {
  79256. var animationCfg = {
  79257. duration: 100,
  79258. easing: 'cubicInOut',
  79259. additive: true
  79260. };
  79261. indicator.x = oldIndicatorPos.x;
  79262. indicator.y = oldIndicatorPos.y;
  79263. indicator.animateTo(indicatorNewProps, animationCfg);
  79264. indicatorLabel.animateTo(labelNewProps, animationCfg);
  79265. } else {
  79266. indicator.attr(indicatorNewProps);
  79267. indicatorLabel.attr(labelNewProps);
  79268. }
  79269. this._firstShowIndicator = false;
  79270. var handleLabels = this._shapes.handleLabels;
  79271. if (handleLabels) {
  79272. for (var i = 0; i < handleLabels.length; i++) {
  79273. // Fade out handle labels.
  79274. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  79275. this._api.enterBlur(handleLabels[i]);
  79276. }
  79277. }
  79278. };
  79279. ContinuousView.prototype._enableHoverLinkToSeries = function () {
  79280. var self = this;
  79281. this._shapes.mainGroup.on('mousemove', function (e) {
  79282. self._hovering = true;
  79283. if (!self._dragging) {
  79284. var itemSize = self.visualMapModel.itemSize;
  79285. var pos = self._applyTransform([e.offsetX, e.offsetY], self._shapes.mainGroup, true, true); // For hover link show when hover handle, which might be
  79286. // below or upper than sizeExtent.
  79287. pos[1] = mathMin$a(mathMax$a(0, pos[1]), itemSize[1]);
  79288. self._doHoverLinkToSeries(pos[1], 0 <= pos[0] && pos[0] <= itemSize[0]);
  79289. }
  79290. }).on('mouseout', function () {
  79291. // When mouse is out of handle, hoverLink still need
  79292. // to be displayed when realtime is set as false.
  79293. self._hovering = false;
  79294. !self._dragging && self._clearHoverLinkToSeries();
  79295. });
  79296. };
  79297. ContinuousView.prototype._enableHoverLinkFromSeries = function () {
  79298. var zr = this.api.getZr();
  79299. if (this.visualMapModel.option.hoverLink) {
  79300. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  79301. zr.on('mouseout', this._hideIndicator, this);
  79302. } else {
  79303. this._clearHoverLinkFromSeries();
  79304. }
  79305. };
  79306. ContinuousView.prototype._doHoverLinkToSeries = function (cursorPos, hoverOnBar) {
  79307. var visualMapModel = this.visualMapModel;
  79308. var itemSize = visualMapModel.itemSize;
  79309. if (!visualMapModel.option.hoverLink) {
  79310. return;
  79311. }
  79312. var sizeExtent = [0, itemSize[1]];
  79313. var dataExtent = visualMapModel.getExtent(); // For hover link show when hover handle, which might be below or upper than sizeExtent.
  79314. cursorPos = mathMin$a(mathMax$a(sizeExtent[0], cursorPos), sizeExtent[1]);
  79315. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  79316. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  79317. var cursorValue = linearMap$2(cursorPos, sizeExtent, dataExtent, true);
  79318. var valueRange = [linearMap$2(hoverRange[0], sizeExtent, dataExtent, true), linearMap$2(hoverRange[1], sizeExtent, dataExtent, true)]; // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  79319. // where china and india has very large population.
  79320. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  79321. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity); // Do not show indicator when mouse is over handle,
  79322. // otherwise labels overlap, especially when dragging.
  79323. if (hoverOnBar) {
  79324. if (valueRange[0] === -Infinity) {
  79325. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  79326. } else if (valueRange[1] === Infinity) {
  79327. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  79328. } else {
  79329. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  79330. }
  79331. } // When realtime is set as false, handles, which are in barGroup,
  79332. // also trigger hoverLink, which help user to realize where they
  79333. // focus on when dragging. (see test/heatmap-large.html)
  79334. // When realtime is set as true, highlight will not show when hover
  79335. // handle, because the label on handle, which displays a exact value
  79336. // but not range, might mislead users.
  79337. var oldBatch = this._hoverLinkDataIndices;
  79338. var newBatch = [];
  79339. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  79340. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  79341. }
  79342. var resultBatches = compressBatches(oldBatch, newBatch);
  79343. this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel));
  79344. this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel));
  79345. };
  79346. ContinuousView.prototype._hoverLinkFromSeriesMouseOver = function (e) {
  79347. var ecData;
  79348. findEventDispatcher(e.target, function (target) {
  79349. var currECData = getECData(target);
  79350. if (currECData.dataIndex != null) {
  79351. ecData = currECData;
  79352. return true;
  79353. }
  79354. }, true);
  79355. if (!ecData) {
  79356. return;
  79357. }
  79358. var dataModel = this.ecModel.getSeriesByIndex(ecData.seriesIndex);
  79359. var visualMapModel = this.visualMapModel;
  79360. if (!visualMapModel.isTargetSeries(dataModel)) {
  79361. return;
  79362. }
  79363. var data = dataModel.getData(ecData.dataType);
  79364. var value = data.getStore().get(visualMapModel.getDataDimensionIndex(data), ecData.dataIndex);
  79365. if (!isNaN(value)) {
  79366. this._showIndicator(value, value);
  79367. }
  79368. };
  79369. ContinuousView.prototype._hideIndicator = function () {
  79370. var shapes = this._shapes;
  79371. shapes.indicator && shapes.indicator.attr('invisible', true);
  79372. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  79373. var handleLabels = this._shapes.handleLabels;
  79374. if (handleLabels) {
  79375. for (var i = 0; i < handleLabels.length; i++) {
  79376. // Fade out handle labels.
  79377. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  79378. this._api.leaveBlur(handleLabels[i]);
  79379. }
  79380. }
  79381. };
  79382. ContinuousView.prototype._clearHoverLinkToSeries = function () {
  79383. this._hideIndicator();
  79384. var indices = this._hoverLinkDataIndices;
  79385. this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel));
  79386. indices.length = 0;
  79387. };
  79388. ContinuousView.prototype._clearHoverLinkFromSeries = function () {
  79389. this._hideIndicator();
  79390. var zr = this.api.getZr();
  79391. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  79392. zr.off('mouseout', this._hideIndicator);
  79393. };
  79394. ContinuousView.prototype._applyTransform = function (vertex, element, inverse, global) {
  79395. var transform = getTransform(element, global ? null : this.group);
  79396. return isArray(vertex) ? applyTransform$1(vertex, transform, inverse) : transformDirection(vertex, transform, inverse);
  79397. }; // TODO: TYPE more specified payload types.
  79398. ContinuousView.prototype._dispatchHighDown = function (type, batch) {
  79399. batch && batch.length && this.api.dispatchAction({
  79400. type: type,
  79401. batch: batch
  79402. });
  79403. };
  79404. /**
  79405. * @override
  79406. */
  79407. ContinuousView.prototype.dispose = function () {
  79408. this._clearHoverLinkFromSeries();
  79409. this._clearHoverLinkToSeries();
  79410. };
  79411. /**
  79412. * @override
  79413. */
  79414. ContinuousView.prototype.remove = function () {
  79415. this._clearHoverLinkFromSeries();
  79416. this._clearHoverLinkToSeries();
  79417. };
  79418. ContinuousView.type = 'visualMap.continuous';
  79419. return ContinuousView;
  79420. }(VisualMapView);
  79421. function createPolygon(points, cursor, onDrift, onDragEnd) {
  79422. return new Polygon({
  79423. shape: {
  79424. points: points
  79425. },
  79426. draggable: !!onDrift,
  79427. cursor: cursor,
  79428. drift: onDrift,
  79429. onmousemove: function (e) {
  79430. // For mobile device, prevent screen slider on the button.
  79431. stop(e.event);
  79432. },
  79433. ondragend: onDragEnd
  79434. });
  79435. }
  79436. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  79437. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  79438. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  79439. if (hoverLinkDataSize) {
  79440. halfHoverLinkSize = linearMap$2(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  79441. }
  79442. return halfHoverLinkSize;
  79443. }
  79444. function useHoverLinkOnHandle(visualMapModel) {
  79445. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  79446. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  79447. }
  79448. function getCursor$1(orient) {
  79449. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  79450. }
  79451. /*
  79452. * Licensed to the Apache Software Foundation (ASF) under one
  79453. * or more contributor license agreements. See the NOTICE file
  79454. * distributed with this work for additional information
  79455. * regarding copyright ownership. The ASF licenses this file
  79456. * to you under the Apache License, Version 2.0 (the
  79457. * "License"); you may not use this file except in compliance
  79458. * with the License. You may obtain a copy of the License at
  79459. *
  79460. * http://www.apache.org/licenses/LICENSE-2.0
  79461. *
  79462. * Unless required by applicable law or agreed to in writing,
  79463. * software distributed under the License is distributed on an
  79464. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79465. * KIND, either express or implied. See the License for the
  79466. * specific language governing permissions and limitations
  79467. * under the License.
  79468. */
  79469. /**
  79470. * AUTO-GENERATED FILE. DO NOT MODIFY.
  79471. */
  79472. /*
  79473. * Licensed to the Apache Software Foundation (ASF) under one
  79474. * or more contributor license agreements. See the NOTICE file
  79475. * distributed with this work for additional information
  79476. * regarding copyright ownership. The ASF licenses this file
  79477. * to you under the Apache License, Version 2.0 (the
  79478. * "License"); you may not use this file except in compliance
  79479. * with the License. You may obtain a copy of the License at
  79480. *
  79481. * http://www.apache.org/licenses/LICENSE-2.0
  79482. *
  79483. * Unless required by applicable law or agreed to in writing,
  79484. * software distributed under the License is distributed on an
  79485. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79486. * KIND, either express or implied. See the License for the
  79487. * specific language governing permissions and limitations
  79488. * under the License.
  79489. */
  79490. var visualMapActionInfo = {
  79491. type: 'selectDataRange',
  79492. event: 'dataRangeSelected',
  79493. // FIXME use updateView appears wrong
  79494. update: 'update'
  79495. };
  79496. var visualMapActionHander = function (payload, ecModel) {
  79497. ecModel.eachComponent({
  79498. mainType: 'visualMap',
  79499. query: payload
  79500. }, function (model) {
  79501. model.setSelected(payload.selected);
  79502. });
  79503. };
  79504. var visualMapEncodingHandlers = [{
  79505. createOnAllSeries: true,
  79506. reset: function (seriesModel, ecModel) {
  79507. var resetDefines = [];
  79508. ecModel.eachComponent('visualMap', function (visualMapModel) {
  79509. var pipelineContext = seriesModel.pipelineContext;
  79510. if (!visualMapModel.isTargetSeries(seriesModel) || pipelineContext && pipelineContext.large) {
  79511. return;
  79512. }
  79513. resetDefines.push(incrementalApplyVisual(visualMapModel.stateList, visualMapModel.targetVisuals, bind(visualMapModel.getValueState, visualMapModel), visualMapModel.getDataDimensionIndex(seriesModel.getData())));
  79514. });
  79515. return resetDefines;
  79516. }
  79517. }, // Only support color.
  79518. {
  79519. createOnAllSeries: true,
  79520. reset: function (seriesModel, ecModel) {
  79521. var data = seriesModel.getData();
  79522. var visualMetaList = [];
  79523. ecModel.eachComponent('visualMap', function (visualMapModel) {
  79524. if (visualMapModel.isTargetSeries(seriesModel)) {
  79525. var visualMeta = visualMapModel.getVisualMeta(bind(getColorVisual, null, seriesModel, visualMapModel)) || {
  79526. stops: [],
  79527. outerColors: []
  79528. };
  79529. var dimIdx = visualMapModel.getDataDimensionIndex(data);
  79530. if (dimIdx >= 0) {
  79531. // visualMeta.dimension should be dimension index, but not concrete dimension.
  79532. visualMeta.dimension = dimIdx;
  79533. visualMetaList.push(visualMeta);
  79534. }
  79535. }
  79536. }); // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  79537. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  79538. }
  79539. }]; // FIXME
  79540. // performance and export for heatmap?
  79541. // value can be Infinity or -Infinity
  79542. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  79543. var mappings = visualMapModel.targetVisuals[valueState];
  79544. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  79545. var resultVisual = {
  79546. color: getVisualFromData(seriesModel.getData(), 'color') // default color.
  79547. };
  79548. for (var i = 0, len = visualTypes.length; i < len; i++) {
  79549. var type = visualTypes[i];
  79550. var mapping = mappings[type === 'opacity' ? '__alphaForOpacity' : type];
  79551. mapping && mapping.applyVisual(value, getVisual, setVisual);
  79552. }
  79553. return resultVisual.color;
  79554. function getVisual(key) {
  79555. return resultVisual[key];
  79556. }
  79557. function setVisual(key, value) {
  79558. resultVisual[key] = value;
  79559. }
  79560. }
  79561. var each$f = each;
  79562. function visualMapPreprocessor(option) {
  79563. var visualMap = option && option.visualMap;
  79564. if (!isArray(visualMap)) {
  79565. visualMap = visualMap ? [visualMap] : [];
  79566. }
  79567. each$f(visualMap, function (opt) {
  79568. if (!opt) {
  79569. return;
  79570. } // rename splitList to pieces
  79571. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  79572. opt.pieces = opt.splitList;
  79573. delete opt.splitList;
  79574. }
  79575. var pieces = opt.pieces;
  79576. if (pieces && isArray(pieces)) {
  79577. each$f(pieces, function (piece) {
  79578. if (isObject(piece)) {
  79579. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  79580. piece.min = piece.start;
  79581. }
  79582. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  79583. piece.max = piece.end;
  79584. }
  79585. }
  79586. });
  79587. }
  79588. });
  79589. }
  79590. function has$1(obj, name) {
  79591. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  79592. }
  79593. var installed$1 = false;
  79594. function installCommon$1(registers) {
  79595. if (installed$1) {
  79596. return;
  79597. }
  79598. installed$1 = true;
  79599. registers.registerSubTypeDefaulter('visualMap', function (option) {
  79600. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  79601. return !option.categories && (!(option.pieces ? option.pieces.length > 0 : option.splitNumber > 0) || option.calculable) ? 'continuous' : 'piecewise';
  79602. });
  79603. registers.registerAction(visualMapActionInfo, visualMapActionHander);
  79604. each(visualMapEncodingHandlers, function (handler) {
  79605. registers.registerVisual(registers.PRIORITY.VISUAL.COMPONENT, handler);
  79606. });
  79607. registers.registerPreprocessor(visualMapPreprocessor);
  79608. }
  79609. function install$N(registers) {
  79610. registers.registerComponentModel(ContinuousModel);
  79611. registers.registerComponentView(ContinuousView);
  79612. installCommon$1(registers);
  79613. }
  79614. var PiecewiseModel =
  79615. /** @class */
  79616. function (_super) {
  79617. __extends(PiecewiseModel, _super);
  79618. function PiecewiseModel() {
  79619. var _this = _super !== null && _super.apply(this, arguments) || this;
  79620. _this.type = PiecewiseModel.type;
  79621. /**
  79622. * The order is always [low, ..., high].
  79623. * [{text: string, interval: Array.<number>}, ...]
  79624. */
  79625. _this._pieceList = [];
  79626. return _this;
  79627. }
  79628. PiecewiseModel.prototype.optionUpdated = function (newOption, isInit) {
  79629. _super.prototype.optionUpdated.apply(this, arguments);
  79630. this.resetExtent();
  79631. var mode = this._mode = this._determineMode();
  79632. this._pieceList = [];
  79633. resetMethods[this._mode].call(this, this._pieceList);
  79634. this._resetSelected(newOption, isInit);
  79635. var categories = this.option.categories;
  79636. this.resetVisual(function (mappingOption, state) {
  79637. if (mode === 'categories') {
  79638. mappingOption.mappingMethod = 'category';
  79639. mappingOption.categories = clone(categories);
  79640. } else {
  79641. mappingOption.dataExtent = this.getExtent();
  79642. mappingOption.mappingMethod = 'piecewise';
  79643. mappingOption.pieceList = map(this._pieceList, function (piece) {
  79644. piece = clone(piece);
  79645. if (state !== 'inRange') {
  79646. // FIXME
  79647. // outOfRange do not support special visual in pieces.
  79648. piece.visual = null;
  79649. }
  79650. return piece;
  79651. });
  79652. }
  79653. });
  79654. };
  79655. /**
  79656. * @protected
  79657. * @override
  79658. */
  79659. PiecewiseModel.prototype.completeVisualOption = function () {
  79660. // Consider this case:
  79661. // visualMap: {
  79662. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  79663. // }
  79664. // where no inRange/outOfRange set but only pieces. So we should make
  79665. // default inRange/outOfRange for this case, otherwise visuals that only
  79666. // appear in `pieces` will not be taken into account in visual encoding.
  79667. var option = this.option;
  79668. var visualTypesInPieces = {};
  79669. var visualTypes = VisualMapping.listVisualTypes();
  79670. var isCategory = this.isCategory();
  79671. each(option.pieces, function (piece) {
  79672. each(visualTypes, function (visualType) {
  79673. if (piece.hasOwnProperty(visualType)) {
  79674. visualTypesInPieces[visualType] = 1;
  79675. }
  79676. });
  79677. });
  79678. each(visualTypesInPieces, function (v, visualType) {
  79679. var exists = false;
  79680. each(this.stateList, function (state) {
  79681. exists = exists || has(option, state, visualType) || has(option.target, state, visualType);
  79682. }, this);
  79683. !exists && each(this.stateList, function (state) {
  79684. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(visualType, state === 'inRange' ? 'active' : 'inactive', isCategory);
  79685. });
  79686. }, this);
  79687. function has(obj, state, visualType) {
  79688. return obj && obj[state] && obj[state].hasOwnProperty(visualType);
  79689. }
  79690. _super.prototype.completeVisualOption.apply(this, arguments);
  79691. };
  79692. PiecewiseModel.prototype._resetSelected = function (newOption, isInit) {
  79693. var thisOption = this.option;
  79694. var pieceList = this._pieceList; // Selected do not merge but all override.
  79695. var selected = (isInit ? thisOption : newOption).selected || {};
  79696. thisOption.selected = selected; // Consider 'not specified' means true.
  79697. each(pieceList, function (piece, index) {
  79698. var key = this.getSelectedMapKey(piece);
  79699. if (!selected.hasOwnProperty(key)) {
  79700. selected[key] = true;
  79701. }
  79702. }, this);
  79703. if (thisOption.selectedMode === 'single') {
  79704. // Ensure there is only one selected.
  79705. var hasSel_1 = false;
  79706. each(pieceList, function (piece, index) {
  79707. var key = this.getSelectedMapKey(piece);
  79708. if (selected[key]) {
  79709. hasSel_1 ? selected[key] = false : hasSel_1 = true;
  79710. }
  79711. }, this);
  79712. } // thisOption.selectedMode === 'multiple', default: all selected.
  79713. };
  79714. /**
  79715. * @public
  79716. */
  79717. PiecewiseModel.prototype.getItemSymbol = function () {
  79718. return this.get('itemSymbol');
  79719. };
  79720. /**
  79721. * @public
  79722. */
  79723. PiecewiseModel.prototype.getSelectedMapKey = function (piece) {
  79724. return this._mode === 'categories' ? piece.value + '' : piece.index + '';
  79725. };
  79726. /**
  79727. * @public
  79728. */
  79729. PiecewiseModel.prototype.getPieceList = function () {
  79730. return this._pieceList;
  79731. };
  79732. /**
  79733. * @return {string}
  79734. */
  79735. PiecewiseModel.prototype._determineMode = function () {
  79736. var option = this.option;
  79737. return option.pieces && option.pieces.length > 0 ? 'pieces' : this.option.categories ? 'categories' : 'splitNumber';
  79738. };
  79739. /**
  79740. * @override
  79741. */
  79742. PiecewiseModel.prototype.setSelected = function (selected) {
  79743. this.option.selected = clone(selected);
  79744. };
  79745. /**
  79746. * @override
  79747. */
  79748. PiecewiseModel.prototype.getValueState = function (value) {
  79749. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  79750. return index != null ? this.option.selected[this.getSelectedMapKey(this._pieceList[index])] ? 'inRange' : 'outOfRange' : 'outOfRange';
  79751. };
  79752. /**
  79753. * @public
  79754. * @param pieceIndex piece index in visualMapModel.getPieceList()
  79755. */
  79756. PiecewiseModel.prototype.findTargetDataIndices = function (pieceIndex) {
  79757. var result = [];
  79758. var pieceList = this._pieceList;
  79759. this.eachTargetSeries(function (seriesModel) {
  79760. var dataIndices = [];
  79761. var data = seriesModel.getData();
  79762. data.each(this.getDataDimensionIndex(data), function (value, dataIndex) {
  79763. // Should always base on model pieceList, because it is order sensitive.
  79764. var pIdx = VisualMapping.findPieceIndex(value, pieceList);
  79765. pIdx === pieceIndex && dataIndices.push(dataIndex);
  79766. }, this);
  79767. result.push({
  79768. seriesId: seriesModel.id,
  79769. dataIndex: dataIndices
  79770. });
  79771. }, this);
  79772. return result;
  79773. };
  79774. /**
  79775. * @private
  79776. * @param piece piece.value or piece.interval is required.
  79777. * @return Can be Infinity or -Infinity
  79778. */
  79779. PiecewiseModel.prototype.getRepresentValue = function (piece) {
  79780. var representValue;
  79781. if (this.isCategory()) {
  79782. representValue = piece.value;
  79783. } else {
  79784. if (piece.value != null) {
  79785. representValue = piece.value;
  79786. } else {
  79787. var pieceInterval = piece.interval || [];
  79788. representValue = pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity ? 0 : (pieceInterval[0] + pieceInterval[1]) / 2;
  79789. }
  79790. }
  79791. return representValue;
  79792. };
  79793. PiecewiseModel.prototype.getVisualMeta = function (getColorVisual) {
  79794. // Do not support category. (category axis is ordinal, numerical)
  79795. if (this.isCategory()) {
  79796. return;
  79797. }
  79798. var stops = [];
  79799. var outerColors = ['', ''];
  79800. var visualMapModel = this;
  79801. function setStop(interval, valueState) {
  79802. var representValue = visualMapModel.getRepresentValue({
  79803. interval: interval
  79804. }); // Not category
  79805. if (!valueState) {
  79806. valueState = visualMapModel.getValueState(representValue);
  79807. }
  79808. var color = getColorVisual(representValue, valueState);
  79809. if (interval[0] === -Infinity) {
  79810. outerColors[0] = color;
  79811. } else if (interval[1] === Infinity) {
  79812. outerColors[1] = color;
  79813. } else {
  79814. stops.push({
  79815. value: interval[0],
  79816. color: color
  79817. }, {
  79818. value: interval[1],
  79819. color: color
  79820. });
  79821. }
  79822. } // Suplement
  79823. var pieceList = this._pieceList.slice();
  79824. if (!pieceList.length) {
  79825. pieceList.push({
  79826. interval: [-Infinity, Infinity]
  79827. });
  79828. } else {
  79829. var edge = pieceList[0].interval[0];
  79830. edge !== -Infinity && pieceList.unshift({
  79831. interval: [-Infinity, edge]
  79832. });
  79833. edge = pieceList[pieceList.length - 1].interval[1];
  79834. edge !== Infinity && pieceList.push({
  79835. interval: [edge, Infinity]
  79836. });
  79837. }
  79838. var curr = -Infinity;
  79839. each(pieceList, function (piece) {
  79840. var interval = piece.interval;
  79841. if (interval) {
  79842. // Fulfill gap.
  79843. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  79844. setStop(interval.slice());
  79845. curr = interval[1];
  79846. }
  79847. }, this);
  79848. return {
  79849. stops: stops,
  79850. outerColors: outerColors
  79851. };
  79852. };
  79853. PiecewiseModel.type = 'visualMap.piecewise';
  79854. PiecewiseModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  79855. selected: null,
  79856. minOpen: false,
  79857. maxOpen: false,
  79858. align: 'auto',
  79859. itemWidth: 20,
  79860. itemHeight: 14,
  79861. itemSymbol: 'roundRect',
  79862. pieces: null,
  79863. categories: null,
  79864. splitNumber: 5,
  79865. selectedMode: 'multiple',
  79866. itemGap: 10,
  79867. hoverLink: true // Enable hover highlight.
  79868. });
  79869. return PiecewiseModel;
  79870. }(VisualMapModel);
  79871. /**
  79872. * Key is this._mode
  79873. * @type {Object}
  79874. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  79875. */
  79876. var resetMethods = {
  79877. splitNumber: function (outPieceList) {
  79878. var thisOption = this.option;
  79879. var precision = Math.min(thisOption.precision, 20);
  79880. var dataExtent = this.getExtent();
  79881. var splitNumber = thisOption.splitNumber;
  79882. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  79883. thisOption.splitNumber = splitNumber;
  79884. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber; // Precision auto-adaption
  79885. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  79886. precision++;
  79887. }
  79888. thisOption.precision = precision;
  79889. splitStep = +splitStep.toFixed(precision);
  79890. if (thisOption.minOpen) {
  79891. outPieceList.push({
  79892. interval: [-Infinity, dataExtent[0]],
  79893. close: [0, 0]
  79894. });
  79895. }
  79896. for (var index = 0, curr = dataExtent[0]; index < splitNumber; curr += splitStep, index++) {
  79897. var max = index === splitNumber - 1 ? dataExtent[1] : curr + splitStep;
  79898. outPieceList.push({
  79899. interval: [curr, max],
  79900. close: [1, 1]
  79901. });
  79902. }
  79903. if (thisOption.maxOpen) {
  79904. outPieceList.push({
  79905. interval: [dataExtent[1], Infinity],
  79906. close: [0, 0]
  79907. });
  79908. }
  79909. reformIntervals(outPieceList);
  79910. each(outPieceList, function (piece, index) {
  79911. piece.index = index;
  79912. piece.text = this.formatValueText(piece.interval);
  79913. }, this);
  79914. },
  79915. categories: function (outPieceList) {
  79916. var thisOption = this.option;
  79917. each(thisOption.categories, function (cate) {
  79918. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  79919. // 是否改一致。
  79920. outPieceList.push({
  79921. text: this.formatValueText(cate, true),
  79922. value: cate
  79923. });
  79924. }, this); // See "Order Rule".
  79925. normalizeReverse(thisOption, outPieceList);
  79926. },
  79927. pieces: function (outPieceList) {
  79928. var thisOption = this.option;
  79929. each(thisOption.pieces, function (pieceListItem, index) {
  79930. if (!isObject(pieceListItem)) {
  79931. pieceListItem = {
  79932. value: pieceListItem
  79933. };
  79934. }
  79935. var item = {
  79936. text: '',
  79937. index: index
  79938. };
  79939. if (pieceListItem.label != null) {
  79940. item.text = pieceListItem.label;
  79941. }
  79942. if (pieceListItem.hasOwnProperty('value')) {
  79943. var value = item.value = pieceListItem.value;
  79944. item.interval = [value, value];
  79945. item.close = [1, 1];
  79946. } else {
  79947. // `min` `max` is legacy option.
  79948. // `lt` `gt` `lte` `gte` is recommended.
  79949. var interval = item.interval = [];
  79950. var close_1 = item.close = [0, 0];
  79951. var closeList = [1, 0, 1];
  79952. var infinityList = [-Infinity, Infinity];
  79953. var useMinMax = [];
  79954. for (var lg = 0; lg < 2; lg++) {
  79955. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  79956. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  79957. interval[lg] = pieceListItem[names[i]];
  79958. close_1[lg] = closeList[i];
  79959. useMinMax[lg] = i === 2;
  79960. }
  79961. interval[lg] == null && (interval[lg] = infinityList[lg]);
  79962. }
  79963. useMinMax[0] && interval[1] === Infinity && (close_1[0] = 0);
  79964. useMinMax[1] && interval[0] === -Infinity && (close_1[1] = 0);
  79965. if ("development" !== 'production') {
  79966. if (interval[0] > interval[1]) {
  79967. console.warn('Piece ' + index + 'is illegal: ' + interval + ' lower bound should not greater then uppper bound.');
  79968. }
  79969. }
  79970. if (interval[0] === interval[1] && close_1[0] && close_1[1]) {
  79971. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  79972. // we use value to lift the priority when min === max
  79973. item.value = interval[0];
  79974. }
  79975. }
  79976. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  79977. outPieceList.push(item);
  79978. }, this); // See "Order Rule".
  79979. normalizeReverse(thisOption, outPieceList); // Only pieces
  79980. reformIntervals(outPieceList);
  79981. each(outPieceList, function (piece) {
  79982. var close = piece.close;
  79983. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  79984. piece.text = piece.text || this.formatValueText(piece.value != null ? piece.value : piece.interval, false, edgeSymbols);
  79985. }, this);
  79986. }
  79987. };
  79988. function normalizeReverse(thisOption, pieceList) {
  79989. var inverse = thisOption.inverse;
  79990. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  79991. pieceList.reverse();
  79992. }
  79993. }
  79994. var PiecewiseVisualMapView =
  79995. /** @class */
  79996. function (_super) {
  79997. __extends(PiecewiseVisualMapView, _super);
  79998. function PiecewiseVisualMapView() {
  79999. var _this = _super !== null && _super.apply(this, arguments) || this;
  80000. _this.type = PiecewiseVisualMapView.type;
  80001. return _this;
  80002. }
  80003. PiecewiseVisualMapView.prototype.doRender = function () {
  80004. var thisGroup = this.group;
  80005. thisGroup.removeAll();
  80006. var visualMapModel = this.visualMapModel;
  80007. var textGap = visualMapModel.get('textGap');
  80008. var textStyleModel = visualMapModel.textStyleModel;
  80009. var textFont = textStyleModel.getFont();
  80010. var textFill = textStyleModel.getTextColor();
  80011. var itemAlign = this._getItemAlign();
  80012. var itemSize = visualMapModel.itemSize;
  80013. var viewData = this._getViewData();
  80014. var endsText = viewData.endsText;
  80015. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  80016. endsText && this._renderEndsText(thisGroup, endsText[0], itemSize, showLabel, itemAlign);
  80017. each(viewData.viewPieceList, function (item) {
  80018. var piece = item.piece;
  80019. var itemGroup = new Group();
  80020. itemGroup.onclick = bind(this._onItemClick, this, piece);
  80021. this._enableHoverLink(itemGroup, item.indexInModelPieceList); // TODO Category
  80022. var representValue = visualMapModel.getRepresentValue(piece);
  80023. this._createItemSymbol(itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]);
  80024. if (showLabel) {
  80025. var visualState = this.visualMapModel.getValueState(representValue);
  80026. itemGroup.add(new ZRText({
  80027. style: {
  80028. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  80029. y: itemSize[1] / 2,
  80030. text: piece.text,
  80031. verticalAlign: 'middle',
  80032. align: itemAlign,
  80033. font: textFont,
  80034. fill: textFill,
  80035. opacity: visualState === 'outOfRange' ? 0.5 : 1
  80036. }
  80037. }));
  80038. }
  80039. thisGroup.add(itemGroup);
  80040. }, this);
  80041. endsText && this._renderEndsText(thisGroup, endsText[1], itemSize, showLabel, itemAlign);
  80042. box(visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap'));
  80043. this.renderBackground(thisGroup);
  80044. this.positionGroup(thisGroup);
  80045. };
  80046. PiecewiseVisualMapView.prototype._enableHoverLink = function (itemGroup, pieceIndex) {
  80047. var _this = this;
  80048. itemGroup.on('mouseover', function () {
  80049. return onHoverLink('highlight');
  80050. }).on('mouseout', function () {
  80051. return onHoverLink('downplay');
  80052. });
  80053. var onHoverLink = function (method) {
  80054. var visualMapModel = _this.visualMapModel; // TODO: TYPE More detailed action types
  80055. visualMapModel.option.hoverLink && _this.api.dispatchAction({
  80056. type: method,
  80057. batch: makeHighDownBatch(visualMapModel.findTargetDataIndices(pieceIndex), visualMapModel)
  80058. });
  80059. };
  80060. };
  80061. PiecewiseVisualMapView.prototype._getItemAlign = function () {
  80062. var visualMapModel = this.visualMapModel;
  80063. var modelOption = visualMapModel.option;
  80064. if (modelOption.orient === 'vertical') {
  80065. return getItemAlign(visualMapModel, this.api, visualMapModel.itemSize);
  80066. } else {
  80067. // horizontal, most case left unless specifying right.
  80068. var align = modelOption.align;
  80069. if (!align || align === 'auto') {
  80070. align = 'left';
  80071. }
  80072. return align;
  80073. }
  80074. };
  80075. PiecewiseVisualMapView.prototype._renderEndsText = function (group, text, itemSize, showLabel, itemAlign) {
  80076. if (!text) {
  80077. return;
  80078. }
  80079. var itemGroup = new Group();
  80080. var textStyleModel = this.visualMapModel.textStyleModel;
  80081. itemGroup.add(new ZRText({
  80082. style: createTextStyle(textStyleModel, {
  80083. x: showLabel ? itemAlign === 'right' ? itemSize[0] : 0 : itemSize[0] / 2,
  80084. y: itemSize[1] / 2,
  80085. verticalAlign: 'middle',
  80086. align: showLabel ? itemAlign : 'center',
  80087. text: text
  80088. })
  80089. }));
  80090. group.add(itemGroup);
  80091. };
  80092. /**
  80093. * @private
  80094. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  80095. */
  80096. PiecewiseVisualMapView.prototype._getViewData = function () {
  80097. var visualMapModel = this.visualMapModel;
  80098. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  80099. return {
  80100. piece: piece,
  80101. indexInModelPieceList: index
  80102. };
  80103. });
  80104. var endsText = visualMapModel.get('text'); // Consider orient and inverse.
  80105. var orient = visualMapModel.get('orient');
  80106. var inverse = visualMapModel.get('inverse'); // Order of model pieceList is always [low, ..., high]
  80107. if (orient === 'horizontal' ? inverse : !inverse) {
  80108. viewPieceList.reverse();
  80109. } // Origin order of endsText is [high, low]
  80110. else if (endsText) {
  80111. endsText = endsText.slice().reverse();
  80112. }
  80113. return {
  80114. viewPieceList: viewPieceList,
  80115. endsText: endsText
  80116. };
  80117. };
  80118. PiecewiseVisualMapView.prototype._createItemSymbol = function (group, representValue, shapeParam) {
  80119. group.add(createSymbol( // symbol will be string
  80120. this.getControllerVisual(representValue, 'symbol'), shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3], // color will be string
  80121. this.getControllerVisual(representValue, 'color')));
  80122. };
  80123. PiecewiseVisualMapView.prototype._onItemClick = function (piece) {
  80124. var visualMapModel = this.visualMapModel;
  80125. var option = visualMapModel.option;
  80126. var selectedMode = option.selectedMode;
  80127. if (!selectedMode) {
  80128. return;
  80129. }
  80130. var selected = clone(option.selected);
  80131. var newKey = visualMapModel.getSelectedMapKey(piece);
  80132. if (selectedMode === 'single' || selectedMode === true) {
  80133. selected[newKey] = true;
  80134. each(selected, function (o, key) {
  80135. selected[key] = key === newKey;
  80136. });
  80137. } else {
  80138. selected[newKey] = !selected[newKey];
  80139. }
  80140. this.api.dispatchAction({
  80141. type: 'selectDataRange',
  80142. from: this.uid,
  80143. visualMapId: this.visualMapModel.id,
  80144. selected: selected
  80145. });
  80146. };
  80147. PiecewiseVisualMapView.type = 'visualMap.piecewise';
  80148. return PiecewiseVisualMapView;
  80149. }(VisualMapView);
  80150. function install$O(registers) {
  80151. registers.registerComponentModel(PiecewiseModel);
  80152. registers.registerComponentView(PiecewiseVisualMapView);
  80153. installCommon$1(registers);
  80154. }
  80155. function install$P(registers) {
  80156. use(install$N);
  80157. use(install$O); // Do not install './dataZoomSelect',
  80158. // since it only work for toolbox dataZoom.
  80159. }
  80160. var DEFAULT_OPTION = {
  80161. label: {
  80162. enabled: true
  80163. },
  80164. decal: {
  80165. show: false
  80166. }
  80167. };
  80168. var inner$l = makeInner();
  80169. var decalPaletteScope = {};
  80170. function ariaVisual(ecModel, api) {
  80171. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  80172. if (!ariaModel.get('enabled')) {
  80173. return;
  80174. }
  80175. var defaultOption = clone(DEFAULT_OPTION);
  80176. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  80177. merge(ariaModel.option, defaultOption, false);
  80178. setDecal();
  80179. setLabel();
  80180. function setDecal() {
  80181. var decalModel = ariaModel.getModel('decal');
  80182. var useDecal = decalModel.get('show');
  80183. if (useDecal) {
  80184. // Each type of series use one scope.
  80185. // Pie and funnel are using different scopes.
  80186. var paletteScopeGroupByType_1 = createHashMap();
  80187. ecModel.eachSeries(function (seriesModel) {
  80188. if (seriesModel.isColorBySeries()) {
  80189. return;
  80190. }
  80191. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  80192. if (!decalScope) {
  80193. decalScope = {};
  80194. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  80195. }
  80196. inner$l(seriesModel).scope = decalScope;
  80197. });
  80198. ecModel.eachRawSeries(function (seriesModel) {
  80199. if (ecModel.isSeriesFiltered(seriesModel)) {
  80200. return;
  80201. }
  80202. if (isFunction(seriesModel.enableAriaDecal)) {
  80203. // Let series define how to use decal palette on data
  80204. seriesModel.enableAriaDecal();
  80205. return;
  80206. }
  80207. var data = seriesModel.getData();
  80208. if (!seriesModel.isColorBySeries()) {
  80209. var dataAll_1 = seriesModel.getRawData();
  80210. var idxMap_1 = {};
  80211. var decalScope_1 = inner$l(seriesModel).scope;
  80212. data.each(function (idx) {
  80213. var rawIdx = data.getRawIndex(idx);
  80214. idxMap_1[rawIdx] = idx;
  80215. });
  80216. var dataCount_1 = dataAll_1.count();
  80217. dataAll_1.each(function (rawIdx) {
  80218. var idx = idxMap_1[rawIdx];
  80219. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  80220. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  80221. var specifiedDecal = data.getItemVisual(idx, 'decal');
  80222. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  80223. });
  80224. } else {
  80225. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  80226. var specifiedDecal = data.getVisual('decal');
  80227. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  80228. }
  80229. function mergeDecal(specifiedDecal, paletteDecal) {
  80230. // Merge decal from palette to decal from itemStyle.
  80231. // User do not need to specify all of the decal props.
  80232. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  80233. resultDecal.dirty = true;
  80234. return resultDecal;
  80235. }
  80236. });
  80237. }
  80238. }
  80239. function setLabel() {
  80240. var labelLocale = ecModel.getLocaleModel().get('aria');
  80241. var labelModel = ariaModel.getModel('label');
  80242. labelModel.option = defaults(labelModel.option, labelLocale);
  80243. if (!labelModel.get('enabled')) {
  80244. return;
  80245. }
  80246. var dom = api.getZr().dom;
  80247. if (labelModel.get('description')) {
  80248. dom.setAttribute('aria-label', labelModel.get('description'));
  80249. return;
  80250. }
  80251. var seriesCnt = ecModel.getSeriesCount();
  80252. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  80253. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  80254. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  80255. var ariaLabel;
  80256. if (seriesCnt < 1) {
  80257. // No series, no aria label
  80258. return;
  80259. } else {
  80260. var title = getTitle();
  80261. if (title) {
  80262. var withTitle = labelModel.get(['general', 'withTitle']);
  80263. ariaLabel = replace(withTitle, {
  80264. title: title
  80265. });
  80266. } else {
  80267. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  80268. }
  80269. var seriesLabels_1 = [];
  80270. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  80271. ariaLabel += replace(prefix, {
  80272. seriesCount: seriesCnt
  80273. });
  80274. ecModel.eachSeries(function (seriesModel, idx) {
  80275. if (idx < displaySeriesCnt) {
  80276. var seriesLabel = void 0;
  80277. var seriesName = seriesModel.get('name');
  80278. var withName = seriesName ? 'withName' : 'withoutName';
  80279. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  80280. seriesLabel = replace(seriesLabel, {
  80281. seriesId: seriesModel.seriesIndex,
  80282. seriesName: seriesModel.get('name'),
  80283. seriesType: getSeriesTypeName(seriesModel.subType)
  80284. });
  80285. var data = seriesModel.getData();
  80286. if (data.count() > maxDataCnt) {
  80287. // Show part of data
  80288. var partialLabel = labelModel.get(['data', 'partialData']);
  80289. seriesLabel += replace(partialLabel, {
  80290. displayCnt: maxDataCnt
  80291. });
  80292. } else {
  80293. seriesLabel += labelModel.get(['data', 'allData']);
  80294. }
  80295. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  80296. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  80297. var dataLabels = [];
  80298. for (var i = 0; i < data.count(); i++) {
  80299. if (i < maxDataCnt) {
  80300. var name_1 = data.getName(i);
  80301. var value = data.getValues(i);
  80302. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  80303. dataLabels.push(replace(dataLabel, {
  80304. name: name_1,
  80305. value: value.join(middleSeparator_1)
  80306. }));
  80307. }
  80308. }
  80309. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  80310. seriesLabels_1.push(seriesLabel);
  80311. }
  80312. });
  80313. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  80314. var middleSeparator = separatorModel.get('middle');
  80315. var endSeparator = separatorModel.get('end');
  80316. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  80317. dom.setAttribute('aria-label', ariaLabel);
  80318. }
  80319. }
  80320. function replace(str, keyValues) {
  80321. if (!isString(str)) {
  80322. return str;
  80323. }
  80324. var result = str;
  80325. each(keyValues, function (value, key) {
  80326. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  80327. });
  80328. return result;
  80329. }
  80330. function getTitle() {
  80331. var title = ecModel.get('title');
  80332. if (title && title.length) {
  80333. title = title[0];
  80334. }
  80335. return title && title.text;
  80336. }
  80337. function getSeriesTypeName(type) {
  80338. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  80339. }
  80340. }
  80341. function ariaPreprocessor(option) {
  80342. if (!option || !option.aria) {
  80343. return;
  80344. }
  80345. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  80346. if (aria.show != null) {
  80347. aria.enabled = aria.show;
  80348. }
  80349. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  80350. each(['description', 'general', 'series', 'data'], function (name) {
  80351. if (aria[name] != null) {
  80352. aria.label[name] = aria[name];
  80353. }
  80354. });
  80355. }
  80356. function install$Q(registers) {
  80357. registers.registerPreprocessor(ariaPreprocessor);
  80358. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  80359. }
  80360. var RELATIONAL_EXPRESSION_OP_ALIAS_MAP = {
  80361. value: 'eq',
  80362. // PENDING: not good for literal semantic?
  80363. '<': 'lt',
  80364. '<=': 'lte',
  80365. '>': 'gt',
  80366. '>=': 'gte',
  80367. '=': 'eq',
  80368. '!=': 'ne',
  80369. '<>': 'ne' // Might be misleading for sake of the difference between '==' and '===',
  80370. // so don't support them.
  80371. // '==': 'eq',
  80372. // '===': 'seq',
  80373. // '!==': 'sne'
  80374. // PENDING: Whether support some common alias "ge", "le", "neq"?
  80375. // ge: 'gte',
  80376. // le: 'lte',
  80377. // neq: 'ne',
  80378. }; // type RelationalExpressionOpEvaluate = (tarVal: unknown, condVal: unknown) => boolean;
  80379. var RegExpEvaluator =
  80380. /** @class */
  80381. function () {
  80382. function RegExpEvaluator(rVal) {
  80383. // Support condVal: RegExp | string
  80384. var condValue = this._condVal = isString(rVal) ? new RegExp(rVal) : isRegExp(rVal) ? rVal : null;
  80385. if (condValue == null) {
  80386. var errMsg = '';
  80387. if ("development" !== 'production') {
  80388. errMsg = makePrintable('Illegal regexp', rVal, 'in');
  80389. }
  80390. throwError(errMsg);
  80391. }
  80392. }
  80393. RegExpEvaluator.prototype.evaluate = function (lVal) {
  80394. var type = typeof lVal;
  80395. return isString(type) ? this._condVal.test(lVal) : isNumber(type) ? this._condVal.test(lVal + '') : false;
  80396. };
  80397. return RegExpEvaluator;
  80398. }();
  80399. var ConstConditionInternal =
  80400. /** @class */
  80401. function () {
  80402. function ConstConditionInternal() {}
  80403. ConstConditionInternal.prototype.evaluate = function () {
  80404. return this.value;
  80405. };
  80406. return ConstConditionInternal;
  80407. }();
  80408. var AndConditionInternal =
  80409. /** @class */
  80410. function () {
  80411. function AndConditionInternal() {}
  80412. AndConditionInternal.prototype.evaluate = function () {
  80413. var children = this.children;
  80414. for (var i = 0; i < children.length; i++) {
  80415. if (!children[i].evaluate()) {
  80416. return false;
  80417. }
  80418. }
  80419. return true;
  80420. };
  80421. return AndConditionInternal;
  80422. }();
  80423. var OrConditionInternal =
  80424. /** @class */
  80425. function () {
  80426. function OrConditionInternal() {}
  80427. OrConditionInternal.prototype.evaluate = function () {
  80428. var children = this.children;
  80429. for (var i = 0; i < children.length; i++) {
  80430. if (children[i].evaluate()) {
  80431. return true;
  80432. }
  80433. }
  80434. return false;
  80435. };
  80436. return OrConditionInternal;
  80437. }();
  80438. var NotConditionInternal =
  80439. /** @class */
  80440. function () {
  80441. function NotConditionInternal() {}
  80442. NotConditionInternal.prototype.evaluate = function () {
  80443. return !this.child.evaluate();
  80444. };
  80445. return NotConditionInternal;
  80446. }();
  80447. var RelationalConditionInternal =
  80448. /** @class */
  80449. function () {
  80450. function RelationalConditionInternal() {}
  80451. RelationalConditionInternal.prototype.evaluate = function () {
  80452. var needParse = !!this.valueParser; // Call getValue with no `this`.
  80453. var getValue = this.getValue;
  80454. var tarValRaw = getValue(this.valueGetterParam);
  80455. var tarValParsed = needParse ? this.valueParser(tarValRaw) : null; // Relational cond follow "and" logic internally.
  80456. for (var i = 0; i < this.subCondList.length; i++) {
  80457. if (!this.subCondList[i].evaluate(needParse ? tarValParsed : tarValRaw)) {
  80458. return false;
  80459. }
  80460. }
  80461. return true;
  80462. };
  80463. return RelationalConditionInternal;
  80464. }();
  80465. function parseOption(exprOption, getters) {
  80466. if (exprOption === true || exprOption === false) {
  80467. var cond = new ConstConditionInternal();
  80468. cond.value = exprOption;
  80469. return cond;
  80470. }
  80471. var errMsg = '';
  80472. if (!isObjectNotArray(exprOption)) {
  80473. if ("development" !== 'production') {
  80474. errMsg = makePrintable('Illegal config. Expect a plain object but actually', exprOption);
  80475. }
  80476. throwError(errMsg);
  80477. }
  80478. if (exprOption.and) {
  80479. return parseAndOrOption('and', exprOption, getters);
  80480. } else if (exprOption.or) {
  80481. return parseAndOrOption('or', exprOption, getters);
  80482. } else if (exprOption.not) {
  80483. return parseNotOption(exprOption, getters);
  80484. }
  80485. return parseRelationalOption(exprOption, getters);
  80486. }
  80487. function parseAndOrOption(op, exprOption, getters) {
  80488. var subOptionArr = exprOption[op];
  80489. var errMsg = '';
  80490. if ("development" !== 'production') {
  80491. errMsg = makePrintable('"and"/"or" condition should only be `' + op + ': [...]` and must not be empty array.', 'Illegal condition:', exprOption);
  80492. }
  80493. if (!isArray(subOptionArr)) {
  80494. throwError(errMsg);
  80495. }
  80496. if (!subOptionArr.length) {
  80497. throwError(errMsg);
  80498. }
  80499. var cond = op === 'and' ? new AndConditionInternal() : new OrConditionInternal();
  80500. cond.children = map(subOptionArr, function (subOption) {
  80501. return parseOption(subOption, getters);
  80502. });
  80503. if (!cond.children.length) {
  80504. throwError(errMsg);
  80505. }
  80506. return cond;
  80507. }
  80508. function parseNotOption(exprOption, getters) {
  80509. var subOption = exprOption.not;
  80510. var errMsg = '';
  80511. if ("development" !== 'production') {
  80512. errMsg = makePrintable('"not" condition should only be `not: {}`.', 'Illegal condition:', exprOption);
  80513. }
  80514. if (!isObjectNotArray(subOption)) {
  80515. throwError(errMsg);
  80516. }
  80517. var cond = new NotConditionInternal();
  80518. cond.child = parseOption(subOption, getters);
  80519. if (!cond.child) {
  80520. throwError(errMsg);
  80521. }
  80522. return cond;
  80523. }
  80524. function parseRelationalOption(exprOption, getters) {
  80525. var errMsg = '';
  80526. var valueGetterParam = getters.prepareGetValue(exprOption);
  80527. var subCondList = [];
  80528. var exprKeys = keys(exprOption);
  80529. var parserName = exprOption.parser;
  80530. var valueParser = parserName ? getRawValueParser(parserName) : null;
  80531. for (var i = 0; i < exprKeys.length; i++) {
  80532. var keyRaw = exprKeys[i];
  80533. if (keyRaw === 'parser' || getters.valueGetterAttrMap.get(keyRaw)) {
  80534. continue;
  80535. }
  80536. var op = hasOwn(RELATIONAL_EXPRESSION_OP_ALIAS_MAP, keyRaw) ? RELATIONAL_EXPRESSION_OP_ALIAS_MAP[keyRaw] : keyRaw;
  80537. var condValueRaw = exprOption[keyRaw];
  80538. var condValueParsed = valueParser ? valueParser(condValueRaw) : condValueRaw;
  80539. var evaluator = createFilterComparator(op, condValueParsed) || op === 'reg' && new RegExpEvaluator(condValueParsed);
  80540. if (!evaluator) {
  80541. if ("development" !== 'production') {
  80542. errMsg = makePrintable('Illegal relational operation: "' + keyRaw + '" in condition:', exprOption);
  80543. }
  80544. throwError(errMsg);
  80545. }
  80546. subCondList.push(evaluator);
  80547. }
  80548. if (!subCondList.length) {
  80549. if ("development" !== 'production') {
  80550. errMsg = makePrintable('Relational condition must have at least one operator.', 'Illegal condition:', exprOption);
  80551. } // No relational operator always disabled in case of dangers result.
  80552. throwError(errMsg);
  80553. }
  80554. var cond = new RelationalConditionInternal();
  80555. cond.valueGetterParam = valueGetterParam;
  80556. cond.valueParser = valueParser;
  80557. cond.getValue = getters.getValue;
  80558. cond.subCondList = subCondList;
  80559. return cond;
  80560. }
  80561. function isObjectNotArray(val) {
  80562. return isObject(val) && !isArrayLike(val);
  80563. }
  80564. var ConditionalExpressionParsed =
  80565. /** @class */
  80566. function () {
  80567. function ConditionalExpressionParsed(exprOption, getters) {
  80568. this._cond = parseOption(exprOption, getters);
  80569. }
  80570. ConditionalExpressionParsed.prototype.evaluate = function () {
  80571. return this._cond.evaluate();
  80572. };
  80573. return ConditionalExpressionParsed;
  80574. }();
  80575. function parseConditionalExpression(exprOption, getters) {
  80576. return new ConditionalExpressionParsed(exprOption, getters);
  80577. }
  80578. var filterTransform = {
  80579. type: 'echarts:filter',
  80580. // PENDING: enhance to filter by index rather than create new data
  80581. transform: function (params) {
  80582. // [Caveat] Fail-Fast:
  80583. // Do not return the whole dataset unless user config indicates it explicitly.
  80584. // For example, if no condition is specified by mistake, returning an empty result
  80585. // is better than returning the entire raw source for the user to find the mistake.
  80586. var upstream = params.upstream;
  80587. var rawItem;
  80588. var condition = parseConditionalExpression(params.config, {
  80589. valueGetterAttrMap: createHashMap({
  80590. dimension: true
  80591. }),
  80592. prepareGetValue: function (exprOption) {
  80593. var errMsg = '';
  80594. var dimLoose = exprOption.dimension;
  80595. if (!hasOwn(exprOption, 'dimension')) {
  80596. if ("development" !== 'production') {
  80597. errMsg = makePrintable('Relation condition must has prop "dimension" specified.', 'Illegal condition:', exprOption);
  80598. }
  80599. throwError(errMsg);
  80600. }
  80601. var dimInfo = upstream.getDimensionInfo(dimLoose);
  80602. if (!dimInfo) {
  80603. if ("development" !== 'production') {
  80604. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal condition:', exprOption, '.\n');
  80605. }
  80606. throwError(errMsg);
  80607. }
  80608. return {
  80609. dimIdx: dimInfo.index
  80610. };
  80611. },
  80612. getValue: function (param) {
  80613. return upstream.retrieveValueFromItem(rawItem, param.dimIdx);
  80614. }
  80615. });
  80616. var resultData = [];
  80617. for (var i = 0, len = upstream.count(); i < len; i++) {
  80618. rawItem = upstream.getRawDataItem(i);
  80619. if (condition.evaluate()) {
  80620. resultData.push(rawItem);
  80621. }
  80622. }
  80623. return {
  80624. data: resultData
  80625. };
  80626. }
  80627. };
  80628. var sampleLog = '';
  80629. if ("development" !== 'production') {
  80630. sampleLog = ['Valid config is like:', '{ dimension: "age", order: "asc" }', 'or [{ dimension: "age", order: "asc"], { dimension: "date", order: "desc" }]'].join(' ');
  80631. }
  80632. var sortTransform = {
  80633. type: 'echarts:sort',
  80634. transform: function (params) {
  80635. var upstream = params.upstream;
  80636. var config = params.config;
  80637. var errMsg = ''; // Normalize
  80638. // const orderExprList: OrderExpression[] = isArray(config[0])
  80639. // ? config as OrderExpression[]
  80640. // : [config as OrderExpression];
  80641. var orderExprList = normalizeToArray(config);
  80642. if (!orderExprList.length) {
  80643. if ("development" !== 'production') {
  80644. errMsg = 'Empty `config` in sort transform.';
  80645. }
  80646. throwError(errMsg);
  80647. }
  80648. var orderDefList = [];
  80649. each(orderExprList, function (orderExpr) {
  80650. var dimLoose = orderExpr.dimension;
  80651. var order = orderExpr.order;
  80652. var parserName = orderExpr.parser;
  80653. var incomparable = orderExpr.incomparable;
  80654. if (dimLoose == null) {
  80655. if ("development" !== 'production') {
  80656. errMsg = 'Sort transform config must has "dimension" specified.' + sampleLog;
  80657. }
  80658. throwError(errMsg);
  80659. }
  80660. if (order !== 'asc' && order !== 'desc') {
  80661. if ("development" !== 'production') {
  80662. errMsg = 'Sort transform config must has "order" specified.' + sampleLog;
  80663. }
  80664. throwError(errMsg);
  80665. }
  80666. if (incomparable && incomparable !== 'min' && incomparable !== 'max') {
  80667. var errMsg_1 = '';
  80668. if ("development" !== 'production') {
  80669. errMsg_1 = 'incomparable must be "min" or "max" rather than "' + incomparable + '".';
  80670. }
  80671. throwError(errMsg_1);
  80672. }
  80673. if (order !== 'asc' && order !== 'desc') {
  80674. var errMsg_2 = '';
  80675. if ("development" !== 'production') {
  80676. errMsg_2 = 'order must be "asc" or "desc" rather than "' + order + '".';
  80677. }
  80678. throwError(errMsg_2);
  80679. }
  80680. var dimInfo = upstream.getDimensionInfo(dimLoose);
  80681. if (!dimInfo) {
  80682. if ("development" !== 'production') {
  80683. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal config:', orderExpr, '.\n');
  80684. }
  80685. throwError(errMsg);
  80686. }
  80687. var parser = parserName ? getRawValueParser(parserName) : null;
  80688. if (parserName && !parser) {
  80689. if ("development" !== 'production') {
  80690. errMsg = makePrintable('Invalid parser name ' + parserName + '.\n', 'Illegal config:', orderExpr, '.\n');
  80691. }
  80692. throwError(errMsg);
  80693. }
  80694. orderDefList.push({
  80695. dimIdx: dimInfo.index,
  80696. parser: parser,
  80697. comparator: new SortOrderComparator(order, incomparable)
  80698. });
  80699. }); // TODO: support it?
  80700. var sourceFormat = upstream.sourceFormat;
  80701. if (sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS) {
  80702. if ("development" !== 'production') {
  80703. errMsg = 'sourceFormat "' + sourceFormat + '" is not supported yet';
  80704. }
  80705. throwError(errMsg);
  80706. } // Other upstream format are all array.
  80707. var resultData = [];
  80708. for (var i = 0, len = upstream.count(); i < len; i++) {
  80709. resultData.push(upstream.getRawDataItem(i));
  80710. }
  80711. resultData.sort(function (item0, item1) {
  80712. for (var i = 0; i < orderDefList.length; i++) {
  80713. var orderDef = orderDefList[i];
  80714. var val0 = upstream.retrieveValueFromItem(item0, orderDef.dimIdx);
  80715. var val1 = upstream.retrieveValueFromItem(item1, orderDef.dimIdx);
  80716. if (orderDef.parser) {
  80717. val0 = orderDef.parser(val0);
  80718. val1 = orderDef.parser(val1);
  80719. }
  80720. var result = orderDef.comparator.evaluate(val0, val1);
  80721. if (result !== 0) {
  80722. return result;
  80723. }
  80724. }
  80725. return 0;
  80726. });
  80727. return {
  80728. data: resultData
  80729. };
  80730. }
  80731. };
  80732. function install$R(registers) {
  80733. registers.registerTransform(filterTransform);
  80734. registers.registerTransform(sortTransform);
  80735. }
  80736. var DatasetModel =
  80737. /** @class */
  80738. function (_super) {
  80739. __extends(DatasetModel, _super);
  80740. function DatasetModel() {
  80741. var _this = _super !== null && _super.apply(this, arguments) || this;
  80742. _this.type = 'dataset';
  80743. return _this;
  80744. }
  80745. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  80746. _super.prototype.init.call(this, option, parentModel, ecModel);
  80747. this._sourceManager = new SourceManager(this);
  80748. disableTransformOptionMerge(this);
  80749. };
  80750. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  80751. _super.prototype.mergeOption.call(this, newOption, ecModel);
  80752. disableTransformOptionMerge(this);
  80753. };
  80754. DatasetModel.prototype.optionUpdated = function () {
  80755. this._sourceManager.dirty();
  80756. };
  80757. DatasetModel.prototype.getSourceManager = function () {
  80758. return this._sourceManager;
  80759. };
  80760. DatasetModel.type = 'dataset';
  80761. DatasetModel.defaultOption = {
  80762. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  80763. };
  80764. return DatasetModel;
  80765. }(ComponentModel);
  80766. var DatasetView =
  80767. /** @class */
  80768. function (_super) {
  80769. __extends(DatasetView, _super);
  80770. function DatasetView() {
  80771. var _this = _super !== null && _super.apply(this, arguments) || this;
  80772. _this.type = 'dataset';
  80773. return _this;
  80774. }
  80775. DatasetView.type = 'dataset';
  80776. return DatasetView;
  80777. }(ComponentView);
  80778. function install$S(registers) {
  80779. registers.registerComponentModel(DatasetModel);
  80780. registers.registerComponentView(DatasetView);
  80781. }
  80782. var CMD$4 = PathProxy.CMD;
  80783. function aroundEqual(a, b) {
  80784. return Math.abs(a - b) < 1e-5;
  80785. }
  80786. function pathToBezierCurves(path) {
  80787. var data = path.data;
  80788. var len = path.len();
  80789. var bezierArrayGroups = [];
  80790. var currentSubpath;
  80791. var xi = 0;
  80792. var yi = 0;
  80793. var x0 = 0;
  80794. var y0 = 0;
  80795. function createNewSubpath(x, y) {
  80796. if (currentSubpath && currentSubpath.length > 2) {
  80797. bezierArrayGroups.push(currentSubpath);
  80798. }
  80799. currentSubpath = [x, y];
  80800. }
  80801. function addLine(x0, y0, x1, y1) {
  80802. if (!(aroundEqual(x0, x1) && aroundEqual(y0, y1))) {
  80803. currentSubpath.push(x0, y0, x1, y1, x1, y1);
  80804. }
  80805. }
  80806. function addArc(startAngle, endAngle, cx, cy, rx, ry) {
  80807. var delta = Math.abs(endAngle - startAngle);
  80808. var len = Math.tan(delta / 4) * 4 / 3;
  80809. var dir = endAngle < startAngle ? -1 : 1;
  80810. var c1 = Math.cos(startAngle);
  80811. var s1 = Math.sin(startAngle);
  80812. var c2 = Math.cos(endAngle);
  80813. var s2 = Math.sin(endAngle);
  80814. var x1 = c1 * rx + cx;
  80815. var y1 = s1 * ry + cy;
  80816. var x4 = c2 * rx + cx;
  80817. var y4 = s2 * ry + cy;
  80818. var hx = rx * len * dir;
  80819. var hy = ry * len * dir;
  80820. currentSubpath.push(x1 - hx * s1, y1 + hy * c1, x4 + hx * s2, y4 - hy * c2, x4, y4);
  80821. }
  80822. var x1;
  80823. var y1;
  80824. var x2;
  80825. var y2;
  80826. for (var i = 0; i < len;) {
  80827. var cmd = data[i++];
  80828. var isFirst = i === 1;
  80829. if (isFirst) {
  80830. xi = data[i];
  80831. yi = data[i + 1];
  80832. x0 = xi;
  80833. y0 = yi;
  80834. if (cmd === CMD$4.L || cmd === CMD$4.C || cmd === CMD$4.Q) {
  80835. currentSubpath = [x0, y0];
  80836. }
  80837. }
  80838. switch (cmd) {
  80839. case CMD$4.M:
  80840. xi = x0 = data[i++];
  80841. yi = y0 = data[i++];
  80842. createNewSubpath(x0, y0);
  80843. break;
  80844. case CMD$4.L:
  80845. x1 = data[i++];
  80846. y1 = data[i++];
  80847. addLine(xi, yi, x1, y1);
  80848. xi = x1;
  80849. yi = y1;
  80850. break;
  80851. case CMD$4.C:
  80852. currentSubpath.push(data[i++], data[i++], data[i++], data[i++], xi = data[i++], yi = data[i++]);
  80853. break;
  80854. case CMD$4.Q:
  80855. x1 = data[i++];
  80856. y1 = data[i++];
  80857. x2 = data[i++];
  80858. y2 = data[i++];
  80859. currentSubpath.push(xi + 2 / 3 * (x1 - xi), yi + 2 / 3 * (y1 - yi), x2 + 2 / 3 * (x1 - x2), y2 + 2 / 3 * (y1 - y2), x2, y2);
  80860. xi = x2;
  80861. yi = y2;
  80862. break;
  80863. case CMD$4.A:
  80864. var cx = data[i++];
  80865. var cy = data[i++];
  80866. var rx = data[i++];
  80867. var ry = data[i++];
  80868. var startAngle = data[i++];
  80869. var endAngle = data[i++] + startAngle;
  80870. i += 1;
  80871. var anticlockwise = !data[i++];
  80872. x1 = Math.cos(startAngle) * rx + cx;
  80873. y1 = Math.sin(startAngle) * ry + cy;
  80874. if (isFirst) {
  80875. x0 = x1;
  80876. y0 = y1;
  80877. createNewSubpath(x0, y0);
  80878. }
  80879. else {
  80880. addLine(xi, yi, x1, y1);
  80881. }
  80882. xi = Math.cos(endAngle) * rx + cx;
  80883. yi = Math.sin(endAngle) * ry + cy;
  80884. var step = (anticlockwise ? -1 : 1) * Math.PI / 2;
  80885. for (var angle = startAngle; anticlockwise ? angle > endAngle : angle < endAngle; angle += step) {
  80886. var nextAngle = anticlockwise ? Math.max(angle + step, endAngle)
  80887. : Math.min(angle + step, endAngle);
  80888. addArc(angle, nextAngle, cx, cy, rx, ry);
  80889. }
  80890. break;
  80891. case CMD$4.R:
  80892. x0 = xi = data[i++];
  80893. y0 = yi = data[i++];
  80894. x1 = x0 + data[i++];
  80895. y1 = y0 + data[i++];
  80896. createNewSubpath(x1, y0);
  80897. addLine(x1, y0, x1, y1);
  80898. addLine(x1, y1, x0, y1);
  80899. addLine(x0, y1, x0, y0);
  80900. addLine(x0, y0, x1, y0);
  80901. break;
  80902. case CMD$4.Z:
  80903. currentSubpath && addLine(xi, yi, x0, y0);
  80904. xi = x0;
  80905. yi = y0;
  80906. break;
  80907. }
  80908. }
  80909. if (currentSubpath && currentSubpath.length > 2) {
  80910. bezierArrayGroups.push(currentSubpath);
  80911. }
  80912. return bezierArrayGroups;
  80913. }
  80914. function adpativeBezier(x0, y0, x1, y1, x2, y2, x3, y3, out, scale) {
  80915. if (aroundEqual(x0, x1) && aroundEqual(y0, y1) && aroundEqual(x2, x3) && aroundEqual(y2, y3)) {
  80916. out.push(x3, y3);
  80917. return;
  80918. }
  80919. var PIXEL_DISTANCE = 2 / scale;
  80920. var PIXEL_DISTANCE_SQR = PIXEL_DISTANCE * PIXEL_DISTANCE;
  80921. var dx = x3 - x0;
  80922. var dy = y3 - y0;
  80923. var d = Math.sqrt(dx * dx + dy * dy);
  80924. dx /= d;
  80925. dy /= d;
  80926. var dx1 = x1 - x0;
  80927. var dy1 = y1 - y0;
  80928. var dx2 = x2 - x3;
  80929. var dy2 = y2 - y3;
  80930. var cp1LenSqr = dx1 * dx1 + dy1 * dy1;
  80931. var cp2LenSqr = dx2 * dx2 + dy2 * dy2;
  80932. if (cp1LenSqr < PIXEL_DISTANCE_SQR && cp2LenSqr < PIXEL_DISTANCE_SQR) {
  80933. out.push(x3, y3);
  80934. return;
  80935. }
  80936. var projLen1 = dx * dx1 + dy * dy1;
  80937. var projLen2 = -dx * dx2 - dy * dy2;
  80938. var d1Sqr = cp1LenSqr - projLen1 * projLen1;
  80939. var d2Sqr = cp2LenSqr - projLen2 * projLen2;
  80940. if (d1Sqr < PIXEL_DISTANCE_SQR && projLen1 >= 0
  80941. && d2Sqr < PIXEL_DISTANCE_SQR && projLen2 >= 0) {
  80942. out.push(x3, y3);
  80943. return;
  80944. }
  80945. var tmpSegX = [];
  80946. var tmpSegY = [];
  80947. cubicSubdivide(x0, x1, x2, x3, 0.5, tmpSegX);
  80948. cubicSubdivide(y0, y1, y2, y3, 0.5, tmpSegY);
  80949. adpativeBezier(tmpSegX[0], tmpSegY[0], tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], tmpSegX[3], tmpSegY[3], out, scale);
  80950. adpativeBezier(tmpSegX[4], tmpSegY[4], tmpSegX[5], tmpSegY[5], tmpSegX[6], tmpSegY[6], tmpSegX[7], tmpSegY[7], out, scale);
  80951. }
  80952. function pathToPolygons(path, scale) {
  80953. var bezierArrayGroups = pathToBezierCurves(path);
  80954. var polygons = [];
  80955. scale = scale || 1;
  80956. for (var i = 0; i < bezierArrayGroups.length; i++) {
  80957. var beziers = bezierArrayGroups[i];
  80958. var polygon = [];
  80959. var x0 = beziers[0];
  80960. var y0 = beziers[1];
  80961. polygon.push(x0, y0);
  80962. for (var k = 2; k < beziers.length;) {
  80963. var x1 = beziers[k++];
  80964. var y1 = beziers[k++];
  80965. var x2 = beziers[k++];
  80966. var y2 = beziers[k++];
  80967. var x3 = beziers[k++];
  80968. var y3 = beziers[k++];
  80969. adpativeBezier(x0, y0, x1, y1, x2, y2, x3, y3, polygon, scale);
  80970. x0 = x3;
  80971. y0 = y3;
  80972. }
  80973. polygons.push(polygon);
  80974. }
  80975. return polygons;
  80976. }
  80977. function getDividingGrids(dimSize, rowDim, count) {
  80978. var rowSize = dimSize[rowDim];
  80979. var columnSize = dimSize[1 - rowDim];
  80980. var ratio = Math.abs(rowSize / columnSize);
  80981. var rowCount = Math.ceil(Math.sqrt(ratio * count));
  80982. var columnCount = Math.floor(count / rowCount);
  80983. if (columnCount === 0) {
  80984. columnCount = 1;
  80985. rowCount = count;
  80986. }
  80987. var grids = [];
  80988. for (var i = 0; i < rowCount; i++) {
  80989. grids.push(columnCount);
  80990. }
  80991. var currentCount = rowCount * columnCount;
  80992. var remained = count - currentCount;
  80993. if (remained > 0) {
  80994. for (var i = 0; i < remained; i++) {
  80995. grids[i % rowCount] += 1;
  80996. }
  80997. }
  80998. return grids;
  80999. }
  81000. function divideSector(sectorShape, count, outShapes) {
  81001. var r0 = sectorShape.r0;
  81002. var r = sectorShape.r;
  81003. var startAngle = sectorShape.startAngle;
  81004. var endAngle = sectorShape.endAngle;
  81005. var angle = Math.abs(endAngle - startAngle);
  81006. var arcLen = angle * r;
  81007. var deltaR = r - r0;
  81008. var isAngleRow = arcLen > Math.abs(deltaR);
  81009. var grids = getDividingGrids([arcLen, deltaR], isAngleRow ? 0 : 1, count);
  81010. var rowSize = (isAngleRow ? angle : deltaR) / grids.length;
  81011. for (var row = 0; row < grids.length; row++) {
  81012. var columnSize = (isAngleRow ? deltaR : angle) / grids[row];
  81013. for (var column = 0; column < grids[row]; column++) {
  81014. var newShape = {};
  81015. if (isAngleRow) {
  81016. newShape.startAngle = startAngle + rowSize * row;
  81017. newShape.endAngle = startAngle + rowSize * (row + 1);
  81018. newShape.r0 = r0 + columnSize * column;
  81019. newShape.r = r0 + columnSize * (column + 1);
  81020. }
  81021. else {
  81022. newShape.startAngle = startAngle + columnSize * column;
  81023. newShape.endAngle = startAngle + columnSize * (column + 1);
  81024. newShape.r0 = r0 + rowSize * row;
  81025. newShape.r = r0 + rowSize * (row + 1);
  81026. }
  81027. newShape.clockwise = sectorShape.clockwise;
  81028. newShape.cx = sectorShape.cx;
  81029. newShape.cy = sectorShape.cy;
  81030. outShapes.push(newShape);
  81031. }
  81032. }
  81033. }
  81034. function divideRect(rectShape, count, outShapes) {
  81035. var width = rectShape.width;
  81036. var height = rectShape.height;
  81037. var isHorizontalRow = width > height;
  81038. var grids = getDividingGrids([width, height], isHorizontalRow ? 0 : 1, count);
  81039. var rowSizeDim = isHorizontalRow ? 'width' : 'height';
  81040. var columnSizeDim = isHorizontalRow ? 'height' : 'width';
  81041. var rowDim = isHorizontalRow ? 'x' : 'y';
  81042. var columnDim = isHorizontalRow ? 'y' : 'x';
  81043. var rowSize = rectShape[rowSizeDim] / grids.length;
  81044. for (var row = 0; row < grids.length; row++) {
  81045. var columnSize = rectShape[columnSizeDim] / grids[row];
  81046. for (var column = 0; column < grids[row]; column++) {
  81047. var newShape = {};
  81048. newShape[rowDim] = row * rowSize;
  81049. newShape[columnDim] = column * columnSize;
  81050. newShape[rowSizeDim] = rowSize;
  81051. newShape[columnSizeDim] = columnSize;
  81052. newShape.x += rectShape.x;
  81053. newShape.y += rectShape.y;
  81054. outShapes.push(newShape);
  81055. }
  81056. }
  81057. }
  81058. function crossProduct2d$1(x1, y1, x2, y2) {
  81059. return x1 * y2 - x2 * y1;
  81060. }
  81061. function lineLineIntersect$1(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  81062. var mx = a2x - a1x;
  81063. var my = a2y - a1y;
  81064. var nx = b2x - b1x;
  81065. var ny = b2y - b1y;
  81066. var nmCrossProduct = crossProduct2d$1(nx, ny, mx, my);
  81067. if (Math.abs(nmCrossProduct) < 1e-6) {
  81068. return null;
  81069. }
  81070. var b1a1x = a1x - b1x;
  81071. var b1a1y = a1y - b1y;
  81072. var p = crossProduct2d$1(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  81073. if (p < 0 || p > 1) {
  81074. return null;
  81075. }
  81076. return new Point(p * mx + a1x, p * my + a1y);
  81077. }
  81078. function projPtOnLine(pt, lineA, lineB) {
  81079. var dir = new Point();
  81080. Point.sub(dir, lineB, lineA);
  81081. dir.normalize();
  81082. var dir2 = new Point();
  81083. Point.sub(dir2, pt, lineA);
  81084. var len = dir2.dot(dir);
  81085. return len;
  81086. }
  81087. function addToPoly(poly, pt) {
  81088. var last = poly[poly.length - 1];
  81089. if (last && last[0] === pt[0] && last[1] === pt[1]) {
  81090. return;
  81091. }
  81092. poly.push(pt);
  81093. }
  81094. function splitPolygonByLine(points, lineA, lineB) {
  81095. var len = points.length;
  81096. var intersections = [];
  81097. for (var i = 0; i < len; i++) {
  81098. var p0 = points[i];
  81099. var p1 = points[(i + 1) % len];
  81100. var intersectionPt = lineLineIntersect$1(p0[0], p0[1], p1[0], p1[1], lineA.x, lineA.y, lineB.x, lineB.y);
  81101. if (intersectionPt) {
  81102. intersections.push({
  81103. projPt: projPtOnLine(intersectionPt, lineA, lineB),
  81104. pt: intersectionPt,
  81105. idx: i
  81106. });
  81107. }
  81108. }
  81109. if (intersections.length < 2) {
  81110. return [{ points: points }, { points: points }];
  81111. }
  81112. intersections.sort(function (a, b) {
  81113. return a.projPt - b.projPt;
  81114. });
  81115. var splitPt0 = intersections[0];
  81116. var splitPt1 = intersections[intersections.length - 1];
  81117. if (splitPt1.idx < splitPt0.idx) {
  81118. var tmp = splitPt0;
  81119. splitPt0 = splitPt1;
  81120. splitPt1 = tmp;
  81121. }
  81122. var splitPt0Arr = [splitPt0.pt.x, splitPt0.pt.y];
  81123. var splitPt1Arr = [splitPt1.pt.x, splitPt1.pt.y];
  81124. var newPolyA = [splitPt0Arr];
  81125. var newPolyB = [splitPt1Arr];
  81126. for (var i = splitPt0.idx + 1; i <= splitPt1.idx; i++) {
  81127. addToPoly(newPolyA, points[i].slice());
  81128. }
  81129. addToPoly(newPolyA, splitPt1Arr);
  81130. addToPoly(newPolyA, splitPt0Arr);
  81131. for (var i = splitPt1.idx + 1; i <= splitPt0.idx + len; i++) {
  81132. addToPoly(newPolyB, points[i % len].slice());
  81133. }
  81134. addToPoly(newPolyB, splitPt0Arr);
  81135. addToPoly(newPolyB, splitPt1Arr);
  81136. return [{
  81137. points: newPolyA
  81138. }, {
  81139. points: newPolyB
  81140. }];
  81141. }
  81142. function binaryDividePolygon(polygonShape) {
  81143. var points = polygonShape.points;
  81144. var min = [];
  81145. var max = [];
  81146. fromPoints(points, min, max);
  81147. var boundingRect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  81148. var width = boundingRect.width;
  81149. var height = boundingRect.height;
  81150. var x = boundingRect.x;
  81151. var y = boundingRect.y;
  81152. var pt0 = new Point();
  81153. var pt1 = new Point();
  81154. if (width > height) {
  81155. pt0.x = pt1.x = x + width / 2;
  81156. pt0.y = y;
  81157. pt1.y = y + height;
  81158. }
  81159. else {
  81160. pt0.y = pt1.y = y + height / 2;
  81161. pt0.x = x;
  81162. pt1.x = x + width;
  81163. }
  81164. return splitPolygonByLine(points, pt0, pt1);
  81165. }
  81166. function binaryDivideRecursive(divider, shape, count, out) {
  81167. if (count === 1) {
  81168. out.push(shape);
  81169. }
  81170. else {
  81171. var mid = Math.floor(count / 2);
  81172. var sub = divider(shape);
  81173. binaryDivideRecursive(divider, sub[0], mid, out);
  81174. binaryDivideRecursive(divider, sub[1], count - mid, out);
  81175. }
  81176. return out;
  81177. }
  81178. function clone$4(path, count) {
  81179. var paths = [];
  81180. for (var i = 0; i < count; i++) {
  81181. paths.push(clonePath(path));
  81182. }
  81183. return paths;
  81184. }
  81185. function copyPathProps(source, target) {
  81186. target.setStyle(source.style);
  81187. target.z = source.z;
  81188. target.z2 = source.z2;
  81189. target.zlevel = source.zlevel;
  81190. }
  81191. function polygonConvert(points) {
  81192. var out = [];
  81193. for (var i = 0; i < points.length;) {
  81194. out.push([points[i++], points[i++]]);
  81195. }
  81196. return out;
  81197. }
  81198. function split(path, count) {
  81199. var outShapes = [];
  81200. var shape = path.shape;
  81201. var OutShapeCtor;
  81202. switch (path.type) {
  81203. case 'rect':
  81204. divideRect(shape, count, outShapes);
  81205. OutShapeCtor = Rect;
  81206. break;
  81207. case 'sector':
  81208. divideSector(shape, count, outShapes);
  81209. OutShapeCtor = Sector;
  81210. break;
  81211. case 'circle':
  81212. divideSector({
  81213. r0: 0, r: shape.r, startAngle: 0, endAngle: Math.PI * 2,
  81214. cx: shape.cx, cy: shape.cy
  81215. }, count, outShapes);
  81216. OutShapeCtor = Sector;
  81217. break;
  81218. default:
  81219. var m = path.getComputedTransform();
  81220. var scale = m ? Math.sqrt(Math.max(m[0] * m[0] + m[1] * m[1], m[2] * m[2] + m[3] * m[3])) : 1;
  81221. var polygons = map(pathToPolygons(path.getUpdatedPathProxy(), scale), function (poly) { return polygonConvert(poly); });
  81222. var polygonCount = polygons.length;
  81223. if (polygonCount === 0) {
  81224. binaryDivideRecursive(binaryDividePolygon, {
  81225. points: polygons[0]
  81226. }, count, outShapes);
  81227. }
  81228. else if (polygonCount === count) {
  81229. for (var i = 0; i < polygonCount; i++) {
  81230. outShapes.push({
  81231. points: polygons[i]
  81232. });
  81233. }
  81234. }
  81235. else {
  81236. var totalArea_1 = 0;
  81237. var items = map(polygons, function (poly) {
  81238. var min = [];
  81239. var max = [];
  81240. fromPoints(poly, min, max);
  81241. var area = (max[1] - min[1]) * (max[0] - min[0]);
  81242. totalArea_1 += area;
  81243. return { poly: poly, area: area };
  81244. });
  81245. items.sort(function (a, b) { return b.area - a.area; });
  81246. var left = count;
  81247. for (var i = 0; i < polygonCount; i++) {
  81248. var item = items[i];
  81249. if (left <= 0) {
  81250. break;
  81251. }
  81252. var selfCount = i === polygonCount - 1
  81253. ? left
  81254. : Math.ceil(item.area / totalArea_1 * count);
  81255. if (selfCount < 0) {
  81256. continue;
  81257. }
  81258. binaryDivideRecursive(binaryDividePolygon, {
  81259. points: item.poly
  81260. }, selfCount, outShapes);
  81261. left -= selfCount;
  81262. }
  81263. }
  81264. OutShapeCtor = Polygon;
  81265. break;
  81266. }
  81267. if (!OutShapeCtor) {
  81268. return clone$4(path, count);
  81269. }
  81270. var out = [];
  81271. for (var i = 0; i < outShapes.length; i++) {
  81272. var subPath = new OutShapeCtor();
  81273. subPath.setShape(outShapes[i]);
  81274. copyPathProps(path, subPath);
  81275. out.push(subPath);
  81276. }
  81277. return out;
  81278. }
  81279. function alignSubpath(subpath1, subpath2) {
  81280. var len1 = subpath1.length;
  81281. var len2 = subpath2.length;
  81282. if (len1 === len2) {
  81283. return [subpath1, subpath2];
  81284. }
  81285. var tmpSegX = [];
  81286. var tmpSegY = [];
  81287. var shorterPath = len1 < len2 ? subpath1 : subpath2;
  81288. var shorterLen = Math.min(len1, len2);
  81289. var diff = Math.abs(len2 - len1) / 6;
  81290. var shorterBezierCount = (shorterLen - 2) / 6;
  81291. var eachCurveSubDivCount = Math.ceil(diff / shorterBezierCount) + 1;
  81292. var newSubpath = [shorterPath[0], shorterPath[1]];
  81293. var remained = diff;
  81294. for (var i = 2; i < shorterLen;) {
  81295. var x0 = shorterPath[i - 2];
  81296. var y0 = shorterPath[i - 1];
  81297. var x1 = shorterPath[i++];
  81298. var y1 = shorterPath[i++];
  81299. var x2 = shorterPath[i++];
  81300. var y2 = shorterPath[i++];
  81301. var x3 = shorterPath[i++];
  81302. var y3 = shorterPath[i++];
  81303. if (remained <= 0) {
  81304. newSubpath.push(x1, y1, x2, y2, x3, y3);
  81305. continue;
  81306. }
  81307. var actualSubDivCount = Math.min(remained, eachCurveSubDivCount - 1) + 1;
  81308. for (var k = 1; k <= actualSubDivCount; k++) {
  81309. var p = k / actualSubDivCount;
  81310. cubicSubdivide(x0, x1, x2, x3, p, tmpSegX);
  81311. cubicSubdivide(y0, y1, y2, y3, p, tmpSegY);
  81312. x0 = tmpSegX[3];
  81313. y0 = tmpSegY[3];
  81314. newSubpath.push(tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], x0, y0);
  81315. x1 = tmpSegX[5];
  81316. y1 = tmpSegY[5];
  81317. x2 = tmpSegX[6];
  81318. y2 = tmpSegY[6];
  81319. }
  81320. remained -= actualSubDivCount - 1;
  81321. }
  81322. return shorterPath === subpath1 ? [newSubpath, subpath2] : [subpath1, newSubpath];
  81323. }
  81324. function createSubpath(lastSubpathSubpath, otherSubpath) {
  81325. var len = lastSubpathSubpath.length;
  81326. var lastX = lastSubpathSubpath[len - 2];
  81327. var lastY = lastSubpathSubpath[len - 1];
  81328. var newSubpath = [];
  81329. for (var i = 0; i < otherSubpath.length;) {
  81330. newSubpath[i++] = lastX;
  81331. newSubpath[i++] = lastY;
  81332. }
  81333. return newSubpath;
  81334. }
  81335. function alignBezierCurves(array1, array2) {
  81336. var _a;
  81337. var lastSubpath1;
  81338. var lastSubpath2;
  81339. var newArray1 = [];
  81340. var newArray2 = [];
  81341. for (var i = 0; i < Math.max(array1.length, array2.length); i++) {
  81342. var subpath1 = array1[i];
  81343. var subpath2 = array2[i];
  81344. var newSubpath1 = void 0;
  81345. var newSubpath2 = void 0;
  81346. if (!subpath1) {
  81347. newSubpath1 = createSubpath(lastSubpath1 || subpath2, subpath2);
  81348. newSubpath2 = subpath2;
  81349. }
  81350. else if (!subpath2) {
  81351. newSubpath2 = createSubpath(lastSubpath2 || subpath1, subpath1);
  81352. newSubpath1 = subpath1;
  81353. }
  81354. else {
  81355. _a = alignSubpath(subpath1, subpath2), newSubpath1 = _a[0], newSubpath2 = _a[1];
  81356. lastSubpath1 = newSubpath1;
  81357. lastSubpath2 = newSubpath2;
  81358. }
  81359. newArray1.push(newSubpath1);
  81360. newArray2.push(newSubpath2);
  81361. }
  81362. return [newArray1, newArray2];
  81363. }
  81364. function centroid$1(array) {
  81365. var signedArea = 0;
  81366. var cx = 0;
  81367. var cy = 0;
  81368. var len = array.length;
  81369. for (var i = 0, j = len - 2; i < len; j = i, i += 2) {
  81370. var x0 = array[j];
  81371. var y0 = array[j + 1];
  81372. var x1 = array[i];
  81373. var y1 = array[i + 1];
  81374. var a = x0 * y1 - x1 * y0;
  81375. signedArea += a;
  81376. cx += (x0 + x1) * a;
  81377. cy += (y0 + y1) * a;
  81378. }
  81379. if (signedArea === 0) {
  81380. return [array[0] || 0, array[1] || 0];
  81381. }
  81382. return [cx / signedArea / 3, cy / signedArea / 3, signedArea];
  81383. }
  81384. function findBestRingOffset(fromSubBeziers, toSubBeziers, fromCp, toCp) {
  81385. var bezierCount = (fromSubBeziers.length - 2) / 6;
  81386. var bestScore = Infinity;
  81387. var bestOffset = 0;
  81388. var len = fromSubBeziers.length;
  81389. var len2 = len - 2;
  81390. for (var offset = 0; offset < bezierCount; offset++) {
  81391. var cursorOffset = offset * 6;
  81392. var score = 0;
  81393. for (var k = 0; k < len; k += 2) {
  81394. var idx = k === 0 ? cursorOffset : ((cursorOffset + k - 2) % len2 + 2);
  81395. var x0 = fromSubBeziers[idx] - fromCp[0];
  81396. var y0 = fromSubBeziers[idx + 1] - fromCp[1];
  81397. var x1 = toSubBeziers[k] - toCp[0];
  81398. var y1 = toSubBeziers[k + 1] - toCp[1];
  81399. var dx = x1 - x0;
  81400. var dy = y1 - y0;
  81401. score += dx * dx + dy * dy;
  81402. }
  81403. if (score < bestScore) {
  81404. bestScore = score;
  81405. bestOffset = offset;
  81406. }
  81407. }
  81408. return bestOffset;
  81409. }
  81410. function reverse(array) {
  81411. var newArr = [];
  81412. var len = array.length;
  81413. for (var i = 0; i < len; i += 2) {
  81414. newArr[i] = array[len - i - 2];
  81415. newArr[i + 1] = array[len - i - 1];
  81416. }
  81417. return newArr;
  81418. }
  81419. function findBestMorphingRotation(fromArr, toArr, searchAngleIteration, searchAngleRange) {
  81420. var result = [];
  81421. var fromNeedsReverse;
  81422. for (var i = 0; i < fromArr.length; i++) {
  81423. var fromSubpathBezier = fromArr[i];
  81424. var toSubpathBezier = toArr[i];
  81425. var fromCp = centroid$1(fromSubpathBezier);
  81426. var toCp = centroid$1(toSubpathBezier);
  81427. if (fromNeedsReverse == null) {
  81428. fromNeedsReverse = fromCp[2] < 0 !== toCp[2] < 0;
  81429. }
  81430. var newFromSubpathBezier = [];
  81431. var newToSubpathBezier = [];
  81432. var bestAngle = 0;
  81433. var bestScore = Infinity;
  81434. var tmpArr = [];
  81435. var len = fromSubpathBezier.length;
  81436. if (fromNeedsReverse) {
  81437. fromSubpathBezier = reverse(fromSubpathBezier);
  81438. }
  81439. var offset = findBestRingOffset(fromSubpathBezier, toSubpathBezier, fromCp, toCp) * 6;
  81440. var len2 = len - 2;
  81441. for (var k = 0; k < len2; k += 2) {
  81442. var idx = (offset + k) % len2 + 2;
  81443. newFromSubpathBezier[k + 2] = fromSubpathBezier[idx] - fromCp[0];
  81444. newFromSubpathBezier[k + 3] = fromSubpathBezier[idx + 1] - fromCp[1];
  81445. }
  81446. newFromSubpathBezier[0] = fromSubpathBezier[offset] - fromCp[0];
  81447. newFromSubpathBezier[1] = fromSubpathBezier[offset + 1] - fromCp[1];
  81448. if (searchAngleIteration > 0) {
  81449. var step = searchAngleRange / searchAngleIteration;
  81450. for (var angle = -searchAngleRange / 2; angle <= searchAngleRange / 2; angle += step) {
  81451. var sa = Math.sin(angle);
  81452. var ca = Math.cos(angle);
  81453. var score = 0;
  81454. for (var k = 0; k < fromSubpathBezier.length; k += 2) {
  81455. var x0 = newFromSubpathBezier[k];
  81456. var y0 = newFromSubpathBezier[k + 1];
  81457. var x1 = toSubpathBezier[k] - toCp[0];
  81458. var y1 = toSubpathBezier[k + 1] - toCp[1];
  81459. var newX1 = x1 * ca - y1 * sa;
  81460. var newY1 = x1 * sa + y1 * ca;
  81461. tmpArr[k] = newX1;
  81462. tmpArr[k + 1] = newY1;
  81463. var dx = newX1 - x0;
  81464. var dy = newY1 - y0;
  81465. score += dx * dx + dy * dy;
  81466. }
  81467. if (score < bestScore) {
  81468. bestScore = score;
  81469. bestAngle = angle;
  81470. for (var m = 0; m < tmpArr.length; m++) {
  81471. newToSubpathBezier[m] = tmpArr[m];
  81472. }
  81473. }
  81474. }
  81475. }
  81476. else {
  81477. for (var i_1 = 0; i_1 < len; i_1 += 2) {
  81478. newToSubpathBezier[i_1] = toSubpathBezier[i_1] - toCp[0];
  81479. newToSubpathBezier[i_1 + 1] = toSubpathBezier[i_1 + 1] - toCp[1];
  81480. }
  81481. }
  81482. result.push({
  81483. from: newFromSubpathBezier,
  81484. to: newToSubpathBezier,
  81485. fromCp: fromCp,
  81486. toCp: toCp,
  81487. rotation: -bestAngle
  81488. });
  81489. }
  81490. return result;
  81491. }
  81492. function isCombineMorphing(path) {
  81493. return path.__isCombineMorphing;
  81494. }
  81495. var SAVED_METHOD_PREFIX = '__mOriginal_';
  81496. function saveAndModifyMethod(obj, methodName, modifiers) {
  81497. var savedMethodName = SAVED_METHOD_PREFIX + methodName;
  81498. var originalMethod = obj[savedMethodName] || obj[methodName];
  81499. if (!obj[savedMethodName]) {
  81500. obj[savedMethodName] = obj[methodName];
  81501. }
  81502. var replace = modifiers.replace;
  81503. var after = modifiers.after;
  81504. var before = modifiers.before;
  81505. obj[methodName] = function () {
  81506. var args = arguments;
  81507. var res;
  81508. before && before.apply(this, args);
  81509. if (replace) {
  81510. res = replace.apply(this, args);
  81511. }
  81512. else {
  81513. res = originalMethod.apply(this, args);
  81514. }
  81515. after && after.apply(this, args);
  81516. return res;
  81517. };
  81518. }
  81519. function restoreMethod(obj, methodName) {
  81520. var savedMethodName = SAVED_METHOD_PREFIX + methodName;
  81521. if (obj[savedMethodName]) {
  81522. obj[methodName] = obj[savedMethodName];
  81523. obj[savedMethodName] = null;
  81524. }
  81525. }
  81526. function applyTransformOnBeziers(bezierCurves, mm) {
  81527. for (var i = 0; i < bezierCurves.length; i++) {
  81528. var subBeziers = bezierCurves[i];
  81529. for (var k = 0; k < subBeziers.length;) {
  81530. var x = subBeziers[k];
  81531. var y = subBeziers[k + 1];
  81532. subBeziers[k++] = mm[0] * x + mm[2] * y + mm[4];
  81533. subBeziers[k++] = mm[1] * x + mm[3] * y + mm[5];
  81534. }
  81535. }
  81536. }
  81537. function prepareMorphPath(fromPath, toPath) {
  81538. var fromPathProxy = fromPath.getUpdatedPathProxy();
  81539. var toPathProxy = toPath.getUpdatedPathProxy();
  81540. var _a = alignBezierCurves(pathToBezierCurves(fromPathProxy), pathToBezierCurves(toPathProxy)), fromBezierCurves = _a[0], toBezierCurves = _a[1];
  81541. var fromPathTransform = fromPath.getComputedTransform();
  81542. var toPathTransform = toPath.getComputedTransform();
  81543. function updateIdentityTransform() {
  81544. this.transform = null;
  81545. }
  81546. fromPathTransform && applyTransformOnBeziers(fromBezierCurves, fromPathTransform);
  81547. toPathTransform && applyTransformOnBeziers(toBezierCurves, toPathTransform);
  81548. saveAndModifyMethod(toPath, 'updateTransform', { replace: updateIdentityTransform });
  81549. toPath.transform = null;
  81550. var morphingData = findBestMorphingRotation(fromBezierCurves, toBezierCurves, 10, Math.PI);
  81551. var tmpArr = [];
  81552. saveAndModifyMethod(toPath, 'buildPath', { replace: function (path) {
  81553. var t = toPath.__morphT;
  81554. var onet = 1 - t;
  81555. var newCp = [];
  81556. for (var i = 0; i < morphingData.length; i++) {
  81557. var item = morphingData[i];
  81558. var from = item.from;
  81559. var to = item.to;
  81560. var angle = item.rotation * t;
  81561. var fromCp = item.fromCp;
  81562. var toCp = item.toCp;
  81563. var sa = Math.sin(angle);
  81564. var ca = Math.cos(angle);
  81565. lerp(newCp, fromCp, toCp, t);
  81566. for (var m = 0; m < from.length; m += 2) {
  81567. var x0_1 = from[m];
  81568. var y0_1 = from[m + 1];
  81569. var x1 = to[m];
  81570. var y1 = to[m + 1];
  81571. var x = x0_1 * onet + x1 * t;
  81572. var y = y0_1 * onet + y1 * t;
  81573. tmpArr[m] = (x * ca - y * sa) + newCp[0];
  81574. tmpArr[m + 1] = (x * sa + y * ca) + newCp[1];
  81575. }
  81576. var x0 = tmpArr[0];
  81577. var y0 = tmpArr[1];
  81578. path.moveTo(x0, y0);
  81579. for (var m = 2; m < from.length;) {
  81580. var x1 = tmpArr[m++];
  81581. var y1 = tmpArr[m++];
  81582. var x2 = tmpArr[m++];
  81583. var y2 = tmpArr[m++];
  81584. var x3 = tmpArr[m++];
  81585. var y3 = tmpArr[m++];
  81586. if (x0 === x1 && y0 === y1 && x2 === x3 && y2 === y3) {
  81587. path.lineTo(x3, y3);
  81588. }
  81589. else {
  81590. path.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  81591. }
  81592. x0 = x3;
  81593. y0 = y3;
  81594. }
  81595. }
  81596. } });
  81597. }
  81598. function morphPath(fromPath, toPath, animationOpts) {
  81599. if (!fromPath || !toPath) {
  81600. return toPath;
  81601. }
  81602. var oldDone = animationOpts.done;
  81603. var oldDuring = animationOpts.during;
  81604. prepareMorphPath(fromPath, toPath);
  81605. toPath.__morphT = 0;
  81606. function restoreToPath() {
  81607. restoreMethod(toPath, 'buildPath');
  81608. restoreMethod(toPath, 'updateTransform');
  81609. toPath.__morphT = -1;
  81610. toPath.createPathProxy();
  81611. toPath.dirtyShape();
  81612. }
  81613. toPath.animateTo({
  81614. __morphT: 1
  81615. }, defaults({
  81616. during: function (p) {
  81617. toPath.dirtyShape();
  81618. oldDuring && oldDuring(p);
  81619. },
  81620. done: function () {
  81621. restoreToPath();
  81622. oldDone && oldDone();
  81623. }
  81624. }, animationOpts));
  81625. return toPath;
  81626. }
  81627. function hilbert(x, y, minX, minY, maxX, maxY) {
  81628. var bits = 16;
  81629. x = (maxX === minX) ? 0 : Math.round(32767 * (x - minX) / (maxX - minX));
  81630. y = (maxY === minY) ? 0 : Math.round(32767 * (y - minY) / (maxY - minY));
  81631. var d = 0;
  81632. var tmp;
  81633. for (var s = (1 << bits) / 2; s > 0; s /= 2) {
  81634. var rx = 0;
  81635. var ry = 0;
  81636. if ((x & s) > 0) {
  81637. rx = 1;
  81638. }
  81639. if ((y & s) > 0) {
  81640. ry = 1;
  81641. }
  81642. d += s * s * ((3 * rx) ^ ry);
  81643. if (ry === 0) {
  81644. if (rx === 1) {
  81645. x = s - 1 - x;
  81646. y = s - 1 - y;
  81647. }
  81648. tmp = x;
  81649. x = y;
  81650. y = tmp;
  81651. }
  81652. }
  81653. return d;
  81654. }
  81655. function sortPaths(pathList) {
  81656. var xMin = Infinity;
  81657. var yMin = Infinity;
  81658. var xMax = -Infinity;
  81659. var yMax = -Infinity;
  81660. var cps = map(pathList, function (path) {
  81661. var rect = path.getBoundingRect();
  81662. var m = path.getComputedTransform();
  81663. var x = rect.x + rect.width / 2 + (m ? m[4] : 0);
  81664. var y = rect.y + rect.height / 2 + (m ? m[5] : 0);
  81665. xMin = Math.min(x, xMin);
  81666. yMin = Math.min(y, yMin);
  81667. xMax = Math.max(x, xMax);
  81668. yMax = Math.max(y, yMax);
  81669. return [x, y];
  81670. });
  81671. var items = map(cps, function (cp, idx) {
  81672. return {
  81673. cp: cp,
  81674. z: hilbert(cp[0], cp[1], xMin, yMin, xMax, yMax),
  81675. path: pathList[idx]
  81676. };
  81677. });
  81678. return items.sort(function (a, b) { return a.z - b.z; }).map(function (item) { return item.path; });
  81679. }
  81680. function defaultDividePath(param) {
  81681. return split(param.path, param.count);
  81682. }
  81683. function createEmptyReturn() {
  81684. return {
  81685. fromIndividuals: [],
  81686. toIndividuals: [],
  81687. count: 0
  81688. };
  81689. }
  81690. function combineMorph(fromList, toPath, animationOpts) {
  81691. var fromPathList = [];
  81692. function addFromPath(fromList) {
  81693. for (var i = 0; i < fromList.length; i++) {
  81694. var from = fromList[i];
  81695. if (isCombineMorphing(from)) {
  81696. addFromPath(from.childrenRef());
  81697. }
  81698. else if (from instanceof Path) {
  81699. fromPathList.push(from);
  81700. }
  81701. }
  81702. }
  81703. addFromPath(fromList);
  81704. var separateCount = fromPathList.length;
  81705. if (!separateCount) {
  81706. return createEmptyReturn();
  81707. }
  81708. var dividePath = animationOpts.dividePath || defaultDividePath;
  81709. var toSubPathList = dividePath({
  81710. path: toPath, count: separateCount
  81711. });
  81712. if (toSubPathList.length !== separateCount) {
  81713. console.error('Invalid morphing: unmatched splitted path');
  81714. return createEmptyReturn();
  81715. }
  81716. fromPathList = sortPaths(fromPathList);
  81717. toSubPathList = sortPaths(toSubPathList);
  81718. var oldDone = animationOpts.done;
  81719. var oldDuring = animationOpts.during;
  81720. var individualDelay = animationOpts.individualDelay;
  81721. var identityTransform = new Transformable();
  81722. for (var i = 0; i < separateCount; i++) {
  81723. var from = fromPathList[i];
  81724. var to = toSubPathList[i];
  81725. to.parent = toPath;
  81726. to.copyTransform(identityTransform);
  81727. if (!individualDelay) {
  81728. prepareMorphPath(from, to);
  81729. }
  81730. }
  81731. toPath.__isCombineMorphing = true;
  81732. toPath.childrenRef = function () {
  81733. return toSubPathList;
  81734. };
  81735. function addToSubPathListToZr(zr) {
  81736. for (var i = 0; i < toSubPathList.length; i++) {
  81737. toSubPathList[i].addSelfToZr(zr);
  81738. }
  81739. }
  81740. saveAndModifyMethod(toPath, 'addSelfToZr', {
  81741. after: function (zr) {
  81742. addToSubPathListToZr(zr);
  81743. }
  81744. });
  81745. saveAndModifyMethod(toPath, 'removeSelfFromZr', {
  81746. after: function (zr) {
  81747. for (var i = 0; i < toSubPathList.length; i++) {
  81748. toSubPathList[i].removeSelfFromZr(zr);
  81749. }
  81750. }
  81751. });
  81752. function restoreToPath() {
  81753. toPath.__isCombineMorphing = false;
  81754. toPath.__morphT = -1;
  81755. toPath.childrenRef = null;
  81756. restoreMethod(toPath, 'addSelfToZr');
  81757. restoreMethod(toPath, 'removeSelfFromZr');
  81758. }
  81759. var toLen = toSubPathList.length;
  81760. if (individualDelay) {
  81761. var animating_1 = toLen;
  81762. var eachDone = function () {
  81763. animating_1--;
  81764. if (animating_1 === 0) {
  81765. restoreToPath();
  81766. oldDone && oldDone();
  81767. }
  81768. };
  81769. for (var i = 0; i < toLen; i++) {
  81770. var indivdualAnimationOpts = individualDelay ? defaults({
  81771. delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toSubPathList[i]),
  81772. done: eachDone
  81773. }, animationOpts) : animationOpts;
  81774. morphPath(fromPathList[i], toSubPathList[i], indivdualAnimationOpts);
  81775. }
  81776. }
  81777. else {
  81778. toPath.__morphT = 0;
  81779. toPath.animateTo({
  81780. __morphT: 1
  81781. }, defaults({
  81782. during: function (p) {
  81783. for (var i = 0; i < toLen; i++) {
  81784. var child = toSubPathList[i];
  81785. child.__morphT = toPath.__morphT;
  81786. child.dirtyShape();
  81787. }
  81788. oldDuring && oldDuring(p);
  81789. },
  81790. done: function () {
  81791. restoreToPath();
  81792. for (var i = 0; i < fromList.length; i++) {
  81793. restoreMethod(fromList[i], 'updateTransform');
  81794. }
  81795. oldDone && oldDone();
  81796. }
  81797. }, animationOpts));
  81798. }
  81799. if (toPath.__zr) {
  81800. addToSubPathListToZr(toPath.__zr);
  81801. }
  81802. return {
  81803. fromIndividuals: fromPathList,
  81804. toIndividuals: toSubPathList,
  81805. count: toLen
  81806. };
  81807. }
  81808. function separateMorph(fromPath, toPathList, animationOpts) {
  81809. var toLen = toPathList.length;
  81810. var fromPathList = [];
  81811. var dividePath = animationOpts.dividePath || defaultDividePath;
  81812. function addFromPath(fromList) {
  81813. for (var i = 0; i < fromList.length; i++) {
  81814. var from = fromList[i];
  81815. if (isCombineMorphing(from)) {
  81816. addFromPath(from.childrenRef());
  81817. }
  81818. else if (from instanceof Path) {
  81819. fromPathList.push(from);
  81820. }
  81821. }
  81822. }
  81823. if (isCombineMorphing(fromPath)) {
  81824. addFromPath(fromPath.childrenRef());
  81825. var fromLen = fromPathList.length;
  81826. if (fromLen < toLen) {
  81827. var k = 0;
  81828. for (var i = fromLen; i < toLen; i++) {
  81829. fromPathList.push(clonePath(fromPathList[k++ % fromLen]));
  81830. }
  81831. }
  81832. fromPathList.length = toLen;
  81833. }
  81834. else {
  81835. fromPathList = dividePath({ path: fromPath, count: toLen });
  81836. var fromPathTransform = fromPath.getComputedTransform();
  81837. for (var i = 0; i < fromPathList.length; i++) {
  81838. fromPathList[i].setLocalTransform(fromPathTransform);
  81839. }
  81840. if (fromPathList.length !== toLen) {
  81841. console.error('Invalid morphing: unmatched splitted path');
  81842. return createEmptyReturn();
  81843. }
  81844. }
  81845. fromPathList = sortPaths(fromPathList);
  81846. toPathList = sortPaths(toPathList);
  81847. var individualDelay = animationOpts.individualDelay;
  81848. for (var i = 0; i < toLen; i++) {
  81849. var indivdualAnimationOpts = individualDelay ? defaults({
  81850. delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toPathList[i])
  81851. }, animationOpts) : animationOpts;
  81852. morphPath(fromPathList[i], toPathList[i], indivdualAnimationOpts);
  81853. }
  81854. return {
  81855. fromIndividuals: fromPathList,
  81856. toIndividuals: toPathList,
  81857. count: toPathList.length
  81858. };
  81859. }
  81860. function isMultiple(elements) {
  81861. return isArray(elements[0]);
  81862. }
  81863. function prepareMorphBatches(one, many) {
  81864. var batches = [];
  81865. var batchCount = one.length;
  81866. for (var i = 0; i < batchCount; i++) {
  81867. batches.push({
  81868. one: one[i],
  81869. many: []
  81870. });
  81871. }
  81872. for (var i = 0; i < many.length; i++) {
  81873. var len = many[i].length;
  81874. var k = void 0;
  81875. for (k = 0; k < len; k++) {
  81876. batches[k % batchCount].many.push(many[i][k]);
  81877. }
  81878. }
  81879. var off = 0; // If one has more paths than each one of many. average them.
  81880. for (var i = batchCount - 1; i >= 0; i--) {
  81881. if (!batches[i].many.length) {
  81882. var moveFrom = batches[off].many;
  81883. if (moveFrom.length <= 1) {
  81884. // Not enough
  81885. // Start from the first one.
  81886. if (off) {
  81887. off = 0;
  81888. } else {
  81889. return batches;
  81890. }
  81891. }
  81892. var len = moveFrom.length;
  81893. var mid = Math.ceil(len / 2);
  81894. batches[i].many = moveFrom.slice(mid, len);
  81895. batches[off].many = moveFrom.slice(0, mid);
  81896. off++;
  81897. }
  81898. }
  81899. return batches;
  81900. }
  81901. var pathDividers = {
  81902. clone: function (params) {
  81903. var ret = []; // Fitting the alpha
  81904. var approxOpacity = 1 - Math.pow(1 - params.path.style.opacity, 1 / params.count);
  81905. for (var i = 0; i < params.count; i++) {
  81906. var cloned = clonePath(params.path);
  81907. cloned.setStyle('opacity', approxOpacity);
  81908. ret.push(cloned);
  81909. }
  81910. return ret;
  81911. },
  81912. // Use the default divider
  81913. split: null
  81914. };
  81915. function applyMorphAnimation(from, to, divideShape, seriesModel, dataIndex, animateOtherProps) {
  81916. if (!from.length || !to.length) {
  81917. return;
  81918. }
  81919. var updateAnimationCfg = getAnimationConfig('update', seriesModel, dataIndex);
  81920. if (!(updateAnimationCfg && updateAnimationCfg.duration > 0)) {
  81921. return;
  81922. }
  81923. var animationDelay = seriesModel.getModel('universalTransition').get('delay');
  81924. var animationCfg = Object.assign({
  81925. // Need to setToFinal so the further calculation based on the style can be correct.
  81926. // Like emphasis color.
  81927. setToFinal: true
  81928. }, updateAnimationCfg);
  81929. var many;
  81930. var one;
  81931. if (isMultiple(from)) {
  81932. // manyToOne
  81933. many = from;
  81934. one = to;
  81935. }
  81936. if (isMultiple(to)) {
  81937. // oneToMany
  81938. many = to;
  81939. one = from;
  81940. }
  81941. function morphOneBatch(batch, fromIsMany, animateIndex, animateCount, forceManyOne) {
  81942. var batchMany = batch.many;
  81943. var batchOne = batch.one;
  81944. if (batchMany.length === 1 && !forceManyOne) {
  81945. // Is one to one
  81946. var batchFrom = fromIsMany ? batchMany[0] : batchOne;
  81947. var batchTo = fromIsMany ? batchOne : batchMany[0];
  81948. if (isCombineMorphing(batchFrom)) {
  81949. // Keep doing combine animation.
  81950. morphOneBatch({
  81951. many: [batchFrom],
  81952. one: batchTo
  81953. }, true, animateIndex, animateCount, true);
  81954. } else {
  81955. var individualAnimationCfg = animationDelay ? defaults({
  81956. delay: animationDelay(animateIndex, animateCount)
  81957. }, animationCfg) : animationCfg;
  81958. morphPath(batchFrom, batchTo, individualAnimationCfg);
  81959. animateOtherProps(batchFrom, batchTo, batchFrom, batchTo, individualAnimationCfg);
  81960. }
  81961. } else {
  81962. var separateAnimationCfg = defaults({
  81963. dividePath: pathDividers[divideShape],
  81964. individualDelay: animationDelay && function (idx, count, fromPath, toPath) {
  81965. return animationDelay(idx + animateIndex, animateCount);
  81966. }
  81967. }, animationCfg);
  81968. var _a = fromIsMany ? combineMorph(batchMany, batchOne, separateAnimationCfg) : separateMorph(batchOne, batchMany, separateAnimationCfg),
  81969. fromIndividuals = _a.fromIndividuals,
  81970. toIndividuals = _a.toIndividuals;
  81971. var count = fromIndividuals.length;
  81972. for (var k = 0; k < count; k++) {
  81973. var individualAnimationCfg = animationDelay ? defaults({
  81974. delay: animationDelay(k, count)
  81975. }, animationCfg) : animationCfg;
  81976. animateOtherProps(fromIndividuals[k], toIndividuals[k], fromIsMany ? batchMany[k] : batch.one, fromIsMany ? batch.one : batchMany[k], individualAnimationCfg);
  81977. }
  81978. }
  81979. }
  81980. var fromIsMany = many ? many === from // Is one to one. If the path number not match. also needs do merge and separate morphing.
  81981. : from.length > to.length;
  81982. var morphBatches = many ? prepareMorphBatches(one, many) : prepareMorphBatches(fromIsMany ? to : from, [fromIsMany ? from : to]);
  81983. var animateCount = 0;
  81984. for (var i = 0; i < morphBatches.length; i++) {
  81985. animateCount += morphBatches[i].many.length;
  81986. }
  81987. var animateIndex = 0;
  81988. for (var i = 0; i < morphBatches.length; i++) {
  81989. morphOneBatch(morphBatches[i], fromIsMany, animateIndex, animateCount);
  81990. animateIndex += morphBatches[i].many.length;
  81991. }
  81992. }
  81993. function getPathList(elements) {
  81994. if (!elements) {
  81995. return [];
  81996. }
  81997. if (isArray(elements)) {
  81998. var pathList_1 = [];
  81999. for (var i = 0; i < elements.length; i++) {
  82000. pathList_1.push(getPathList(elements[i]));
  82001. }
  82002. return pathList_1;
  82003. }
  82004. var pathList = [];
  82005. elements.traverse(function (el) {
  82006. if (el instanceof Path && !el.disableMorphing && !el.invisible && !el.ignore) {
  82007. pathList.push(el);
  82008. }
  82009. });
  82010. return pathList;
  82011. }
  82012. var DATA_COUNT_THRESHOLD = 1e4;
  82013. var getUniversalTransitionGlobalStore = makeInner();
  82014. function getGroupIdDimension(data) {
  82015. var dimensions = data.dimensions;
  82016. for (var i = 0; i < dimensions.length; i++) {
  82017. var dimInfo = data.getDimensionInfo(dimensions[i]);
  82018. if (dimInfo && dimInfo.otherDims.itemGroupId === 0) {
  82019. return dimensions[i];
  82020. }
  82021. }
  82022. }
  82023. function flattenDataDiffItems(list) {
  82024. var items = [];
  82025. each(list, function (seriesInfo) {
  82026. var data = seriesInfo.data;
  82027. if (data.count() > DATA_COUNT_THRESHOLD) {
  82028. if ("development" !== 'production') {
  82029. warn('Universal transition is disabled on large data > 10k.');
  82030. }
  82031. return;
  82032. }
  82033. var indices = data.getIndices();
  82034. var groupDim = getGroupIdDimension(data);
  82035. for (var dataIndex = 0; dataIndex < indices.length; dataIndex++) {
  82036. items.push({
  82037. dataGroupId: seriesInfo.dataGroupId,
  82038. data: data,
  82039. dim: seriesInfo.dim || groupDim,
  82040. divide: seriesInfo.divide,
  82041. dataIndex: dataIndex
  82042. });
  82043. }
  82044. });
  82045. return items;
  82046. }
  82047. function fadeInElement(newEl, newSeries, newIndex) {
  82048. newEl.traverse(function (el) {
  82049. if (el instanceof Path) {
  82050. // TODO use fade in animation for target element.
  82051. initProps(el, {
  82052. style: {
  82053. opacity: 0
  82054. }
  82055. }, newSeries, {
  82056. dataIndex: newIndex,
  82057. isFrom: true
  82058. });
  82059. }
  82060. });
  82061. }
  82062. function removeEl$1(el) {
  82063. if (el.parent) {
  82064. // Bake parent transform to element.
  82065. // So it can still have proper transform to transition after it's removed.
  82066. var computedTransform = el.getComputedTransform();
  82067. el.setLocalTransform(computedTransform);
  82068. el.parent.remove(el);
  82069. }
  82070. }
  82071. function stopAnimation(el) {
  82072. el.stopAnimation();
  82073. if (el.isGroup) {
  82074. el.traverse(function (child) {
  82075. child.stopAnimation();
  82076. });
  82077. }
  82078. }
  82079. function animateElementStyles(el, dataIndex, seriesModel) {
  82080. var animationConfig = getAnimationConfig('update', seriesModel, dataIndex);
  82081. animationConfig && el.traverse(function (child) {
  82082. if (child instanceof Displayable) {
  82083. var oldStyle = getOldStyle(child);
  82084. if (oldStyle) {
  82085. child.animateFrom({
  82086. style: oldStyle
  82087. }, animationConfig);
  82088. }
  82089. }
  82090. });
  82091. }
  82092. function isAllIdSame(oldDiffItems, newDiffItems) {
  82093. var len = oldDiffItems.length;
  82094. if (len !== newDiffItems.length) {
  82095. return false;
  82096. }
  82097. for (var i = 0; i < len; i++) {
  82098. var oldItem = oldDiffItems[i];
  82099. var newItem = newDiffItems[i];
  82100. if (oldItem.data.getId(oldItem.dataIndex) !== newItem.data.getId(newItem.dataIndex)) {
  82101. return false;
  82102. }
  82103. }
  82104. return true;
  82105. }
  82106. function transitionBetween(oldList, newList, api) {
  82107. var oldDiffItems = flattenDataDiffItems(oldList);
  82108. var newDiffItems = flattenDataDiffItems(newList);
  82109. function updateMorphingPathProps(from, to, rawFrom, rawTo, animationCfg) {
  82110. if (rawFrom || from) {
  82111. to.animateFrom({
  82112. style: rawFrom && rawFrom !== from ? // dividingMethod like clone may override the style(opacity)
  82113. // So extend it to raw style.
  82114. extend(extend({}, rawFrom.style), from.style) : from.style
  82115. }, animationCfg);
  82116. }
  82117. }
  82118. function findKeyDim(items) {
  82119. for (var i = 0; i < items.length; i++) {
  82120. if (items[i].dim) {
  82121. return items[i].dim;
  82122. }
  82123. }
  82124. }
  82125. var oldKeyDim = findKeyDim(oldDiffItems);
  82126. var newKeyDim = findKeyDim(newDiffItems);
  82127. var hasMorphAnimation = false;
  82128. function createKeyGetter(isOld, onlyGetId) {
  82129. return function (diffItem) {
  82130. var data = diffItem.data;
  82131. var dataIndex = diffItem.dataIndex; // TODO if specified dim
  82132. if (onlyGetId) {
  82133. return data.getId(dataIndex);
  82134. } // Use group id as transition key by default.
  82135. // So we can achieve multiple to multiple animation like drilldown / up naturally.
  82136. // If group id not exits. Use id instead. If so, only one to one transition will be applied.
  82137. var dataGroupId = diffItem.dataGroupId; // If specified key dimension(itemGroupId by default). Use this same dimension from other data.
  82138. // PENDING: If only use key dimension of newData.
  82139. var keyDim = isOld ? oldKeyDim || newKeyDim : newKeyDim || oldKeyDim;
  82140. var dimInfo = keyDim && data.getDimensionInfo(keyDim);
  82141. var dimOrdinalMeta = dimInfo && dimInfo.ordinalMeta;
  82142. if (dimInfo) {
  82143. // Get from encode.itemGroupId.
  82144. var key = data.get(dimInfo.name, dataIndex);
  82145. if (dimOrdinalMeta) {
  82146. return dimOrdinalMeta.categories[key] || key + '';
  82147. }
  82148. return key + '';
  82149. } // Get groupId from raw item. { groupId: '' }
  82150. var itemVal = data.getRawDataItem(dataIndex);
  82151. if (itemVal && itemVal.groupId) {
  82152. return itemVal.groupId + '';
  82153. }
  82154. return dataGroupId || data.getId(dataIndex);
  82155. };
  82156. } // Use id if it's very likely to be an one to one animation
  82157. // It's more robust than groupId
  82158. // TODO Check if key dimension is specified.
  82159. var useId = isAllIdSame(oldDiffItems, newDiffItems);
  82160. var isElementStillInChart = {};
  82161. if (!useId) {
  82162. // We may have different diff strategy with basicTransition if we use other dimension as key.
  82163. // If so, we can't simply check if oldEl is same with newEl. We need a map to check if oldEl is still being used in the new chart.
  82164. // We can't use the elements that already being morphed. Let it keep it's original basic transition.
  82165. for (var i = 0; i < newDiffItems.length; i++) {
  82166. var newItem = newDiffItems[i];
  82167. var el = newItem.data.getItemGraphicEl(newItem.dataIndex);
  82168. if (el) {
  82169. isElementStillInChart[el.id] = true;
  82170. }
  82171. }
  82172. }
  82173. function updateOneToOne(newIndex, oldIndex) {
  82174. var oldItem = oldDiffItems[oldIndex];
  82175. var newItem = newDiffItems[newIndex];
  82176. var newSeries = newItem.data.hostModel; // TODO Mark this elements is morphed and don't morph them anymore
  82177. var oldEl = oldItem.data.getItemGraphicEl(oldItem.dataIndex);
  82178. var newEl = newItem.data.getItemGraphicEl(newItem.dataIndex); // Can't handle same elements.
  82179. if (oldEl === newEl) {
  82180. newEl && animateElementStyles(newEl, newItem.dataIndex, newSeries);
  82181. return;
  82182. }
  82183. if ( // We can't use the elements that already being morphed
  82184. oldEl && isElementStillInChart[oldEl.id]) {
  82185. return;
  82186. }
  82187. if (newEl) {
  82188. // TODO: If keep animating the group in case
  82189. // some of the elements don't want to be morphed.
  82190. // TODO Label?
  82191. stopAnimation(newEl);
  82192. if (oldEl) {
  82193. stopAnimation(oldEl); // If old element is doing leaving animation. stop it and remove it immediately.
  82194. removeEl$1(oldEl);
  82195. hasMorphAnimation = true;
  82196. applyMorphAnimation(getPathList(oldEl), getPathList(newEl), newItem.divide, newSeries, newIndex, updateMorphingPathProps);
  82197. } else {
  82198. fadeInElement(newEl, newSeries, newIndex);
  82199. }
  82200. } // else keep oldEl leaving animation.
  82201. }
  82202. new DataDiffer(oldDiffItems, newDiffItems, createKeyGetter(true, useId), createKeyGetter(false, useId), null, 'multiple').update(updateOneToOne).updateManyToOne(function (newIndex, oldIndices) {
  82203. var newItem = newDiffItems[newIndex];
  82204. var newData = newItem.data;
  82205. var newSeries = newData.hostModel;
  82206. var newEl = newData.getItemGraphicEl(newItem.dataIndex);
  82207. var oldElsList = filter(map(oldIndices, function (idx) {
  82208. return oldDiffItems[idx].data.getItemGraphicEl(oldDiffItems[idx].dataIndex);
  82209. }), function (oldEl) {
  82210. return oldEl && oldEl !== newEl && !isElementStillInChart[oldEl.id];
  82211. });
  82212. if (newEl) {
  82213. stopAnimation(newEl);
  82214. if (oldElsList.length) {
  82215. // If old element is doing leaving animation. stop it and remove it immediately.
  82216. each(oldElsList, function (oldEl) {
  82217. stopAnimation(oldEl);
  82218. removeEl$1(oldEl);
  82219. });
  82220. hasMorphAnimation = true;
  82221. applyMorphAnimation(getPathList(oldElsList), getPathList(newEl), newItem.divide, newSeries, newIndex, updateMorphingPathProps);
  82222. } else {
  82223. fadeInElement(newEl, newSeries, newItem.dataIndex);
  82224. }
  82225. } // else keep oldEl leaving animation.
  82226. }).updateOneToMany(function (newIndices, oldIndex) {
  82227. var oldItem = oldDiffItems[oldIndex];
  82228. var oldEl = oldItem.data.getItemGraphicEl(oldItem.dataIndex); // We can't use the elements that already being morphed
  82229. if (oldEl && isElementStillInChart[oldEl.id]) {
  82230. return;
  82231. }
  82232. var newElsList = filter(map(newIndices, function (idx) {
  82233. return newDiffItems[idx].data.getItemGraphicEl(newDiffItems[idx].dataIndex);
  82234. }), function (el) {
  82235. return el && el !== oldEl;
  82236. });
  82237. var newSeris = newDiffItems[newIndices[0]].data.hostModel;
  82238. if (newElsList.length) {
  82239. each(newElsList, function (newEl) {
  82240. return stopAnimation(newEl);
  82241. });
  82242. if (oldEl) {
  82243. stopAnimation(oldEl); // If old element is doing leaving animation. stop it and remove it immediately.
  82244. removeEl$1(oldEl);
  82245. hasMorphAnimation = true;
  82246. applyMorphAnimation(getPathList(oldEl), getPathList(newElsList), oldItem.divide, // Use divide on old.
  82247. newSeris, newIndices[0], updateMorphingPathProps);
  82248. } else {
  82249. each(newElsList, function (newEl) {
  82250. return fadeInElement(newEl, newSeris, newIndices[0]);
  82251. });
  82252. }
  82253. } // else keep oldEl leaving animation.
  82254. }).updateManyToMany(function (newIndices, oldIndices) {
  82255. // If two data are same and both have groupId.
  82256. // Normally they should be diff by id.
  82257. new DataDiffer(oldIndices, newIndices, function (rawIdx) {
  82258. return oldDiffItems[rawIdx].data.getId(oldDiffItems[rawIdx].dataIndex);
  82259. }, function (rawIdx) {
  82260. return newDiffItems[rawIdx].data.getId(newDiffItems[rawIdx].dataIndex);
  82261. }).update(function (newIndex, oldIndex) {
  82262. // Use the original index
  82263. updateOneToOne(newIndices[newIndex], oldIndices[oldIndex]);
  82264. }).execute();
  82265. }).execute();
  82266. if (hasMorphAnimation) {
  82267. each(newList, function (_a) {
  82268. var data = _a.data;
  82269. var seriesModel = data.hostModel;
  82270. var view = seriesModel && api.getViewOfSeriesModel(seriesModel);
  82271. var animationCfg = getAnimationConfig('update', seriesModel, 0); // use 0 index.
  82272. if (view && seriesModel.isAnimationEnabled() && animationCfg && animationCfg.duration > 0) {
  82273. view.group.traverse(function (el) {
  82274. if (el instanceof Path && !el.animators.length) {
  82275. // We can't accept there still exists element that has no animation
  82276. // if universalTransition is enabled
  82277. el.animateFrom({
  82278. style: {
  82279. opacity: 0
  82280. }
  82281. }, animationCfg);
  82282. }
  82283. });
  82284. }
  82285. });
  82286. }
  82287. }
  82288. function getSeriesTransitionKey(series) {
  82289. var seriesKey = series.getModel('universalTransition').get('seriesKey');
  82290. if (!seriesKey) {
  82291. // Use series id by default.
  82292. return series.id;
  82293. }
  82294. return seriesKey;
  82295. }
  82296. function convertArraySeriesKeyToString(seriesKey) {
  82297. if (isArray(seriesKey)) {
  82298. // Order independent.
  82299. return seriesKey.sort().join(',');
  82300. }
  82301. return seriesKey;
  82302. }
  82303. function getDivideShapeFromData(data) {
  82304. if (data.hostModel) {
  82305. return data.hostModel.getModel('universalTransition').get('divideShape');
  82306. }
  82307. }
  82308. function findTransitionSeriesBatches(globalStore, params) {
  82309. var updateBatches = createHashMap();
  82310. var oldDataMap = createHashMap(); // Map that only store key in array seriesKey.
  82311. // Which is used to query the old data when transition from one to multiple series.
  82312. var oldDataMapForSplit = createHashMap();
  82313. each(globalStore.oldSeries, function (series, idx) {
  82314. var oldDataGroupId = globalStore.oldDataGroupIds[idx];
  82315. var oldData = globalStore.oldData[idx];
  82316. var transitionKey = getSeriesTransitionKey(series);
  82317. var transitionKeyStr = convertArraySeriesKeyToString(transitionKey);
  82318. oldDataMap.set(transitionKeyStr, {
  82319. dataGroupId: oldDataGroupId,
  82320. data: oldData
  82321. });
  82322. if (isArray(transitionKey)) {
  82323. // Same key can't in different array seriesKey.
  82324. each(transitionKey, function (key) {
  82325. oldDataMapForSplit.set(key, {
  82326. key: transitionKeyStr,
  82327. dataGroupId: oldDataGroupId,
  82328. data: oldData
  82329. });
  82330. });
  82331. }
  82332. });
  82333. function checkTransitionSeriesKeyDuplicated(transitionKeyStr) {
  82334. if (updateBatches.get(transitionKeyStr)) {
  82335. warn("Duplicated seriesKey in universalTransition " + transitionKeyStr);
  82336. }
  82337. }
  82338. each(params.updatedSeries, function (series) {
  82339. if (series.isUniversalTransitionEnabled() && series.isAnimationEnabled()) {
  82340. var newDataGroupId = series.get('dataGroupId');
  82341. var newData = series.getData();
  82342. var transitionKey = getSeriesTransitionKey(series);
  82343. var transitionKeyStr = convertArraySeriesKeyToString(transitionKey); // Only transition between series with same id.
  82344. var oldData = oldDataMap.get(transitionKeyStr); // string transition key is the best match.
  82345. if (oldData) {
  82346. if ("development" !== 'production') {
  82347. checkTransitionSeriesKeyDuplicated(transitionKeyStr);
  82348. } // TODO check if data is same?
  82349. updateBatches.set(transitionKeyStr, {
  82350. oldSeries: [{
  82351. dataGroupId: oldData.dataGroupId,
  82352. divide: getDivideShapeFromData(oldData.data),
  82353. data: oldData.data
  82354. }],
  82355. newSeries: [{
  82356. dataGroupId: newDataGroupId,
  82357. divide: getDivideShapeFromData(newData),
  82358. data: newData
  82359. }]
  82360. });
  82361. } else {
  82362. // Transition from multiple series.
  82363. if (isArray(transitionKey)) {
  82364. if ("development" !== 'production') {
  82365. checkTransitionSeriesKeyDuplicated(transitionKeyStr);
  82366. }
  82367. var oldSeries_1 = [];
  82368. each(transitionKey, function (key) {
  82369. var oldData = oldDataMap.get(key);
  82370. if (oldData.data) {
  82371. oldSeries_1.push({
  82372. dataGroupId: oldData.dataGroupId,
  82373. divide: getDivideShapeFromData(oldData.data),
  82374. data: oldData.data
  82375. });
  82376. }
  82377. });
  82378. if (oldSeries_1.length) {
  82379. updateBatches.set(transitionKeyStr, {
  82380. oldSeries: oldSeries_1,
  82381. newSeries: [{
  82382. dataGroupId: newDataGroupId,
  82383. data: newData,
  82384. divide: getDivideShapeFromData(newData)
  82385. }]
  82386. });
  82387. }
  82388. } else {
  82389. // Try transition to multiple series.
  82390. var oldData_1 = oldDataMapForSplit.get(transitionKey);
  82391. if (oldData_1) {
  82392. var batch = updateBatches.get(oldData_1.key);
  82393. if (!batch) {
  82394. batch = {
  82395. oldSeries: [{
  82396. dataGroupId: oldData_1.dataGroupId,
  82397. data: oldData_1.data,
  82398. divide: getDivideShapeFromData(oldData_1.data)
  82399. }],
  82400. newSeries: []
  82401. };
  82402. updateBatches.set(oldData_1.key, batch);
  82403. }
  82404. batch.newSeries.push({
  82405. dataGroupId: newDataGroupId,
  82406. data: newData,
  82407. divide: getDivideShapeFromData(newData)
  82408. });
  82409. }
  82410. }
  82411. }
  82412. }
  82413. });
  82414. return updateBatches;
  82415. }
  82416. function querySeries(series, finder) {
  82417. for (var i = 0; i < series.length; i++) {
  82418. var found = finder.seriesIndex != null && finder.seriesIndex === series[i].seriesIndex || finder.seriesId != null && finder.seriesId === series[i].id;
  82419. if (found) {
  82420. return i;
  82421. }
  82422. }
  82423. }
  82424. function transitionSeriesFromOpt(transitionOpt, globalStore, params, api) {
  82425. var from = [];
  82426. var to = [];
  82427. each(normalizeToArray(transitionOpt.from), function (finder) {
  82428. var idx = querySeries(globalStore.oldSeries, finder);
  82429. if (idx >= 0) {
  82430. from.push({
  82431. dataGroupId: globalStore.oldDataGroupIds[idx],
  82432. data: globalStore.oldData[idx],
  82433. // TODO can specify divideShape in transition.
  82434. divide: getDivideShapeFromData(globalStore.oldData[idx]),
  82435. dim: finder.dimension
  82436. });
  82437. }
  82438. });
  82439. each(normalizeToArray(transitionOpt.to), function (finder) {
  82440. var idx = querySeries(params.updatedSeries, finder);
  82441. if (idx >= 0) {
  82442. var data = params.updatedSeries[idx].getData();
  82443. to.push({
  82444. dataGroupId: globalStore.oldDataGroupIds[idx],
  82445. data: data,
  82446. divide: getDivideShapeFromData(data),
  82447. dim: finder.dimension
  82448. });
  82449. }
  82450. });
  82451. if (from.length > 0 && to.length > 0) {
  82452. transitionBetween(from, to, api);
  82453. }
  82454. }
  82455. function installUniversalTransition(registers) {
  82456. registers.registerUpdateLifecycle('series:beforeupdate', function (ecMOdel, api, params) {
  82457. each(normalizeToArray(params.seriesTransition), function (transOpt) {
  82458. each(normalizeToArray(transOpt.to), function (finder) {
  82459. var series = params.updatedSeries;
  82460. for (var i = 0; i < series.length; i++) {
  82461. if (finder.seriesIndex != null && finder.seriesIndex === series[i].seriesIndex || finder.seriesId != null && finder.seriesId === series[i].id) {
  82462. series[i][SERIES_UNIVERSAL_TRANSITION_PROP] = true;
  82463. }
  82464. }
  82465. });
  82466. });
  82467. });
  82468. registers.registerUpdateLifecycle('series:transition', function (ecModel, api, params) {
  82469. // TODO api provide an namespace that can save stuff per instance
  82470. var globalStore = getUniversalTransitionGlobalStore(api); // TODO multiple to multiple series.
  82471. if (globalStore.oldSeries && params.updatedSeries && params.optionChanged) {
  82472. // Use give transition config if its' give;
  82473. var transitionOpt = params.seriesTransition;
  82474. if (transitionOpt) {
  82475. each(normalizeToArray(transitionOpt), function (opt) {
  82476. transitionSeriesFromOpt(opt, globalStore, params, api);
  82477. });
  82478. } else {
  82479. // Else guess from series based on transition series key.
  82480. var updateBatches_1 = findTransitionSeriesBatches(globalStore, params);
  82481. each(updateBatches_1.keys(), function (key) {
  82482. var batch = updateBatches_1.get(key);
  82483. transitionBetween(batch.oldSeries, batch.newSeries, api);
  82484. });
  82485. } // Reset
  82486. each(params.updatedSeries, function (series) {
  82487. // Reset;
  82488. if (series[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  82489. series[SERIES_UNIVERSAL_TRANSITION_PROP] = false;
  82490. }
  82491. });
  82492. } // Save all series of current update. Not only the updated one.
  82493. var allSeries = ecModel.getSeries();
  82494. var savedSeries = globalStore.oldSeries = [];
  82495. var savedDataGroupIds = globalStore.oldDataGroupIds = [];
  82496. var savedData = globalStore.oldData = [];
  82497. for (var i = 0; i < allSeries.length; i++) {
  82498. var data = allSeries[i].getData(); // Only save the data that can have transition.
  82499. // Avoid large data costing too much extra memory
  82500. if (data.count() < DATA_COUNT_THRESHOLD) {
  82501. savedSeries.push(allSeries[i]);
  82502. savedDataGroupIds.push(allSeries[i].get('dataGroupId'));
  82503. savedData.push(data);
  82504. }
  82505. }
  82506. });
  82507. }
  82508. // Render engines
  82509. // -----------------
  82510. // Render via Canvas.
  82511. // echarts.init(dom, null, { renderer: 'canvas' })
  82512. use([install$1]); // Render via SVG.
  82513. // echarts.init(dom, null, { renderer: 'svg' })
  82514. use([install]); // ----------------
  82515. // Charts (series)
  82516. // ----------------
  82517. // All of the series types, for example:
  82518. // chart.setOption({
  82519. // series: [{
  82520. // type: 'line' // or 'bar', 'pie', ...
  82521. // }]
  82522. // });
  82523. use([install$2, install$3, install$4, install$6, install$8, install$a, install$b, install$c, install$d, install$e, install$f, install$h, install$i, install$j, install$k, install$l, install$m, install$n, install$o, install$p, install$q, install$r]); // -------------------
  82524. // Coordinate systems
  82525. // -------------------
  82526. // All of the axis modules have been included in the
  82527. // coordinate system module below, do not need to
  82528. // make extra import.
  82529. // `cartesian` coordinate system. For some historical
  82530. // reasons, it is named as grid, for example:
  82531. // chart.setOption({
  82532. // grid: {...},
  82533. // xAxis: {...},
  82534. // yAxis: {...},
  82535. // series: [{...}]
  82536. // });
  82537. use(install$t); // `polar` coordinate system, for example:
  82538. // chart.setOption({
  82539. // polar: {...},
  82540. // radiusAxis: {...},
  82541. // angleAxis: {...},
  82542. // series: [{
  82543. // coordinateSystem: 'polar'
  82544. // }]
  82545. // });
  82546. use(install$u); // `geo` coordinate system, for example:
  82547. // chart.setOption({
  82548. // geo: {...},
  82549. // series: [{
  82550. // coordinateSystem: 'geo'
  82551. // }]
  82552. // });
  82553. use(install$9); // `singleAxis` coordinate system (notice, it is a coordinate system
  82554. // with only one axis, work for chart like theme river), for example:
  82555. // chart.setOption({
  82556. // singleAxis: {...}
  82557. // series: [{type: 'themeRiver', ...}]
  82558. // });
  82559. use(install$v); // `parallel` coordinate system, only work for parallel series, for example:
  82560. // chart.setOption({
  82561. // parallel: {...},
  82562. // parallelAxis: [{...}, ...],
  82563. // series: [{
  82564. // type: 'parallel'
  82565. // }]
  82566. // });
  82567. use(install$g); // `calendar` coordinate system. for example,
  82568. // chart.setOptionp({
  82569. // calendar: {...},
  82570. // series: [{
  82571. // coordinateSystem: 'calendar'
  82572. // }]
  82573. // );
  82574. use(install$w); // ------------------
  82575. // Other components
  82576. // ------------------
  82577. // `graphic` component, for example:
  82578. // chart.setOption({
  82579. // graphic: {...}
  82580. // });
  82581. use(install$x); // `toolbox` component, for example:
  82582. // chart.setOption({
  82583. // toolbox: {...}
  82584. // });
  82585. use(install$z); // `tooltip` component, for example:
  82586. // chart.setOption({
  82587. // tooltip: {...}
  82588. // });
  82589. use(install$A); // `axisPointer` component, for example:
  82590. // chart.setOption({
  82591. // tooltip: {axisPointer: {...}, ...}
  82592. // });
  82593. // Or
  82594. // chart.setOption({
  82595. // axisPointer: {...}
  82596. // });
  82597. use(install$s); // `brush` component, for example:
  82598. // chart.setOption({
  82599. // brush: {...}
  82600. // });
  82601. // Or
  82602. // chart.setOption({
  82603. // tooltip: {feature: {brush: {...}}
  82604. // })
  82605. use(install$B); // `title` component, for example:
  82606. // chart.setOption({
  82607. // title: {...}
  82608. // });
  82609. use(install$C); // `timeline` component, for example:
  82610. // chart.setOption({
  82611. // timeline: {...}
  82612. // });
  82613. use(install$D); // `markPoint` component, for example:
  82614. // chart.setOption({
  82615. // series: [{markPoint: {...}}]
  82616. // });
  82617. use(install$E); // `markLine` component, for example:
  82618. // chart.setOption({
  82619. // series: [{markLine: {...}}]
  82620. // });
  82621. use(install$F); // `markArea` component, for example:
  82622. // chart.setOption({
  82623. // series: [{markArea: {...}}]
  82624. // });
  82625. use(install$G); // `legend` component not scrollable. for example:
  82626. // chart.setOption({
  82627. // legend: {...}
  82628. // });
  82629. use(install$J); // `dataZoom` component including both `dataZoomInside` and `dataZoomSlider`.
  82630. use(install$M); // `dataZoom` component providing drag, pinch, wheel behaviors
  82631. // inside coodinate system, for example:
  82632. // chart.setOption({
  82633. // dataZoom: {type: 'inside'}
  82634. // });
  82635. use(install$K); // `dataZoom` component providing a slider bar, for example:
  82636. // chart.setOption({
  82637. // dataZoom: {type: 'slider'}
  82638. // });
  82639. use(install$L); // `visualMap` component including both `visualMapContinuous` and `visualMapPiecewise`.
  82640. use(install$P); // `visualMap` component providing continuous bar, for example:
  82641. // chart.setOption({
  82642. // visualMap: {type: 'continuous'}
  82643. // });
  82644. use(install$N); // `visualMap` component providing pieces bar, for example:
  82645. // chart.setOption({
  82646. // visualMap: {type: 'piecewise'}
  82647. // });
  82648. use(install$O); // `aria` component providing aria, for example:
  82649. // chart.setOption({
  82650. // aria: {...}
  82651. // });
  82652. use(install$Q); // dataset transform
  82653. // chart.setOption({
  82654. // dataset: {
  82655. // transform: []
  82656. // }
  82657. // });
  82658. use(install$R);
  82659. use(install$S); // universal transition
  82660. // chart.setOption({
  82661. // series: {
  82662. // universalTransition: { enabled: true }
  82663. // }
  82664. // })
  82665. use(installUniversalTransition); // label layout
  82666. // chart.setOption({
  82667. // series: {
  82668. // labelLayout: { hideOverlap: true }
  82669. // }
  82670. // })
  82671. use(installLabelLayout);
  82672. exports.Axis = Axis;
  82673. exports.ChartView = ChartView;
  82674. exports.ComponentModel = ComponentModel;
  82675. exports.ComponentView = ComponentView;
  82676. exports.List = SeriesData;
  82677. exports.Model = Model;
  82678. exports.PRIORITY = PRIORITY;
  82679. exports.SeriesModel = SeriesModel;
  82680. exports.color = color;
  82681. exports.connect = connect;
  82682. exports.dataTool = dataTool;
  82683. exports.dependencies = dependencies;
  82684. exports.disConnect = disConnect;
  82685. exports.disconnect = disconnect;
  82686. exports.dispose = dispose$1;
  82687. exports.env = env;
  82688. exports.extendChartView = extendChartView;
  82689. exports.extendComponentModel = extendComponentModel;
  82690. exports.extendComponentView = extendComponentView;
  82691. exports.extendSeriesModel = extendSeriesModel;
  82692. exports.format = format$1;
  82693. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  82694. exports.getInstanceByDom = getInstanceByDom;
  82695. exports.getInstanceById = getInstanceById;
  82696. exports.getMap = getMap;
  82697. exports.graphic = graphic$1;
  82698. exports.helper = helper;
  82699. exports.init = init$1;
  82700. exports.innerDrawElementOnCanvas = brushSingle;
  82701. exports.matrix = matrix;
  82702. exports.number = number;
  82703. exports.parseGeoJSON = parseGeoJSON;
  82704. exports.parseGeoJson = parseGeoJSON;
  82705. exports.registerAction = registerAction;
  82706. exports.registerCoordinateSystem = registerCoordinateSystem;
  82707. exports.registerLayout = registerLayout;
  82708. exports.registerLoading = registerLoading;
  82709. exports.registerLocale = registerLocale;
  82710. exports.registerMap = registerMap;
  82711. exports.registerPostInit = registerPostInit;
  82712. exports.registerPostUpdate = registerPostUpdate;
  82713. exports.registerPreprocessor = registerPreprocessor;
  82714. exports.registerProcessor = registerProcessor;
  82715. exports.registerTheme = registerTheme;
  82716. exports.registerTransform = registerTransform;
  82717. exports.registerUpdateLifecycle = registerUpdateLifecycle;
  82718. exports.registerVisual = registerVisual;
  82719. exports.setCanvasCreator = setCanvasCreator;
  82720. exports.setPlatformAPI = setPlatformAPI;
  82721. exports.throttle = throttle;
  82722. exports.time = time;
  82723. exports.use = use;
  82724. exports.util = util$1;
  82725. exports.vector = vector;
  82726. exports.version = version$1;
  82727. exports.zrUtil = util;
  82728. exports.zrender = zrender;
  82729. Object.defineProperty(exports, '__esModule', { value: true });
  82730. })));
  82731. //# sourceMappingURL=echarts.js.map