echarts.js 3.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.echarts = {}));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. (function (global, factory) {
  25. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  26. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  27. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.echarts = {}));
  28. }(this, (function (exports) { 'use strict';
  29. /*! *****************************************************************************
  30. Copyright (c) Microsoft Corporation.
  31. Permission to use, copy, modify, and/or distribute this software for any
  32. purpose with or without fee is hereby granted.
  33. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  34. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  35. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  36. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  37. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  38. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  39. PERFORMANCE OF THIS SOFTWARE.
  40. ***************************************************************************** */
  41. /* global Reflect, Promise */
  42. var extendStatics = function(d, b) {
  43. extendStatics = Object.setPrototypeOf ||
  44. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  45. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  46. return extendStatics(d, b);
  47. };
  48. function __extends(d, b) {
  49. if (typeof b !== "function" && b !== null)
  50. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  51. extendStatics(d, b);
  52. function __() { this.constructor = d; }
  53. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  54. }
  55. var __assign = function() {
  56. __assign = Object.assign || function __assign(t) {
  57. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58. s = arguments[i];
  59. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  60. }
  61. return t;
  62. };
  63. return __assign.apply(this, arguments);
  64. };
  65. function __spreadArray(to, from, pack) {
  66. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  67. if (ar || !(i in from)) {
  68. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  69. ar[i] = from[i];
  70. }
  71. }
  72. return to.concat(ar || from);
  73. }
  74. var Browser = (function () {
  75. function Browser() {
  76. this.firefox = false;
  77. this.ie = false;
  78. this.edge = false;
  79. this.newEdge = false;
  80. this.weChat = false;
  81. }
  82. return Browser;
  83. }());
  84. var Env = (function () {
  85. function Env() {
  86. this.browser = new Browser();
  87. this.node = false;
  88. this.wxa = false;
  89. this.worker = false;
  90. this.canvasSupported = false;
  91. this.svgSupported = false;
  92. this.touchEventsSupported = false;
  93. this.pointerEventsSupported = false;
  94. this.domSupported = false;
  95. this.transformSupported = false;
  96. this.transform3dSupported = false;
  97. }
  98. return Env;
  99. }());
  100. var env = new Env();
  101. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  102. env.wxa = true;
  103. env.canvasSupported = true;
  104. env.touchEventsSupported = true;
  105. }
  106. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  107. env.worker = true;
  108. env.canvasSupported = true;
  109. }
  110. else if (typeof navigator === 'undefined') {
  111. env.node = true;
  112. env.canvasSupported = true;
  113. env.svgSupported = true;
  114. }
  115. else {
  116. detect(navigator.userAgent, env);
  117. }
  118. function detect(ua, env) {
  119. var browser = env.browser;
  120. var firefox = ua.match(/Firefox\/([\d.]+)/);
  121. var ie = ua.match(/MSIE\s([\d.]+)/)
  122. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  123. var edge = ua.match(/Edge?\/([\d.]+)/);
  124. var weChat = (/micromessenger/i).test(ua);
  125. if (firefox) {
  126. browser.firefox = true;
  127. browser.version = firefox[1];
  128. }
  129. if (ie) {
  130. browser.ie = true;
  131. browser.version = ie[1];
  132. }
  133. if (edge) {
  134. browser.edge = true;
  135. browser.version = edge[1];
  136. browser.newEdge = +edge[1].split('.')[0] > 18;
  137. }
  138. if (weChat) {
  139. browser.weChat = true;
  140. }
  141. env.canvasSupported = !!document.createElement('canvas').getContext;
  142. env.svgSupported = typeof SVGRect !== 'undefined';
  143. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  144. env.pointerEventsSupported = 'onpointerdown' in window
  145. && (browser.edge || (browser.ie && +browser.version >= 11));
  146. env.domSupported = typeof document !== 'undefined';
  147. var style = document.documentElement.style;
  148. env.transform3dSupported = ((browser.ie && 'transition' in style)
  149. || browser.edge
  150. || (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
  151. || 'MozPerspective' in style)
  152. && !('OTransition' in style);
  153. env.transformSupported = env.transform3dSupported
  154. || (browser.ie && +browser.version >= 9);
  155. }
  156. var BUILTIN_OBJECT = {
  157. '[object Function]': true,
  158. '[object RegExp]': true,
  159. '[object Date]': true,
  160. '[object Error]': true,
  161. '[object CanvasGradient]': true,
  162. '[object CanvasPattern]': true,
  163. '[object Image]': true,
  164. '[object Canvas]': true
  165. };
  166. var TYPED_ARRAY = {
  167. '[object Int8Array]': true,
  168. '[object Uint8Array]': true,
  169. '[object Uint8ClampedArray]': true,
  170. '[object Int16Array]': true,
  171. '[object Uint16Array]': true,
  172. '[object Int32Array]': true,
  173. '[object Uint32Array]': true,
  174. '[object Float32Array]': true,
  175. '[object Float64Array]': true
  176. };
  177. var objToString = Object.prototype.toString;
  178. var arrayProto = Array.prototype;
  179. var nativeForEach = arrayProto.forEach;
  180. var nativeFilter = arrayProto.filter;
  181. var nativeSlice = arrayProto.slice;
  182. var nativeMap = arrayProto.map;
  183. var ctorFunction = function () { }.constructor;
  184. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  185. var methods = {};
  186. function $override(name, fn) {
  187. methods[name] = fn;
  188. }
  189. var idStart = 0x0907;
  190. function guid() {
  191. return idStart++;
  192. }
  193. function logError() {
  194. var args = [];
  195. for (var _i = 0; _i < arguments.length; _i++) {
  196. args[_i] = arguments[_i];
  197. }
  198. if (typeof console !== 'undefined') {
  199. console.error.apply(console, args);
  200. }
  201. }
  202. function clone(source) {
  203. if (source == null || typeof source !== 'object') {
  204. return source;
  205. }
  206. var result = source;
  207. var typeStr = objToString.call(source);
  208. if (typeStr === '[object Array]') {
  209. if (!isPrimitive(source)) {
  210. result = [];
  211. for (var i = 0, len = source.length; i < len; i++) {
  212. result[i] = clone(source[i]);
  213. }
  214. }
  215. }
  216. else if (TYPED_ARRAY[typeStr]) {
  217. if (!isPrimitive(source)) {
  218. var Ctor = source.constructor;
  219. if (Ctor.from) {
  220. result = Ctor.from(source);
  221. }
  222. else {
  223. result = new Ctor(source.length);
  224. for (var i = 0, len = source.length; i < len; i++) {
  225. result[i] = clone(source[i]);
  226. }
  227. }
  228. }
  229. }
  230. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  231. result = {};
  232. for (var key in source) {
  233. if (source.hasOwnProperty(key)) {
  234. result[key] = clone(source[key]);
  235. }
  236. }
  237. }
  238. return result;
  239. }
  240. function merge(target, source, overwrite) {
  241. if (!isObject(source) || !isObject(target)) {
  242. return overwrite ? clone(source) : target;
  243. }
  244. for (var key in source) {
  245. if (source.hasOwnProperty(key)) {
  246. var targetProp = target[key];
  247. var sourceProp = source[key];
  248. if (isObject(sourceProp)
  249. && isObject(targetProp)
  250. && !isArray(sourceProp)
  251. && !isArray(targetProp)
  252. && !isDom(sourceProp)
  253. && !isDom(targetProp)
  254. && !isBuiltInObject(sourceProp)
  255. && !isBuiltInObject(targetProp)
  256. && !isPrimitive(sourceProp)
  257. && !isPrimitive(targetProp)) {
  258. merge(targetProp, sourceProp, overwrite);
  259. }
  260. else if (overwrite || !(key in target)) {
  261. target[key] = clone(source[key]);
  262. }
  263. }
  264. }
  265. return target;
  266. }
  267. function mergeAll(targetAndSources, overwrite) {
  268. var result = targetAndSources[0];
  269. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  270. result = merge(result, targetAndSources[i], overwrite);
  271. }
  272. return result;
  273. }
  274. function extend(target, source) {
  275. if (Object.assign) {
  276. Object.assign(target, source);
  277. }
  278. else {
  279. for (var key in source) {
  280. if (source.hasOwnProperty(key)) {
  281. target[key] = source[key];
  282. }
  283. }
  284. }
  285. return target;
  286. }
  287. function defaults(target, source, overlay) {
  288. var keysArr = keys(source);
  289. for (var i = 0; i < keysArr.length; i++) {
  290. var key = keysArr[i];
  291. if ((overlay ? source[key] != null : target[key] == null)) {
  292. target[key] = source[key];
  293. }
  294. }
  295. return target;
  296. }
  297. var createCanvas = function () {
  298. return methods.createCanvas();
  299. };
  300. methods.createCanvas = function () {
  301. return document.createElement('canvas');
  302. };
  303. function indexOf(array, value) {
  304. if (array) {
  305. if (array.indexOf) {
  306. return array.indexOf(value);
  307. }
  308. for (var i = 0, len = array.length; i < len; i++) {
  309. if (array[i] === value) {
  310. return i;
  311. }
  312. }
  313. }
  314. return -1;
  315. }
  316. function inherits(clazz, baseClazz) {
  317. var clazzPrototype = clazz.prototype;
  318. function F() { }
  319. F.prototype = baseClazz.prototype;
  320. clazz.prototype = new F();
  321. for (var prop in clazzPrototype) {
  322. if (clazzPrototype.hasOwnProperty(prop)) {
  323. clazz.prototype[prop] = clazzPrototype[prop];
  324. }
  325. }
  326. clazz.prototype.constructor = clazz;
  327. clazz.superClass = baseClazz;
  328. }
  329. function mixin(target, source, override) {
  330. target = 'prototype' in target ? target.prototype : target;
  331. source = 'prototype' in source ? source.prototype : source;
  332. if (Object.getOwnPropertyNames) {
  333. var keyList = Object.getOwnPropertyNames(source);
  334. for (var i = 0; i < keyList.length; i++) {
  335. var key = keyList[i];
  336. if (key !== 'constructor') {
  337. if ((override ? source[key] != null : target[key] == null)) {
  338. target[key] = source[key];
  339. }
  340. }
  341. }
  342. }
  343. else {
  344. defaults(target, source, override);
  345. }
  346. }
  347. function isArrayLike(data) {
  348. if (!data) {
  349. return false;
  350. }
  351. if (typeof data === 'string') {
  352. return false;
  353. }
  354. return typeof data.length === 'number';
  355. }
  356. function each(arr, cb, context) {
  357. if (!(arr && cb)) {
  358. return;
  359. }
  360. if (arr.forEach && arr.forEach === nativeForEach) {
  361. arr.forEach(cb, context);
  362. }
  363. else if (arr.length === +arr.length) {
  364. for (var i = 0, len = arr.length; i < len; i++) {
  365. cb.call(context, arr[i], i, arr);
  366. }
  367. }
  368. else {
  369. for (var key in arr) {
  370. if (arr.hasOwnProperty(key)) {
  371. cb.call(context, arr[key], key, arr);
  372. }
  373. }
  374. }
  375. }
  376. function map(arr, cb, context) {
  377. if (!arr) {
  378. return [];
  379. }
  380. if (!cb) {
  381. return slice(arr);
  382. }
  383. if (arr.map && arr.map === nativeMap) {
  384. return arr.map(cb, context);
  385. }
  386. else {
  387. var result = [];
  388. for (var i = 0, len = arr.length; i < len; i++) {
  389. result.push(cb.call(context, arr[i], i, arr));
  390. }
  391. return result;
  392. }
  393. }
  394. function reduce(arr, cb, memo, context) {
  395. if (!(arr && cb)) {
  396. return;
  397. }
  398. for (var i = 0, len = arr.length; i < len; i++) {
  399. memo = cb.call(context, memo, arr[i], i, arr);
  400. }
  401. return memo;
  402. }
  403. function filter(arr, cb, context) {
  404. if (!arr) {
  405. return [];
  406. }
  407. if (!cb) {
  408. return slice(arr);
  409. }
  410. if (arr.filter && arr.filter === nativeFilter) {
  411. return arr.filter(cb, context);
  412. }
  413. else {
  414. var result = [];
  415. for (var i = 0, len = arr.length; i < len; i++) {
  416. if (cb.call(context, arr[i], i, arr)) {
  417. result.push(arr[i]);
  418. }
  419. }
  420. return result;
  421. }
  422. }
  423. function find(arr, cb, context) {
  424. if (!(arr && cb)) {
  425. return;
  426. }
  427. for (var i = 0, len = arr.length; i < len; i++) {
  428. if (cb.call(context, arr[i], i, arr)) {
  429. return arr[i];
  430. }
  431. }
  432. }
  433. function keys(obj) {
  434. if (!obj) {
  435. return [];
  436. }
  437. if (Object.keys) {
  438. return Object.keys(obj);
  439. }
  440. var keyList = [];
  441. for (var key in obj) {
  442. if (obj.hasOwnProperty(key)) {
  443. keyList.push(key);
  444. }
  445. }
  446. return keyList;
  447. }
  448. function bindPolyfill(func, context) {
  449. var args = [];
  450. for (var _i = 2; _i < arguments.length; _i++) {
  451. args[_i - 2] = arguments[_i];
  452. }
  453. return function () {
  454. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  455. };
  456. }
  457. var bind = (protoFunction && isFunction(protoFunction.bind))
  458. ? protoFunction.call.bind(protoFunction.bind)
  459. : bindPolyfill;
  460. function curry(func) {
  461. var args = [];
  462. for (var _i = 1; _i < arguments.length; _i++) {
  463. args[_i - 1] = arguments[_i];
  464. }
  465. return function () {
  466. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  467. };
  468. }
  469. function isArray(value) {
  470. if (Array.isArray) {
  471. return Array.isArray(value);
  472. }
  473. return objToString.call(value) === '[object Array]';
  474. }
  475. function isFunction(value) {
  476. return typeof value === 'function';
  477. }
  478. function isString(value) {
  479. return typeof value === 'string';
  480. }
  481. function isStringSafe(value) {
  482. return objToString.call(value) === '[object String]';
  483. }
  484. function isNumber(value) {
  485. return typeof value === 'number';
  486. }
  487. function isObject(value) {
  488. var type = typeof value;
  489. return type === 'function' || (!!value && type === 'object');
  490. }
  491. function isBuiltInObject(value) {
  492. return !!BUILTIN_OBJECT[objToString.call(value)];
  493. }
  494. function isTypedArray(value) {
  495. return !!TYPED_ARRAY[objToString.call(value)];
  496. }
  497. function isDom(value) {
  498. return typeof value === 'object'
  499. && typeof value.nodeType === 'number'
  500. && typeof value.ownerDocument === 'object';
  501. }
  502. function isGradientObject(value) {
  503. return value.colorStops != null;
  504. }
  505. function isImagePatternObject(value) {
  506. return value.image != null;
  507. }
  508. function isRegExp(value) {
  509. return objToString.call(value) === '[object RegExp]';
  510. }
  511. function eqNaN(value) {
  512. return value !== value;
  513. }
  514. function retrieve() {
  515. var args = [];
  516. for (var _i = 0; _i < arguments.length; _i++) {
  517. args[_i] = arguments[_i];
  518. }
  519. for (var i = 0, len = args.length; i < len; i++) {
  520. if (args[i] != null) {
  521. return args[i];
  522. }
  523. }
  524. }
  525. function retrieve2(value0, value1) {
  526. return value0 != null
  527. ? value0
  528. : value1;
  529. }
  530. function retrieve3(value0, value1, value2) {
  531. return value0 != null
  532. ? value0
  533. : value1 != null
  534. ? value1
  535. : value2;
  536. }
  537. function slice(arr) {
  538. var args = [];
  539. for (var _i = 1; _i < arguments.length; _i++) {
  540. args[_i - 1] = arguments[_i];
  541. }
  542. return nativeSlice.apply(arr, args);
  543. }
  544. function normalizeCssArray(val) {
  545. if (typeof (val) === 'number') {
  546. return [val, val, val, val];
  547. }
  548. var len = val.length;
  549. if (len === 2) {
  550. return [val[0], val[1], val[0], val[1]];
  551. }
  552. else if (len === 3) {
  553. return [val[0], val[1], val[2], val[1]];
  554. }
  555. return val;
  556. }
  557. function assert(condition, message) {
  558. if (!condition) {
  559. throw new Error(message);
  560. }
  561. }
  562. function trim(str) {
  563. if (str == null) {
  564. return null;
  565. }
  566. else if (typeof str.trim === 'function') {
  567. return str.trim();
  568. }
  569. else {
  570. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  571. }
  572. }
  573. var primitiveKey = '__ec_primitive__';
  574. function setAsPrimitive(obj) {
  575. obj[primitiveKey] = true;
  576. }
  577. function isPrimitive(obj) {
  578. return obj[primitiveKey];
  579. }
  580. var HashMap = (function () {
  581. function HashMap(obj) {
  582. this.data = {};
  583. var isArr = isArray(obj);
  584. this.data = {};
  585. var thisMap = this;
  586. (obj instanceof HashMap)
  587. ? obj.each(visit)
  588. : (obj && each(obj, visit));
  589. function visit(value, key) {
  590. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  591. }
  592. }
  593. HashMap.prototype.get = function (key) {
  594. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  595. };
  596. HashMap.prototype.set = function (key, value) {
  597. return (this.data[key] = value);
  598. };
  599. HashMap.prototype.each = function (cb, context) {
  600. for (var key in this.data) {
  601. if (this.data.hasOwnProperty(key)) {
  602. cb.call(context, this.data[key], key);
  603. }
  604. }
  605. };
  606. HashMap.prototype.keys = function () {
  607. return keys(this.data);
  608. };
  609. HashMap.prototype.removeKey = function (key) {
  610. delete this.data[key];
  611. };
  612. return HashMap;
  613. }());
  614. function createHashMap(obj) {
  615. return new HashMap(obj);
  616. }
  617. function concatArray(a, b) {
  618. var newArray = new a.constructor(a.length + b.length);
  619. for (var i = 0; i < a.length; i++) {
  620. newArray[i] = a[i];
  621. }
  622. var offset = a.length;
  623. for (var i = 0; i < b.length; i++) {
  624. newArray[i + offset] = b[i];
  625. }
  626. return newArray;
  627. }
  628. function createObject(proto, properties) {
  629. var obj;
  630. if (Object.create) {
  631. obj = Object.create(proto);
  632. }
  633. else {
  634. var StyleCtor = function () { };
  635. StyleCtor.prototype = proto;
  636. obj = new StyleCtor();
  637. }
  638. if (properties) {
  639. extend(obj, properties);
  640. }
  641. return obj;
  642. }
  643. function hasOwn(own, prop) {
  644. return own.hasOwnProperty(prop);
  645. }
  646. function noop() { }
  647. var util = /*#__PURE__*/Object.freeze({
  648. __proto__: null,
  649. $override: $override,
  650. guid: guid,
  651. logError: logError,
  652. clone: clone,
  653. merge: merge,
  654. mergeAll: mergeAll,
  655. extend: extend,
  656. defaults: defaults,
  657. createCanvas: createCanvas,
  658. indexOf: indexOf,
  659. inherits: inherits,
  660. mixin: mixin,
  661. isArrayLike: isArrayLike,
  662. each: each,
  663. map: map,
  664. reduce: reduce,
  665. filter: filter,
  666. find: find,
  667. keys: keys,
  668. bind: bind,
  669. curry: curry,
  670. isArray: isArray,
  671. isFunction: isFunction,
  672. isString: isString,
  673. isStringSafe: isStringSafe,
  674. isNumber: isNumber,
  675. isObject: isObject,
  676. isBuiltInObject: isBuiltInObject,
  677. isTypedArray: isTypedArray,
  678. isDom: isDom,
  679. isGradientObject: isGradientObject,
  680. isImagePatternObject: isImagePatternObject,
  681. isRegExp: isRegExp,
  682. eqNaN: eqNaN,
  683. retrieve: retrieve,
  684. retrieve2: retrieve2,
  685. retrieve3: retrieve3,
  686. slice: slice,
  687. normalizeCssArray: normalizeCssArray,
  688. assert: assert,
  689. trim: trim,
  690. setAsPrimitive: setAsPrimitive,
  691. isPrimitive: isPrimitive,
  692. HashMap: HashMap,
  693. createHashMap: createHashMap,
  694. concatArray: concatArray,
  695. createObject: createObject,
  696. hasOwn: hasOwn,
  697. noop: noop
  698. });
  699. function create(x, y) {
  700. if (x == null) {
  701. x = 0;
  702. }
  703. if (y == null) {
  704. y = 0;
  705. }
  706. return [x, y];
  707. }
  708. function copy(out, v) {
  709. out[0] = v[0];
  710. out[1] = v[1];
  711. return out;
  712. }
  713. function clone$1(v) {
  714. return [v[0], v[1]];
  715. }
  716. function set(out, a, b) {
  717. out[0] = a;
  718. out[1] = b;
  719. return out;
  720. }
  721. function add(out, v1, v2) {
  722. out[0] = v1[0] + v2[0];
  723. out[1] = v1[1] + v2[1];
  724. return out;
  725. }
  726. function scaleAndAdd(out, v1, v2, a) {
  727. out[0] = v1[0] + v2[0] * a;
  728. out[1] = v1[1] + v2[1] * a;
  729. return out;
  730. }
  731. function sub(out, v1, v2) {
  732. out[0] = v1[0] - v2[0];
  733. out[1] = v1[1] - v2[1];
  734. return out;
  735. }
  736. function len(v) {
  737. return Math.sqrt(lenSquare(v));
  738. }
  739. var length = len;
  740. function lenSquare(v) {
  741. return v[0] * v[0] + v[1] * v[1];
  742. }
  743. var lengthSquare = lenSquare;
  744. function mul(out, v1, v2) {
  745. out[0] = v1[0] * v2[0];
  746. out[1] = v1[1] * v2[1];
  747. return out;
  748. }
  749. function div(out, v1, v2) {
  750. out[0] = v1[0] / v2[0];
  751. out[1] = v1[1] / v2[1];
  752. return out;
  753. }
  754. function dot(v1, v2) {
  755. return v1[0] * v2[0] + v1[1] * v2[1];
  756. }
  757. function scale(out, v, s) {
  758. out[0] = v[0] * s;
  759. out[1] = v[1] * s;
  760. return out;
  761. }
  762. function normalize(out, v) {
  763. var d = len(v);
  764. if (d === 0) {
  765. out[0] = 0;
  766. out[1] = 0;
  767. }
  768. else {
  769. out[0] = v[0] / d;
  770. out[1] = v[1] / d;
  771. }
  772. return out;
  773. }
  774. function distance(v1, v2) {
  775. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  776. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  777. }
  778. var dist = distance;
  779. function distanceSquare(v1, v2) {
  780. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  781. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  782. }
  783. var distSquare = distanceSquare;
  784. function negate(out, v) {
  785. out[0] = -v[0];
  786. out[1] = -v[1];
  787. return out;
  788. }
  789. function lerp(out, v1, v2, t) {
  790. out[0] = v1[0] + t * (v2[0] - v1[0]);
  791. out[1] = v1[1] + t * (v2[1] - v1[1]);
  792. return out;
  793. }
  794. function applyTransform(out, v, m) {
  795. var x = v[0];
  796. var y = v[1];
  797. out[0] = m[0] * x + m[2] * y + m[4];
  798. out[1] = m[1] * x + m[3] * y + m[5];
  799. return out;
  800. }
  801. function min(out, v1, v2) {
  802. out[0] = Math.min(v1[0], v2[0]);
  803. out[1] = Math.min(v1[1], v2[1]);
  804. return out;
  805. }
  806. function max(out, v1, v2) {
  807. out[0] = Math.max(v1[0], v2[0]);
  808. out[1] = Math.max(v1[1], v2[1]);
  809. return out;
  810. }
  811. var vector = /*#__PURE__*/Object.freeze({
  812. __proto__: null,
  813. create: create,
  814. copy: copy,
  815. clone: clone$1,
  816. set: set,
  817. add: add,
  818. scaleAndAdd: scaleAndAdd,
  819. sub: sub,
  820. len: len,
  821. length: length,
  822. lenSquare: lenSquare,
  823. lengthSquare: lengthSquare,
  824. mul: mul,
  825. div: div,
  826. dot: dot,
  827. scale: scale,
  828. normalize: normalize,
  829. distance: distance,
  830. dist: dist,
  831. distanceSquare: distanceSquare,
  832. distSquare: distSquare,
  833. negate: negate,
  834. lerp: lerp,
  835. applyTransform: applyTransform,
  836. min: min,
  837. max: max
  838. });
  839. var Param = (function () {
  840. function Param(target, e) {
  841. this.target = target;
  842. this.topTarget = e && e.topTarget;
  843. }
  844. return Param;
  845. }());
  846. var Draggable = (function () {
  847. function Draggable(handler) {
  848. this.handler = handler;
  849. handler.on('mousedown', this._dragStart, this);
  850. handler.on('mousemove', this._drag, this);
  851. handler.on('mouseup', this._dragEnd, this);
  852. }
  853. Draggable.prototype._dragStart = function (e) {
  854. var draggingTarget = e.target;
  855. while (draggingTarget && !draggingTarget.draggable) {
  856. draggingTarget = draggingTarget.parent;
  857. }
  858. if (draggingTarget) {
  859. this._draggingTarget = draggingTarget;
  860. draggingTarget.dragging = true;
  861. this._x = e.offsetX;
  862. this._y = e.offsetY;
  863. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  864. }
  865. };
  866. Draggable.prototype._drag = function (e) {
  867. var draggingTarget = this._draggingTarget;
  868. if (draggingTarget) {
  869. var x = e.offsetX;
  870. var y = e.offsetY;
  871. var dx = x - this._x;
  872. var dy = y - this._y;
  873. this._x = x;
  874. this._y = y;
  875. draggingTarget.drift(dx, dy, e);
  876. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  877. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  878. var lastDropTarget = this._dropTarget;
  879. this._dropTarget = dropTarget;
  880. if (draggingTarget !== dropTarget) {
  881. if (lastDropTarget && dropTarget !== lastDropTarget) {
  882. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  883. }
  884. if (dropTarget && dropTarget !== lastDropTarget) {
  885. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  886. }
  887. }
  888. }
  889. };
  890. Draggable.prototype._dragEnd = function (e) {
  891. var draggingTarget = this._draggingTarget;
  892. if (draggingTarget) {
  893. draggingTarget.dragging = false;
  894. }
  895. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  896. if (this._dropTarget) {
  897. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  898. }
  899. this._draggingTarget = null;
  900. this._dropTarget = null;
  901. };
  902. return Draggable;
  903. }());
  904. var Eventful = (function () {
  905. function Eventful(eventProcessors) {
  906. if (eventProcessors) {
  907. this._$eventProcessor = eventProcessors;
  908. }
  909. }
  910. Eventful.prototype.on = function (event, query, handler, context) {
  911. if (!this._$handlers) {
  912. this._$handlers = {};
  913. }
  914. var _h = this._$handlers;
  915. if (typeof query === 'function') {
  916. context = handler;
  917. handler = query;
  918. query = null;
  919. }
  920. if (!handler || !event) {
  921. return this;
  922. }
  923. var eventProcessor = this._$eventProcessor;
  924. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  925. query = eventProcessor.normalizeQuery(query);
  926. }
  927. if (!_h[event]) {
  928. _h[event] = [];
  929. }
  930. for (var i = 0; i < _h[event].length; i++) {
  931. if (_h[event][i].h === handler) {
  932. return this;
  933. }
  934. }
  935. var wrap = {
  936. h: handler,
  937. query: query,
  938. ctx: (context || this),
  939. callAtLast: handler.zrEventfulCallAtLast
  940. };
  941. var lastIndex = _h[event].length - 1;
  942. var lastWrap = _h[event][lastIndex];
  943. (lastWrap && lastWrap.callAtLast)
  944. ? _h[event].splice(lastIndex, 0, wrap)
  945. : _h[event].push(wrap);
  946. return this;
  947. };
  948. Eventful.prototype.isSilent = function (eventName) {
  949. var _h = this._$handlers;
  950. return !_h || !_h[eventName] || !_h[eventName].length;
  951. };
  952. Eventful.prototype.off = function (eventType, handler) {
  953. var _h = this._$handlers;
  954. if (!_h) {
  955. return this;
  956. }
  957. if (!eventType) {
  958. this._$handlers = {};
  959. return this;
  960. }
  961. if (handler) {
  962. if (_h[eventType]) {
  963. var newList = [];
  964. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  965. if (_h[eventType][i].h !== handler) {
  966. newList.push(_h[eventType][i]);
  967. }
  968. }
  969. _h[eventType] = newList;
  970. }
  971. if (_h[eventType] && _h[eventType].length === 0) {
  972. delete _h[eventType];
  973. }
  974. }
  975. else {
  976. delete _h[eventType];
  977. }
  978. return this;
  979. };
  980. Eventful.prototype.trigger = function (eventType) {
  981. var args = [];
  982. for (var _i = 1; _i < arguments.length; _i++) {
  983. args[_i - 1] = arguments[_i];
  984. }
  985. if (!this._$handlers) {
  986. return this;
  987. }
  988. var _h = this._$handlers[eventType];
  989. var eventProcessor = this._$eventProcessor;
  990. if (_h) {
  991. var argLen = args.length;
  992. var len = _h.length;
  993. for (var i = 0; i < len; i++) {
  994. var hItem = _h[i];
  995. if (eventProcessor
  996. && eventProcessor.filter
  997. && hItem.query != null
  998. && !eventProcessor.filter(eventType, hItem.query)) {
  999. continue;
  1000. }
  1001. switch (argLen) {
  1002. case 0:
  1003. hItem.h.call(hItem.ctx);
  1004. break;
  1005. case 1:
  1006. hItem.h.call(hItem.ctx, args[0]);
  1007. break;
  1008. case 2:
  1009. hItem.h.call(hItem.ctx, args[0], args[1]);
  1010. break;
  1011. default:
  1012. hItem.h.apply(hItem.ctx, args);
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. eventProcessor && eventProcessor.afterTrigger
  1018. && eventProcessor.afterTrigger(eventType);
  1019. return this;
  1020. };
  1021. Eventful.prototype.triggerWithContext = function (type) {
  1022. var args = [];
  1023. for (var _i = 1; _i < arguments.length; _i++) {
  1024. args[_i - 1] = arguments[_i];
  1025. }
  1026. if (!this._$handlers) {
  1027. return this;
  1028. }
  1029. var _h = this._$handlers[type];
  1030. var eventProcessor = this._$eventProcessor;
  1031. if (_h) {
  1032. var argLen = args.length;
  1033. var ctx = args[argLen - 1];
  1034. var len = _h.length;
  1035. for (var i = 0; i < len; i++) {
  1036. var hItem = _h[i];
  1037. if (eventProcessor
  1038. && eventProcessor.filter
  1039. && hItem.query != null
  1040. && !eventProcessor.filter(type, hItem.query)) {
  1041. continue;
  1042. }
  1043. switch (argLen) {
  1044. case 0:
  1045. hItem.h.call(ctx);
  1046. break;
  1047. case 1:
  1048. hItem.h.call(ctx, args[0]);
  1049. break;
  1050. case 2:
  1051. hItem.h.call(ctx, args[0], args[1]);
  1052. break;
  1053. default:
  1054. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1055. break;
  1056. }
  1057. }
  1058. }
  1059. eventProcessor && eventProcessor.afterTrigger
  1060. && eventProcessor.afterTrigger(type);
  1061. return this;
  1062. };
  1063. return Eventful;
  1064. }());
  1065. var LN2 = Math.log(2);
  1066. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1067. var cacheKey = rowMask + '-' + colMask;
  1068. var fullRank = rows.length;
  1069. if (detCache.hasOwnProperty(cacheKey)) {
  1070. return detCache[cacheKey];
  1071. }
  1072. if (rank === 1) {
  1073. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1074. return rows[rowStart][colStart];
  1075. }
  1076. var subRowMask = rowMask | (1 << rowStart);
  1077. var subRowStart = rowStart + 1;
  1078. while (rowMask & (1 << subRowStart)) {
  1079. subRowStart++;
  1080. }
  1081. var sum = 0;
  1082. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1083. var colTag = 1 << j;
  1084. if (!(colTag & colMask)) {
  1085. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1086. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1087. colLocalIdx++;
  1088. }
  1089. }
  1090. detCache[cacheKey] = sum;
  1091. return sum;
  1092. }
  1093. function buildTransformer(src, dest) {
  1094. var mA = [
  1095. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1096. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1097. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1098. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1099. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1100. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1101. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1102. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1103. ];
  1104. var detCache = {};
  1105. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1106. if (det === 0) {
  1107. return;
  1108. }
  1109. var vh = [];
  1110. for (var i = 0; i < 8; i++) {
  1111. for (var j = 0; j < 8; j++) {
  1112. vh[j] == null && (vh[j] = 0);
  1113. vh[j] += ((i + j) % 2 ? -1 : 1)
  1114. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1115. / det * dest[i];
  1116. }
  1117. }
  1118. return function (out, srcPointX, srcPointY) {
  1119. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1120. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1121. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1122. };
  1123. }
  1124. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1125. var _calcOut = [];
  1126. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1127. return transformCoordWithViewport(_calcOut, elFrom, inX, inY, true)
  1128. && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1]);
  1129. }
  1130. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1131. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1132. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1133. var markers = prepareCoordMarkers(el, saved);
  1134. var transformer = preparePointerTransformer(markers, saved, inverse);
  1135. if (transformer) {
  1136. transformer(out, inX, inY);
  1137. return true;
  1138. }
  1139. }
  1140. return false;
  1141. }
  1142. function prepareCoordMarkers(el, saved) {
  1143. var markers = saved.markers;
  1144. if (markers) {
  1145. return markers;
  1146. }
  1147. markers = saved.markers = [];
  1148. var propLR = ['left', 'right'];
  1149. var propTB = ['top', 'bottom'];
  1150. for (var i = 0; i < 4; i++) {
  1151. var marker = document.createElement('div');
  1152. var stl = marker.style;
  1153. var idxLR = i % 2;
  1154. var idxTB = (i >> 1) % 2;
  1155. stl.cssText = [
  1156. 'position: absolute',
  1157. 'visibility: hidden',
  1158. 'padding: 0',
  1159. 'margin: 0',
  1160. 'border-width: 0',
  1161. 'user-select: none',
  1162. 'width:0',
  1163. 'height:0',
  1164. propLR[idxLR] + ':0',
  1165. propTB[idxTB] + ':0',
  1166. propLR[1 - idxLR] + ':auto',
  1167. propTB[1 - idxTB] + ':auto',
  1168. ''
  1169. ].join('!important;');
  1170. el.appendChild(marker);
  1171. markers.push(marker);
  1172. }
  1173. return markers;
  1174. }
  1175. function preparePointerTransformer(markers, saved, inverse) {
  1176. var transformerName = inverse ? 'invTrans' : 'trans';
  1177. var transformer = saved[transformerName];
  1178. var oldSrcCoords = saved.srcCoords;
  1179. var srcCoords = [];
  1180. var destCoords = [];
  1181. var oldCoordTheSame = true;
  1182. for (var i = 0; i < 4; i++) {
  1183. var rect = markers[i].getBoundingClientRect();
  1184. var ii = 2 * i;
  1185. var x = rect.left;
  1186. var y = rect.top;
  1187. srcCoords.push(x, y);
  1188. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1189. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1190. }
  1191. return (oldCoordTheSame && transformer)
  1192. ? transformer
  1193. : (saved.srcCoords = srcCoords,
  1194. saved[transformerName] = inverse
  1195. ? buildTransformer(destCoords, srcCoords)
  1196. : buildTransformer(srcCoords, destCoords));
  1197. }
  1198. function isCanvasEl(el) {
  1199. return el.nodeName.toUpperCase() === 'CANVAS';
  1200. }
  1201. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1202. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1203. var _calcOut$1 = [];
  1204. function clientToLocal(el, e, out, calculate) {
  1205. out = out || {};
  1206. if (calculate || !env.canvasSupported) {
  1207. calculateZrXY(el, e, out);
  1208. }
  1209. else if (env.browser.firefox
  1210. && e.layerX != null
  1211. && e.layerX !== e.offsetX) {
  1212. out.zrX = e.layerX;
  1213. out.zrY = e.layerY;
  1214. }
  1215. else if (e.offsetX != null) {
  1216. out.zrX = e.offsetX;
  1217. out.zrY = e.offsetY;
  1218. }
  1219. else {
  1220. calculateZrXY(el, e, out);
  1221. }
  1222. return out;
  1223. }
  1224. function calculateZrXY(el, e, out) {
  1225. if (env.domSupported && el.getBoundingClientRect) {
  1226. var ex = e.clientX;
  1227. var ey = e.clientY;
  1228. if (isCanvasEl(el)) {
  1229. var box = el.getBoundingClientRect();
  1230. out.zrX = ex - box.left;
  1231. out.zrY = ey - box.top;
  1232. return;
  1233. }
  1234. else {
  1235. if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) {
  1236. out.zrX = _calcOut$1[0];
  1237. out.zrY = _calcOut$1[1];
  1238. return;
  1239. }
  1240. }
  1241. }
  1242. out.zrX = out.zrY = 0;
  1243. }
  1244. function getNativeEvent(e) {
  1245. return e
  1246. || window.event;
  1247. }
  1248. function normalizeEvent(el, e, calculate) {
  1249. e = getNativeEvent(e);
  1250. if (e.zrX != null) {
  1251. return e;
  1252. }
  1253. var eventType = e.type;
  1254. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1255. if (!isTouch) {
  1256. clientToLocal(el, e, e, calculate);
  1257. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1258. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1259. }
  1260. else {
  1261. var touch = eventType !== 'touchend'
  1262. ? e.targetTouches[0]
  1263. : e.changedTouches[0];
  1264. touch && clientToLocal(el, touch, e, calculate);
  1265. }
  1266. var button = e.button;
  1267. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1268. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1269. }
  1270. return e;
  1271. }
  1272. function getWheelDeltaMayPolyfill(e) {
  1273. var rawWheelDelta = e.wheelDelta;
  1274. if (rawWheelDelta) {
  1275. return rawWheelDelta;
  1276. }
  1277. var deltaX = e.deltaX;
  1278. var deltaY = e.deltaY;
  1279. if (deltaX == null || deltaY == null) {
  1280. return rawWheelDelta;
  1281. }
  1282. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1283. var sign = deltaY > 0 ? -1
  1284. : deltaY < 0 ? 1
  1285. : deltaX > 0 ? -1
  1286. : 1;
  1287. return 3 * delta * sign;
  1288. }
  1289. function addEventListener(el, name, handler, opt) {
  1290. if (isDomLevel2) {
  1291. el.addEventListener(name, handler, opt);
  1292. }
  1293. else {
  1294. el.attachEvent('on' + name, handler);
  1295. }
  1296. }
  1297. function removeEventListener(el, name, handler, opt) {
  1298. if (isDomLevel2) {
  1299. el.removeEventListener(name, handler, opt);
  1300. }
  1301. else {
  1302. el.detachEvent('on' + name, handler);
  1303. }
  1304. }
  1305. var stop = isDomLevel2
  1306. ? function (e) {
  1307. e.preventDefault();
  1308. e.stopPropagation();
  1309. e.cancelBubble = true;
  1310. }
  1311. : function (e) {
  1312. e.returnValue = false;
  1313. e.cancelBubble = true;
  1314. };
  1315. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1316. return e.which === 2 || e.which === 3;
  1317. }
  1318. var GestureMgr = (function () {
  1319. function GestureMgr() {
  1320. this._track = [];
  1321. }
  1322. GestureMgr.prototype.recognize = function (event, target, root) {
  1323. this._doTrack(event, target, root);
  1324. return this._recognize(event);
  1325. };
  1326. GestureMgr.prototype.clear = function () {
  1327. this._track.length = 0;
  1328. return this;
  1329. };
  1330. GestureMgr.prototype._doTrack = function (event, target, root) {
  1331. var touches = event.touches;
  1332. if (!touches) {
  1333. return;
  1334. }
  1335. var trackItem = {
  1336. points: [],
  1337. touches: [],
  1338. target: target,
  1339. event: event
  1340. };
  1341. for (var i = 0, len = touches.length; i < len; i++) {
  1342. var touch = touches[i];
  1343. var pos = clientToLocal(root, touch, {});
  1344. trackItem.points.push([pos.zrX, pos.zrY]);
  1345. trackItem.touches.push(touch);
  1346. }
  1347. this._track.push(trackItem);
  1348. };
  1349. GestureMgr.prototype._recognize = function (event) {
  1350. for (var eventName in recognizers) {
  1351. if (recognizers.hasOwnProperty(eventName)) {
  1352. var gestureInfo = recognizers[eventName](this._track, event);
  1353. if (gestureInfo) {
  1354. return gestureInfo;
  1355. }
  1356. }
  1357. }
  1358. };
  1359. return GestureMgr;
  1360. }());
  1361. function dist$1(pointPair) {
  1362. var dx = pointPair[1][0] - pointPair[0][0];
  1363. var dy = pointPair[1][1] - pointPair[0][1];
  1364. return Math.sqrt(dx * dx + dy * dy);
  1365. }
  1366. function center(pointPair) {
  1367. return [
  1368. (pointPair[0][0] + pointPair[1][0]) / 2,
  1369. (pointPair[0][1] + pointPair[1][1]) / 2
  1370. ];
  1371. }
  1372. var recognizers = {
  1373. pinch: function (tracks, event) {
  1374. var trackLen = tracks.length;
  1375. if (!trackLen) {
  1376. return;
  1377. }
  1378. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1379. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1380. if (pinchPre
  1381. && pinchPre.length > 1
  1382. && pinchEnd
  1383. && pinchEnd.length > 1) {
  1384. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1385. !isFinite(pinchScale) && (pinchScale = 1);
  1386. event.pinchScale = pinchScale;
  1387. var pinchCenter = center(pinchEnd);
  1388. event.pinchX = pinchCenter[0];
  1389. event.pinchY = pinchCenter[1];
  1390. return {
  1391. type: 'pinch',
  1392. target: tracks[0].target,
  1393. event: event
  1394. };
  1395. }
  1396. }
  1397. };
  1398. var SILENT = 'silent';
  1399. function makeEventPacket(eveType, targetInfo, event) {
  1400. return {
  1401. type: eveType,
  1402. event: event,
  1403. target: targetInfo.target,
  1404. topTarget: targetInfo.topTarget,
  1405. cancelBubble: false,
  1406. offsetX: event.zrX,
  1407. offsetY: event.zrY,
  1408. gestureEvent: event.gestureEvent,
  1409. pinchX: event.pinchX,
  1410. pinchY: event.pinchY,
  1411. pinchScale: event.pinchScale,
  1412. wheelDelta: event.zrDelta,
  1413. zrByTouch: event.zrByTouch,
  1414. which: event.which,
  1415. stop: stopEvent
  1416. };
  1417. }
  1418. function stopEvent() {
  1419. stop(this.event);
  1420. }
  1421. var EmptyProxy = (function (_super) {
  1422. __extends(EmptyProxy, _super);
  1423. function EmptyProxy() {
  1424. var _this = _super !== null && _super.apply(this, arguments) || this;
  1425. _this.handler = null;
  1426. return _this;
  1427. }
  1428. EmptyProxy.prototype.dispose = function () { };
  1429. EmptyProxy.prototype.setCursor = function () { };
  1430. return EmptyProxy;
  1431. }(Eventful));
  1432. var HoveredResult = (function () {
  1433. function HoveredResult(x, y) {
  1434. this.x = x;
  1435. this.y = y;
  1436. }
  1437. return HoveredResult;
  1438. }());
  1439. var handlerNames = [
  1440. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1441. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1442. ];
  1443. var Handler = (function (_super) {
  1444. __extends(Handler, _super);
  1445. function Handler(storage, painter, proxy, painterRoot) {
  1446. var _this = _super.call(this) || this;
  1447. _this._hovered = new HoveredResult(0, 0);
  1448. _this.storage = storage;
  1449. _this.painter = painter;
  1450. _this.painterRoot = painterRoot;
  1451. proxy = proxy || new EmptyProxy();
  1452. _this.proxy = null;
  1453. _this.setHandlerProxy(proxy);
  1454. _this._draggingMgr = new Draggable(_this);
  1455. return _this;
  1456. }
  1457. Handler.prototype.setHandlerProxy = function (proxy) {
  1458. if (this.proxy) {
  1459. this.proxy.dispose();
  1460. }
  1461. if (proxy) {
  1462. each(handlerNames, function (name) {
  1463. proxy.on && proxy.on(name, this[name], this);
  1464. }, this);
  1465. proxy.handler = this;
  1466. }
  1467. this.proxy = proxy;
  1468. };
  1469. Handler.prototype.mousemove = function (event) {
  1470. var x = event.zrX;
  1471. var y = event.zrY;
  1472. var isOutside = isOutsideBoundary(this, x, y);
  1473. var lastHovered = this._hovered;
  1474. var lastHoveredTarget = lastHovered.target;
  1475. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1476. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1477. lastHoveredTarget = lastHovered.target;
  1478. }
  1479. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  1480. var hoveredTarget = hovered.target;
  1481. var proxy = this.proxy;
  1482. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1483. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1484. this.dispatchToElement(lastHovered, 'mouseout', event);
  1485. }
  1486. this.dispatchToElement(hovered, 'mousemove', event);
  1487. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1488. this.dispatchToElement(hovered, 'mouseover', event);
  1489. }
  1490. };
  1491. Handler.prototype.mouseout = function (event) {
  1492. var eventControl = event.zrEventControl;
  1493. if (eventControl !== 'only_globalout') {
  1494. this.dispatchToElement(this._hovered, 'mouseout', event);
  1495. }
  1496. if (eventControl !== 'no_globalout') {
  1497. this.trigger('globalout', { type: 'globalout', event: event });
  1498. }
  1499. };
  1500. Handler.prototype.resize = function () {
  1501. this._hovered = new HoveredResult(0, 0);
  1502. };
  1503. Handler.prototype.dispatch = function (eventName, eventArgs) {
  1504. var handler = this[eventName];
  1505. handler && handler.call(this, eventArgs);
  1506. };
  1507. Handler.prototype.dispose = function () {
  1508. this.proxy.dispose();
  1509. this.storage = null;
  1510. this.proxy = null;
  1511. this.painter = null;
  1512. };
  1513. Handler.prototype.setCursorStyle = function (cursorStyle) {
  1514. var proxy = this.proxy;
  1515. proxy.setCursor && proxy.setCursor(cursorStyle);
  1516. };
  1517. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  1518. targetInfo = targetInfo || {};
  1519. var el = targetInfo.target;
  1520. if (el && el.silent) {
  1521. return;
  1522. }
  1523. var eventKey = ('on' + eventName);
  1524. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1525. while (el) {
  1526. el[eventKey]
  1527. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  1528. el.trigger(eventName, eventPacket);
  1529. el = el.__hostTarget ? el.__hostTarget : el.parent;
  1530. if (eventPacket.cancelBubble) {
  1531. break;
  1532. }
  1533. }
  1534. if (!eventPacket.cancelBubble) {
  1535. this.trigger(eventName, eventPacket);
  1536. if (this.painter && this.painter.eachOtherLayer) {
  1537. this.painter.eachOtherLayer(function (layer) {
  1538. if (typeof (layer[eventKey]) === 'function') {
  1539. layer[eventKey].call(layer, eventPacket);
  1540. }
  1541. if (layer.trigger) {
  1542. layer.trigger(eventName, eventPacket);
  1543. }
  1544. });
  1545. }
  1546. }
  1547. };
  1548. Handler.prototype.findHover = function (x, y, exclude) {
  1549. var list = this.storage.getDisplayList();
  1550. var out = new HoveredResult(x, y);
  1551. for (var i = list.length - 1; i >= 0; i--) {
  1552. var hoverCheckResult = void 0;
  1553. if (list[i] !== exclude
  1554. && !list[i].ignore
  1555. && (hoverCheckResult = isHover(list[i], x, y))) {
  1556. !out.topTarget && (out.topTarget = list[i]);
  1557. if (hoverCheckResult !== SILENT) {
  1558. out.target = list[i];
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. return out;
  1564. };
  1565. Handler.prototype.processGesture = function (event, stage) {
  1566. if (!this._gestureMgr) {
  1567. this._gestureMgr = new GestureMgr();
  1568. }
  1569. var gestureMgr = this._gestureMgr;
  1570. stage === 'start' && gestureMgr.clear();
  1571. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  1572. stage === 'end' && gestureMgr.clear();
  1573. if (gestureInfo) {
  1574. var type = gestureInfo.type;
  1575. event.gestureEvent = type;
  1576. var res = new HoveredResult();
  1577. res.target = gestureInfo.target;
  1578. this.dispatchToElement(res, type, gestureInfo.event);
  1579. }
  1580. };
  1581. return Handler;
  1582. }(Eventful));
  1583. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1584. Handler.prototype[name] = function (event) {
  1585. var x = event.zrX;
  1586. var y = event.zrY;
  1587. var isOutside = isOutsideBoundary(this, x, y);
  1588. var hovered;
  1589. var hoveredTarget;
  1590. if (name !== 'mouseup' || !isOutside) {
  1591. hovered = this.findHover(x, y);
  1592. hoveredTarget = hovered.target;
  1593. }
  1594. if (name === 'mousedown') {
  1595. this._downEl = hoveredTarget;
  1596. this._downPoint = [event.zrX, event.zrY];
  1597. this._upEl = hoveredTarget;
  1598. }
  1599. else if (name === 'mouseup') {
  1600. this._upEl = hoveredTarget;
  1601. }
  1602. else if (name === 'click') {
  1603. if (this._downEl !== this._upEl
  1604. || !this._downPoint
  1605. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  1606. return;
  1607. }
  1608. this._downPoint = null;
  1609. }
  1610. this.dispatchToElement(hovered, name, event);
  1611. };
  1612. });
  1613. function isHover(displayable, x, y) {
  1614. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1615. var el = displayable;
  1616. var isSilent = void 0;
  1617. var ignoreClip = false;
  1618. while (el) {
  1619. if (el.ignoreClip) {
  1620. ignoreClip = true;
  1621. }
  1622. if (!ignoreClip) {
  1623. var clipPath = el.getClipPath();
  1624. if (clipPath && !clipPath.contain(x, y)) {
  1625. return false;
  1626. }
  1627. if (el.silent) {
  1628. isSilent = true;
  1629. }
  1630. }
  1631. var hostEl = el.__hostTarget;
  1632. el = hostEl ? hostEl : el.parent;
  1633. }
  1634. return isSilent ? SILENT : true;
  1635. }
  1636. return false;
  1637. }
  1638. function isOutsideBoundary(handlerInstance, x, y) {
  1639. var painter = handlerInstance.painter;
  1640. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  1641. }
  1642. var DEFAULT_MIN_MERGE = 32;
  1643. var DEFAULT_MIN_GALLOPING = 7;
  1644. function minRunLength(n) {
  1645. var r = 0;
  1646. while (n >= DEFAULT_MIN_MERGE) {
  1647. r |= n & 1;
  1648. n >>= 1;
  1649. }
  1650. return n + r;
  1651. }
  1652. function makeAscendingRun(array, lo, hi, compare) {
  1653. var runHi = lo + 1;
  1654. if (runHi === hi) {
  1655. return 1;
  1656. }
  1657. if (compare(array[runHi++], array[lo]) < 0) {
  1658. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  1659. runHi++;
  1660. }
  1661. reverseRun(array, lo, runHi);
  1662. }
  1663. else {
  1664. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  1665. runHi++;
  1666. }
  1667. }
  1668. return runHi - lo;
  1669. }
  1670. function reverseRun(array, lo, hi) {
  1671. hi--;
  1672. while (lo < hi) {
  1673. var t = array[lo];
  1674. array[lo++] = array[hi];
  1675. array[hi--] = t;
  1676. }
  1677. }
  1678. function binaryInsertionSort(array, lo, hi, start, compare) {
  1679. if (start === lo) {
  1680. start++;
  1681. }
  1682. for (; start < hi; start++) {
  1683. var pivot = array[start];
  1684. var left = lo;
  1685. var right = start;
  1686. var mid;
  1687. while (left < right) {
  1688. mid = left + right >>> 1;
  1689. if (compare(pivot, array[mid]) < 0) {
  1690. right = mid;
  1691. }
  1692. else {
  1693. left = mid + 1;
  1694. }
  1695. }
  1696. var n = start - left;
  1697. switch (n) {
  1698. case 3:
  1699. array[left + 3] = array[left + 2];
  1700. case 2:
  1701. array[left + 2] = array[left + 1];
  1702. case 1:
  1703. array[left + 1] = array[left];
  1704. break;
  1705. default:
  1706. while (n > 0) {
  1707. array[left + n] = array[left + n - 1];
  1708. n--;
  1709. }
  1710. }
  1711. array[left] = pivot;
  1712. }
  1713. }
  1714. function gallopLeft(value, array, start, length, hint, compare) {
  1715. var lastOffset = 0;
  1716. var maxOffset = 0;
  1717. var offset = 1;
  1718. if (compare(value, array[start + hint]) > 0) {
  1719. maxOffset = length - hint;
  1720. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  1721. lastOffset = offset;
  1722. offset = (offset << 1) + 1;
  1723. if (offset <= 0) {
  1724. offset = maxOffset;
  1725. }
  1726. }
  1727. if (offset > maxOffset) {
  1728. offset = maxOffset;
  1729. }
  1730. lastOffset += hint;
  1731. offset += hint;
  1732. }
  1733. else {
  1734. maxOffset = hint + 1;
  1735. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  1736. lastOffset = offset;
  1737. offset = (offset << 1) + 1;
  1738. if (offset <= 0) {
  1739. offset = maxOffset;
  1740. }
  1741. }
  1742. if (offset > maxOffset) {
  1743. offset = maxOffset;
  1744. }
  1745. var tmp = lastOffset;
  1746. lastOffset = hint - offset;
  1747. offset = hint - tmp;
  1748. }
  1749. lastOffset++;
  1750. while (lastOffset < offset) {
  1751. var m = lastOffset + (offset - lastOffset >>> 1);
  1752. if (compare(value, array[start + m]) > 0) {
  1753. lastOffset = m + 1;
  1754. }
  1755. else {
  1756. offset = m;
  1757. }
  1758. }
  1759. return offset;
  1760. }
  1761. function gallopRight(value, array, start, length, hint, compare) {
  1762. var lastOffset = 0;
  1763. var maxOffset = 0;
  1764. var offset = 1;
  1765. if (compare(value, array[start + hint]) < 0) {
  1766. maxOffset = hint + 1;
  1767. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  1768. lastOffset = offset;
  1769. offset = (offset << 1) + 1;
  1770. if (offset <= 0) {
  1771. offset = maxOffset;
  1772. }
  1773. }
  1774. if (offset > maxOffset) {
  1775. offset = maxOffset;
  1776. }
  1777. var tmp = lastOffset;
  1778. lastOffset = hint - offset;
  1779. offset = hint - tmp;
  1780. }
  1781. else {
  1782. maxOffset = length - hint;
  1783. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  1784. lastOffset = offset;
  1785. offset = (offset << 1) + 1;
  1786. if (offset <= 0) {
  1787. offset = maxOffset;
  1788. }
  1789. }
  1790. if (offset > maxOffset) {
  1791. offset = maxOffset;
  1792. }
  1793. lastOffset += hint;
  1794. offset += hint;
  1795. }
  1796. lastOffset++;
  1797. while (lastOffset < offset) {
  1798. var m = lastOffset + (offset - lastOffset >>> 1);
  1799. if (compare(value, array[start + m]) < 0) {
  1800. offset = m;
  1801. }
  1802. else {
  1803. lastOffset = m + 1;
  1804. }
  1805. }
  1806. return offset;
  1807. }
  1808. function TimSort(array, compare) {
  1809. var minGallop = DEFAULT_MIN_GALLOPING;
  1810. var length = 0;
  1811. var runStart;
  1812. var runLength;
  1813. var stackSize = 0;
  1814. length = array.length;
  1815. var tmp = [];
  1816. runStart = [];
  1817. runLength = [];
  1818. function pushRun(_runStart, _runLength) {
  1819. runStart[stackSize] = _runStart;
  1820. runLength[stackSize] = _runLength;
  1821. stackSize += 1;
  1822. }
  1823. function mergeRuns() {
  1824. while (stackSize > 1) {
  1825. var n = stackSize - 2;
  1826. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  1827. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  1828. if (runLength[n - 1] < runLength[n + 1]) {
  1829. n--;
  1830. }
  1831. }
  1832. else if (runLength[n] > runLength[n + 1]) {
  1833. break;
  1834. }
  1835. mergeAt(n);
  1836. }
  1837. }
  1838. function forceMergeRuns() {
  1839. while (stackSize > 1) {
  1840. var n = stackSize - 2;
  1841. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  1842. n--;
  1843. }
  1844. mergeAt(n);
  1845. }
  1846. }
  1847. function mergeAt(i) {
  1848. var start1 = runStart[i];
  1849. var length1 = runLength[i];
  1850. var start2 = runStart[i + 1];
  1851. var length2 = runLength[i + 1];
  1852. runLength[i] = length1 + length2;
  1853. if (i === stackSize - 3) {
  1854. runStart[i + 1] = runStart[i + 2];
  1855. runLength[i + 1] = runLength[i + 2];
  1856. }
  1857. stackSize--;
  1858. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  1859. start1 += k;
  1860. length1 -= k;
  1861. if (length1 === 0) {
  1862. return;
  1863. }
  1864. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  1865. if (length2 === 0) {
  1866. return;
  1867. }
  1868. if (length1 <= length2) {
  1869. mergeLow(start1, length1, start2, length2);
  1870. }
  1871. else {
  1872. mergeHigh(start1, length1, start2, length2);
  1873. }
  1874. }
  1875. function mergeLow(start1, length1, start2, length2) {
  1876. var i = 0;
  1877. for (i = 0; i < length1; i++) {
  1878. tmp[i] = array[start1 + i];
  1879. }
  1880. var cursor1 = 0;
  1881. var cursor2 = start2;
  1882. var dest = start1;
  1883. array[dest++] = array[cursor2++];
  1884. if (--length2 === 0) {
  1885. for (i = 0; i < length1; i++) {
  1886. array[dest + i] = tmp[cursor1 + i];
  1887. }
  1888. return;
  1889. }
  1890. if (length1 === 1) {
  1891. for (i = 0; i < length2; i++) {
  1892. array[dest + i] = array[cursor2 + i];
  1893. }
  1894. array[dest + length2] = tmp[cursor1];
  1895. return;
  1896. }
  1897. var _minGallop = minGallop;
  1898. var count1;
  1899. var count2;
  1900. var exit;
  1901. while (1) {
  1902. count1 = 0;
  1903. count2 = 0;
  1904. exit = false;
  1905. do {
  1906. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  1907. array[dest++] = array[cursor2++];
  1908. count2++;
  1909. count1 = 0;
  1910. if (--length2 === 0) {
  1911. exit = true;
  1912. break;
  1913. }
  1914. }
  1915. else {
  1916. array[dest++] = tmp[cursor1++];
  1917. count1++;
  1918. count2 = 0;
  1919. if (--length1 === 1) {
  1920. exit = true;
  1921. break;
  1922. }
  1923. }
  1924. } while ((count1 | count2) < _minGallop);
  1925. if (exit) {
  1926. break;
  1927. }
  1928. do {
  1929. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  1930. if (count1 !== 0) {
  1931. for (i = 0; i < count1; i++) {
  1932. array[dest + i] = tmp[cursor1 + i];
  1933. }
  1934. dest += count1;
  1935. cursor1 += count1;
  1936. length1 -= count1;
  1937. if (length1 <= 1) {
  1938. exit = true;
  1939. break;
  1940. }
  1941. }
  1942. array[dest++] = array[cursor2++];
  1943. if (--length2 === 0) {
  1944. exit = true;
  1945. break;
  1946. }
  1947. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  1948. if (count2 !== 0) {
  1949. for (i = 0; i < count2; i++) {
  1950. array[dest + i] = array[cursor2 + i];
  1951. }
  1952. dest += count2;
  1953. cursor2 += count2;
  1954. length2 -= count2;
  1955. if (length2 === 0) {
  1956. exit = true;
  1957. break;
  1958. }
  1959. }
  1960. array[dest++] = tmp[cursor1++];
  1961. if (--length1 === 1) {
  1962. exit = true;
  1963. break;
  1964. }
  1965. _minGallop--;
  1966. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  1967. if (exit) {
  1968. break;
  1969. }
  1970. if (_minGallop < 0) {
  1971. _minGallop = 0;
  1972. }
  1973. _minGallop += 2;
  1974. }
  1975. minGallop = _minGallop;
  1976. minGallop < 1 && (minGallop = 1);
  1977. if (length1 === 1) {
  1978. for (i = 0; i < length2; i++) {
  1979. array[dest + i] = array[cursor2 + i];
  1980. }
  1981. array[dest + length2] = tmp[cursor1];
  1982. }
  1983. else if (length1 === 0) {
  1984. throw new Error();
  1985. }
  1986. else {
  1987. for (i = 0; i < length1; i++) {
  1988. array[dest + i] = tmp[cursor1 + i];
  1989. }
  1990. }
  1991. }
  1992. function mergeHigh(start1, length1, start2, length2) {
  1993. var i = 0;
  1994. for (i = 0; i < length2; i++) {
  1995. tmp[i] = array[start2 + i];
  1996. }
  1997. var cursor1 = start1 + length1 - 1;
  1998. var cursor2 = length2 - 1;
  1999. var dest = start2 + length2 - 1;
  2000. var customCursor = 0;
  2001. var customDest = 0;
  2002. array[dest--] = array[cursor1--];
  2003. if (--length1 === 0) {
  2004. customCursor = dest - (length2 - 1);
  2005. for (i = 0; i < length2; i++) {
  2006. array[customCursor + i] = tmp[i];
  2007. }
  2008. return;
  2009. }
  2010. if (length2 === 1) {
  2011. dest -= length1;
  2012. cursor1 -= length1;
  2013. customDest = dest + 1;
  2014. customCursor = cursor1 + 1;
  2015. for (i = length1 - 1; i >= 0; i--) {
  2016. array[customDest + i] = array[customCursor + i];
  2017. }
  2018. array[dest] = tmp[cursor2];
  2019. return;
  2020. }
  2021. var _minGallop = minGallop;
  2022. while (true) {
  2023. var count1 = 0;
  2024. var count2 = 0;
  2025. var exit = false;
  2026. do {
  2027. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  2028. array[dest--] = array[cursor1--];
  2029. count1++;
  2030. count2 = 0;
  2031. if (--length1 === 0) {
  2032. exit = true;
  2033. break;
  2034. }
  2035. }
  2036. else {
  2037. array[dest--] = tmp[cursor2--];
  2038. count2++;
  2039. count1 = 0;
  2040. if (--length2 === 1) {
  2041. exit = true;
  2042. break;
  2043. }
  2044. }
  2045. } while ((count1 | count2) < _minGallop);
  2046. if (exit) {
  2047. break;
  2048. }
  2049. do {
  2050. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  2051. if (count1 !== 0) {
  2052. dest -= count1;
  2053. cursor1 -= count1;
  2054. length1 -= count1;
  2055. customDest = dest + 1;
  2056. customCursor = cursor1 + 1;
  2057. for (i = count1 - 1; i >= 0; i--) {
  2058. array[customDest + i] = array[customCursor + i];
  2059. }
  2060. if (length1 === 0) {
  2061. exit = true;
  2062. break;
  2063. }
  2064. }
  2065. array[dest--] = tmp[cursor2--];
  2066. if (--length2 === 1) {
  2067. exit = true;
  2068. break;
  2069. }
  2070. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  2071. if (count2 !== 0) {
  2072. dest -= count2;
  2073. cursor2 -= count2;
  2074. length2 -= count2;
  2075. customDest = dest + 1;
  2076. customCursor = cursor2 + 1;
  2077. for (i = 0; i < count2; i++) {
  2078. array[customDest + i] = tmp[customCursor + i];
  2079. }
  2080. if (length2 <= 1) {
  2081. exit = true;
  2082. break;
  2083. }
  2084. }
  2085. array[dest--] = array[cursor1--];
  2086. if (--length1 === 0) {
  2087. exit = true;
  2088. break;
  2089. }
  2090. _minGallop--;
  2091. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  2092. if (exit) {
  2093. break;
  2094. }
  2095. if (_minGallop < 0) {
  2096. _minGallop = 0;
  2097. }
  2098. _minGallop += 2;
  2099. }
  2100. minGallop = _minGallop;
  2101. if (minGallop < 1) {
  2102. minGallop = 1;
  2103. }
  2104. if (length2 === 1) {
  2105. dest -= length1;
  2106. cursor1 -= length1;
  2107. customDest = dest + 1;
  2108. customCursor = cursor1 + 1;
  2109. for (i = length1 - 1; i >= 0; i--) {
  2110. array[customDest + i] = array[customCursor + i];
  2111. }
  2112. array[dest] = tmp[cursor2];
  2113. }
  2114. else if (length2 === 0) {
  2115. throw new Error();
  2116. }
  2117. else {
  2118. customCursor = dest - (length2 - 1);
  2119. for (i = 0; i < length2; i++) {
  2120. array[customCursor + i] = tmp[i];
  2121. }
  2122. }
  2123. }
  2124. return {
  2125. mergeRuns: mergeRuns,
  2126. forceMergeRuns: forceMergeRuns,
  2127. pushRun: pushRun
  2128. };
  2129. }
  2130. function sort(array, compare, lo, hi) {
  2131. if (!lo) {
  2132. lo = 0;
  2133. }
  2134. if (!hi) {
  2135. hi = array.length;
  2136. }
  2137. var remaining = hi - lo;
  2138. if (remaining < 2) {
  2139. return;
  2140. }
  2141. var runLength = 0;
  2142. if (remaining < DEFAULT_MIN_MERGE) {
  2143. runLength = makeAscendingRun(array, lo, hi, compare);
  2144. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  2145. return;
  2146. }
  2147. var ts = TimSort(array, compare);
  2148. var minRun = minRunLength(remaining);
  2149. do {
  2150. runLength = makeAscendingRun(array, lo, hi, compare);
  2151. if (runLength < minRun) {
  2152. var force = remaining;
  2153. if (force > minRun) {
  2154. force = minRun;
  2155. }
  2156. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  2157. runLength = force;
  2158. }
  2159. ts.pushRun(lo, runLength);
  2160. ts.mergeRuns();
  2161. remaining -= runLength;
  2162. lo += runLength;
  2163. } while (remaining !== 0);
  2164. ts.forceMergeRuns();
  2165. }
  2166. var REDARAW_BIT = 1;
  2167. var STYLE_CHANGED_BIT = 2;
  2168. var SHAPE_CHANGED_BIT = 4;
  2169. var invalidZErrorLogged = false;
  2170. function logInvalidZError() {
  2171. if (invalidZErrorLogged) {
  2172. return;
  2173. }
  2174. invalidZErrorLogged = true;
  2175. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  2176. }
  2177. function shapeCompareFunc(a, b) {
  2178. if (a.zlevel === b.zlevel) {
  2179. if (a.z === b.z) {
  2180. return a.z2 - b.z2;
  2181. }
  2182. return a.z - b.z;
  2183. }
  2184. return a.zlevel - b.zlevel;
  2185. }
  2186. var Storage = (function () {
  2187. function Storage() {
  2188. this._roots = [];
  2189. this._displayList = [];
  2190. this._displayListLen = 0;
  2191. this.displayableSortFunc = shapeCompareFunc;
  2192. }
  2193. Storage.prototype.traverse = function (cb, context) {
  2194. for (var i = 0; i < this._roots.length; i++) {
  2195. this._roots[i].traverse(cb, context);
  2196. }
  2197. };
  2198. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  2199. includeIgnore = includeIgnore || false;
  2200. var displayList = this._displayList;
  2201. if (update || !displayList.length) {
  2202. this.updateDisplayList(includeIgnore);
  2203. }
  2204. return displayList;
  2205. };
  2206. Storage.prototype.updateDisplayList = function (includeIgnore) {
  2207. this._displayListLen = 0;
  2208. var roots = this._roots;
  2209. var displayList = this._displayList;
  2210. for (var i = 0, len = roots.length; i < len; i++) {
  2211. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  2212. }
  2213. displayList.length = this._displayListLen;
  2214. env.canvasSupported && sort(displayList, shapeCompareFunc);
  2215. };
  2216. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  2217. if (el.ignore && !includeIgnore) {
  2218. return;
  2219. }
  2220. el.beforeUpdate();
  2221. el.update();
  2222. el.afterUpdate();
  2223. var userSetClipPath = el.getClipPath();
  2224. if (el.ignoreClip) {
  2225. clipPaths = null;
  2226. }
  2227. else if (userSetClipPath) {
  2228. if (clipPaths) {
  2229. clipPaths = clipPaths.slice();
  2230. }
  2231. else {
  2232. clipPaths = [];
  2233. }
  2234. var currentClipPath = userSetClipPath;
  2235. var parentClipPath = el;
  2236. while (currentClipPath) {
  2237. currentClipPath.parent = parentClipPath;
  2238. currentClipPath.updateTransform();
  2239. clipPaths.push(currentClipPath);
  2240. parentClipPath = currentClipPath;
  2241. currentClipPath = currentClipPath.getClipPath();
  2242. }
  2243. }
  2244. if (el.childrenRef) {
  2245. var children = el.childrenRef();
  2246. for (var i = 0; i < children.length; i++) {
  2247. var child = children[i];
  2248. if (el.__dirty) {
  2249. child.__dirty |= REDARAW_BIT;
  2250. }
  2251. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  2252. }
  2253. el.__dirty = 0;
  2254. }
  2255. else {
  2256. var disp = el;
  2257. if (clipPaths && clipPaths.length) {
  2258. disp.__clipPaths = clipPaths;
  2259. }
  2260. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  2261. disp.__clipPaths = [];
  2262. }
  2263. if (isNaN(disp.z)) {
  2264. logInvalidZError();
  2265. disp.z = 0;
  2266. }
  2267. if (isNaN(disp.z2)) {
  2268. logInvalidZError();
  2269. disp.z2 = 0;
  2270. }
  2271. if (isNaN(disp.zlevel)) {
  2272. logInvalidZError();
  2273. disp.zlevel = 0;
  2274. }
  2275. this._displayList[this._displayListLen++] = disp;
  2276. }
  2277. var decalEl = el.getDecalElement && el.getDecalElement();
  2278. if (decalEl) {
  2279. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  2280. }
  2281. var textGuide = el.getTextGuideLine();
  2282. if (textGuide) {
  2283. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  2284. }
  2285. var textEl = el.getTextContent();
  2286. if (textEl) {
  2287. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  2288. }
  2289. };
  2290. Storage.prototype.addRoot = function (el) {
  2291. if (el.__zr && el.__zr.storage === this) {
  2292. return;
  2293. }
  2294. this._roots.push(el);
  2295. };
  2296. Storage.prototype.delRoot = function (el) {
  2297. if (el instanceof Array) {
  2298. for (var i = 0, l = el.length; i < l; i++) {
  2299. this.delRoot(el[i]);
  2300. }
  2301. return;
  2302. }
  2303. var idx = indexOf(this._roots, el);
  2304. if (idx >= 0) {
  2305. this._roots.splice(idx, 1);
  2306. }
  2307. };
  2308. Storage.prototype.delAllRoots = function () {
  2309. this._roots = [];
  2310. this._displayList = [];
  2311. this._displayListLen = 0;
  2312. return;
  2313. };
  2314. Storage.prototype.getRoots = function () {
  2315. return this._roots;
  2316. };
  2317. Storage.prototype.dispose = function () {
  2318. this._displayList = null;
  2319. this._roots = null;
  2320. };
  2321. return Storage;
  2322. }());
  2323. var requestAnimationFrame;
  2324. requestAnimationFrame = (typeof window !== 'undefined'
  2325. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  2326. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  2327. || window.mozRequestAnimationFrame
  2328. || window.webkitRequestAnimationFrame)) || function (func) {
  2329. return setTimeout(func, 16);
  2330. };
  2331. var requestAnimationFrame$1 = requestAnimationFrame;
  2332. var easing = {
  2333. linear: function (k) {
  2334. return k;
  2335. },
  2336. quadraticIn: function (k) {
  2337. return k * k;
  2338. },
  2339. quadraticOut: function (k) {
  2340. return k * (2 - k);
  2341. },
  2342. quadraticInOut: function (k) {
  2343. if ((k *= 2) < 1) {
  2344. return 0.5 * k * k;
  2345. }
  2346. return -0.5 * (--k * (k - 2) - 1);
  2347. },
  2348. cubicIn: function (k) {
  2349. return k * k * k;
  2350. },
  2351. cubicOut: function (k) {
  2352. return --k * k * k + 1;
  2353. },
  2354. cubicInOut: function (k) {
  2355. if ((k *= 2) < 1) {
  2356. return 0.5 * k * k * k;
  2357. }
  2358. return 0.5 * ((k -= 2) * k * k + 2);
  2359. },
  2360. quarticIn: function (k) {
  2361. return k * k * k * k;
  2362. },
  2363. quarticOut: function (k) {
  2364. return 1 - (--k * k * k * k);
  2365. },
  2366. quarticInOut: function (k) {
  2367. if ((k *= 2) < 1) {
  2368. return 0.5 * k * k * k * k;
  2369. }
  2370. return -0.5 * ((k -= 2) * k * k * k - 2);
  2371. },
  2372. quinticIn: function (k) {
  2373. return k * k * k * k * k;
  2374. },
  2375. quinticOut: function (k) {
  2376. return --k * k * k * k * k + 1;
  2377. },
  2378. quinticInOut: function (k) {
  2379. if ((k *= 2) < 1) {
  2380. return 0.5 * k * k * k * k * k;
  2381. }
  2382. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2383. },
  2384. sinusoidalIn: function (k) {
  2385. return 1 - Math.cos(k * Math.PI / 2);
  2386. },
  2387. sinusoidalOut: function (k) {
  2388. return Math.sin(k * Math.PI / 2);
  2389. },
  2390. sinusoidalInOut: function (k) {
  2391. return 0.5 * (1 - Math.cos(Math.PI * k));
  2392. },
  2393. exponentialIn: function (k) {
  2394. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2395. },
  2396. exponentialOut: function (k) {
  2397. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2398. },
  2399. exponentialInOut: function (k) {
  2400. if (k === 0) {
  2401. return 0;
  2402. }
  2403. if (k === 1) {
  2404. return 1;
  2405. }
  2406. if ((k *= 2) < 1) {
  2407. return 0.5 * Math.pow(1024, k - 1);
  2408. }
  2409. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2410. },
  2411. circularIn: function (k) {
  2412. return 1 - Math.sqrt(1 - k * k);
  2413. },
  2414. circularOut: function (k) {
  2415. return Math.sqrt(1 - (--k * k));
  2416. },
  2417. circularInOut: function (k) {
  2418. if ((k *= 2) < 1) {
  2419. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2420. }
  2421. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2422. },
  2423. elasticIn: function (k) {
  2424. var s;
  2425. var a = 0.1;
  2426. var p = 0.4;
  2427. if (k === 0) {
  2428. return 0;
  2429. }
  2430. if (k === 1) {
  2431. return 1;
  2432. }
  2433. if (!a || a < 1) {
  2434. a = 1;
  2435. s = p / 4;
  2436. }
  2437. else {
  2438. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2439. }
  2440. return -(a * Math.pow(2, 10 * (k -= 1))
  2441. * Math.sin((k - s) * (2 * Math.PI) / p));
  2442. },
  2443. elasticOut: function (k) {
  2444. var s;
  2445. var a = 0.1;
  2446. var p = 0.4;
  2447. if (k === 0) {
  2448. return 0;
  2449. }
  2450. if (k === 1) {
  2451. return 1;
  2452. }
  2453. if (!a || a < 1) {
  2454. a = 1;
  2455. s = p / 4;
  2456. }
  2457. else {
  2458. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2459. }
  2460. return (a * Math.pow(2, -10 * k)
  2461. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2462. },
  2463. elasticInOut: function (k) {
  2464. var s;
  2465. var a = 0.1;
  2466. var p = 0.4;
  2467. if (k === 0) {
  2468. return 0;
  2469. }
  2470. if (k === 1) {
  2471. return 1;
  2472. }
  2473. if (!a || a < 1) {
  2474. a = 1;
  2475. s = p / 4;
  2476. }
  2477. else {
  2478. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2479. }
  2480. if ((k *= 2) < 1) {
  2481. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2482. * Math.sin((k - s) * (2 * Math.PI) / p));
  2483. }
  2484. return a * Math.pow(2, -10 * (k -= 1))
  2485. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2486. },
  2487. backIn: function (k) {
  2488. var s = 1.70158;
  2489. return k * k * ((s + 1) * k - s);
  2490. },
  2491. backOut: function (k) {
  2492. var s = 1.70158;
  2493. return --k * k * ((s + 1) * k + s) + 1;
  2494. },
  2495. backInOut: function (k) {
  2496. var s = 1.70158 * 1.525;
  2497. if ((k *= 2) < 1) {
  2498. return 0.5 * (k * k * ((s + 1) * k - s));
  2499. }
  2500. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2501. },
  2502. bounceIn: function (k) {
  2503. return 1 - easing.bounceOut(1 - k);
  2504. },
  2505. bounceOut: function (k) {
  2506. if (k < (1 / 2.75)) {
  2507. return 7.5625 * k * k;
  2508. }
  2509. else if (k < (2 / 2.75)) {
  2510. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2511. }
  2512. else if (k < (2.5 / 2.75)) {
  2513. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2514. }
  2515. else {
  2516. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2517. }
  2518. },
  2519. bounceInOut: function (k) {
  2520. if (k < 0.5) {
  2521. return easing.bounceIn(k * 2) * 0.5;
  2522. }
  2523. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2524. }
  2525. };
  2526. var Clip = (function () {
  2527. function Clip(opts) {
  2528. this._initialized = false;
  2529. this._startTime = 0;
  2530. this._pausedTime = 0;
  2531. this._paused = false;
  2532. this._life = opts.life || 1000;
  2533. this._delay = opts.delay || 0;
  2534. this.loop = opts.loop == null ? false : opts.loop;
  2535. this.gap = opts.gap || 0;
  2536. this.easing = opts.easing || 'linear';
  2537. this.onframe = opts.onframe;
  2538. this.ondestroy = opts.ondestroy;
  2539. this.onrestart = opts.onrestart;
  2540. }
  2541. Clip.prototype.step = function (globalTime, deltaTime) {
  2542. if (!this._initialized) {
  2543. this._startTime = globalTime + this._delay;
  2544. this._initialized = true;
  2545. }
  2546. if (this._paused) {
  2547. this._pausedTime += deltaTime;
  2548. return;
  2549. }
  2550. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2551. if (percent < 0) {
  2552. percent = 0;
  2553. }
  2554. percent = Math.min(percent, 1);
  2555. var easing$1 = this.easing;
  2556. var easingFunc = typeof easing$1 === 'string'
  2557. ? easing[easing$1] : easing$1;
  2558. var schedule = typeof easingFunc === 'function'
  2559. ? easingFunc(percent)
  2560. : percent;
  2561. this.onframe && this.onframe(schedule);
  2562. if (percent === 1) {
  2563. if (this.loop) {
  2564. this._restart(globalTime);
  2565. this.onrestart && this.onrestart();
  2566. }
  2567. else {
  2568. return true;
  2569. }
  2570. }
  2571. return false;
  2572. };
  2573. Clip.prototype._restart = function (globalTime) {
  2574. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2575. this._startTime = globalTime - remainder + this.gap;
  2576. this._pausedTime = 0;
  2577. };
  2578. Clip.prototype.pause = function () {
  2579. this._paused = true;
  2580. };
  2581. Clip.prototype.resume = function () {
  2582. this._paused = false;
  2583. };
  2584. return Clip;
  2585. }());
  2586. var Entry = (function () {
  2587. function Entry(val) {
  2588. this.value = val;
  2589. }
  2590. return Entry;
  2591. }());
  2592. var LinkedList = (function () {
  2593. function LinkedList() {
  2594. this._len = 0;
  2595. }
  2596. LinkedList.prototype.insert = function (val) {
  2597. var entry = new Entry(val);
  2598. this.insertEntry(entry);
  2599. return entry;
  2600. };
  2601. LinkedList.prototype.insertEntry = function (entry) {
  2602. if (!this.head) {
  2603. this.head = this.tail = entry;
  2604. }
  2605. else {
  2606. this.tail.next = entry;
  2607. entry.prev = this.tail;
  2608. entry.next = null;
  2609. this.tail = entry;
  2610. }
  2611. this._len++;
  2612. };
  2613. LinkedList.prototype.remove = function (entry) {
  2614. var prev = entry.prev;
  2615. var next = entry.next;
  2616. if (prev) {
  2617. prev.next = next;
  2618. }
  2619. else {
  2620. this.head = next;
  2621. }
  2622. if (next) {
  2623. next.prev = prev;
  2624. }
  2625. else {
  2626. this.tail = prev;
  2627. }
  2628. entry.next = entry.prev = null;
  2629. this._len--;
  2630. };
  2631. LinkedList.prototype.len = function () {
  2632. return this._len;
  2633. };
  2634. LinkedList.prototype.clear = function () {
  2635. this.head = this.tail = null;
  2636. this._len = 0;
  2637. };
  2638. return LinkedList;
  2639. }());
  2640. var LRU = (function () {
  2641. function LRU(maxSize) {
  2642. this._list = new LinkedList();
  2643. this._maxSize = 10;
  2644. this._map = {};
  2645. this._maxSize = maxSize;
  2646. }
  2647. LRU.prototype.put = function (key, value) {
  2648. var list = this._list;
  2649. var map = this._map;
  2650. var removed = null;
  2651. if (map[key] == null) {
  2652. var len = list.len();
  2653. var entry = this._lastRemovedEntry;
  2654. if (len >= this._maxSize && len > 0) {
  2655. var leastUsedEntry = list.head;
  2656. list.remove(leastUsedEntry);
  2657. delete map[leastUsedEntry.key];
  2658. removed = leastUsedEntry.value;
  2659. this._lastRemovedEntry = leastUsedEntry;
  2660. }
  2661. if (entry) {
  2662. entry.value = value;
  2663. }
  2664. else {
  2665. entry = new Entry(value);
  2666. }
  2667. entry.key = key;
  2668. list.insertEntry(entry);
  2669. map[key] = entry;
  2670. }
  2671. return removed;
  2672. };
  2673. LRU.prototype.get = function (key) {
  2674. var entry = this._map[key];
  2675. var list = this._list;
  2676. if (entry != null) {
  2677. if (entry !== list.tail) {
  2678. list.remove(entry);
  2679. list.insertEntry(entry);
  2680. }
  2681. return entry.value;
  2682. }
  2683. };
  2684. LRU.prototype.clear = function () {
  2685. this._list.clear();
  2686. this._map = {};
  2687. };
  2688. LRU.prototype.len = function () {
  2689. return this._list.len();
  2690. };
  2691. return LRU;
  2692. }());
  2693. var kCSSColorTable = {
  2694. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  2695. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  2696. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  2697. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  2698. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  2699. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  2700. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  2701. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  2702. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  2703. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  2704. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  2705. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  2706. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  2707. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  2708. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  2709. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  2710. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  2711. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  2712. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  2713. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  2714. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  2715. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  2716. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  2717. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  2718. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  2719. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  2720. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  2721. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  2722. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  2723. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  2724. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  2725. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  2726. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  2727. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  2728. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  2729. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  2730. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  2731. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  2732. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  2733. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  2734. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  2735. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  2736. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  2737. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  2738. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  2739. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  2740. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  2741. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  2742. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  2743. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  2744. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  2745. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  2746. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  2747. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  2748. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  2749. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  2750. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  2751. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  2752. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  2753. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  2754. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  2755. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  2756. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  2757. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  2758. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  2759. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  2760. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  2761. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  2762. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  2763. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  2764. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  2765. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  2766. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  2767. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  2768. };
  2769. function clampCssByte(i) {
  2770. i = Math.round(i);
  2771. return i < 0 ? 0 : i > 255 ? 255 : i;
  2772. }
  2773. function clampCssAngle(i) {
  2774. i = Math.round(i);
  2775. return i < 0 ? 0 : i > 360 ? 360 : i;
  2776. }
  2777. function clampCssFloat(f) {
  2778. return f < 0 ? 0 : f > 1 ? 1 : f;
  2779. }
  2780. function parseCssInt(val) {
  2781. var str = val;
  2782. if (str.length && str.charAt(str.length - 1) === '%') {
  2783. return clampCssByte(parseFloat(str) / 100 * 255);
  2784. }
  2785. return clampCssByte(parseInt(str, 10));
  2786. }
  2787. function parseCssFloat(val) {
  2788. var str = val;
  2789. if (str.length && str.charAt(str.length - 1) === '%') {
  2790. return clampCssFloat(parseFloat(str) / 100);
  2791. }
  2792. return clampCssFloat(parseFloat(str));
  2793. }
  2794. function cssHueToRgb(m1, m2, h) {
  2795. if (h < 0) {
  2796. h += 1;
  2797. }
  2798. else if (h > 1) {
  2799. h -= 1;
  2800. }
  2801. if (h * 6 < 1) {
  2802. return m1 + (m2 - m1) * h * 6;
  2803. }
  2804. if (h * 2 < 1) {
  2805. return m2;
  2806. }
  2807. if (h * 3 < 2) {
  2808. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  2809. }
  2810. return m1;
  2811. }
  2812. function lerpNumber(a, b, p) {
  2813. return a + (b - a) * p;
  2814. }
  2815. function setRgba(out, r, g, b, a) {
  2816. out[0] = r;
  2817. out[1] = g;
  2818. out[2] = b;
  2819. out[3] = a;
  2820. return out;
  2821. }
  2822. function copyRgba(out, a) {
  2823. out[0] = a[0];
  2824. out[1] = a[1];
  2825. out[2] = a[2];
  2826. out[3] = a[3];
  2827. return out;
  2828. }
  2829. var colorCache = new LRU(20);
  2830. var lastRemovedArr = null;
  2831. function putToCache(colorStr, rgbaArr) {
  2832. if (lastRemovedArr) {
  2833. copyRgba(lastRemovedArr, rgbaArr);
  2834. }
  2835. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2836. }
  2837. function parse(colorStr, rgbaArr) {
  2838. if (!colorStr) {
  2839. return;
  2840. }
  2841. rgbaArr = rgbaArr || [];
  2842. var cached = colorCache.get(colorStr);
  2843. if (cached) {
  2844. return copyRgba(rgbaArr, cached);
  2845. }
  2846. colorStr = colorStr + '';
  2847. var str = colorStr.replace(/ /g, '').toLowerCase();
  2848. if (str in kCSSColorTable) {
  2849. copyRgba(rgbaArr, kCSSColorTable[str]);
  2850. putToCache(colorStr, rgbaArr);
  2851. return rgbaArr;
  2852. }
  2853. var strLen = str.length;
  2854. if (str.charAt(0) === '#') {
  2855. if (strLen === 4 || strLen === 5) {
  2856. var iv = parseInt(str.slice(1, 4), 16);
  2857. if (!(iv >= 0 && iv <= 0xfff)) {
  2858. setRgba(rgbaArr, 0, 0, 0, 1);
  2859. return;
  2860. }
  2861. 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);
  2862. putToCache(colorStr, rgbaArr);
  2863. return rgbaArr;
  2864. }
  2865. else if (strLen === 7 || strLen === 9) {
  2866. var iv = parseInt(str.slice(1, 7), 16);
  2867. if (!(iv >= 0 && iv <= 0xffffff)) {
  2868. setRgba(rgbaArr, 0, 0, 0, 1);
  2869. return;
  2870. }
  2871. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  2872. putToCache(colorStr, rgbaArr);
  2873. return rgbaArr;
  2874. }
  2875. return;
  2876. }
  2877. var op = str.indexOf('(');
  2878. var ep = str.indexOf(')');
  2879. if (op !== -1 && ep + 1 === strLen) {
  2880. var fname = str.substr(0, op);
  2881. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2882. var alpha = 1;
  2883. switch (fname) {
  2884. case 'rgba':
  2885. if (params.length !== 4) {
  2886. return params.length === 3
  2887. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  2888. : setRgba(rgbaArr, 0, 0, 0, 1);
  2889. }
  2890. alpha = parseCssFloat(params.pop());
  2891. case 'rgb':
  2892. if (params.length !== 3) {
  2893. setRgba(rgbaArr, 0, 0, 0, 1);
  2894. return;
  2895. }
  2896. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha);
  2897. putToCache(colorStr, rgbaArr);
  2898. return rgbaArr;
  2899. case 'hsla':
  2900. if (params.length !== 4) {
  2901. setRgba(rgbaArr, 0, 0, 0, 1);
  2902. return;
  2903. }
  2904. params[3] = parseCssFloat(params[3]);
  2905. hsla2rgba(params, rgbaArr);
  2906. putToCache(colorStr, rgbaArr);
  2907. return rgbaArr;
  2908. case 'hsl':
  2909. if (params.length !== 3) {
  2910. setRgba(rgbaArr, 0, 0, 0, 1);
  2911. return;
  2912. }
  2913. hsla2rgba(params, rgbaArr);
  2914. putToCache(colorStr, rgbaArr);
  2915. return rgbaArr;
  2916. default:
  2917. return;
  2918. }
  2919. }
  2920. setRgba(rgbaArr, 0, 0, 0, 1);
  2921. return;
  2922. }
  2923. function hsla2rgba(hsla, rgba) {
  2924. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  2925. var s = parseCssFloat(hsla[1]);
  2926. var l = parseCssFloat(hsla[2]);
  2927. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2928. var m1 = l * 2 - m2;
  2929. rgba = rgba || [];
  2930. 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);
  2931. if (hsla.length === 4) {
  2932. rgba[3] = hsla[3];
  2933. }
  2934. return rgba;
  2935. }
  2936. function rgba2hsla(rgba) {
  2937. if (!rgba) {
  2938. return;
  2939. }
  2940. var R = rgba[0] / 255;
  2941. var G = rgba[1] / 255;
  2942. var B = rgba[2] / 255;
  2943. var vMin = Math.min(R, G, B);
  2944. var vMax = Math.max(R, G, B);
  2945. var delta = vMax - vMin;
  2946. var L = (vMax + vMin) / 2;
  2947. var H;
  2948. var S;
  2949. if (delta === 0) {
  2950. H = 0;
  2951. S = 0;
  2952. }
  2953. else {
  2954. if (L < 0.5) {
  2955. S = delta / (vMax + vMin);
  2956. }
  2957. else {
  2958. S = delta / (2 - vMax - vMin);
  2959. }
  2960. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2961. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2962. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2963. if (R === vMax) {
  2964. H = deltaB - deltaG;
  2965. }
  2966. else if (G === vMax) {
  2967. H = (1 / 3) + deltaR - deltaB;
  2968. }
  2969. else if (B === vMax) {
  2970. H = (2 / 3) + deltaG - deltaR;
  2971. }
  2972. if (H < 0) {
  2973. H += 1;
  2974. }
  2975. if (H > 1) {
  2976. H -= 1;
  2977. }
  2978. }
  2979. var hsla = [H * 360, S, L];
  2980. if (rgba[3] != null) {
  2981. hsla.push(rgba[3]);
  2982. }
  2983. return hsla;
  2984. }
  2985. function lift(color, level) {
  2986. var colorArr = parse(color);
  2987. if (colorArr) {
  2988. for (var i = 0; i < 3; i++) {
  2989. if (level < 0) {
  2990. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2991. }
  2992. else {
  2993. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2994. }
  2995. if (colorArr[i] > 255) {
  2996. colorArr[i] = 255;
  2997. }
  2998. else if (colorArr[i] < 0) {
  2999. colorArr[i] = 0;
  3000. }
  3001. }
  3002. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3003. }
  3004. }
  3005. function toHex(color) {
  3006. var colorArr = parse(color);
  3007. if (colorArr) {
  3008. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3009. }
  3010. }
  3011. function fastLerp(normalizedValue, colors, out) {
  3012. if (!(colors && colors.length)
  3013. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3014. return;
  3015. }
  3016. out = out || [];
  3017. var value = normalizedValue * (colors.length - 1);
  3018. var leftIndex = Math.floor(value);
  3019. var rightIndex = Math.ceil(value);
  3020. var leftColor = colors[leftIndex];
  3021. var rightColor = colors[rightIndex];
  3022. var dv = value - leftIndex;
  3023. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3024. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3025. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3026. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3027. return out;
  3028. }
  3029. var fastMapToColor = fastLerp;
  3030. function lerp$1(normalizedValue, colors, fullOutput) {
  3031. if (!(colors && colors.length)
  3032. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3033. return;
  3034. }
  3035. var value = normalizedValue * (colors.length - 1);
  3036. var leftIndex = Math.floor(value);
  3037. var rightIndex = Math.ceil(value);
  3038. var leftColor = parse(colors[leftIndex]);
  3039. var rightColor = parse(colors[rightIndex]);
  3040. var dv = value - leftIndex;
  3041. var color = stringify([
  3042. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3043. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3044. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3045. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3046. ], 'rgba');
  3047. return fullOutput
  3048. ? {
  3049. color: color,
  3050. leftIndex: leftIndex,
  3051. rightIndex: rightIndex,
  3052. value: value
  3053. }
  3054. : color;
  3055. }
  3056. var mapToColor = lerp$1;
  3057. function modifyHSL(color, h, s, l) {
  3058. var colorArr = parse(color);
  3059. if (color) {
  3060. colorArr = rgba2hsla(colorArr);
  3061. h != null && (colorArr[0] = clampCssAngle(h));
  3062. s != null && (colorArr[1] = parseCssFloat(s));
  3063. l != null && (colorArr[2] = parseCssFloat(l));
  3064. return stringify(hsla2rgba(colorArr), 'rgba');
  3065. }
  3066. }
  3067. function modifyAlpha(color, alpha) {
  3068. var colorArr = parse(color);
  3069. if (colorArr && alpha != null) {
  3070. colorArr[3] = clampCssFloat(alpha);
  3071. return stringify(colorArr, 'rgba');
  3072. }
  3073. }
  3074. function stringify(arrColor, type) {
  3075. if (!arrColor || !arrColor.length) {
  3076. return;
  3077. }
  3078. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3079. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3080. colorStr += ',' + arrColor[3];
  3081. }
  3082. return type + '(' + colorStr + ')';
  3083. }
  3084. function lum(color, backgroundLum) {
  3085. var arr = parse(color);
  3086. return arr
  3087. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  3088. + (1 - arr[3]) * backgroundLum
  3089. : 0;
  3090. }
  3091. function random() {
  3092. var r = Math.round(Math.random() * 255);
  3093. var g = Math.round(Math.random() * 255);
  3094. var b = Math.round(Math.random() * 255);
  3095. return 'rgb(' + r + ',' + g + ',' + b + ')';
  3096. }
  3097. var color = /*#__PURE__*/Object.freeze({
  3098. __proto__: null,
  3099. parse: parse,
  3100. lift: lift,
  3101. toHex: toHex,
  3102. fastLerp: fastLerp,
  3103. fastMapToColor: fastMapToColor,
  3104. lerp: lerp$1,
  3105. mapToColor: mapToColor,
  3106. modifyHSL: modifyHSL,
  3107. modifyAlpha: modifyAlpha,
  3108. stringify: stringify,
  3109. lum: lum,
  3110. random: random
  3111. });
  3112. var arraySlice = Array.prototype.slice;
  3113. function interpolateNumber(p0, p1, percent) {
  3114. return (p1 - p0) * percent + p0;
  3115. }
  3116. function step(p0, p1, percent) {
  3117. return percent > 0.5 ? p1 : p0;
  3118. }
  3119. function interpolate1DArray(out, p0, p1, percent) {
  3120. var len = p0.length;
  3121. for (var i = 0; i < len; i++) {
  3122. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3123. }
  3124. }
  3125. function interpolate2DArray(out, p0, p1, percent) {
  3126. var len = p0.length;
  3127. var len2 = len && p0[0].length;
  3128. for (var i = 0; i < len; i++) {
  3129. if (!out[i]) {
  3130. out[i] = [];
  3131. }
  3132. for (var j = 0; j < len2; j++) {
  3133. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  3134. }
  3135. }
  3136. }
  3137. function add1DArray(out, p0, p1, sign) {
  3138. var len = p0.length;
  3139. for (var i = 0; i < len; i++) {
  3140. out[i] = p0[i] + p1[i] * sign;
  3141. }
  3142. return out;
  3143. }
  3144. function add2DArray(out, p0, p1, sign) {
  3145. var len = p0.length;
  3146. var len2 = len && p0[0].length;
  3147. for (var i = 0; i < len; i++) {
  3148. if (!out[i]) {
  3149. out[i] = [];
  3150. }
  3151. for (var j = 0; j < len2; j++) {
  3152. out[i][j] = p0[i][j] + p1[i][j] * sign;
  3153. }
  3154. }
  3155. return out;
  3156. }
  3157. function fillArray(val0, val1, arrDim) {
  3158. var arr0 = val0;
  3159. var arr1 = val1;
  3160. if (!arr0.push || !arr1.push) {
  3161. return;
  3162. }
  3163. var arr0Len = arr0.length;
  3164. var arr1Len = arr1.length;
  3165. if (arr0Len !== arr1Len) {
  3166. var isPreviousLarger = arr0Len > arr1Len;
  3167. if (isPreviousLarger) {
  3168. arr0.length = arr1Len;
  3169. }
  3170. else {
  3171. for (var i = arr0Len; i < arr1Len; i++) {
  3172. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  3173. }
  3174. }
  3175. }
  3176. var len2 = arr0[0] && arr0[0].length;
  3177. for (var i = 0; i < arr0.length; i++) {
  3178. if (arrDim === 1) {
  3179. if (isNaN(arr0[i])) {
  3180. arr0[i] = arr1[i];
  3181. }
  3182. }
  3183. else {
  3184. for (var j = 0; j < len2; j++) {
  3185. if (isNaN(arr0[i][j])) {
  3186. arr0[i][j] = arr1[i][j];
  3187. }
  3188. }
  3189. }
  3190. }
  3191. }
  3192. function is1DArraySame(arr0, arr1) {
  3193. var len = arr0.length;
  3194. if (len !== arr1.length) {
  3195. return false;
  3196. }
  3197. for (var i = 0; i < len; i++) {
  3198. if (arr0[i] !== arr1[i]) {
  3199. return false;
  3200. }
  3201. }
  3202. return true;
  3203. }
  3204. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3205. var v0 = (p2 - p0) * 0.5;
  3206. var v1 = (p3 - p1) * 0.5;
  3207. return (2 * (p1 - p2) + v0 + v1) * t3
  3208. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3209. + v0 * t + p1;
  3210. }
  3211. function catmullRomInterpolate1DArray(out, p0, p1, p2, p3, t, t2, t3) {
  3212. var len = p0.length;
  3213. for (var i = 0; i < len; i++) {
  3214. out[i] = catmullRomInterpolate(p0[i], p1[i], p2[i], p3[i], t, t2, t3);
  3215. }
  3216. }
  3217. function catmullRomInterpolate2DArray(out, p0, p1, p2, p3, t, t2, t3) {
  3218. var len = p0.length;
  3219. var len2 = p0[0].length;
  3220. for (var i = 0; i < len; i++) {
  3221. if (!out[i]) {
  3222. out[1] = [];
  3223. }
  3224. for (var j = 0; j < len2; j++) {
  3225. out[i][j] = catmullRomInterpolate(p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3);
  3226. }
  3227. }
  3228. }
  3229. function cloneValue(value) {
  3230. if (isArrayLike(value)) {
  3231. var len = value.length;
  3232. if (isArrayLike(value[0])) {
  3233. var ret = [];
  3234. for (var i = 0; i < len; i++) {
  3235. ret.push(arraySlice.call(value[i]));
  3236. }
  3237. return ret;
  3238. }
  3239. return arraySlice.call(value);
  3240. }
  3241. return value;
  3242. }
  3243. function rgba2String(rgba) {
  3244. rgba[0] = Math.floor(rgba[0]);
  3245. rgba[1] = Math.floor(rgba[1]);
  3246. rgba[2] = Math.floor(rgba[2]);
  3247. return 'rgba(' + rgba.join(',') + ')';
  3248. }
  3249. function guessArrayDim(value) {
  3250. return isArrayLike(value && value[0]) ? 2 : 1;
  3251. }
  3252. var tmpRgba = [0, 0, 0, 0];
  3253. var Track = (function () {
  3254. function Track(propName) {
  3255. this.keyframes = [];
  3256. this.maxTime = 0;
  3257. this.arrDim = 0;
  3258. this.interpolable = true;
  3259. this._needsSort = false;
  3260. this._isAllValueEqual = true;
  3261. this._lastFrame = 0;
  3262. this._lastFramePercent = 0;
  3263. this.propName = propName;
  3264. }
  3265. Track.prototype.isFinished = function () {
  3266. return this._finished;
  3267. };
  3268. Track.prototype.setFinished = function () {
  3269. this._finished = true;
  3270. if (this._additiveTrack) {
  3271. this._additiveTrack.setFinished();
  3272. }
  3273. };
  3274. Track.prototype.needsAnimate = function () {
  3275. return !this._isAllValueEqual
  3276. && this.keyframes.length >= 2
  3277. && this.interpolable
  3278. && this.maxTime > 0;
  3279. };
  3280. Track.prototype.getAdditiveTrack = function () {
  3281. return this._additiveTrack;
  3282. };
  3283. Track.prototype.addKeyframe = function (time, value) {
  3284. if (time >= this.maxTime) {
  3285. this.maxTime = time;
  3286. }
  3287. else {
  3288. this._needsSort = true;
  3289. }
  3290. var keyframes = this.keyframes;
  3291. var len = keyframes.length;
  3292. if (this.interpolable) {
  3293. if (isArrayLike(value)) {
  3294. var arrayDim = guessArrayDim(value);
  3295. if (len > 0 && this.arrDim !== arrayDim) {
  3296. this.interpolable = false;
  3297. return;
  3298. }
  3299. if (arrayDim === 1 && typeof value[0] !== 'number'
  3300. || arrayDim === 2 && typeof value[0][0] !== 'number') {
  3301. this.interpolable = false;
  3302. return;
  3303. }
  3304. if (len > 0) {
  3305. var lastFrame = keyframes[len - 1];
  3306. if (this._isAllValueEqual) {
  3307. if (arrayDim === 1) {
  3308. if (!is1DArraySame(value, lastFrame.value)) {
  3309. this._isAllValueEqual = false;
  3310. }
  3311. }
  3312. else {
  3313. this._isAllValueEqual = false;
  3314. }
  3315. }
  3316. }
  3317. this.arrDim = arrayDim;
  3318. }
  3319. else {
  3320. if (this.arrDim > 0) {
  3321. this.interpolable = false;
  3322. return;
  3323. }
  3324. if (typeof value === 'string') {
  3325. var colorArray = parse(value);
  3326. if (colorArray) {
  3327. value = colorArray;
  3328. this.isValueColor = true;
  3329. }
  3330. else {
  3331. this.interpolable = false;
  3332. }
  3333. }
  3334. else if (typeof value !== 'number' || isNaN(value)) {
  3335. this.interpolable = false;
  3336. return;
  3337. }
  3338. if (this._isAllValueEqual && len > 0) {
  3339. var lastFrame = keyframes[len - 1];
  3340. if (this.isValueColor && !is1DArraySame(lastFrame.value, value)) {
  3341. this._isAllValueEqual = false;
  3342. }
  3343. else if (lastFrame.value !== value) {
  3344. this._isAllValueEqual = false;
  3345. }
  3346. }
  3347. }
  3348. }
  3349. var kf = {
  3350. time: time,
  3351. value: value,
  3352. percent: 0
  3353. };
  3354. this.keyframes.push(kf);
  3355. return kf;
  3356. };
  3357. Track.prototype.prepare = function (additiveTrack) {
  3358. var kfs = this.keyframes;
  3359. if (this._needsSort) {
  3360. kfs.sort(function (a, b) {
  3361. return a.time - b.time;
  3362. });
  3363. }
  3364. var arrDim = this.arrDim;
  3365. var kfsLen = kfs.length;
  3366. var lastKf = kfs[kfsLen - 1];
  3367. for (var i = 0; i < kfsLen; i++) {
  3368. kfs[i].percent = kfs[i].time / this.maxTime;
  3369. if (arrDim > 0 && i !== kfsLen - 1) {
  3370. fillArray(kfs[i].value, lastKf.value, arrDim);
  3371. }
  3372. }
  3373. if (additiveTrack
  3374. && this.needsAnimate()
  3375. && additiveTrack.needsAnimate()
  3376. && arrDim === additiveTrack.arrDim
  3377. && this.isValueColor === additiveTrack.isValueColor
  3378. && !additiveTrack._finished) {
  3379. this._additiveTrack = additiveTrack;
  3380. var startValue = kfs[0].value;
  3381. for (var i = 0; i < kfsLen; i++) {
  3382. if (arrDim === 0) {
  3383. if (this.isValueColor) {
  3384. kfs[i].additiveValue =
  3385. add1DArray([], kfs[i].value, startValue, -1);
  3386. }
  3387. else {
  3388. kfs[i].additiveValue = kfs[i].value - startValue;
  3389. }
  3390. }
  3391. else if (arrDim === 1) {
  3392. kfs[i].additiveValue = add1DArray([], kfs[i].value, startValue, -1);
  3393. }
  3394. else if (arrDim === 2) {
  3395. kfs[i].additiveValue = add2DArray([], kfs[i].value, startValue, -1);
  3396. }
  3397. }
  3398. }
  3399. };
  3400. Track.prototype.step = function (target, percent) {
  3401. if (this._finished) {
  3402. return;
  3403. }
  3404. if (this._additiveTrack && this._additiveTrack._finished) {
  3405. this._additiveTrack = null;
  3406. }
  3407. var isAdditive = this._additiveTrack != null;
  3408. var valueKey = isAdditive ? 'additiveValue' : 'value';
  3409. var keyframes = this.keyframes;
  3410. var kfsNum = this.keyframes.length;
  3411. var propName = this.propName;
  3412. var arrDim = this.arrDim;
  3413. var isValueColor = this.isValueColor;
  3414. var frameIdx;
  3415. if (percent < 0) {
  3416. frameIdx = 0;
  3417. }
  3418. else if (percent < this._lastFramePercent) {
  3419. var start = Math.min(this._lastFrame + 1, kfsNum - 1);
  3420. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  3421. if (keyframes[frameIdx].percent <= percent) {
  3422. break;
  3423. }
  3424. }
  3425. frameIdx = Math.min(frameIdx, kfsNum - 2);
  3426. }
  3427. else {
  3428. for (frameIdx = this._lastFrame; frameIdx < kfsNum; frameIdx++) {
  3429. if (keyframes[frameIdx].percent > percent) {
  3430. break;
  3431. }
  3432. }
  3433. frameIdx = Math.min(frameIdx - 1, kfsNum - 2);
  3434. }
  3435. var nextFrame = keyframes[frameIdx + 1];
  3436. var frame = keyframes[frameIdx];
  3437. if (!(frame && nextFrame)) {
  3438. return;
  3439. }
  3440. this._lastFrame = frameIdx;
  3441. this._lastFramePercent = percent;
  3442. var range = (nextFrame.percent - frame.percent);
  3443. if (range === 0) {
  3444. return;
  3445. }
  3446. var w = (percent - frame.percent) / range;
  3447. var targetArr = isAdditive ? this._additiveValue
  3448. : (isValueColor ? tmpRgba : target[propName]);
  3449. if ((arrDim > 0 || isValueColor) && !targetArr) {
  3450. targetArr = this._additiveValue = [];
  3451. }
  3452. if (this.useSpline) {
  3453. var p1 = keyframes[frameIdx][valueKey];
  3454. var p0 = keyframes[frameIdx === 0 ? frameIdx : frameIdx - 1][valueKey];
  3455. var p2 = keyframes[frameIdx > kfsNum - 2 ? kfsNum - 1 : frameIdx + 1][valueKey];
  3456. var p3 = keyframes[frameIdx > kfsNum - 3 ? kfsNum - 1 : frameIdx + 2][valueKey];
  3457. if (arrDim > 0) {
  3458. arrDim === 1
  3459. ? catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w)
  3460. : catmullRomInterpolate2DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w);
  3461. }
  3462. else if (isValueColor) {
  3463. catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w);
  3464. if (!isAdditive) {
  3465. target[propName] = rgba2String(targetArr);
  3466. }
  3467. }
  3468. else {
  3469. var value = void 0;
  3470. if (!this.interpolable) {
  3471. value = p2;
  3472. }
  3473. else {
  3474. value = catmullRomInterpolate(p0, p1, p2, p3, w, w * w, w * w * w);
  3475. }
  3476. if (isAdditive) {
  3477. this._additiveValue = value;
  3478. }
  3479. else {
  3480. target[propName] = value;
  3481. }
  3482. }
  3483. }
  3484. else {
  3485. if (arrDim > 0) {
  3486. arrDim === 1
  3487. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  3488. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3489. }
  3490. else if (isValueColor) {
  3491. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3492. if (!isAdditive) {
  3493. target[propName] = rgba2String(targetArr);
  3494. }
  3495. }
  3496. else {
  3497. var value = void 0;
  3498. if (!this.interpolable) {
  3499. value = step(frame[valueKey], nextFrame[valueKey], w);
  3500. }
  3501. else {
  3502. value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  3503. }
  3504. if (isAdditive) {
  3505. this._additiveValue = value;
  3506. }
  3507. else {
  3508. target[propName] = value;
  3509. }
  3510. }
  3511. }
  3512. if (isAdditive) {
  3513. this._addToTarget(target);
  3514. }
  3515. };
  3516. Track.prototype._addToTarget = function (target) {
  3517. var arrDim = this.arrDim;
  3518. var propName = this.propName;
  3519. var additiveValue = this._additiveValue;
  3520. if (arrDim === 0) {
  3521. if (this.isValueColor) {
  3522. parse(target[propName], tmpRgba);
  3523. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  3524. target[propName] = rgba2String(tmpRgba);
  3525. }
  3526. else {
  3527. target[propName] = target[propName] + additiveValue;
  3528. }
  3529. }
  3530. else if (arrDim === 1) {
  3531. add1DArray(target[propName], target[propName], additiveValue, 1);
  3532. }
  3533. else if (arrDim === 2) {
  3534. add2DArray(target[propName], target[propName], additiveValue, 1);
  3535. }
  3536. };
  3537. return Track;
  3538. }());
  3539. var Animator = (function () {
  3540. function Animator(target, loop, additiveTo) {
  3541. this._tracks = {};
  3542. this._trackKeys = [];
  3543. this._delay = 0;
  3544. this._maxTime = 0;
  3545. this._paused = false;
  3546. this._started = 0;
  3547. this._clip = null;
  3548. this._target = target;
  3549. this._loop = loop;
  3550. if (loop && additiveTo) {
  3551. logError('Can\' use additive animation on looped animation.');
  3552. return;
  3553. }
  3554. this._additiveAnimators = additiveTo;
  3555. }
  3556. Animator.prototype.getTarget = function () {
  3557. return this._target;
  3558. };
  3559. Animator.prototype.changeTarget = function (target) {
  3560. this._target = target;
  3561. };
  3562. Animator.prototype.when = function (time, props) {
  3563. return this.whenWithKeys(time, props, keys(props));
  3564. };
  3565. Animator.prototype.whenWithKeys = function (time, props, propNames) {
  3566. var tracks = this._tracks;
  3567. for (var i = 0; i < propNames.length; i++) {
  3568. var propName = propNames[i];
  3569. var track = tracks[propName];
  3570. if (!track) {
  3571. track = tracks[propName] = new Track(propName);
  3572. var initialValue = void 0;
  3573. var additiveTrack = this._getAdditiveTrack(propName);
  3574. if (additiveTrack) {
  3575. var lastFinalKf = additiveTrack.keyframes[additiveTrack.keyframes.length - 1];
  3576. initialValue = lastFinalKf && lastFinalKf.value;
  3577. if (additiveTrack.isValueColor && initialValue) {
  3578. initialValue = rgba2String(initialValue);
  3579. }
  3580. }
  3581. else {
  3582. initialValue = this._target[propName];
  3583. }
  3584. if (initialValue == null) {
  3585. continue;
  3586. }
  3587. if (time !== 0) {
  3588. track.addKeyframe(0, cloneValue(initialValue));
  3589. }
  3590. this._trackKeys.push(propName);
  3591. }
  3592. track.addKeyframe(time, cloneValue(props[propName]));
  3593. }
  3594. this._maxTime = Math.max(this._maxTime, time);
  3595. return this;
  3596. };
  3597. Animator.prototype.pause = function () {
  3598. this._clip.pause();
  3599. this._paused = true;
  3600. };
  3601. Animator.prototype.resume = function () {
  3602. this._clip.resume();
  3603. this._paused = false;
  3604. };
  3605. Animator.prototype.isPaused = function () {
  3606. return !!this._paused;
  3607. };
  3608. Animator.prototype._doneCallback = function () {
  3609. this._setTracksFinished();
  3610. this._clip = null;
  3611. var doneList = this._doneCbs;
  3612. if (doneList) {
  3613. var len = doneList.length;
  3614. for (var i = 0; i < len; i++) {
  3615. doneList[i].call(this);
  3616. }
  3617. }
  3618. };
  3619. Animator.prototype._abortedCallback = function () {
  3620. this._setTracksFinished();
  3621. var animation = this.animation;
  3622. var abortedList = this._abortedCbs;
  3623. if (animation) {
  3624. animation.removeClip(this._clip);
  3625. }
  3626. this._clip = null;
  3627. if (abortedList) {
  3628. for (var i = 0; i < abortedList.length; i++) {
  3629. abortedList[i].call(this);
  3630. }
  3631. }
  3632. };
  3633. Animator.prototype._setTracksFinished = function () {
  3634. var tracks = this._tracks;
  3635. var tracksKeys = this._trackKeys;
  3636. for (var i = 0; i < tracksKeys.length; i++) {
  3637. tracks[tracksKeys[i]].setFinished();
  3638. }
  3639. };
  3640. Animator.prototype._getAdditiveTrack = function (trackName) {
  3641. var additiveTrack;
  3642. var additiveAnimators = this._additiveAnimators;
  3643. if (additiveAnimators) {
  3644. for (var i = 0; i < additiveAnimators.length; i++) {
  3645. var track = additiveAnimators[i].getTrack(trackName);
  3646. if (track) {
  3647. additiveTrack = track;
  3648. }
  3649. }
  3650. }
  3651. return additiveTrack;
  3652. };
  3653. Animator.prototype.start = function (easing, forceAnimate) {
  3654. if (this._started > 0) {
  3655. return;
  3656. }
  3657. this._started = 1;
  3658. var self = this;
  3659. var tracks = [];
  3660. for (var i = 0; i < this._trackKeys.length; i++) {
  3661. var propName = this._trackKeys[i];
  3662. var track = this._tracks[propName];
  3663. var additiveTrack = this._getAdditiveTrack(propName);
  3664. var kfs = track.keyframes;
  3665. track.prepare(additiveTrack);
  3666. if (track.needsAnimate()) {
  3667. tracks.push(track);
  3668. }
  3669. else if (!track.interpolable) {
  3670. var lastKf = kfs[kfs.length - 1];
  3671. if (lastKf) {
  3672. self._target[track.propName] = lastKf.value;
  3673. }
  3674. }
  3675. }
  3676. if (tracks.length || forceAnimate) {
  3677. var clip = new Clip({
  3678. life: this._maxTime,
  3679. loop: this._loop,
  3680. delay: this._delay,
  3681. onframe: function (percent) {
  3682. self._started = 2;
  3683. var additiveAnimators = self._additiveAnimators;
  3684. if (additiveAnimators) {
  3685. var stillHasAdditiveAnimator = false;
  3686. for (var i = 0; i < additiveAnimators.length; i++) {
  3687. if (additiveAnimators[i]._clip) {
  3688. stillHasAdditiveAnimator = true;
  3689. break;
  3690. }
  3691. }
  3692. if (!stillHasAdditiveAnimator) {
  3693. self._additiveAnimators = null;
  3694. }
  3695. }
  3696. for (var i = 0; i < tracks.length; i++) {
  3697. tracks[i].step(self._target, percent);
  3698. }
  3699. var onframeList = self._onframeCbs;
  3700. if (onframeList) {
  3701. for (var i = 0; i < onframeList.length; i++) {
  3702. onframeList[i](self._target, percent);
  3703. }
  3704. }
  3705. },
  3706. ondestroy: function () {
  3707. self._doneCallback();
  3708. }
  3709. });
  3710. this._clip = clip;
  3711. if (this.animation) {
  3712. this.animation.addClip(clip);
  3713. }
  3714. if (easing && easing !== 'spline') {
  3715. clip.easing = easing;
  3716. }
  3717. }
  3718. else {
  3719. this._doneCallback();
  3720. }
  3721. return this;
  3722. };
  3723. Animator.prototype.stop = function (forwardToLast) {
  3724. if (!this._clip) {
  3725. return;
  3726. }
  3727. var clip = this._clip;
  3728. if (forwardToLast) {
  3729. clip.onframe(1);
  3730. }
  3731. this._abortedCallback();
  3732. };
  3733. Animator.prototype.delay = function (time) {
  3734. this._delay = time;
  3735. return this;
  3736. };
  3737. Animator.prototype.during = function (cb) {
  3738. if (cb) {
  3739. if (!this._onframeCbs) {
  3740. this._onframeCbs = [];
  3741. }
  3742. this._onframeCbs.push(cb);
  3743. }
  3744. return this;
  3745. };
  3746. Animator.prototype.done = function (cb) {
  3747. if (cb) {
  3748. if (!this._doneCbs) {
  3749. this._doneCbs = [];
  3750. }
  3751. this._doneCbs.push(cb);
  3752. }
  3753. return this;
  3754. };
  3755. Animator.prototype.aborted = function (cb) {
  3756. if (cb) {
  3757. if (!this._abortedCbs) {
  3758. this._abortedCbs = [];
  3759. }
  3760. this._abortedCbs.push(cb);
  3761. }
  3762. return this;
  3763. };
  3764. Animator.prototype.getClip = function () {
  3765. return this._clip;
  3766. };
  3767. Animator.prototype.getTrack = function (propName) {
  3768. return this._tracks[propName];
  3769. };
  3770. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  3771. if (!propNames.length || !this._clip) {
  3772. return true;
  3773. }
  3774. var tracks = this._tracks;
  3775. var tracksKeys = this._trackKeys;
  3776. for (var i = 0; i < propNames.length; i++) {
  3777. var track = tracks[propNames[i]];
  3778. if (track) {
  3779. if (forwardToLast) {
  3780. track.step(this._target, 1);
  3781. }
  3782. else if (this._started === 1) {
  3783. track.step(this._target, 0);
  3784. }
  3785. track.setFinished();
  3786. }
  3787. }
  3788. var allAborted = true;
  3789. for (var i = 0; i < tracksKeys.length; i++) {
  3790. if (!tracks[tracksKeys[i]].isFinished()) {
  3791. allAborted = false;
  3792. break;
  3793. }
  3794. }
  3795. if (allAborted) {
  3796. this._abortedCallback();
  3797. }
  3798. return allAborted;
  3799. };
  3800. Animator.prototype.saveFinalToTarget = function (target, trackKeys) {
  3801. if (!target) {
  3802. return;
  3803. }
  3804. trackKeys = trackKeys || this._trackKeys;
  3805. for (var i = 0; i < trackKeys.length; i++) {
  3806. var propName = trackKeys[i];
  3807. var track = this._tracks[propName];
  3808. if (!track || track.isFinished()) {
  3809. continue;
  3810. }
  3811. var kfs = track.keyframes;
  3812. var lastKf = kfs[kfs.length - 1];
  3813. if (lastKf) {
  3814. var val = cloneValue(lastKf.value);
  3815. if (track.isValueColor) {
  3816. val = rgba2String(val);
  3817. }
  3818. target[propName] = val;
  3819. }
  3820. }
  3821. };
  3822. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  3823. trackKeys = trackKeys || keys(finalProps);
  3824. for (var i = 0; i < trackKeys.length; i++) {
  3825. var propName = trackKeys[i];
  3826. var track = this._tracks[propName];
  3827. if (!track) {
  3828. continue;
  3829. }
  3830. var kfs = track.keyframes;
  3831. if (kfs.length > 1) {
  3832. var lastKf = kfs.pop();
  3833. track.addKeyframe(lastKf.time, finalProps[propName]);
  3834. track.prepare(track.getAdditiveTrack());
  3835. }
  3836. }
  3837. };
  3838. return Animator;
  3839. }());
  3840. var Animation = (function (_super) {
  3841. __extends(Animation, _super);
  3842. function Animation(opts) {
  3843. var _this = _super.call(this) || this;
  3844. _this._running = false;
  3845. _this._time = 0;
  3846. _this._pausedTime = 0;
  3847. _this._pauseStart = 0;
  3848. _this._paused = false;
  3849. opts = opts || {};
  3850. _this.stage = opts.stage || {};
  3851. _this.onframe = opts.onframe || function () { };
  3852. return _this;
  3853. }
  3854. Animation.prototype.addClip = function (clip) {
  3855. if (clip.animation) {
  3856. this.removeClip(clip);
  3857. }
  3858. if (!this._clipsHead) {
  3859. this._clipsHead = this._clipsTail = clip;
  3860. }
  3861. else {
  3862. this._clipsTail.next = clip;
  3863. clip.prev = this._clipsTail;
  3864. clip.next = null;
  3865. this._clipsTail = clip;
  3866. }
  3867. clip.animation = this;
  3868. };
  3869. Animation.prototype.addAnimator = function (animator) {
  3870. animator.animation = this;
  3871. var clip = animator.getClip();
  3872. if (clip) {
  3873. this.addClip(clip);
  3874. }
  3875. };
  3876. Animation.prototype.removeClip = function (clip) {
  3877. if (!clip.animation) {
  3878. return;
  3879. }
  3880. var prev = clip.prev;
  3881. var next = clip.next;
  3882. if (prev) {
  3883. prev.next = next;
  3884. }
  3885. else {
  3886. this._clipsHead = next;
  3887. }
  3888. if (next) {
  3889. next.prev = prev;
  3890. }
  3891. else {
  3892. this._clipsTail = prev;
  3893. }
  3894. clip.next = clip.prev = clip.animation = null;
  3895. };
  3896. Animation.prototype.removeAnimator = function (animator) {
  3897. var clip = animator.getClip();
  3898. if (clip) {
  3899. this.removeClip(clip);
  3900. }
  3901. animator.animation = null;
  3902. };
  3903. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  3904. var time = new Date().getTime() - this._pausedTime;
  3905. var delta = time - this._time;
  3906. var clip = this._clipsHead;
  3907. while (clip) {
  3908. var nextClip = clip.next;
  3909. var finished = clip.step(time, delta);
  3910. if (finished) {
  3911. clip.ondestroy && clip.ondestroy();
  3912. this.removeClip(clip);
  3913. clip = nextClip;
  3914. }
  3915. else {
  3916. clip = nextClip;
  3917. }
  3918. }
  3919. this._time = time;
  3920. if (!notTriggerFrameAndStageUpdate) {
  3921. this.onframe(delta);
  3922. this.trigger('frame', delta);
  3923. this.stage.update && this.stage.update();
  3924. }
  3925. };
  3926. Animation.prototype._startLoop = function () {
  3927. var self = this;
  3928. this._running = true;
  3929. function step() {
  3930. if (self._running) {
  3931. requestAnimationFrame$1(step);
  3932. !self._paused && self.update();
  3933. }
  3934. }
  3935. requestAnimationFrame$1(step);
  3936. };
  3937. Animation.prototype.start = function () {
  3938. if (this._running) {
  3939. return;
  3940. }
  3941. this._time = new Date().getTime();
  3942. this._pausedTime = 0;
  3943. this._startLoop();
  3944. };
  3945. Animation.prototype.stop = function () {
  3946. this._running = false;
  3947. };
  3948. Animation.prototype.pause = function () {
  3949. if (!this._paused) {
  3950. this._pauseStart = new Date().getTime();
  3951. this._paused = true;
  3952. }
  3953. };
  3954. Animation.prototype.resume = function () {
  3955. if (this._paused) {
  3956. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  3957. this._paused = false;
  3958. }
  3959. };
  3960. Animation.prototype.clear = function () {
  3961. var clip = this._clipsHead;
  3962. while (clip) {
  3963. var nextClip = clip.next;
  3964. clip.prev = clip.next = clip.animation = null;
  3965. clip = nextClip;
  3966. }
  3967. this._clipsHead = this._clipsTail = null;
  3968. };
  3969. Animation.prototype.isFinished = function () {
  3970. return this._clipsHead == null;
  3971. };
  3972. Animation.prototype.animate = function (target, options) {
  3973. options = options || {};
  3974. this.start();
  3975. var animator = new Animator(target, options.loop);
  3976. this.addAnimator(animator);
  3977. return animator;
  3978. };
  3979. return Animation;
  3980. }(Eventful));
  3981. var TOUCH_CLICK_DELAY = 300;
  3982. var globalEventSupported = env.domSupported;
  3983. var localNativeListenerNames = (function () {
  3984. var mouseHandlerNames = [
  3985. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  3986. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  3987. ];
  3988. var touchHandlerNames = [
  3989. 'touchstart', 'touchend', 'touchmove'
  3990. ];
  3991. var pointerEventNameMap = {
  3992. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  3993. };
  3994. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  3995. var nm = name.replace('mouse', 'pointer');
  3996. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  3997. });
  3998. return {
  3999. mouse: mouseHandlerNames,
  4000. touch: touchHandlerNames,
  4001. pointer: pointerHandlerNames
  4002. };
  4003. })();
  4004. var globalNativeListenerNames = {
  4005. mouse: ['mousemove', 'mouseup'],
  4006. pointer: ['pointermove', 'pointerup']
  4007. };
  4008. var wheelEventSupported = false;
  4009. function isPointerFromTouch(event) {
  4010. var pointerType = event.pointerType;
  4011. return pointerType === 'pen' || pointerType === 'touch';
  4012. }
  4013. function setTouchTimer(scope) {
  4014. scope.touching = true;
  4015. if (scope.touchTimer != null) {
  4016. clearTimeout(scope.touchTimer);
  4017. scope.touchTimer = null;
  4018. }
  4019. scope.touchTimer = setTimeout(function () {
  4020. scope.touching = false;
  4021. scope.touchTimer = null;
  4022. }, 700);
  4023. }
  4024. function markTouch(event) {
  4025. event && (event.zrByTouch = true);
  4026. }
  4027. function normalizeGlobalEvent(instance, event) {
  4028. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  4029. }
  4030. function isLocalEl(instance, el) {
  4031. var elTmp = el;
  4032. var isLocal = false;
  4033. while (elTmp && elTmp.nodeType !== 9
  4034. && !(isLocal = elTmp.domBelongToZr
  4035. || (elTmp !== el && elTmp === instance.painterRoot))) {
  4036. elTmp = elTmp.parentNode;
  4037. }
  4038. return isLocal;
  4039. }
  4040. var FakeGlobalEvent = (function () {
  4041. function FakeGlobalEvent(instance, event) {
  4042. this.stopPropagation = noop;
  4043. this.stopImmediatePropagation = noop;
  4044. this.preventDefault = noop;
  4045. this.type = event.type;
  4046. this.target = this.currentTarget = instance.dom;
  4047. this.pointerType = event.pointerType;
  4048. this.clientX = event.clientX;
  4049. this.clientY = event.clientY;
  4050. }
  4051. return FakeGlobalEvent;
  4052. }());
  4053. var localDOMHandlers = {
  4054. mousedown: function (event) {
  4055. event = normalizeEvent(this.dom, event);
  4056. this.__mayPointerCapture = [event.zrX, event.zrY];
  4057. this.trigger('mousedown', event);
  4058. },
  4059. mousemove: function (event) {
  4060. event = normalizeEvent(this.dom, event);
  4061. var downPoint = this.__mayPointerCapture;
  4062. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  4063. this.__togglePointerCapture(true);
  4064. }
  4065. this.trigger('mousemove', event);
  4066. },
  4067. mouseup: function (event) {
  4068. event = normalizeEvent(this.dom, event);
  4069. this.__togglePointerCapture(false);
  4070. this.trigger('mouseup', event);
  4071. },
  4072. mouseout: function (event) {
  4073. event = normalizeEvent(this.dom, event);
  4074. var element = event.toElement || event.relatedTarget;
  4075. if (!isLocalEl(this, element)) {
  4076. if (this.__pointerCapturing) {
  4077. event.zrEventControl = 'no_globalout';
  4078. }
  4079. this.trigger('mouseout', event);
  4080. }
  4081. },
  4082. wheel: function (event) {
  4083. wheelEventSupported = true;
  4084. event = normalizeEvent(this.dom, event);
  4085. this.trigger('mousewheel', event);
  4086. },
  4087. mousewheel: function (event) {
  4088. if (wheelEventSupported) {
  4089. return;
  4090. }
  4091. event = normalizeEvent(this.dom, event);
  4092. this.trigger('mousewheel', event);
  4093. },
  4094. touchstart: function (event) {
  4095. event = normalizeEvent(this.dom, event);
  4096. markTouch(event);
  4097. this.__lastTouchMoment = new Date();
  4098. this.handler.processGesture(event, 'start');
  4099. localDOMHandlers.mousemove.call(this, event);
  4100. localDOMHandlers.mousedown.call(this, event);
  4101. },
  4102. touchmove: function (event) {
  4103. event = normalizeEvent(this.dom, event);
  4104. markTouch(event);
  4105. this.handler.processGesture(event, 'change');
  4106. localDOMHandlers.mousemove.call(this, event);
  4107. },
  4108. touchend: function (event) {
  4109. event = normalizeEvent(this.dom, event);
  4110. markTouch(event);
  4111. this.handler.processGesture(event, 'end');
  4112. localDOMHandlers.mouseup.call(this, event);
  4113. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  4114. localDOMHandlers.click.call(this, event);
  4115. }
  4116. },
  4117. pointerdown: function (event) {
  4118. localDOMHandlers.mousedown.call(this, event);
  4119. },
  4120. pointermove: function (event) {
  4121. if (!isPointerFromTouch(event)) {
  4122. localDOMHandlers.mousemove.call(this, event);
  4123. }
  4124. },
  4125. pointerup: function (event) {
  4126. localDOMHandlers.mouseup.call(this, event);
  4127. },
  4128. pointerout: function (event) {
  4129. if (!isPointerFromTouch(event)) {
  4130. localDOMHandlers.mouseout.call(this, event);
  4131. }
  4132. }
  4133. };
  4134. each(['click', 'dblclick', 'contextmenu'], function (name) {
  4135. localDOMHandlers[name] = function (event) {
  4136. event = normalizeEvent(this.dom, event);
  4137. this.trigger(name, event);
  4138. };
  4139. });
  4140. var globalDOMHandlers = {
  4141. pointermove: function (event) {
  4142. if (!isPointerFromTouch(event)) {
  4143. globalDOMHandlers.mousemove.call(this, event);
  4144. }
  4145. },
  4146. pointerup: function (event) {
  4147. globalDOMHandlers.mouseup.call(this, event);
  4148. },
  4149. mousemove: function (event) {
  4150. this.trigger('mousemove', event);
  4151. },
  4152. mouseup: function (event) {
  4153. var pointerCaptureReleasing = this.__pointerCapturing;
  4154. this.__togglePointerCapture(false);
  4155. this.trigger('mouseup', event);
  4156. if (pointerCaptureReleasing) {
  4157. event.zrEventControl = 'only_globalout';
  4158. this.trigger('mouseout', event);
  4159. }
  4160. }
  4161. };
  4162. function mountLocalDOMEventListeners(instance, scope) {
  4163. var domHandlers = scope.domHandlers;
  4164. if (env.pointerEventsSupported) {
  4165. each(localNativeListenerNames.pointer, function (nativeEventName) {
  4166. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  4167. domHandlers[nativeEventName].call(instance, event);
  4168. });
  4169. });
  4170. }
  4171. else {
  4172. if (env.touchEventsSupported) {
  4173. each(localNativeListenerNames.touch, function (nativeEventName) {
  4174. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  4175. domHandlers[nativeEventName].call(instance, event);
  4176. setTouchTimer(scope);
  4177. });
  4178. });
  4179. }
  4180. each(localNativeListenerNames.mouse, function (nativeEventName) {
  4181. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  4182. event = getNativeEvent(event);
  4183. if (!scope.touching) {
  4184. domHandlers[nativeEventName].call(instance, event);
  4185. }
  4186. });
  4187. });
  4188. }
  4189. }
  4190. function mountGlobalDOMEventListeners(instance, scope) {
  4191. if (env.pointerEventsSupported) {
  4192. each(globalNativeListenerNames.pointer, mount);
  4193. }
  4194. else if (!env.touchEventsSupported) {
  4195. each(globalNativeListenerNames.mouse, mount);
  4196. }
  4197. function mount(nativeEventName) {
  4198. function nativeEventListener(event) {
  4199. event = getNativeEvent(event);
  4200. if (!isLocalEl(instance, event.target)) {
  4201. event = normalizeGlobalEvent(instance, event);
  4202. scope.domHandlers[nativeEventName].call(instance, event);
  4203. }
  4204. }
  4205. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  4206. }
  4207. }
  4208. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  4209. scope.mounted[nativeEventName] = listener;
  4210. scope.listenerOpts[nativeEventName] = opt;
  4211. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  4212. }
  4213. function unmountDOMEventListeners(scope) {
  4214. var mounted = scope.mounted;
  4215. for (var nativeEventName in mounted) {
  4216. if (mounted.hasOwnProperty(nativeEventName)) {
  4217. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  4218. }
  4219. }
  4220. scope.mounted = {};
  4221. }
  4222. var DOMHandlerScope = (function () {
  4223. function DOMHandlerScope(domTarget, domHandlers) {
  4224. this.mounted = {};
  4225. this.listenerOpts = {};
  4226. this.touching = false;
  4227. this.domTarget = domTarget;
  4228. this.domHandlers = domHandlers;
  4229. }
  4230. return DOMHandlerScope;
  4231. }());
  4232. var HandlerDomProxy = (function (_super) {
  4233. __extends(HandlerDomProxy, _super);
  4234. function HandlerDomProxy(dom, painterRoot) {
  4235. var _this = _super.call(this) || this;
  4236. _this.__pointerCapturing = false;
  4237. _this.dom = dom;
  4238. _this.painterRoot = painterRoot;
  4239. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  4240. if (globalEventSupported) {
  4241. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  4242. }
  4243. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  4244. return _this;
  4245. }
  4246. HandlerDomProxy.prototype.dispose = function () {
  4247. unmountDOMEventListeners(this._localHandlerScope);
  4248. if (globalEventSupported) {
  4249. unmountDOMEventListeners(this._globalHandlerScope);
  4250. }
  4251. };
  4252. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  4253. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  4254. };
  4255. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  4256. this.__mayPointerCapture = null;
  4257. if (globalEventSupported
  4258. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  4259. this.__pointerCapturing = isPointerCapturing;
  4260. var globalHandlerScope = this._globalHandlerScope;
  4261. isPointerCapturing
  4262. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  4263. : unmountDOMEventListeners(globalHandlerScope);
  4264. }
  4265. };
  4266. return HandlerDomProxy;
  4267. }(Eventful));
  4268. var dpr = 1;
  4269. if (typeof window !== 'undefined') {
  4270. dpr = Math.max(window.devicePixelRatio
  4271. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  4272. || 1, 1);
  4273. }
  4274. var devicePixelRatio = dpr;
  4275. var DARK_MODE_THRESHOLD = 0.4;
  4276. var DARK_LABEL_COLOR = '#333';
  4277. var LIGHT_LABEL_COLOR = '#ccc';
  4278. var LIGHTER_LABEL_COLOR = '#eee';
  4279. function create$1() {
  4280. return [1, 0, 0, 1, 0, 0];
  4281. }
  4282. function identity(out) {
  4283. out[0] = 1;
  4284. out[1] = 0;
  4285. out[2] = 0;
  4286. out[3] = 1;
  4287. out[4] = 0;
  4288. out[5] = 0;
  4289. return out;
  4290. }
  4291. function copy$1(out, m) {
  4292. out[0] = m[0];
  4293. out[1] = m[1];
  4294. out[2] = m[2];
  4295. out[3] = m[3];
  4296. out[4] = m[4];
  4297. out[5] = m[5];
  4298. return out;
  4299. }
  4300. function mul$1(out, m1, m2) {
  4301. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  4302. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  4303. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  4304. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  4305. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  4306. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  4307. out[0] = out0;
  4308. out[1] = out1;
  4309. out[2] = out2;
  4310. out[3] = out3;
  4311. out[4] = out4;
  4312. out[5] = out5;
  4313. return out;
  4314. }
  4315. function translate(out, a, v) {
  4316. out[0] = a[0];
  4317. out[1] = a[1];
  4318. out[2] = a[2];
  4319. out[3] = a[3];
  4320. out[4] = a[4] + v[0];
  4321. out[5] = a[5] + v[1];
  4322. return out;
  4323. }
  4324. function rotate(out, a, rad) {
  4325. var aa = a[0];
  4326. var ac = a[2];
  4327. var atx = a[4];
  4328. var ab = a[1];
  4329. var ad = a[3];
  4330. var aty = a[5];
  4331. var st = Math.sin(rad);
  4332. var ct = Math.cos(rad);
  4333. out[0] = aa * ct + ab * st;
  4334. out[1] = -aa * st + ab * ct;
  4335. out[2] = ac * ct + ad * st;
  4336. out[3] = -ac * st + ct * ad;
  4337. out[4] = ct * atx + st * aty;
  4338. out[5] = ct * aty - st * atx;
  4339. return out;
  4340. }
  4341. function scale$1(out, a, v) {
  4342. var vx = v[0];
  4343. var vy = v[1];
  4344. out[0] = a[0] * vx;
  4345. out[1] = a[1] * vy;
  4346. out[2] = a[2] * vx;
  4347. out[3] = a[3] * vy;
  4348. out[4] = a[4] * vx;
  4349. out[5] = a[5] * vy;
  4350. return out;
  4351. }
  4352. function invert(out, a) {
  4353. var aa = a[0];
  4354. var ac = a[2];
  4355. var atx = a[4];
  4356. var ab = a[1];
  4357. var ad = a[3];
  4358. var aty = a[5];
  4359. var det = aa * ad - ab * ac;
  4360. if (!det) {
  4361. return null;
  4362. }
  4363. det = 1.0 / det;
  4364. out[0] = ad * det;
  4365. out[1] = -ab * det;
  4366. out[2] = -ac * det;
  4367. out[3] = aa * det;
  4368. out[4] = (ac * aty - ad * atx) * det;
  4369. out[5] = (ab * atx - aa * aty) * det;
  4370. return out;
  4371. }
  4372. function clone$2(a) {
  4373. var b = create$1();
  4374. copy$1(b, a);
  4375. return b;
  4376. }
  4377. var matrix = /*#__PURE__*/Object.freeze({
  4378. __proto__: null,
  4379. create: create$1,
  4380. identity: identity,
  4381. copy: copy$1,
  4382. mul: mul$1,
  4383. translate: translate,
  4384. rotate: rotate,
  4385. scale: scale$1,
  4386. invert: invert,
  4387. clone: clone$2
  4388. });
  4389. var mIdentity = identity;
  4390. var EPSILON = 5e-5;
  4391. function isNotAroundZero(val) {
  4392. return val > EPSILON || val < -EPSILON;
  4393. }
  4394. var scaleTmp = [];
  4395. var tmpTransform = [];
  4396. var originTransform = create$1();
  4397. var abs = Math.abs;
  4398. var Transformable = (function () {
  4399. function Transformable() {
  4400. }
  4401. Transformable.prototype.getLocalTransform = function (m) {
  4402. return Transformable.getLocalTransform(this, m);
  4403. };
  4404. Transformable.prototype.setPosition = function (arr) {
  4405. this.x = arr[0];
  4406. this.y = arr[1];
  4407. };
  4408. Transformable.prototype.setScale = function (arr) {
  4409. this.scaleX = arr[0];
  4410. this.scaleY = arr[1];
  4411. };
  4412. Transformable.prototype.setSkew = function (arr) {
  4413. this.skewX = arr[0];
  4414. this.skewY = arr[1];
  4415. };
  4416. Transformable.prototype.setOrigin = function (arr) {
  4417. this.originX = arr[0];
  4418. this.originY = arr[1];
  4419. };
  4420. Transformable.prototype.needLocalTransform = function () {
  4421. return isNotAroundZero(this.rotation)
  4422. || isNotAroundZero(this.x)
  4423. || isNotAroundZero(this.y)
  4424. || isNotAroundZero(this.scaleX - 1)
  4425. || isNotAroundZero(this.scaleY - 1);
  4426. };
  4427. Transformable.prototype.updateTransform = function () {
  4428. var parentTransform = this.parent && this.parent.transform;
  4429. var needLocalTransform = this.needLocalTransform();
  4430. var m = this.transform;
  4431. if (!(needLocalTransform || parentTransform)) {
  4432. m && mIdentity(m);
  4433. return;
  4434. }
  4435. m = m || create$1();
  4436. if (needLocalTransform) {
  4437. this.getLocalTransform(m);
  4438. }
  4439. else {
  4440. mIdentity(m);
  4441. }
  4442. if (parentTransform) {
  4443. if (needLocalTransform) {
  4444. mul$1(m, parentTransform, m);
  4445. }
  4446. else {
  4447. copy$1(m, parentTransform);
  4448. }
  4449. }
  4450. this.transform = m;
  4451. this._resolveGlobalScaleRatio(m);
  4452. };
  4453. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  4454. var globalScaleRatio = this.globalScaleRatio;
  4455. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  4456. this.getGlobalScale(scaleTmp);
  4457. var relX = scaleTmp[0] < 0 ? -1 : 1;
  4458. var relY = scaleTmp[1] < 0 ? -1 : 1;
  4459. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  4460. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  4461. m[0] *= sx;
  4462. m[1] *= sx;
  4463. m[2] *= sy;
  4464. m[3] *= sy;
  4465. }
  4466. this.invTransform = this.invTransform || create$1();
  4467. invert(this.invTransform, m);
  4468. };
  4469. Transformable.prototype.getComputedTransform = function () {
  4470. var transformNode = this;
  4471. var ancestors = [];
  4472. while (transformNode) {
  4473. ancestors.push(transformNode);
  4474. transformNode = transformNode.parent;
  4475. }
  4476. while (transformNode = ancestors.pop()) {
  4477. transformNode.updateTransform();
  4478. }
  4479. return this.transform;
  4480. };
  4481. Transformable.prototype.setLocalTransform = function (m) {
  4482. if (!m) {
  4483. return;
  4484. }
  4485. var sx = m[0] * m[0] + m[1] * m[1];
  4486. var sy = m[2] * m[2] + m[3] * m[3];
  4487. var rotation = Math.atan2(m[1], m[0]);
  4488. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  4489. sy = Math.sqrt(sy) * Math.cos(shearX);
  4490. sx = Math.sqrt(sx);
  4491. this.skewX = shearX;
  4492. this.skewY = 0;
  4493. this.rotation = -rotation;
  4494. this.x = +m[4];
  4495. this.y = +m[5];
  4496. this.scaleX = sx;
  4497. this.scaleY = sy;
  4498. this.originX = 0;
  4499. this.originY = 0;
  4500. };
  4501. Transformable.prototype.decomposeTransform = function () {
  4502. if (!this.transform) {
  4503. return;
  4504. }
  4505. var parent = this.parent;
  4506. var m = this.transform;
  4507. if (parent && parent.transform) {
  4508. mul$1(tmpTransform, parent.invTransform, m);
  4509. m = tmpTransform;
  4510. }
  4511. var ox = this.originX;
  4512. var oy = this.originY;
  4513. if (ox || oy) {
  4514. originTransform[4] = ox;
  4515. originTransform[5] = oy;
  4516. mul$1(tmpTransform, m, originTransform);
  4517. tmpTransform[4] -= ox;
  4518. tmpTransform[5] -= oy;
  4519. m = tmpTransform;
  4520. }
  4521. this.setLocalTransform(m);
  4522. };
  4523. Transformable.prototype.getGlobalScale = function (out) {
  4524. var m = this.transform;
  4525. out = out || [];
  4526. if (!m) {
  4527. out[0] = 1;
  4528. out[1] = 1;
  4529. return out;
  4530. }
  4531. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  4532. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  4533. if (m[0] < 0) {
  4534. out[0] = -out[0];
  4535. }
  4536. if (m[3] < 0) {
  4537. out[1] = -out[1];
  4538. }
  4539. return out;
  4540. };
  4541. Transformable.prototype.transformCoordToLocal = function (x, y) {
  4542. var v2 = [x, y];
  4543. var invTransform = this.invTransform;
  4544. if (invTransform) {
  4545. applyTransform(v2, v2, invTransform);
  4546. }
  4547. return v2;
  4548. };
  4549. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  4550. var v2 = [x, y];
  4551. var transform = this.transform;
  4552. if (transform) {
  4553. applyTransform(v2, v2, transform);
  4554. }
  4555. return v2;
  4556. };
  4557. Transformable.prototype.getLineScale = function () {
  4558. var m = this.transform;
  4559. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  4560. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  4561. : 1;
  4562. };
  4563. Transformable.prototype.copyTransform = function (source) {
  4564. var target = this;
  4565. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  4566. var propName = TRANSFORMABLE_PROPS[i];
  4567. target[propName] = source[propName];
  4568. }
  4569. };
  4570. Transformable.getLocalTransform = function (target, m) {
  4571. m = m || [];
  4572. var ox = target.originX || 0;
  4573. var oy = target.originY || 0;
  4574. var sx = target.scaleX;
  4575. var sy = target.scaleY;
  4576. var rotation = target.rotation || 0;
  4577. var x = target.x;
  4578. var y = target.y;
  4579. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  4580. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  4581. if (ox || oy) {
  4582. m[4] = -ox * sx - skewX * oy * sy;
  4583. m[5] = -oy * sy - skewY * ox * sx;
  4584. }
  4585. else {
  4586. m[4] = m[5] = 0;
  4587. }
  4588. m[0] = sx;
  4589. m[3] = sy;
  4590. m[1] = skewY * sx;
  4591. m[2] = skewX * sy;
  4592. rotation && rotate(m, m, rotation);
  4593. m[4] += ox + x;
  4594. m[5] += oy + y;
  4595. return m;
  4596. };
  4597. Transformable.initDefaultProps = (function () {
  4598. var proto = Transformable.prototype;
  4599. proto.x = 0;
  4600. proto.y = 0;
  4601. proto.scaleX = 1;
  4602. proto.scaleY = 1;
  4603. proto.originX = 0;
  4604. proto.originY = 0;
  4605. proto.skewX = 0;
  4606. proto.skewY = 0;
  4607. proto.rotation = 0;
  4608. proto.globalScaleRatio = 1;
  4609. })();
  4610. return Transformable;
  4611. }());
  4612. var TRANSFORMABLE_PROPS = [
  4613. 'x', 'y', 'originX', 'originY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  4614. ];
  4615. var Point = (function () {
  4616. function Point(x, y) {
  4617. this.x = x || 0;
  4618. this.y = y || 0;
  4619. }
  4620. Point.prototype.copy = function (other) {
  4621. this.x = other.x;
  4622. this.y = other.y;
  4623. return this;
  4624. };
  4625. Point.prototype.clone = function () {
  4626. return new Point(this.x, this.y);
  4627. };
  4628. Point.prototype.set = function (x, y) {
  4629. this.x = x;
  4630. this.y = y;
  4631. return this;
  4632. };
  4633. Point.prototype.equal = function (other) {
  4634. return other.x === this.x && other.y === this.y;
  4635. };
  4636. Point.prototype.add = function (other) {
  4637. this.x += other.x;
  4638. this.y += other.y;
  4639. return this;
  4640. };
  4641. Point.prototype.scale = function (scalar) {
  4642. this.x *= scalar;
  4643. this.y *= scalar;
  4644. };
  4645. Point.prototype.scaleAndAdd = function (other, scalar) {
  4646. this.x += other.x * scalar;
  4647. this.y += other.y * scalar;
  4648. };
  4649. Point.prototype.sub = function (other) {
  4650. this.x -= other.x;
  4651. this.y -= other.y;
  4652. return this;
  4653. };
  4654. Point.prototype.dot = function (other) {
  4655. return this.x * other.x + this.y * other.y;
  4656. };
  4657. Point.prototype.len = function () {
  4658. return Math.sqrt(this.x * this.x + this.y * this.y);
  4659. };
  4660. Point.prototype.lenSquare = function () {
  4661. return this.x * this.x + this.y * this.y;
  4662. };
  4663. Point.prototype.normalize = function () {
  4664. var len = this.len();
  4665. this.x /= len;
  4666. this.y /= len;
  4667. return this;
  4668. };
  4669. Point.prototype.distance = function (other) {
  4670. var dx = this.x - other.x;
  4671. var dy = this.y - other.y;
  4672. return Math.sqrt(dx * dx + dy * dy);
  4673. };
  4674. Point.prototype.distanceSquare = function (other) {
  4675. var dx = this.x - other.x;
  4676. var dy = this.y - other.y;
  4677. return dx * dx + dy * dy;
  4678. };
  4679. Point.prototype.negate = function () {
  4680. this.x = -this.x;
  4681. this.y = -this.y;
  4682. return this;
  4683. };
  4684. Point.prototype.transform = function (m) {
  4685. if (!m) {
  4686. return;
  4687. }
  4688. var x = this.x;
  4689. var y = this.y;
  4690. this.x = m[0] * x + m[2] * y + m[4];
  4691. this.y = m[1] * x + m[3] * y + m[5];
  4692. return this;
  4693. };
  4694. Point.prototype.toArray = function (out) {
  4695. out[0] = this.x;
  4696. out[1] = this.y;
  4697. return out;
  4698. };
  4699. Point.prototype.fromArray = function (input) {
  4700. this.x = input[0];
  4701. this.y = input[1];
  4702. };
  4703. Point.set = function (p, x, y) {
  4704. p.x = x;
  4705. p.y = y;
  4706. };
  4707. Point.copy = function (p, p2) {
  4708. p.x = p2.x;
  4709. p.y = p2.y;
  4710. };
  4711. Point.len = function (p) {
  4712. return Math.sqrt(p.x * p.x + p.y * p.y);
  4713. };
  4714. Point.lenSquare = function (p) {
  4715. return p.x * p.x + p.y * p.y;
  4716. };
  4717. Point.dot = function (p0, p1) {
  4718. return p0.x * p1.x + p0.y * p1.y;
  4719. };
  4720. Point.add = function (out, p0, p1) {
  4721. out.x = p0.x + p1.x;
  4722. out.y = p0.y + p1.y;
  4723. };
  4724. Point.sub = function (out, p0, p1) {
  4725. out.x = p0.x - p1.x;
  4726. out.y = p0.y - p1.y;
  4727. };
  4728. Point.scale = function (out, p0, scalar) {
  4729. out.x = p0.x * scalar;
  4730. out.y = p0.y * scalar;
  4731. };
  4732. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  4733. out.x = p0.x + p1.x * scalar;
  4734. out.y = p0.y + p1.y * scalar;
  4735. };
  4736. Point.lerp = function (out, p0, p1, t) {
  4737. var onet = 1 - t;
  4738. out.x = onet * p0.x + t * p1.x;
  4739. out.y = onet * p0.y + t * p1.y;
  4740. };
  4741. return Point;
  4742. }());
  4743. var mathMin = Math.min;
  4744. var mathMax = Math.max;
  4745. var lt = new Point();
  4746. var rb = new Point();
  4747. var lb = new Point();
  4748. var rt = new Point();
  4749. var minTv = new Point();
  4750. var maxTv = new Point();
  4751. var BoundingRect = (function () {
  4752. function BoundingRect(x, y, width, height) {
  4753. if (width < 0) {
  4754. x = x + width;
  4755. width = -width;
  4756. }
  4757. if (height < 0) {
  4758. y = y + height;
  4759. height = -height;
  4760. }
  4761. this.x = x;
  4762. this.y = y;
  4763. this.width = width;
  4764. this.height = height;
  4765. }
  4766. BoundingRect.prototype.union = function (other) {
  4767. var x = mathMin(other.x, this.x);
  4768. var y = mathMin(other.y, this.y);
  4769. if (isFinite(this.x) && isFinite(this.width)) {
  4770. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  4771. }
  4772. else {
  4773. this.width = other.width;
  4774. }
  4775. if (isFinite(this.y) && isFinite(this.height)) {
  4776. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  4777. }
  4778. else {
  4779. this.height = other.height;
  4780. }
  4781. this.x = x;
  4782. this.y = y;
  4783. };
  4784. BoundingRect.prototype.applyTransform = function (m) {
  4785. BoundingRect.applyTransform(this, this, m);
  4786. };
  4787. BoundingRect.prototype.calculateTransform = function (b) {
  4788. var a = this;
  4789. var sx = b.width / a.width;
  4790. var sy = b.height / a.height;
  4791. var m = create$1();
  4792. translate(m, m, [-a.x, -a.y]);
  4793. scale$1(m, m, [sx, sy]);
  4794. translate(m, m, [b.x, b.y]);
  4795. return m;
  4796. };
  4797. BoundingRect.prototype.intersect = function (b, mtv) {
  4798. if (!b) {
  4799. return false;
  4800. }
  4801. if (!(b instanceof BoundingRect)) {
  4802. b = BoundingRect.create(b);
  4803. }
  4804. var a = this;
  4805. var ax0 = a.x;
  4806. var ax1 = a.x + a.width;
  4807. var ay0 = a.y;
  4808. var ay1 = a.y + a.height;
  4809. var bx0 = b.x;
  4810. var bx1 = b.x + b.width;
  4811. var by0 = b.y;
  4812. var by1 = b.y + b.height;
  4813. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4814. if (mtv) {
  4815. var dMin = Infinity;
  4816. var dMax = 0;
  4817. var d0 = Math.abs(ax1 - bx0);
  4818. var d1 = Math.abs(bx1 - ax0);
  4819. var d2 = Math.abs(ay1 - by0);
  4820. var d3 = Math.abs(by1 - ay0);
  4821. var dx = Math.min(d0, d1);
  4822. var dy = Math.min(d2, d3);
  4823. if (ax1 < bx0 || bx1 < ax0) {
  4824. if (dx > dMax) {
  4825. dMax = dx;
  4826. if (d0 < d1) {
  4827. Point.set(maxTv, -d0, 0);
  4828. }
  4829. else {
  4830. Point.set(maxTv, d1, 0);
  4831. }
  4832. }
  4833. }
  4834. else {
  4835. if (dx < dMin) {
  4836. dMin = dx;
  4837. if (d0 < d1) {
  4838. Point.set(minTv, d0, 0);
  4839. }
  4840. else {
  4841. Point.set(minTv, -d1, 0);
  4842. }
  4843. }
  4844. }
  4845. if (ay1 < by0 || by1 < ay0) {
  4846. if (dy > dMax) {
  4847. dMax = dy;
  4848. if (d2 < d3) {
  4849. Point.set(maxTv, 0, -d2);
  4850. }
  4851. else {
  4852. Point.set(maxTv, 0, d3);
  4853. }
  4854. }
  4855. }
  4856. else {
  4857. if (dx < dMin) {
  4858. dMin = dx;
  4859. if (d2 < d3) {
  4860. Point.set(minTv, 0, d2);
  4861. }
  4862. else {
  4863. Point.set(minTv, 0, -d3);
  4864. }
  4865. }
  4866. }
  4867. }
  4868. if (mtv) {
  4869. Point.copy(mtv, overlap ? minTv : maxTv);
  4870. }
  4871. return overlap;
  4872. };
  4873. BoundingRect.prototype.contain = function (x, y) {
  4874. var rect = this;
  4875. return x >= rect.x
  4876. && x <= (rect.x + rect.width)
  4877. && y >= rect.y
  4878. && y <= (rect.y + rect.height);
  4879. };
  4880. BoundingRect.prototype.clone = function () {
  4881. return new BoundingRect(this.x, this.y, this.width, this.height);
  4882. };
  4883. BoundingRect.prototype.copy = function (other) {
  4884. BoundingRect.copy(this, other);
  4885. };
  4886. BoundingRect.prototype.plain = function () {
  4887. return {
  4888. x: this.x,
  4889. y: this.y,
  4890. width: this.width,
  4891. height: this.height
  4892. };
  4893. };
  4894. BoundingRect.prototype.isFinite = function () {
  4895. return isFinite(this.x)
  4896. && isFinite(this.y)
  4897. && isFinite(this.width)
  4898. && isFinite(this.height);
  4899. };
  4900. BoundingRect.prototype.isZero = function () {
  4901. return this.width === 0 || this.height === 0;
  4902. };
  4903. BoundingRect.create = function (rect) {
  4904. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4905. };
  4906. BoundingRect.copy = function (target, source) {
  4907. target.x = source.x;
  4908. target.y = source.y;
  4909. target.width = source.width;
  4910. target.height = source.height;
  4911. };
  4912. BoundingRect.applyTransform = function (target, source, m) {
  4913. if (!m) {
  4914. if (target !== source) {
  4915. BoundingRect.copy(target, source);
  4916. }
  4917. return;
  4918. }
  4919. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  4920. var sx = m[0];
  4921. var sy = m[3];
  4922. var tx = m[4];
  4923. var ty = m[5];
  4924. target.x = source.x * sx + tx;
  4925. target.y = source.y * sy + ty;
  4926. target.width = source.width * sx;
  4927. target.height = source.height * sy;
  4928. if (target.width < 0) {
  4929. target.x += target.width;
  4930. target.width = -target.width;
  4931. }
  4932. if (target.height < 0) {
  4933. target.y += target.height;
  4934. target.height = -target.height;
  4935. }
  4936. return;
  4937. }
  4938. lt.x = lb.x = source.x;
  4939. lt.y = rt.y = source.y;
  4940. rb.x = rt.x = source.x + source.width;
  4941. rb.y = lb.y = source.y + source.height;
  4942. lt.transform(m);
  4943. rt.transform(m);
  4944. rb.transform(m);
  4945. lb.transform(m);
  4946. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  4947. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  4948. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  4949. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  4950. target.width = maxX - target.x;
  4951. target.height = maxY - target.y;
  4952. };
  4953. return BoundingRect;
  4954. }());
  4955. var textWidthCache = {};
  4956. var DEFAULT_FONT = '12px sans-serif';
  4957. var _ctx;
  4958. var _cachedFont;
  4959. function defaultMeasureText(text, font) {
  4960. if (!_ctx) {
  4961. _ctx = createCanvas().getContext('2d');
  4962. }
  4963. if (_cachedFont !== font) {
  4964. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  4965. }
  4966. return _ctx.measureText(text);
  4967. }
  4968. var methods$1 = {
  4969. measureText: defaultMeasureText
  4970. };
  4971. function getWidth(text, font) {
  4972. font = font || DEFAULT_FONT;
  4973. var cacheOfFont = textWidthCache[font];
  4974. if (!cacheOfFont) {
  4975. cacheOfFont = textWidthCache[font] = new LRU(500);
  4976. }
  4977. var width = cacheOfFont.get(text);
  4978. if (width == null) {
  4979. width = methods$1.measureText(text, font).width;
  4980. cacheOfFont.put(text, width);
  4981. }
  4982. return width;
  4983. }
  4984. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  4985. var width = getWidth(text, font);
  4986. var height = getLineHeight(font);
  4987. var x = adjustTextX(0, width, textAlign);
  4988. var y = adjustTextY(0, height, textBaseline);
  4989. var rect = new BoundingRect(x, y, width, height);
  4990. return rect;
  4991. }
  4992. function getBoundingRect(text, font, textAlign, textBaseline) {
  4993. var textLines = ((text || '') + '').split('\n');
  4994. var len = textLines.length;
  4995. if (len === 1) {
  4996. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  4997. }
  4998. else {
  4999. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5000. for (var i = 0; i < textLines.length; i++) {
  5001. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5002. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5003. }
  5004. return uniondRect;
  5005. }
  5006. }
  5007. function adjustTextX(x, width, textAlign) {
  5008. if (textAlign === 'right') {
  5009. x -= width;
  5010. }
  5011. else if (textAlign === 'center') {
  5012. x -= width / 2;
  5013. }
  5014. return x;
  5015. }
  5016. function adjustTextY(y, height, verticalAlign) {
  5017. if (verticalAlign === 'middle') {
  5018. y -= height / 2;
  5019. }
  5020. else if (verticalAlign === 'bottom') {
  5021. y -= height;
  5022. }
  5023. return y;
  5024. }
  5025. function getLineHeight(font) {
  5026. return getWidth('国', font);
  5027. }
  5028. function parsePercent(value, maxValue) {
  5029. if (typeof value === 'string') {
  5030. if (value.lastIndexOf('%') >= 0) {
  5031. return parseFloat(value) / 100 * maxValue;
  5032. }
  5033. return parseFloat(value);
  5034. }
  5035. return value;
  5036. }
  5037. function calculateTextPosition(out, opts, rect) {
  5038. var textPosition = opts.position || 'inside';
  5039. var distance = opts.distance != null ? opts.distance : 5;
  5040. var height = rect.height;
  5041. var width = rect.width;
  5042. var halfHeight = height / 2;
  5043. var x = rect.x;
  5044. var y = rect.y;
  5045. var textAlign = 'left';
  5046. var textVerticalAlign = 'top';
  5047. if (textPosition instanceof Array) {
  5048. x += parsePercent(textPosition[0], rect.width);
  5049. y += parsePercent(textPosition[1], rect.height);
  5050. textAlign = null;
  5051. textVerticalAlign = null;
  5052. }
  5053. else {
  5054. switch (textPosition) {
  5055. case 'left':
  5056. x -= distance;
  5057. y += halfHeight;
  5058. textAlign = 'right';
  5059. textVerticalAlign = 'middle';
  5060. break;
  5061. case 'right':
  5062. x += distance + width;
  5063. y += halfHeight;
  5064. textVerticalAlign = 'middle';
  5065. break;
  5066. case 'top':
  5067. x += width / 2;
  5068. y -= distance;
  5069. textAlign = 'center';
  5070. textVerticalAlign = 'bottom';
  5071. break;
  5072. case 'bottom':
  5073. x += width / 2;
  5074. y += height + distance;
  5075. textAlign = 'center';
  5076. break;
  5077. case 'inside':
  5078. x += width / 2;
  5079. y += halfHeight;
  5080. textAlign = 'center';
  5081. textVerticalAlign = 'middle';
  5082. break;
  5083. case 'insideLeft':
  5084. x += distance;
  5085. y += halfHeight;
  5086. textVerticalAlign = 'middle';
  5087. break;
  5088. case 'insideRight':
  5089. x += width - distance;
  5090. y += halfHeight;
  5091. textAlign = 'right';
  5092. textVerticalAlign = 'middle';
  5093. break;
  5094. case 'insideTop':
  5095. x += width / 2;
  5096. y += distance;
  5097. textAlign = 'center';
  5098. break;
  5099. case 'insideBottom':
  5100. x += width / 2;
  5101. y += height - distance;
  5102. textAlign = 'center';
  5103. textVerticalAlign = 'bottom';
  5104. break;
  5105. case 'insideTopLeft':
  5106. x += distance;
  5107. y += distance;
  5108. break;
  5109. case 'insideTopRight':
  5110. x += width - distance;
  5111. y += distance;
  5112. textAlign = 'right';
  5113. break;
  5114. case 'insideBottomLeft':
  5115. x += distance;
  5116. y += height - distance;
  5117. textVerticalAlign = 'bottom';
  5118. break;
  5119. case 'insideBottomRight':
  5120. x += width - distance;
  5121. y += height - distance;
  5122. textAlign = 'right';
  5123. textVerticalAlign = 'bottom';
  5124. break;
  5125. }
  5126. }
  5127. out = out || {};
  5128. out.x = x;
  5129. out.y = y;
  5130. out.align = textAlign;
  5131. out.verticalAlign = textVerticalAlign;
  5132. return out;
  5133. }
  5134. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5135. var PRIMARY_STATES_KEYS = ['x', 'y', 'scaleX', 'scaleY', 'originX', 'originY', 'rotation', 'ignore'];
  5136. var DEFAULT_ANIMATABLE_MAP = {
  5137. x: true,
  5138. y: true,
  5139. scaleX: true,
  5140. scaleY: true,
  5141. originX: true,
  5142. originY: true,
  5143. rotation: true,
  5144. ignore: false
  5145. };
  5146. var tmpTextPosCalcRes = {};
  5147. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5148. var Element = (function () {
  5149. function Element(props) {
  5150. this.id = guid();
  5151. this.animators = [];
  5152. this.currentStates = [];
  5153. this.states = {};
  5154. this._init(props);
  5155. }
  5156. Element.prototype._init = function (props) {
  5157. this.attr(props);
  5158. };
  5159. Element.prototype.drift = function (dx, dy, e) {
  5160. switch (this.draggable) {
  5161. case 'horizontal':
  5162. dy = 0;
  5163. break;
  5164. case 'vertical':
  5165. dx = 0;
  5166. break;
  5167. }
  5168. var m = this.transform;
  5169. if (!m) {
  5170. m = this.transform = [1, 0, 0, 1, 0, 0];
  5171. }
  5172. m[4] += dx;
  5173. m[5] += dy;
  5174. this.decomposeTransform();
  5175. this.markRedraw();
  5176. };
  5177. Element.prototype.beforeUpdate = function () { };
  5178. Element.prototype.afterUpdate = function () { };
  5179. Element.prototype.update = function () {
  5180. this.updateTransform();
  5181. if (this.__dirty) {
  5182. this.updateInnerText();
  5183. }
  5184. };
  5185. Element.prototype.updateInnerText = function (forceUpdate) {
  5186. var textEl = this._textContent;
  5187. if (textEl && (!textEl.ignore || forceUpdate)) {
  5188. if (!this.textConfig) {
  5189. this.textConfig = {};
  5190. }
  5191. var textConfig = this.textConfig;
  5192. var isLocal = textConfig.local;
  5193. var innerTransformable = textEl.innerTransformable;
  5194. var textAlign = void 0;
  5195. var textVerticalAlign = void 0;
  5196. var textStyleChanged = false;
  5197. innerTransformable.parent = isLocal ? this : null;
  5198. var innerOrigin = false;
  5199. innerTransformable.copyTransform(textEl);
  5200. if (textConfig.position != null) {
  5201. var layoutRect = tmpBoundingRect;
  5202. if (textConfig.layoutRect) {
  5203. layoutRect.copy(textConfig.layoutRect);
  5204. }
  5205. else {
  5206. layoutRect.copy(this.getBoundingRect());
  5207. }
  5208. if (!isLocal) {
  5209. layoutRect.applyTransform(this.transform);
  5210. }
  5211. if (this.calculateTextPosition) {
  5212. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5213. }
  5214. else {
  5215. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5216. }
  5217. innerTransformable.x = tmpTextPosCalcRes.x;
  5218. innerTransformable.y = tmpTextPosCalcRes.y;
  5219. textAlign = tmpTextPosCalcRes.align;
  5220. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5221. var textOrigin = textConfig.origin;
  5222. if (textOrigin && textConfig.rotation != null) {
  5223. var relOriginX = void 0;
  5224. var relOriginY = void 0;
  5225. if (textOrigin === 'center') {
  5226. relOriginX = layoutRect.width * 0.5;
  5227. relOriginY = layoutRect.height * 0.5;
  5228. }
  5229. else {
  5230. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5231. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5232. }
  5233. innerOrigin = true;
  5234. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5235. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5236. }
  5237. }
  5238. if (textConfig.rotation != null) {
  5239. innerTransformable.rotation = textConfig.rotation;
  5240. }
  5241. var textOffset = textConfig.offset;
  5242. if (textOffset) {
  5243. innerTransformable.x += textOffset[0];
  5244. innerTransformable.y += textOffset[1];
  5245. if (!innerOrigin) {
  5246. innerTransformable.originX = -textOffset[0];
  5247. innerTransformable.originY = -textOffset[1];
  5248. }
  5249. }
  5250. var isInside = textConfig.inside == null
  5251. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5252. : textConfig.inside;
  5253. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5254. var textFill = void 0;
  5255. var textStroke = void 0;
  5256. var autoStroke = void 0;
  5257. if (isInside && this.canBeInsideText()) {
  5258. textFill = textConfig.insideFill;
  5259. textStroke = textConfig.insideStroke;
  5260. if (textFill == null || textFill === 'auto') {
  5261. textFill = this.getInsideTextFill();
  5262. }
  5263. if (textStroke == null || textStroke === 'auto') {
  5264. textStroke = this.getInsideTextStroke(textFill);
  5265. autoStroke = true;
  5266. }
  5267. }
  5268. else {
  5269. textFill = textConfig.outsideFill;
  5270. textStroke = textConfig.outsideStroke;
  5271. if (textFill == null || textFill === 'auto') {
  5272. textFill = this.getOutsideFill();
  5273. }
  5274. if (textStroke == null || textStroke === 'auto') {
  5275. textStroke = this.getOutsideStroke(textFill);
  5276. autoStroke = true;
  5277. }
  5278. }
  5279. textFill = textFill || '#000';
  5280. if (textFill !== innerTextDefaultStyle.fill
  5281. || textStroke !== innerTextDefaultStyle.stroke
  5282. || autoStroke !== innerTextDefaultStyle.autoStroke
  5283. || textAlign !== innerTextDefaultStyle.align
  5284. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5285. textStyleChanged = true;
  5286. innerTextDefaultStyle.fill = textFill;
  5287. innerTextDefaultStyle.stroke = textStroke;
  5288. innerTextDefaultStyle.autoStroke = autoStroke;
  5289. innerTextDefaultStyle.align = textAlign;
  5290. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5291. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5292. }
  5293. textEl.__dirty |= REDARAW_BIT;
  5294. if (textStyleChanged) {
  5295. textEl.dirtyStyle(true);
  5296. }
  5297. }
  5298. };
  5299. Element.prototype.canBeInsideText = function () {
  5300. return true;
  5301. };
  5302. Element.prototype.getInsideTextFill = function () {
  5303. return '#fff';
  5304. };
  5305. Element.prototype.getInsideTextStroke = function (textFill) {
  5306. return '#000';
  5307. };
  5308. Element.prototype.getOutsideFill = function () {
  5309. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5310. };
  5311. Element.prototype.getOutsideStroke = function (textFill) {
  5312. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5313. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5314. if (!colorArr) {
  5315. colorArr = [255, 255, 255, 1];
  5316. }
  5317. var alpha = colorArr[3];
  5318. var isDark = this.__zr.isDarkMode();
  5319. for (var i = 0; i < 3; i++) {
  5320. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5321. }
  5322. colorArr[3] = 1;
  5323. return stringify(colorArr, 'rgba');
  5324. };
  5325. Element.prototype.traverse = function (cb, context) { };
  5326. Element.prototype.attrKV = function (key, value) {
  5327. if (key === 'textConfig') {
  5328. this.setTextConfig(value);
  5329. }
  5330. else if (key === 'textContent') {
  5331. this.setTextContent(value);
  5332. }
  5333. else if (key === 'clipPath') {
  5334. this.setClipPath(value);
  5335. }
  5336. else if (key === 'extra') {
  5337. this.extra = this.extra || {};
  5338. extend(this.extra, value);
  5339. }
  5340. else {
  5341. this[key] = value;
  5342. }
  5343. };
  5344. Element.prototype.hide = function () {
  5345. this.ignore = true;
  5346. this.markRedraw();
  5347. };
  5348. Element.prototype.show = function () {
  5349. this.ignore = false;
  5350. this.markRedraw();
  5351. };
  5352. Element.prototype.attr = function (keyOrObj, value) {
  5353. if (typeof keyOrObj === 'string') {
  5354. this.attrKV(keyOrObj, value);
  5355. }
  5356. else if (isObject(keyOrObj)) {
  5357. var obj = keyOrObj;
  5358. var keysArr = keys(obj);
  5359. for (var i = 0; i < keysArr.length; i++) {
  5360. var key = keysArr[i];
  5361. this.attrKV(key, keyOrObj[key]);
  5362. }
  5363. }
  5364. this.markRedraw();
  5365. return this;
  5366. };
  5367. Element.prototype.saveCurrentToNormalState = function (toState) {
  5368. this._innerSaveToNormal(toState);
  5369. var normalState = this._normalState;
  5370. for (var i = 0; i < this.animators.length; i++) {
  5371. var animator = this.animators[i];
  5372. var fromStateTransition = animator.__fromStateTransition;
  5373. if (fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  5374. continue;
  5375. }
  5376. var targetName = animator.targetName;
  5377. var target = targetName
  5378. ? normalState[targetName] : normalState;
  5379. animator.saveFinalToTarget(target);
  5380. }
  5381. };
  5382. Element.prototype._innerSaveToNormal = function (toState) {
  5383. var normalState = this._normalState;
  5384. if (!normalState) {
  5385. normalState = this._normalState = {};
  5386. }
  5387. if (toState.textConfig && !normalState.textConfig) {
  5388. normalState.textConfig = this.textConfig;
  5389. }
  5390. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  5391. };
  5392. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  5393. for (var i = 0; i < primaryKeys.length; i++) {
  5394. var key = primaryKeys[i];
  5395. if (toState[key] != null && !(key in normalState)) {
  5396. normalState[key] = this[key];
  5397. }
  5398. }
  5399. };
  5400. Element.prototype.hasState = function () {
  5401. return this.currentStates.length > 0;
  5402. };
  5403. Element.prototype.getState = function (name) {
  5404. return this.states[name];
  5405. };
  5406. Element.prototype.ensureState = function (name) {
  5407. var states = this.states;
  5408. if (!states[name]) {
  5409. states[name] = {};
  5410. }
  5411. return states[name];
  5412. };
  5413. Element.prototype.clearStates = function (noAnimation) {
  5414. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  5415. };
  5416. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  5417. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  5418. var hasStates = this.hasState();
  5419. if (!hasStates && toNormalState) {
  5420. return;
  5421. }
  5422. var currentStates = this.currentStates;
  5423. var animationCfg = this.stateTransition;
  5424. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  5425. return;
  5426. }
  5427. var state;
  5428. if (this.stateProxy && !toNormalState) {
  5429. state = this.stateProxy(stateName);
  5430. }
  5431. if (!state) {
  5432. state = (this.states && this.states[stateName]);
  5433. }
  5434. if (!state && !toNormalState) {
  5435. logError("State " + stateName + " not exists.");
  5436. return;
  5437. }
  5438. if (!toNormalState) {
  5439. this.saveCurrentToNormalState(state);
  5440. }
  5441. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  5442. if (useHoverLayer) {
  5443. this._toggleHoverLayerFlag(true);
  5444. }
  5445. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  5446. var textContent = this._textContent;
  5447. var textGuide = this._textGuide;
  5448. if (textContent) {
  5449. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  5450. }
  5451. if (textGuide) {
  5452. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  5453. }
  5454. if (toNormalState) {
  5455. this.currentStates = [];
  5456. this._normalState = {};
  5457. }
  5458. else {
  5459. if (!keepCurrentStates) {
  5460. this.currentStates = [stateName];
  5461. }
  5462. else {
  5463. this.currentStates.push(stateName);
  5464. }
  5465. }
  5466. this._updateAnimationTargets();
  5467. this.markRedraw();
  5468. if (!useHoverLayer && this.__inHover) {
  5469. this._toggleHoverLayerFlag(false);
  5470. this.__dirty &= ~REDARAW_BIT;
  5471. }
  5472. return state;
  5473. };
  5474. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  5475. if (!states.length) {
  5476. this.clearStates();
  5477. }
  5478. else {
  5479. var stateObjects = [];
  5480. var currentStates = this.currentStates;
  5481. var len = states.length;
  5482. var notChange = len === currentStates.length;
  5483. if (notChange) {
  5484. for (var i = 0; i < len; i++) {
  5485. if (states[i] !== currentStates[i]) {
  5486. notChange = false;
  5487. break;
  5488. }
  5489. }
  5490. }
  5491. if (notChange) {
  5492. return;
  5493. }
  5494. for (var i = 0; i < len; i++) {
  5495. var stateName = states[i];
  5496. var stateObj = void 0;
  5497. if (this.stateProxy) {
  5498. stateObj = this.stateProxy(stateName, states);
  5499. }
  5500. if (!stateObj) {
  5501. stateObj = this.states[stateName];
  5502. }
  5503. if (stateObj) {
  5504. stateObjects.push(stateObj);
  5505. }
  5506. }
  5507. var lastStateObj = stateObjects[len - 1];
  5508. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  5509. if (useHoverLayer) {
  5510. this._toggleHoverLayerFlag(true);
  5511. }
  5512. var mergedState = this._mergeStates(stateObjects);
  5513. var animationCfg = this.stateTransition;
  5514. this.saveCurrentToNormalState(mergedState);
  5515. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  5516. var textContent = this._textContent;
  5517. var textGuide = this._textGuide;
  5518. if (textContent) {
  5519. textContent.useStates(states, noAnimation, useHoverLayer);
  5520. }
  5521. if (textGuide) {
  5522. textGuide.useStates(states, noAnimation, useHoverLayer);
  5523. }
  5524. this._updateAnimationTargets();
  5525. this.currentStates = states.slice();
  5526. this.markRedraw();
  5527. if (!useHoverLayer && this.__inHover) {
  5528. this._toggleHoverLayerFlag(false);
  5529. this.__dirty &= ~REDARAW_BIT;
  5530. }
  5531. }
  5532. };
  5533. Element.prototype._updateAnimationTargets = function () {
  5534. for (var i = 0; i < this.animators.length; i++) {
  5535. var animator = this.animators[i];
  5536. if (animator.targetName) {
  5537. animator.changeTarget(this[animator.targetName]);
  5538. }
  5539. }
  5540. };
  5541. Element.prototype.removeState = function (state) {
  5542. var idx = indexOf(this.currentStates, state);
  5543. if (idx >= 0) {
  5544. var currentStates = this.currentStates.slice();
  5545. currentStates.splice(idx, 1);
  5546. this.useStates(currentStates);
  5547. }
  5548. };
  5549. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  5550. var currentStates = this.currentStates.slice();
  5551. var idx = indexOf(currentStates, oldState);
  5552. var newStateExists = indexOf(currentStates, newState) >= 0;
  5553. if (idx >= 0) {
  5554. if (!newStateExists) {
  5555. currentStates[idx] = newState;
  5556. }
  5557. else {
  5558. currentStates.splice(idx, 1);
  5559. }
  5560. }
  5561. else if (forceAdd && !newStateExists) {
  5562. currentStates.push(newState);
  5563. }
  5564. this.useStates(currentStates);
  5565. };
  5566. Element.prototype.toggleState = function (state, enable) {
  5567. if (enable) {
  5568. this.useState(state, true);
  5569. }
  5570. else {
  5571. this.removeState(state);
  5572. }
  5573. };
  5574. Element.prototype._mergeStates = function (states) {
  5575. var mergedState = {};
  5576. var mergedTextConfig;
  5577. for (var i = 0; i < states.length; i++) {
  5578. var state = states[i];
  5579. extend(mergedState, state);
  5580. if (state.textConfig) {
  5581. mergedTextConfig = mergedTextConfig || {};
  5582. extend(mergedTextConfig, state.textConfig);
  5583. }
  5584. }
  5585. if (mergedTextConfig) {
  5586. mergedState.textConfig = mergedTextConfig;
  5587. }
  5588. return mergedState;
  5589. };
  5590. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  5591. var needsRestoreToNormal = !(state && keepCurrentStates);
  5592. if (state && state.textConfig) {
  5593. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  5594. extend(this.textConfig, state.textConfig);
  5595. }
  5596. else if (needsRestoreToNormal) {
  5597. if (normalState.textConfig) {
  5598. this.textConfig = normalState.textConfig;
  5599. }
  5600. }
  5601. var transitionTarget = {};
  5602. var hasTransition = false;
  5603. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  5604. var key = PRIMARY_STATES_KEYS[i];
  5605. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  5606. if (state && state[key] != null) {
  5607. if (propNeedsTransition) {
  5608. hasTransition = true;
  5609. transitionTarget[key] = state[key];
  5610. }
  5611. else {
  5612. this[key] = state[key];
  5613. }
  5614. }
  5615. else if (needsRestoreToNormal) {
  5616. if (normalState[key] != null) {
  5617. if (propNeedsTransition) {
  5618. hasTransition = true;
  5619. transitionTarget[key] = normalState[key];
  5620. }
  5621. else {
  5622. this[key] = normalState[key];
  5623. }
  5624. }
  5625. }
  5626. }
  5627. if (!transition) {
  5628. for (var i = 0; i < this.animators.length; i++) {
  5629. var animator = this.animators[i];
  5630. var targetName = animator.targetName;
  5631. animator.__changeFinalValue(targetName
  5632. ? (state || normalState)[targetName]
  5633. : (state || normalState));
  5634. }
  5635. }
  5636. if (hasTransition) {
  5637. this._transitionState(stateName, transitionTarget, animationCfg);
  5638. }
  5639. };
  5640. Element.prototype._attachComponent = function (componentEl) {
  5641. if (componentEl.__zr && !componentEl.__hostTarget) {
  5642. throw new Error('Text element has been added to zrender.');
  5643. }
  5644. if (componentEl === this) {
  5645. throw new Error('Recursive component attachment.');
  5646. }
  5647. var zr = this.__zr;
  5648. if (zr) {
  5649. componentEl.addSelfToZr(zr);
  5650. }
  5651. componentEl.__zr = zr;
  5652. componentEl.__hostTarget = this;
  5653. };
  5654. Element.prototype._detachComponent = function (componentEl) {
  5655. if (componentEl.__zr) {
  5656. componentEl.removeSelfFromZr(componentEl.__zr);
  5657. }
  5658. componentEl.__zr = null;
  5659. componentEl.__hostTarget = null;
  5660. };
  5661. Element.prototype.getClipPath = function () {
  5662. return this._clipPath;
  5663. };
  5664. Element.prototype.setClipPath = function (clipPath) {
  5665. if (this._clipPath && this._clipPath !== clipPath) {
  5666. this.removeClipPath();
  5667. }
  5668. this._attachComponent(clipPath);
  5669. this._clipPath = clipPath;
  5670. this.markRedraw();
  5671. };
  5672. Element.prototype.removeClipPath = function () {
  5673. var clipPath = this._clipPath;
  5674. if (clipPath) {
  5675. this._detachComponent(clipPath);
  5676. this._clipPath = null;
  5677. this.markRedraw();
  5678. }
  5679. };
  5680. Element.prototype.getTextContent = function () {
  5681. return this._textContent;
  5682. };
  5683. Element.prototype.setTextContent = function (textEl) {
  5684. var previousTextContent = this._textContent;
  5685. if (previousTextContent === textEl) {
  5686. return;
  5687. }
  5688. if (previousTextContent && previousTextContent !== textEl) {
  5689. this.removeTextContent();
  5690. }
  5691. if (textEl.__zr && !textEl.__hostTarget) {
  5692. throw new Error('Text element has been added to zrender.');
  5693. }
  5694. textEl.innerTransformable = new Transformable();
  5695. this._attachComponent(textEl);
  5696. this._textContent = textEl;
  5697. this.markRedraw();
  5698. };
  5699. Element.prototype.setTextConfig = function (cfg) {
  5700. if (!this.textConfig) {
  5701. this.textConfig = {};
  5702. }
  5703. extend(this.textConfig, cfg);
  5704. this.markRedraw();
  5705. };
  5706. Element.prototype.removeTextConfig = function () {
  5707. this.textConfig = null;
  5708. this.markRedraw();
  5709. };
  5710. Element.prototype.removeTextContent = function () {
  5711. var textEl = this._textContent;
  5712. if (textEl) {
  5713. textEl.innerTransformable = null;
  5714. this._detachComponent(textEl);
  5715. this._textContent = null;
  5716. this._innerTextDefaultStyle = null;
  5717. this.markRedraw();
  5718. }
  5719. };
  5720. Element.prototype.getTextGuideLine = function () {
  5721. return this._textGuide;
  5722. };
  5723. Element.prototype.setTextGuideLine = function (guideLine) {
  5724. if (this._textGuide && this._textGuide !== guideLine) {
  5725. this.removeTextGuideLine();
  5726. }
  5727. this._attachComponent(guideLine);
  5728. this._textGuide = guideLine;
  5729. this.markRedraw();
  5730. };
  5731. Element.prototype.removeTextGuideLine = function () {
  5732. var textGuide = this._textGuide;
  5733. if (textGuide) {
  5734. this._detachComponent(textGuide);
  5735. this._textGuide = null;
  5736. this.markRedraw();
  5737. }
  5738. };
  5739. Element.prototype.markRedraw = function () {
  5740. this.__dirty |= REDARAW_BIT;
  5741. var zr = this.__zr;
  5742. if (zr) {
  5743. if (this.__inHover) {
  5744. zr.refreshHover();
  5745. }
  5746. else {
  5747. zr.refresh();
  5748. }
  5749. }
  5750. if (this.__hostTarget) {
  5751. this.__hostTarget.markRedraw();
  5752. }
  5753. };
  5754. Element.prototype.dirty = function () {
  5755. this.markRedraw();
  5756. };
  5757. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  5758. this.__inHover = inHover;
  5759. var textContent = this._textContent;
  5760. var textGuide = this._textGuide;
  5761. if (textContent) {
  5762. textContent.__inHover = inHover;
  5763. }
  5764. if (textGuide) {
  5765. textGuide.__inHover = inHover;
  5766. }
  5767. };
  5768. Element.prototype.addSelfToZr = function (zr) {
  5769. if (this.__zr === zr) {
  5770. return;
  5771. }
  5772. this.__zr = zr;
  5773. var animators = this.animators;
  5774. if (animators) {
  5775. for (var i = 0; i < animators.length; i++) {
  5776. zr.animation.addAnimator(animators[i]);
  5777. }
  5778. }
  5779. if (this._clipPath) {
  5780. this._clipPath.addSelfToZr(zr);
  5781. }
  5782. if (this._textContent) {
  5783. this._textContent.addSelfToZr(zr);
  5784. }
  5785. if (this._textGuide) {
  5786. this._textGuide.addSelfToZr(zr);
  5787. }
  5788. };
  5789. Element.prototype.removeSelfFromZr = function (zr) {
  5790. if (!this.__zr) {
  5791. return;
  5792. }
  5793. this.__zr = null;
  5794. var animators = this.animators;
  5795. if (animators) {
  5796. for (var i = 0; i < animators.length; i++) {
  5797. zr.animation.removeAnimator(animators[i]);
  5798. }
  5799. }
  5800. if (this._clipPath) {
  5801. this._clipPath.removeSelfFromZr(zr);
  5802. }
  5803. if (this._textContent) {
  5804. this._textContent.removeSelfFromZr(zr);
  5805. }
  5806. if (this._textGuide) {
  5807. this._textGuide.removeSelfFromZr(zr);
  5808. }
  5809. };
  5810. Element.prototype.animate = function (key, loop) {
  5811. var target = key ? this[key] : this;
  5812. if (!target) {
  5813. logError('Property "'
  5814. + key
  5815. + '" is not existed in element '
  5816. + this.id);
  5817. return;
  5818. }
  5819. var animator = new Animator(target, loop);
  5820. this.addAnimator(animator, key);
  5821. return animator;
  5822. };
  5823. Element.prototype.addAnimator = function (animator, key) {
  5824. var zr = this.__zr;
  5825. var el = this;
  5826. animator.during(function () {
  5827. el.updateDuringAnimation(key);
  5828. }).done(function () {
  5829. var animators = el.animators;
  5830. var idx = indexOf(animators, animator);
  5831. if (idx >= 0) {
  5832. animators.splice(idx, 1);
  5833. }
  5834. });
  5835. this.animators.push(animator);
  5836. if (zr) {
  5837. zr.animation.addAnimator(animator);
  5838. }
  5839. zr && zr.wakeUp();
  5840. };
  5841. Element.prototype.updateDuringAnimation = function (key) {
  5842. this.markRedraw();
  5843. };
  5844. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  5845. var animators = this.animators;
  5846. var len = animators.length;
  5847. var leftAnimators = [];
  5848. for (var i = 0; i < len; i++) {
  5849. var animator = animators[i];
  5850. if (!scope || scope === animator.scope) {
  5851. animator.stop(forwardToLast);
  5852. }
  5853. else {
  5854. leftAnimators.push(animator);
  5855. }
  5856. }
  5857. this.animators = leftAnimators;
  5858. return this;
  5859. };
  5860. Element.prototype.animateTo = function (target, cfg, animationProps) {
  5861. animateTo(this, target, cfg, animationProps);
  5862. };
  5863. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  5864. animateTo(this, target, cfg, animationProps, true);
  5865. };
  5866. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  5867. var animators = animateTo(this, target, cfg, animationProps);
  5868. for (var i = 0; i < animators.length; i++) {
  5869. animators[i].__fromStateTransition = stateName;
  5870. }
  5871. };
  5872. Element.prototype.getBoundingRect = function () {
  5873. return null;
  5874. };
  5875. Element.prototype.getPaintRect = function () {
  5876. return null;
  5877. };
  5878. Element.initDefaultProps = (function () {
  5879. var elProto = Element.prototype;
  5880. elProto.type = 'element';
  5881. elProto.name = '';
  5882. elProto.ignore = false;
  5883. elProto.silent = false;
  5884. elProto.isGroup = false;
  5885. elProto.draggable = false;
  5886. elProto.dragging = false;
  5887. elProto.ignoreClip = false;
  5888. elProto.__inHover = false;
  5889. elProto.__dirty = REDARAW_BIT;
  5890. var logs = {};
  5891. function logDeprecatedError(key, xKey, yKey) {
  5892. if (!logs[key + xKey + yKey]) {
  5893. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  5894. logs[key + xKey + yKey] = true;
  5895. }
  5896. }
  5897. function createLegacyProperty(key, privateKey, xKey, yKey) {
  5898. Object.defineProperty(elProto, key, {
  5899. get: function () {
  5900. logDeprecatedError(key, xKey, yKey);
  5901. if (!this[privateKey]) {
  5902. var pos = this[privateKey] = [];
  5903. enhanceArray(this, pos);
  5904. }
  5905. return this[privateKey];
  5906. },
  5907. set: function (pos) {
  5908. logDeprecatedError(key, xKey, yKey);
  5909. this[xKey] = pos[0];
  5910. this[yKey] = pos[1];
  5911. this[privateKey] = pos;
  5912. enhanceArray(this, pos);
  5913. }
  5914. });
  5915. function enhanceArray(self, pos) {
  5916. Object.defineProperty(pos, 0, {
  5917. get: function () {
  5918. return self[xKey];
  5919. },
  5920. set: function (val) {
  5921. self[xKey] = val;
  5922. }
  5923. });
  5924. Object.defineProperty(pos, 1, {
  5925. get: function () {
  5926. return self[yKey];
  5927. },
  5928. set: function (val) {
  5929. self[yKey] = val;
  5930. }
  5931. });
  5932. }
  5933. }
  5934. if (Object.defineProperty && (!env.browser.ie || env.browser.version > 8)) {
  5935. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  5936. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  5937. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  5938. }
  5939. })();
  5940. return Element;
  5941. }());
  5942. mixin(Element, Eventful);
  5943. mixin(Element, Transformable);
  5944. function animateTo(animatable, target, cfg, animationProps, reverse) {
  5945. cfg = cfg || {};
  5946. var animators = [];
  5947. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  5948. var finishCount = animators.length;
  5949. var doneHappened = false;
  5950. var cfgDone = cfg.done;
  5951. var cfgAborted = cfg.aborted;
  5952. var doneCb = function () {
  5953. doneHappened = true;
  5954. finishCount--;
  5955. if (finishCount <= 0) {
  5956. doneHappened
  5957. ? (cfgDone && cfgDone())
  5958. : (cfgAborted && cfgAborted());
  5959. }
  5960. };
  5961. var abortedCb = function () {
  5962. finishCount--;
  5963. if (finishCount <= 0) {
  5964. doneHappened
  5965. ? (cfgDone && cfgDone())
  5966. : (cfgAborted && cfgAborted());
  5967. }
  5968. };
  5969. if (!finishCount) {
  5970. cfgDone && cfgDone();
  5971. }
  5972. if (animators.length > 0 && cfg.during) {
  5973. animators[0].during(function (target, percent) {
  5974. cfg.during(percent);
  5975. });
  5976. }
  5977. for (var i = 0; i < animators.length; i++) {
  5978. var animator = animators[i];
  5979. if (doneCb) {
  5980. animator.done(doneCb);
  5981. }
  5982. if (abortedCb) {
  5983. animator.aborted(abortedCb);
  5984. }
  5985. animator.start(cfg.easing, cfg.force);
  5986. }
  5987. return animators;
  5988. }
  5989. function copyArrShallow(source, target, len) {
  5990. for (var i = 0; i < len; i++) {
  5991. source[i] = target[i];
  5992. }
  5993. }
  5994. function is2DArray(value) {
  5995. return isArrayLike(value[0]);
  5996. }
  5997. function copyValue(target, source, key) {
  5998. if (isArrayLike(source[key])) {
  5999. if (!isArrayLike(target[key])) {
  6000. target[key] = [];
  6001. }
  6002. if (isTypedArray(source[key])) {
  6003. var len = source[key].length;
  6004. if (target[key].length !== len) {
  6005. target[key] = new (source[key].constructor)(len);
  6006. copyArrShallow(target[key], source[key], len);
  6007. }
  6008. }
  6009. else {
  6010. var sourceArr = source[key];
  6011. var targetArr = target[key];
  6012. var len0 = sourceArr.length;
  6013. if (is2DArray(sourceArr)) {
  6014. var len1 = sourceArr[0].length;
  6015. for (var i = 0; i < len0; i++) {
  6016. if (!targetArr[i]) {
  6017. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6018. }
  6019. else {
  6020. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6021. }
  6022. }
  6023. }
  6024. else {
  6025. copyArrShallow(targetArr, sourceArr, len0);
  6026. }
  6027. targetArr.length = sourceArr.length;
  6028. }
  6029. }
  6030. else {
  6031. target[key] = source[key];
  6032. }
  6033. }
  6034. function animateToShallow(animatable, topKey, source, target, cfg, animationProps, animators, reverse) {
  6035. var animatableKeys = [];
  6036. var changedKeys = [];
  6037. var targetKeys = keys(target);
  6038. var duration = cfg.duration;
  6039. var delay = cfg.delay;
  6040. var additive = cfg.additive;
  6041. var setToFinal = cfg.setToFinal;
  6042. var animateAll = !isObject(animationProps);
  6043. for (var k = 0; k < targetKeys.length; k++) {
  6044. var innerKey = targetKeys[k];
  6045. if (source[innerKey] != null
  6046. && target[innerKey] != null
  6047. && (animateAll || animationProps[innerKey])) {
  6048. if (isObject(target[innerKey]) && !isArrayLike(target[innerKey])) {
  6049. if (topKey) {
  6050. if (!reverse) {
  6051. source[innerKey] = target[innerKey];
  6052. animatable.updateDuringAnimation(topKey);
  6053. }
  6054. continue;
  6055. }
  6056. animateToShallow(animatable, innerKey, source[innerKey], target[innerKey], cfg, animationProps && animationProps[innerKey], animators, reverse);
  6057. }
  6058. else {
  6059. animatableKeys.push(innerKey);
  6060. changedKeys.push(innerKey);
  6061. }
  6062. }
  6063. else if (!reverse) {
  6064. source[innerKey] = target[innerKey];
  6065. animatable.updateDuringAnimation(topKey);
  6066. changedKeys.push(innerKey);
  6067. }
  6068. }
  6069. var keyLen = animatableKeys.length;
  6070. if (keyLen > 0
  6071. || (cfg.force && !animators.length)) {
  6072. var existsAnimators = animatable.animators;
  6073. var existsAnimatorsOnSameTarget = [];
  6074. for (var i = 0; i < existsAnimators.length; i++) {
  6075. if (existsAnimators[i].targetName === topKey) {
  6076. existsAnimatorsOnSameTarget.push(existsAnimators[i]);
  6077. }
  6078. }
  6079. if (!additive && existsAnimatorsOnSameTarget.length) {
  6080. for (var i = 0; i < existsAnimatorsOnSameTarget.length; i++) {
  6081. var allAborted = existsAnimatorsOnSameTarget[i].stopTracks(changedKeys);
  6082. if (allAborted) {
  6083. var idx = indexOf(existsAnimators, existsAnimatorsOnSameTarget[i]);
  6084. existsAnimators.splice(idx, 1);
  6085. }
  6086. }
  6087. }
  6088. var revertedSource = void 0;
  6089. var reversedTarget = void 0;
  6090. var sourceClone = void 0;
  6091. if (reverse) {
  6092. reversedTarget = {};
  6093. if (setToFinal) {
  6094. revertedSource = {};
  6095. }
  6096. for (var i = 0; i < keyLen; i++) {
  6097. var innerKey = animatableKeys[i];
  6098. reversedTarget[innerKey] = source[innerKey];
  6099. if (setToFinal) {
  6100. revertedSource[innerKey] = target[innerKey];
  6101. }
  6102. else {
  6103. source[innerKey] = target[innerKey];
  6104. }
  6105. }
  6106. }
  6107. else if (setToFinal) {
  6108. sourceClone = {};
  6109. for (var i = 0; i < keyLen; i++) {
  6110. var innerKey = animatableKeys[i];
  6111. sourceClone[innerKey] = cloneValue(source[innerKey]);
  6112. copyValue(source, target, innerKey);
  6113. }
  6114. }
  6115. var animator = new Animator(source, false, additive ? existsAnimatorsOnSameTarget : null);
  6116. animator.targetName = topKey;
  6117. if (cfg.scope) {
  6118. animator.scope = cfg.scope;
  6119. }
  6120. if (setToFinal && revertedSource) {
  6121. animator.whenWithKeys(0, revertedSource, animatableKeys);
  6122. }
  6123. if (sourceClone) {
  6124. animator.whenWithKeys(0, sourceClone, animatableKeys);
  6125. }
  6126. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animatableKeys).delay(delay || 0);
  6127. animatable.addAnimator(animator, topKey);
  6128. animators.push(animator);
  6129. }
  6130. }
  6131. var Group = (function (_super) {
  6132. __extends(Group, _super);
  6133. function Group(opts) {
  6134. var _this = _super.call(this) || this;
  6135. _this.isGroup = true;
  6136. _this._children = [];
  6137. _this.attr(opts);
  6138. return _this;
  6139. }
  6140. Group.prototype.childrenRef = function () {
  6141. return this._children;
  6142. };
  6143. Group.prototype.children = function () {
  6144. return this._children.slice();
  6145. };
  6146. Group.prototype.childAt = function (idx) {
  6147. return this._children[idx];
  6148. };
  6149. Group.prototype.childOfName = function (name) {
  6150. var children = this._children;
  6151. for (var i = 0; i < children.length; i++) {
  6152. if (children[i].name === name) {
  6153. return children[i];
  6154. }
  6155. }
  6156. };
  6157. Group.prototype.childCount = function () {
  6158. return this._children.length;
  6159. };
  6160. Group.prototype.add = function (child) {
  6161. if (child) {
  6162. if (child !== this && child.parent !== this) {
  6163. this._children.push(child);
  6164. this._doAdd(child);
  6165. }
  6166. if (child.__hostTarget) {
  6167. throw 'This elemenet has been used as an attachment';
  6168. }
  6169. }
  6170. return this;
  6171. };
  6172. Group.prototype.addBefore = function (child, nextSibling) {
  6173. if (child && child !== this && child.parent !== this
  6174. && nextSibling && nextSibling.parent === this) {
  6175. var children = this._children;
  6176. var idx = children.indexOf(nextSibling);
  6177. if (idx >= 0) {
  6178. children.splice(idx, 0, child);
  6179. this._doAdd(child);
  6180. }
  6181. }
  6182. return this;
  6183. };
  6184. Group.prototype.replace = function (oldChild, newChild) {
  6185. var idx = indexOf(this._children, oldChild);
  6186. if (idx >= 0) {
  6187. this.replaceAt(newChild, idx);
  6188. }
  6189. return this;
  6190. };
  6191. Group.prototype.replaceAt = function (child, index) {
  6192. var children = this._children;
  6193. var old = children[index];
  6194. if (child && child !== this && child.parent !== this && child !== old) {
  6195. children[index] = child;
  6196. old.parent = null;
  6197. var zr = this.__zr;
  6198. if (zr) {
  6199. old.removeSelfFromZr(zr);
  6200. }
  6201. this._doAdd(child);
  6202. }
  6203. return this;
  6204. };
  6205. Group.prototype._doAdd = function (child) {
  6206. if (child.parent) {
  6207. child.parent.remove(child);
  6208. }
  6209. child.parent = this;
  6210. var zr = this.__zr;
  6211. if (zr && zr !== child.__zr) {
  6212. child.addSelfToZr(zr);
  6213. }
  6214. zr && zr.refresh();
  6215. };
  6216. Group.prototype.remove = function (child) {
  6217. var zr = this.__zr;
  6218. var children = this._children;
  6219. var idx = indexOf(children, child);
  6220. if (idx < 0) {
  6221. return this;
  6222. }
  6223. children.splice(idx, 1);
  6224. child.parent = null;
  6225. if (zr) {
  6226. child.removeSelfFromZr(zr);
  6227. }
  6228. zr && zr.refresh();
  6229. return this;
  6230. };
  6231. Group.prototype.removeAll = function () {
  6232. var children = this._children;
  6233. var zr = this.__zr;
  6234. for (var i = 0; i < children.length; i++) {
  6235. var child = children[i];
  6236. if (zr) {
  6237. child.removeSelfFromZr(zr);
  6238. }
  6239. child.parent = null;
  6240. }
  6241. children.length = 0;
  6242. return this;
  6243. };
  6244. Group.prototype.eachChild = function (cb, context) {
  6245. var children = this._children;
  6246. for (var i = 0; i < children.length; i++) {
  6247. var child = children[i];
  6248. cb.call(context, child, i);
  6249. }
  6250. return this;
  6251. };
  6252. Group.prototype.traverse = function (cb, context) {
  6253. for (var i = 0; i < this._children.length; i++) {
  6254. var child = this._children[i];
  6255. var stopped = cb.call(context, child);
  6256. if (child.isGroup && !stopped) {
  6257. child.traverse(cb, context);
  6258. }
  6259. }
  6260. return this;
  6261. };
  6262. Group.prototype.addSelfToZr = function (zr) {
  6263. _super.prototype.addSelfToZr.call(this, zr);
  6264. for (var i = 0; i < this._children.length; i++) {
  6265. var child = this._children[i];
  6266. child.addSelfToZr(zr);
  6267. }
  6268. };
  6269. Group.prototype.removeSelfFromZr = function (zr) {
  6270. _super.prototype.removeSelfFromZr.call(this, zr);
  6271. for (var i = 0; i < this._children.length; i++) {
  6272. var child = this._children[i];
  6273. child.removeSelfFromZr(zr);
  6274. }
  6275. };
  6276. Group.prototype.getBoundingRect = function (includeChildren) {
  6277. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6278. var children = includeChildren || this._children;
  6279. var tmpMat = [];
  6280. var rect = null;
  6281. for (var i = 0; i < children.length; i++) {
  6282. var child = children[i];
  6283. if (child.ignore || child.invisible) {
  6284. continue;
  6285. }
  6286. var childRect = child.getBoundingRect();
  6287. var transform = child.getLocalTransform(tmpMat);
  6288. if (transform) {
  6289. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6290. rect = rect || tmpRect.clone();
  6291. rect.union(tmpRect);
  6292. }
  6293. else {
  6294. rect = rect || childRect.clone();
  6295. rect.union(childRect);
  6296. }
  6297. }
  6298. return rect || tmpRect;
  6299. };
  6300. return Group;
  6301. }(Element));
  6302. Group.prototype.type = 'group';
  6303. /*!
  6304. * ZRender, a high performance 2d drawing library.
  6305. *
  6306. * Copyright (c) 2013, Baidu Inc.
  6307. * All rights reserved.
  6308. *
  6309. * LICENSE
  6310. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6311. */
  6312. var useVML = !env.canvasSupported;
  6313. var painterCtors = {};
  6314. var instances = {};
  6315. function delInstance(id) {
  6316. delete instances[id];
  6317. }
  6318. function isDarkMode(backgroundColor) {
  6319. if (!backgroundColor) {
  6320. return false;
  6321. }
  6322. if (typeof backgroundColor === 'string') {
  6323. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6324. }
  6325. else if (backgroundColor.colorStops) {
  6326. var colorStops = backgroundColor.colorStops;
  6327. var totalLum = 0;
  6328. var len = colorStops.length;
  6329. for (var i = 0; i < len; i++) {
  6330. totalLum += lum(colorStops[i].color, 1);
  6331. }
  6332. totalLum /= len;
  6333. return totalLum < DARK_MODE_THRESHOLD;
  6334. }
  6335. return false;
  6336. }
  6337. var ZRender = (function () {
  6338. function ZRender(id, dom, opts) {
  6339. var _this = this;
  6340. this._sleepAfterStill = 10;
  6341. this._stillFrameAccum = 0;
  6342. this._needsRefresh = true;
  6343. this._needsRefreshHover = true;
  6344. this._darkMode = false;
  6345. opts = opts || {};
  6346. this.dom = dom;
  6347. this.id = id;
  6348. var storage = new Storage();
  6349. var rendererType = opts.renderer || 'canvas';
  6350. if (useVML) {
  6351. throw new Error('IE8 support has been dropped since 5.0');
  6352. }
  6353. if (!painterCtors[rendererType]) {
  6354. rendererType = keys(painterCtors)[0];
  6355. }
  6356. if (!painterCtors[rendererType]) {
  6357. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  6358. }
  6359. opts.useDirtyRect = opts.useDirtyRect == null
  6360. ? false
  6361. : opts.useDirtyRect;
  6362. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  6363. this.storage = storage;
  6364. this.painter = painter;
  6365. var handerProxy = (!env.node && !env.worker)
  6366. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  6367. : null;
  6368. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  6369. this.animation = new Animation({
  6370. stage: {
  6371. update: function () { return _this._flush(true); }
  6372. }
  6373. });
  6374. this.animation.start();
  6375. }
  6376. ZRender.prototype.add = function (el) {
  6377. if (!el) {
  6378. return;
  6379. }
  6380. this.storage.addRoot(el);
  6381. el.addSelfToZr(this);
  6382. this.refresh();
  6383. };
  6384. ZRender.prototype.remove = function (el) {
  6385. if (!el) {
  6386. return;
  6387. }
  6388. this.storage.delRoot(el);
  6389. el.removeSelfFromZr(this);
  6390. this.refresh();
  6391. };
  6392. ZRender.prototype.configLayer = function (zLevel, config) {
  6393. if (this.painter.configLayer) {
  6394. this.painter.configLayer(zLevel, config);
  6395. }
  6396. this.refresh();
  6397. };
  6398. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  6399. if (this.painter.setBackgroundColor) {
  6400. this.painter.setBackgroundColor(backgroundColor);
  6401. }
  6402. this.refresh();
  6403. this._backgroundColor = backgroundColor;
  6404. this._darkMode = isDarkMode(backgroundColor);
  6405. };
  6406. ZRender.prototype.getBackgroundColor = function () {
  6407. return this._backgroundColor;
  6408. };
  6409. ZRender.prototype.setDarkMode = function (darkMode) {
  6410. this._darkMode = darkMode;
  6411. };
  6412. ZRender.prototype.isDarkMode = function () {
  6413. return this._darkMode;
  6414. };
  6415. ZRender.prototype.refreshImmediately = function (fromInside) {
  6416. if (!fromInside) {
  6417. this.animation.update(true);
  6418. }
  6419. this._needsRefresh = false;
  6420. this.painter.refresh();
  6421. this._needsRefresh = false;
  6422. };
  6423. ZRender.prototype.refresh = function () {
  6424. this._needsRefresh = true;
  6425. this.animation.start();
  6426. };
  6427. ZRender.prototype.flush = function () {
  6428. this._flush(false);
  6429. };
  6430. ZRender.prototype._flush = function (fromInside) {
  6431. var triggerRendered;
  6432. var start = new Date().getTime();
  6433. if (this._needsRefresh) {
  6434. triggerRendered = true;
  6435. this.refreshImmediately(fromInside);
  6436. }
  6437. if (this._needsRefreshHover) {
  6438. triggerRendered = true;
  6439. this.refreshHoverImmediately();
  6440. }
  6441. var end = new Date().getTime();
  6442. if (triggerRendered) {
  6443. this._stillFrameAccum = 0;
  6444. this.trigger('rendered', {
  6445. elapsedTime: end - start
  6446. });
  6447. }
  6448. else if (this._sleepAfterStill > 0) {
  6449. this._stillFrameAccum++;
  6450. if (this._stillFrameAccum > this._sleepAfterStill) {
  6451. this.animation.stop();
  6452. }
  6453. }
  6454. };
  6455. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  6456. this._sleepAfterStill = stillFramesCount;
  6457. };
  6458. ZRender.prototype.wakeUp = function () {
  6459. this.animation.start();
  6460. this._stillFrameAccum = 0;
  6461. };
  6462. ZRender.prototype.addHover = function (el) {
  6463. };
  6464. ZRender.prototype.removeHover = function (el) {
  6465. };
  6466. ZRender.prototype.clearHover = function () {
  6467. };
  6468. ZRender.prototype.refreshHover = function () {
  6469. this._needsRefreshHover = true;
  6470. };
  6471. ZRender.prototype.refreshHoverImmediately = function () {
  6472. this._needsRefreshHover = false;
  6473. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  6474. this.painter.refreshHover();
  6475. }
  6476. };
  6477. ZRender.prototype.resize = function (opts) {
  6478. opts = opts || {};
  6479. this.painter.resize(opts.width, opts.height);
  6480. this.handler.resize();
  6481. };
  6482. ZRender.prototype.clearAnimation = function () {
  6483. this.animation.clear();
  6484. };
  6485. ZRender.prototype.getWidth = function () {
  6486. return this.painter.getWidth();
  6487. };
  6488. ZRender.prototype.getHeight = function () {
  6489. return this.painter.getHeight();
  6490. };
  6491. ZRender.prototype.pathToImage = function (e, dpr) {
  6492. if (this.painter.pathToImage) {
  6493. return this.painter.pathToImage(e, dpr);
  6494. }
  6495. };
  6496. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  6497. this.handler.setCursorStyle(cursorStyle);
  6498. };
  6499. ZRender.prototype.findHover = function (x, y) {
  6500. return this.handler.findHover(x, y);
  6501. };
  6502. ZRender.prototype.on = function (eventName, eventHandler, context) {
  6503. this.handler.on(eventName, eventHandler, context);
  6504. return this;
  6505. };
  6506. ZRender.prototype.off = function (eventName, eventHandler) {
  6507. this.handler.off(eventName, eventHandler);
  6508. };
  6509. ZRender.prototype.trigger = function (eventName, event) {
  6510. this.handler.trigger(eventName, event);
  6511. };
  6512. ZRender.prototype.clear = function () {
  6513. var roots = this.storage.getRoots();
  6514. for (var i = 0; i < roots.length; i++) {
  6515. if (roots[i] instanceof Group) {
  6516. roots[i].removeSelfFromZr(this);
  6517. }
  6518. }
  6519. this.storage.delAllRoots();
  6520. this.painter.clear();
  6521. };
  6522. ZRender.prototype.dispose = function () {
  6523. this.animation.stop();
  6524. this.clear();
  6525. this.storage.dispose();
  6526. this.painter.dispose();
  6527. this.handler.dispose();
  6528. this.animation =
  6529. this.storage =
  6530. this.painter =
  6531. this.handler = null;
  6532. delInstance(this.id);
  6533. };
  6534. return ZRender;
  6535. }());
  6536. function init(dom, opts) {
  6537. var zr = new ZRender(guid(), dom, opts);
  6538. instances[zr.id] = zr;
  6539. return zr;
  6540. }
  6541. function dispose(zr) {
  6542. zr.dispose();
  6543. }
  6544. function disposeAll() {
  6545. for (var key in instances) {
  6546. if (instances.hasOwnProperty(key)) {
  6547. instances[key].dispose();
  6548. }
  6549. }
  6550. instances = {};
  6551. }
  6552. function getInstance(id) {
  6553. return instances[id];
  6554. }
  6555. function registerPainter(name, Ctor) {
  6556. painterCtors[name] = Ctor;
  6557. }
  6558. var version = '5.2.0';
  6559. var zrender = /*#__PURE__*/Object.freeze({
  6560. __proto__: null,
  6561. init: init,
  6562. dispose: dispose,
  6563. disposeAll: disposeAll,
  6564. getInstance: getInstance,
  6565. registerPainter: registerPainter,
  6566. version: version
  6567. });
  6568. var RADIAN_EPSILON = 1e-4; // Although chrome already enlarge this number to 100 for `toFixed`, but
  6569. // we sill follow the spec for compatibility.
  6570. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  6571. function _trim(str) {
  6572. return str.replace(/^\s+|\s+$/g, '');
  6573. }
  6574. /**
  6575. * Linear mapping a value from domain to range
  6576. * @param val
  6577. * @param domain Domain extent domain[0] can be bigger than domain[1]
  6578. * @param range Range extent range[0] can be bigger than range[1]
  6579. * @param clamp Default to be false
  6580. */
  6581. function linearMap(val, domain, range, clamp) {
  6582. var d0 = domain[0];
  6583. var d1 = domain[1];
  6584. var r0 = range[0];
  6585. var r1 = range[1];
  6586. var subDomain = d1 - d0;
  6587. var subRange = r1 - r0;
  6588. if (subDomain === 0) {
  6589. return subRange === 0 ? r0 : (r0 + r1) / 2;
  6590. } // Avoid accuracy problem in edge, such as
  6591. // 146.39 - 62.83 === 83.55999999999999.
  6592. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  6593. // It is a little verbose for efficiency considering this method
  6594. // is a hotspot.
  6595. if (clamp) {
  6596. if (subDomain > 0) {
  6597. if (val <= d0) {
  6598. return r0;
  6599. } else if (val >= d1) {
  6600. return r1;
  6601. }
  6602. } else {
  6603. if (val >= d0) {
  6604. return r0;
  6605. } else if (val <= d1) {
  6606. return r1;
  6607. }
  6608. }
  6609. } else {
  6610. if (val === d0) {
  6611. return r0;
  6612. }
  6613. if (val === d1) {
  6614. return r1;
  6615. }
  6616. }
  6617. return (val - d0) / subDomain * subRange + r0;
  6618. }
  6619. /**
  6620. * Convert a percent string to absolute number.
  6621. * Returns NaN if percent is not a valid string or number
  6622. */
  6623. function parsePercent$1(percent, all) {
  6624. switch (percent) {
  6625. case 'center':
  6626. case 'middle':
  6627. percent = '50%';
  6628. break;
  6629. case 'left':
  6630. case 'top':
  6631. percent = '0%';
  6632. break;
  6633. case 'right':
  6634. case 'bottom':
  6635. percent = '100%';
  6636. break;
  6637. }
  6638. if (typeof percent === 'string') {
  6639. if (_trim(percent).match(/%$/)) {
  6640. return parseFloat(percent) / 100 * all;
  6641. }
  6642. return parseFloat(percent);
  6643. }
  6644. return percent == null ? NaN : +percent;
  6645. }
  6646. function round(x, precision, returnStr) {
  6647. if (precision == null) {
  6648. precision = 10;
  6649. } // Avoid range error
  6650. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX); // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  6651. x = (+x).toFixed(precision);
  6652. return returnStr ? x : +x;
  6653. }
  6654. /**
  6655. * Inplacd asc sort arr.
  6656. * The input arr will be modified.
  6657. */
  6658. function asc(arr) {
  6659. arr.sort(function (a, b) {
  6660. return a - b;
  6661. });
  6662. return arr;
  6663. }
  6664. /**
  6665. * Get precision.
  6666. */
  6667. function getPrecision(val) {
  6668. val = +val;
  6669. if (isNaN(val)) {
  6670. return 0;
  6671. } // It is much faster than methods converting number to string as follows
  6672. // let tmp = val.toString();
  6673. // return tmp.length - 1 - tmp.indexOf('.');
  6674. // especially when precision is low
  6675. // Notice:
  6676. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  6677. // (see https://jsbench.me/2vkpcekkvw/1)
  6678. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  6679. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  6680. if (val > 1e-14) {
  6681. var e = 1;
  6682. for (var i = 0; i < 15; i++, e *= 10) {
  6683. if (Math.round(val * e) / e === val) {
  6684. return i;
  6685. }
  6686. }
  6687. }
  6688. return getPrecisionSafe(val);
  6689. }
  6690. /**
  6691. * Get precision with slow but safe method
  6692. */
  6693. function getPrecisionSafe(val) {
  6694. // toLowerCase for: '3.4E-12'
  6695. var str = val.toString().toLowerCase(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  6696. var eIndex = str.indexOf('e');
  6697. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  6698. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  6699. var dotIndex = str.indexOf('.');
  6700. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  6701. return Math.max(0, decimalPartLen - exp);
  6702. }
  6703. /**
  6704. * Minimal dicernible data precisioin according to a single pixel.
  6705. */
  6706. function getPixelPrecision(dataExtent, pixelExtent) {
  6707. var log = Math.log;
  6708. var LN10 = Math.LN10;
  6709. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  6710. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  6711. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  6712. return !isFinite(precision) ? 20 : precision;
  6713. }
  6714. /**
  6715. * Get a data of given precision, assuring the sum of percentages
  6716. * in valueList is 1.
  6717. * The largest remainer method is used.
  6718. * https://en.wikipedia.org/wiki/Largest_remainder_method
  6719. *
  6720. * @param valueList a list of all data
  6721. * @param idx index of the data to be processed in valueList
  6722. * @param precision integer number showing digits of precision
  6723. * @return percent ranging from 0 to 100
  6724. */
  6725. function getPercentWithPrecision(valueList, idx, precision) {
  6726. if (!valueList[idx]) {
  6727. return 0;
  6728. }
  6729. var sum = reduce(valueList, function (acc, val) {
  6730. return acc + (isNaN(val) ? 0 : val);
  6731. }, 0);
  6732. if (sum === 0) {
  6733. return 0;
  6734. }
  6735. var digits = Math.pow(10, precision);
  6736. var votesPerQuota = map(valueList, function (val) {
  6737. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  6738. });
  6739. var targetSeats = digits * 100;
  6740. var seats = map(votesPerQuota, function (votes) {
  6741. // Assign automatic seats.
  6742. return Math.floor(votes);
  6743. });
  6744. var currentSum = reduce(seats, function (acc, val) {
  6745. return acc + val;
  6746. }, 0);
  6747. var remainder = map(votesPerQuota, function (votes, idx) {
  6748. return votes - seats[idx];
  6749. }); // Has remainding votes.
  6750. while (currentSum < targetSeats) {
  6751. // Find next largest remainder.
  6752. var max = Number.NEGATIVE_INFINITY;
  6753. var maxId = null;
  6754. for (var i = 0, len = remainder.length; i < len; ++i) {
  6755. if (remainder[i] > max) {
  6756. max = remainder[i];
  6757. maxId = i;
  6758. }
  6759. } // Add a vote to max remainder.
  6760. ++seats[maxId];
  6761. remainder[maxId] = 0;
  6762. ++currentSum;
  6763. }
  6764. return seats[idx] / digits;
  6765. }
  6766. /**
  6767. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  6768. * See <http://0.30000000000000004.com/>
  6769. */
  6770. function addSafe(val0, val1) {
  6771. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1)); // const multiplier = Math.pow(10, maxPrecision);
  6772. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  6773. var sum = val0 + val1; // // PENDING: support more?
  6774. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  6775. } // Number.MAX_SAFE_INTEGER, ie do not support.
  6776. var MAX_SAFE_INTEGER = 9007199254740991;
  6777. /**
  6778. * To 0 - 2 * PI, considering negative radian.
  6779. */
  6780. function remRadian(radian) {
  6781. var pi2 = Math.PI * 2;
  6782. return (radian % pi2 + pi2) % pi2;
  6783. }
  6784. /**
  6785. * @param {type} radian
  6786. * @return {boolean}
  6787. */
  6788. function isRadianAroundZero(val) {
  6789. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  6790. } // eslint-disable-next-line
  6791. 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
  6792. /**
  6793. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  6794. * These values can be accepted:
  6795. * + An instance of Date, represent a time in its own time zone.
  6796. * + Or string in a subset of ISO 8601, only including:
  6797. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  6798. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  6799. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  6800. * all of which will be treated as local time if time zone is not specified
  6801. * (see <https://momentjs.com/>).
  6802. * + Or other string format, including (all of which will be treated as loacal time):
  6803. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  6804. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  6805. * + a timestamp, which represent a time in UTC.
  6806. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  6807. */
  6808. function parseDate(value) {
  6809. if (value instanceof Date) {
  6810. return value;
  6811. } else if (typeof value === 'string') {
  6812. // Different browsers parse date in different way, so we parse it manually.
  6813. // Some other issues:
  6814. // new Date('1970-01-01') is UTC,
  6815. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  6816. // See issue #3623
  6817. var match = TIME_REG.exec(value);
  6818. if (!match) {
  6819. // return Invalid Date.
  6820. return new Date(NaN);
  6821. } // Use local time when no timezone offset specifed.
  6822. if (!match[8]) {
  6823. // match[n] can only be string or undefined.
  6824. // But take care of '12' + 1 => '121'.
  6825. 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);
  6826. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  6827. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  6828. // For example, system timezone is set as "Time Zone: America/Toronto",
  6829. // then these code will get different result:
  6830. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  6831. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  6832. // So we should not use `new Date`, but use `Date.UTC`.
  6833. else {
  6834. var hour = +match[4] || 0;
  6835. if (match[8].toUpperCase() !== 'Z') {
  6836. hour -= +match[8].slice(0, 3);
  6837. }
  6838. 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));
  6839. }
  6840. } else if (value == null) {
  6841. return new Date(NaN);
  6842. }
  6843. return new Date(Math.round(value));
  6844. }
  6845. /**
  6846. * Quantity of a number. e.g. 0.1, 1, 10, 100
  6847. *
  6848. * @param val
  6849. * @return
  6850. */
  6851. function quantity(val) {
  6852. return Math.pow(10, quantityExponent(val));
  6853. }
  6854. /**
  6855. * Exponent of the quantity of a number
  6856. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  6857. *
  6858. * @param val non-negative value
  6859. * @return
  6860. */
  6861. function quantityExponent(val) {
  6862. if (val === 0) {
  6863. return 0;
  6864. }
  6865. var exp = Math.floor(Math.log(val) / Math.LN10);
  6866. /**
  6867. * exp is expected to be the rounded-down result of the base-10 log of val.
  6868. * But due to the precision loss with Math.log(val), we need to restore it
  6869. * using 10^exp to make sure we can get val back from exp. #11249
  6870. */
  6871. if (val / Math.pow(10, exp) >= 10) {
  6872. exp++;
  6873. }
  6874. return exp;
  6875. }
  6876. /**
  6877. * find a “nice” number approximately equal to x. Round the number if round = true,
  6878. * take ceiling if round = false. The primary observation is that the “nicest”
  6879. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  6880. *
  6881. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  6882. *
  6883. * @param val Non-negative value.
  6884. * @param round
  6885. * @return Niced number
  6886. */
  6887. function nice(val, round) {
  6888. var exponent = quantityExponent(val);
  6889. var exp10 = Math.pow(10, exponent);
  6890. var f = val / exp10; // 1 <= f < 10
  6891. var nf;
  6892. if (round) {
  6893. if (f < 1.5) {
  6894. nf = 1;
  6895. } else if (f < 2.5) {
  6896. nf = 2;
  6897. } else if (f < 4) {
  6898. nf = 3;
  6899. } else if (f < 7) {
  6900. nf = 5;
  6901. } else {
  6902. nf = 10;
  6903. }
  6904. } else {
  6905. if (f < 1) {
  6906. nf = 1;
  6907. } else if (f < 2) {
  6908. nf = 2;
  6909. } else if (f < 3) {
  6910. nf = 3;
  6911. } else if (f < 5) {
  6912. nf = 5;
  6913. } else {
  6914. nf = 10;
  6915. }
  6916. }
  6917. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  6918. // 20 is the uppper bound of toFixed.
  6919. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  6920. }
  6921. /**
  6922. * This code was copied from "d3.js"
  6923. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  6924. * See the license statement at the head of this file.
  6925. * @param ascArr
  6926. */
  6927. function quantile(ascArr, p) {
  6928. var H = (ascArr.length - 1) * p + 1;
  6929. var h = Math.floor(H);
  6930. var v = +ascArr[h - 1];
  6931. var e = H - h;
  6932. return e ? v + e * (ascArr[h] - v) : v;
  6933. }
  6934. /**
  6935. * Order intervals asc, and split them when overlap.
  6936. * expect(numberUtil.reformIntervals([
  6937. * {interval: [18, 62], close: [1, 1]},
  6938. * {interval: [-Infinity, -70], close: [0, 0]},
  6939. * {interval: [-70, -26], close: [1, 1]},
  6940. * {interval: [-26, 18], close: [1, 1]},
  6941. * {interval: [62, 150], close: [1, 1]},
  6942. * {interval: [106, 150], close: [1, 1]},
  6943. * {interval: [150, Infinity], close: [0, 0]}
  6944. * ])).toEqual([
  6945. * {interval: [-Infinity, -70], close: [0, 0]},
  6946. * {interval: [-70, -26], close: [1, 1]},
  6947. * {interval: [-26, 18], close: [0, 1]},
  6948. * {interval: [18, 62], close: [0, 1]},
  6949. * {interval: [62, 150], close: [0, 1]},
  6950. * {interval: [150, Infinity], close: [0, 0]}
  6951. * ]);
  6952. * @param list, where `close` mean open or close
  6953. * of the interval, and Infinity can be used.
  6954. * @return The origin list, which has been reformed.
  6955. */
  6956. function reformIntervals(list) {
  6957. list.sort(function (a, b) {
  6958. return littleThan(a, b, 0) ? -1 : 1;
  6959. });
  6960. var curr = -Infinity;
  6961. var currClose = 1;
  6962. for (var i = 0; i < list.length;) {
  6963. var interval = list[i].interval;
  6964. var close_1 = list[i].close;
  6965. for (var lg = 0; lg < 2; lg++) {
  6966. if (interval[lg] <= curr) {
  6967. interval[lg] = curr;
  6968. close_1[lg] = !lg ? 1 - currClose : 1;
  6969. }
  6970. curr = interval[lg];
  6971. currClose = close_1[lg];
  6972. }
  6973. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  6974. list.splice(i, 1);
  6975. } else {
  6976. i++;
  6977. }
  6978. }
  6979. return list;
  6980. function littleThan(a, b, lg) {
  6981. 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));
  6982. }
  6983. }
  6984. /**
  6985. * [Numberic is defined as]:
  6986. * `parseFloat(val) == val`
  6987. * For example:
  6988. * numeric:
  6989. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  6990. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  6991. * not-numeric:
  6992. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  6993. * empty string, string with only white-spaces or line-terminal (see es spec),
  6994. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  6995. * non-string, ...
  6996. *
  6997. * @test See full test cases in `test/ut/spec/util/number.js`.
  6998. * @return Must be a typeof number. If not numeric, return NaN.
  6999. */
  7000. function numericToNumber(val) {
  7001. var valFloat = parseFloat(val);
  7002. return valFloat == val // eslint-disable-line eqeqeq
  7003. && (valFloat !== 0 || typeof val !== 'string' || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7004. ? valFloat : NaN;
  7005. }
  7006. /**
  7007. * Definition of "numeric": see `numericToNumber`.
  7008. */
  7009. function isNumeric(val) {
  7010. return !isNaN(numericToNumber(val));
  7011. }
  7012. /**
  7013. * Use random base to prevent users hard code depending on
  7014. * this auto generated marker id.
  7015. * @return An positive integer.
  7016. */
  7017. function getRandomIdBase() {
  7018. return Math.round(Math.random() * 9);
  7019. }
  7020. /**
  7021. * Get the greatest common dividor
  7022. *
  7023. * @param {number} a one number
  7024. * @param {number} b the other number
  7025. */
  7026. function getGreatestCommonDividor(a, b) {
  7027. if (b === 0) {
  7028. return a;
  7029. }
  7030. return getGreatestCommonDividor(b, a % b);
  7031. }
  7032. /**
  7033. * Get the least common multiple
  7034. *
  7035. * @param {number} a one number
  7036. * @param {number} b the other number
  7037. */
  7038. function getLeastCommonMultiple(a, b) {
  7039. if (a == null) {
  7040. return b;
  7041. }
  7042. if (b == null) {
  7043. return a;
  7044. }
  7045. return a * b / getGreatestCommonDividor(a, b);
  7046. }
  7047. var ECHARTS_PREFIX = '[ECharts] ';
  7048. var storedLogs = {};
  7049. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  7050. && console.warn && console.log;
  7051. function warn(str) {
  7052. if (hasConsole) {
  7053. console.warn(ECHARTS_PREFIX + str);
  7054. }
  7055. }
  7056. function error(str) {
  7057. if (hasConsole) {
  7058. console.error(ECHARTS_PREFIX + str);
  7059. }
  7060. }
  7061. function deprecateLog(str) {
  7062. if ("development" !== 'production') {
  7063. if (storedLogs[str]) {
  7064. // Not display duplicate message.
  7065. return;
  7066. }
  7067. if (hasConsole) {
  7068. storedLogs[str] = true;
  7069. console.warn(ECHARTS_PREFIX + 'DEPRECATED: ' + str);
  7070. }
  7071. }
  7072. }
  7073. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7074. if ("development" !== 'production') {
  7075. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7076. }
  7077. }
  7078. function consoleLog() {
  7079. var args = [];
  7080. for (var _i = 0; _i < arguments.length; _i++) {
  7081. args[_i] = arguments[_i];
  7082. }
  7083. if ("development" !== 'production') {
  7084. /* eslint-disable no-console */
  7085. if (typeof console !== 'undefined' && console.log) {
  7086. console.log.apply(console, args);
  7087. }
  7088. /* eslint-enable no-console */
  7089. }
  7090. }
  7091. /**
  7092. * If in __DEV__ environment, get console printable message for users hint.
  7093. * Parameters are separated by ' '.
  7094. * @usuage
  7095. * makePrintable('This is an error on', someVar, someObj);
  7096. *
  7097. * @param hintInfo anything about the current execution context to hint users.
  7098. * @throws Error
  7099. */
  7100. function makePrintable() {
  7101. var hintInfo = [];
  7102. for (var _i = 0; _i < arguments.length; _i++) {
  7103. hintInfo[_i] = arguments[_i];
  7104. }
  7105. var msg = '';
  7106. if ("development" !== 'production') {
  7107. // Fuzzy stringify for print.
  7108. // This code only exist in dev environment.
  7109. var makePrintableStringIfPossible_1 = function (val) {
  7110. 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;
  7111. };
  7112. msg = map(hintInfo, function (arg) {
  7113. if (isString(arg)) {
  7114. // Print without quotation mark for some statement.
  7115. return arg;
  7116. } else {
  7117. var printableStr = makePrintableStringIfPossible_1(arg);
  7118. if (printableStr != null) {
  7119. return printableStr;
  7120. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7121. try {
  7122. return JSON.stringify(arg, function (n, val) {
  7123. var printableStr = makePrintableStringIfPossible_1(val);
  7124. return printableStr == null ? val : printableStr;
  7125. }); // In most cases the info object is small, so do not line break.
  7126. } catch (err) {
  7127. return '?';
  7128. }
  7129. } else {
  7130. return '?';
  7131. }
  7132. }
  7133. }).join(' ');
  7134. }
  7135. return msg;
  7136. }
  7137. /**
  7138. * @throws Error
  7139. */
  7140. function throwError(msg) {
  7141. throw new Error(msg);
  7142. }
  7143. /**
  7144. * Make the name displayable. But we should
  7145. * make sure it is not duplicated with user
  7146. * specified name, so use '\0';
  7147. */
  7148. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7149. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7150. /**
  7151. * If value is not array, then translate it to array.
  7152. * @param {*} value
  7153. * @return {Array} [value] or value
  7154. */
  7155. function normalizeToArray(value) {
  7156. return value instanceof Array ? value : value == null ? [] : [value];
  7157. }
  7158. /**
  7159. * Sync default option between normal and emphasis like `position` and `show`
  7160. * In case some one will write code like
  7161. * label: {
  7162. * show: false,
  7163. * position: 'outside',
  7164. * fontSize: 18
  7165. * },
  7166. * emphasis: {
  7167. * label: { show: true }
  7168. * }
  7169. */
  7170. function defaultEmphasis(opt, key, subOpts) {
  7171. // Caution: performance sensitive.
  7172. if (opt) {
  7173. opt[key] = opt[key] || {};
  7174. opt.emphasis = opt.emphasis || {};
  7175. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7176. for (var i = 0, len = subOpts.length; i < len; i++) {
  7177. var subOptName = subOpts[i];
  7178. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7179. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7180. }
  7181. }
  7182. }
  7183. }
  7184. 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([
  7185. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7186. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7187. // // FIXME: deprecated, check and remove it.
  7188. // 'textStyle'
  7189. // ]);
  7190. /**
  7191. * The method do not ensure performance.
  7192. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7193. * This helper method retieves value from data.
  7194. */
  7195. function getDataItemValue(dataItem) {
  7196. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7197. }
  7198. /**
  7199. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7200. * This helper method determine if dataItem has extra option besides value
  7201. */
  7202. function isDataItemOption(dataItem) {
  7203. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7204. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7205. }
  7206. /**
  7207. * Mapping to existings for merge.
  7208. *
  7209. * Mode "normalMege":
  7210. * The mapping result (merge result) will keep the order of the existing
  7211. * component, rather than the order of new option. Because we should ensure
  7212. * some specified index reference (like xAxisIndex) keep work.
  7213. * And in most cases, "merge option" is used to update partial option but not
  7214. * be expected to change the order.
  7215. *
  7216. * Mode "replaceMege":
  7217. * (1) Only the id mapped components will be merged.
  7218. * (2) Other existing components (except internal compoonets) will be removed.
  7219. * (3) Other new options will be used to create new component.
  7220. * (4) The index of the existing compoents will not be modified.
  7221. * That means their might be "hole" after the removal.
  7222. * The new components are created first at those available index.
  7223. *
  7224. * Mode "replaceAll":
  7225. * This mode try to support that reproduce an echarts instance from another
  7226. * echarts instance (via `getOption`) in some simple cases.
  7227. * In this senario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7228. * which ensures the compoennt index referring (like `xAxisIndex: ?`) corrent. That is,
  7229. * the "hole" in `newCmptOptions` will also be kept.
  7230. * On the contrary, other modes try best to eliminate holes.
  7231. * PENDING: This is an experimental mode yet.
  7232. *
  7233. * @return See the comment of <MappingResult>.
  7234. */
  7235. function mappingToExists(existings, newCmptOptions, mode) {
  7236. var isNormalMergeMode = mode === 'normalMerge';
  7237. var isReplaceMergeMode = mode === 'replaceMerge';
  7238. var isReplaceAllMode = mode === 'replaceAll';
  7239. existings = existings || [];
  7240. newCmptOptions = (newCmptOptions || []).slice();
  7241. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7242. each(newCmptOptions, function (cmptOption, index) {
  7243. if (!isObject(cmptOption)) {
  7244. newCmptOptions[index] = null;
  7245. return;
  7246. }
  7247. if ("development" !== 'production') {
  7248. // There is some legacy case that name is set as `false`.
  7249. // But should work normally rather than throw error.
  7250. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7251. warnInvalidateIdOrName(cmptOption.id);
  7252. }
  7253. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7254. warnInvalidateIdOrName(cmptOption.name);
  7255. }
  7256. }
  7257. });
  7258. var result = prepareResult(existings, existingIdIdxMap, mode);
  7259. if (isNormalMergeMode || isReplaceMergeMode) {
  7260. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7261. }
  7262. if (isNormalMergeMode) {
  7263. mappingByName(result, newCmptOptions);
  7264. }
  7265. if (isNormalMergeMode || isReplaceMergeMode) {
  7266. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7267. } else if (isReplaceAllMode) {
  7268. mappingInReplaceAllMode(result, newCmptOptions);
  7269. }
  7270. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7271. // forEach will ommit those items and result in incorrect result.
  7272. return result;
  7273. }
  7274. function prepareResult(existings, existingIdIdxMap, mode) {
  7275. var result = [];
  7276. if (mode === 'replaceAll') {
  7277. return result;
  7278. } // Do not use native `map` to in case that the array `existings`
  7279. // contains elided items, which will be ommited.
  7280. for (var index = 0; index < existings.length; index++) {
  7281. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7282. if (existing && existing.id != null) {
  7283. existingIdIdxMap.set(existing.id, index);
  7284. } // For non-internal-componnets:
  7285. // Mode "normalMerge": all existings kept.
  7286. // Mode "replaceMerge": all existing removed unless mapped by id.
  7287. // For internal-components:
  7288. // go with "replaceMerge" approach in both mode.
  7289. result.push({
  7290. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7291. newOption: null,
  7292. keyInfo: null,
  7293. brandNew: null
  7294. });
  7295. }
  7296. return result;
  7297. }
  7298. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7299. // Mapping by id if specified.
  7300. each(newCmptOptions, function (cmptOption, index) {
  7301. if (!cmptOption || cmptOption.id == null) {
  7302. return;
  7303. }
  7304. var optionId = makeComparableKey(cmptOption.id);
  7305. var existingIdx = existingIdIdxMap.get(optionId);
  7306. if (existingIdx != null) {
  7307. var resultItem = result[existingIdx];
  7308. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7309. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7310. // the existings rather than creating new component model.
  7311. resultItem.existing = existings[existingIdx];
  7312. newCmptOptions[index] = null;
  7313. }
  7314. });
  7315. }
  7316. function mappingByName(result, newCmptOptions) {
  7317. // Mapping by name if specified.
  7318. each(newCmptOptions, function (cmptOption, index) {
  7319. if (!cmptOption || cmptOption.name == null) {
  7320. return;
  7321. }
  7322. for (var i = 0; i < result.length; i++) {
  7323. var existing = result[i].existing;
  7324. if (!result[i].newOption // Consider name: two map to one.
  7325. // Can not match when both ids existing but different.
  7326. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  7327. result[i].newOption = cmptOption;
  7328. newCmptOptions[index] = null;
  7329. return;
  7330. }
  7331. }
  7332. });
  7333. }
  7334. function mappingByIndex(result, newCmptOptions, brandNew) {
  7335. each(newCmptOptions, function (cmptOption) {
  7336. if (!cmptOption) {
  7337. return;
  7338. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  7339. var resultItem;
  7340. var nextIdx = 0;
  7341. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  7342. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  7343. // after mapping performed, model will always be assigned with an id if user not given.
  7344. // After that all models have id.
  7345. // (2) If new option has id, it can only set to a hole or append to the last. It should
  7346. // not be merged to the existings with different id. Because id should not be overwritten.
  7347. // (3) Name can be overwritten, because axis use name as 'show label text'.
  7348. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  7349. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  7350. nextIdx++;
  7351. }
  7352. if (resultItem) {
  7353. resultItem.newOption = cmptOption;
  7354. resultItem.brandNew = brandNew;
  7355. } else {
  7356. result.push({
  7357. newOption: cmptOption,
  7358. brandNew: brandNew,
  7359. existing: null,
  7360. keyInfo: null
  7361. });
  7362. }
  7363. nextIdx++;
  7364. });
  7365. }
  7366. function mappingInReplaceAllMode(result, newCmptOptions) {
  7367. each(newCmptOptions, function (cmptOption) {
  7368. // The feature "reproduce" requires "hole" will also reproduced
  7369. // in case that compoennt index referring are broken.
  7370. result.push({
  7371. newOption: cmptOption,
  7372. brandNew: true,
  7373. existing: null,
  7374. keyInfo: null
  7375. });
  7376. });
  7377. }
  7378. /**
  7379. * Make id and name for mapping result (result of mappingToExists)
  7380. * into `keyInfo` field.
  7381. */
  7382. function makeIdAndName(mapResult) {
  7383. // We use this id to hash component models and view instances
  7384. // in echarts. id can be specified by user, or auto generated.
  7385. // The id generation rule ensures new view instance are able
  7386. // to mapped to old instance when setOption are called in
  7387. // no-merge mode. So we generate model id by name and plus
  7388. // type in view id.
  7389. // name can be duplicated among components, which is convenient
  7390. // to specify multi components (like series) by one name.
  7391. // Ensure that each id is distinct.
  7392. var idMap = createHashMap();
  7393. each(mapResult, function (item) {
  7394. var existing = item.existing;
  7395. existing && idMap.set(existing.id, item);
  7396. });
  7397. each(mapResult, function (item) {
  7398. var opt = item.newOption; // Force ensure id not duplicated.
  7399. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  7400. opt && opt.id != null && idMap.set(opt.id, item);
  7401. !item.keyInfo && (item.keyInfo = {});
  7402. }); // Make name and id.
  7403. each(mapResult, function (item, index) {
  7404. var existing = item.existing;
  7405. var opt = item.newOption;
  7406. var keyInfo = item.keyInfo;
  7407. if (!isObject(opt)) {
  7408. return;
  7409. } // name can be overwitten. Consider case: axis.name = '20km'.
  7410. // But id generated by name will not be changed, which affect
  7411. // only in that case: setOption with 'not merge mode' and view
  7412. // instance will be recreated, which can be accepted.
  7413. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid diffferent series has the same name,
  7414. // because name may be used like in color pallet.
  7415. : DUMMY_COMPONENT_NAME_PREFIX + index;
  7416. if (existing) {
  7417. keyInfo.id = makeComparableKey(existing.id);
  7418. } else if (opt.id != null) {
  7419. keyInfo.id = makeComparableKey(opt.id);
  7420. } else {
  7421. // Consider this situatoin:
  7422. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  7423. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  7424. // Series with the same name between optionA and optionB
  7425. // should be mapped.
  7426. var idNum = 0;
  7427. do {
  7428. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  7429. } while (idMap.get(keyInfo.id));
  7430. }
  7431. idMap.set(keyInfo.id, item);
  7432. });
  7433. }
  7434. function keyExistAndEqual(attr, obj1, obj2) {
  7435. var key1 = convertOptionIdName(obj1[attr], null);
  7436. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  7437. return key1 != null && key2 != null && key1 === key2;
  7438. }
  7439. /**
  7440. * @return return null if not exist.
  7441. */
  7442. function makeComparableKey(val) {
  7443. if ("development" !== 'production') {
  7444. if (val == null) {
  7445. throw new Error();
  7446. }
  7447. }
  7448. return convertOptionIdName(val, '');
  7449. }
  7450. function convertOptionIdName(idOrName, defaultValue) {
  7451. if (idOrName == null) {
  7452. return defaultValue;
  7453. }
  7454. var type = typeof idOrName;
  7455. return type === 'string' ? idOrName : type === 'number' || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  7456. }
  7457. function warnInvalidateIdOrName(idOrName) {
  7458. if ("development" !== 'production') {
  7459. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  7460. }
  7461. }
  7462. function isValidIdOrName(idOrName) {
  7463. return isStringSafe(idOrName) || isNumeric(idOrName);
  7464. }
  7465. function isNameSpecified(componentModel) {
  7466. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  7467. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  7468. }
  7469. /**
  7470. * @public
  7471. * @param {Object} cmptOption
  7472. * @return {boolean}
  7473. */
  7474. function isComponentIdInternal(cmptOption) {
  7475. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  7476. }
  7477. function makeInternalComponentId(idSuffix) {
  7478. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  7479. }
  7480. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  7481. // Set mainType and complete subType.
  7482. each(mappingResult, function (item) {
  7483. var newOption = item.newOption;
  7484. if (isObject(newOption)) {
  7485. item.keyInfo.mainType = mainType;
  7486. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  7487. }
  7488. });
  7489. }
  7490. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  7491. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  7492. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  7493. return subType;
  7494. }
  7495. /**
  7496. * A helper for removing duplicate items between batchA and batchB,
  7497. * and in themselves, and categorize by series.
  7498. *
  7499. * @param batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  7500. * @param batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  7501. * @return result: [resultBatchA, resultBatchB]
  7502. */
  7503. function compressBatches(batchA, batchB) {
  7504. var mapA = {};
  7505. var mapB = {};
  7506. makeMap(batchA || [], mapA);
  7507. makeMap(batchB || [], mapB, mapA);
  7508. return [mapToArray(mapA), mapToArray(mapB)];
  7509. function makeMap(sourceBatch, map, otherMap) {
  7510. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  7511. var seriesId = convertOptionIdName(sourceBatch[i].seriesId, null);
  7512. if (seriesId == null) {
  7513. return;
  7514. }
  7515. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  7516. var otherDataIndices = otherMap && otherMap[seriesId];
  7517. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  7518. var dataIndex = dataIndices[j];
  7519. if (otherDataIndices && otherDataIndices[dataIndex]) {
  7520. otherDataIndices[dataIndex] = null;
  7521. } else {
  7522. (map[seriesId] || (map[seriesId] = {}))[dataIndex] = 1;
  7523. }
  7524. }
  7525. }
  7526. }
  7527. function mapToArray(map, isData) {
  7528. var result = [];
  7529. for (var i in map) {
  7530. if (map.hasOwnProperty(i) && map[i] != null) {
  7531. if (isData) {
  7532. result.push(+i);
  7533. } else {
  7534. var dataIndices = mapToArray(map[i], true);
  7535. dataIndices.length && result.push({
  7536. seriesId: i,
  7537. dataIndex: dataIndices
  7538. });
  7539. }
  7540. }
  7541. }
  7542. return result;
  7543. }
  7544. }
  7545. /**
  7546. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  7547. * each of which can be Array or primary type.
  7548. * @return dataIndex If not found, return undefined/null.
  7549. */
  7550. function queryDataIndex(data, payload) {
  7551. if (payload.dataIndexInside != null) {
  7552. return payload.dataIndexInside;
  7553. } else if (payload.dataIndex != null) {
  7554. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  7555. return data.indexOfRawIndex(value);
  7556. }) : data.indexOfRawIndex(payload.dataIndex);
  7557. } else if (payload.name != null) {
  7558. return isArray(payload.name) ? map(payload.name, function (value) {
  7559. return data.indexOfName(value);
  7560. }) : data.indexOfName(payload.name);
  7561. }
  7562. }
  7563. /**
  7564. * Enable property storage to any host object.
  7565. * Notice: Serialization is not supported.
  7566. *
  7567. * For example:
  7568. * let inner = zrUitl.makeInner();
  7569. *
  7570. * function some1(hostObj) {
  7571. * inner(hostObj).someProperty = 1212;
  7572. * ...
  7573. * }
  7574. * function some2() {
  7575. * let fields = inner(this);
  7576. * fields.someProperty1 = 1212;
  7577. * fields.someProperty2 = 'xx';
  7578. * ...
  7579. * }
  7580. *
  7581. * @return {Function}
  7582. */
  7583. function makeInner() {
  7584. var key = '__ec_inner_' + innerUniqueIndex++;
  7585. return function (hostObj) {
  7586. return hostObj[key] || (hostObj[key] = {});
  7587. };
  7588. }
  7589. var innerUniqueIndex = getRandomIdBase();
  7590. /**
  7591. * The same behavior as `component.getReferringComponents`.
  7592. */
  7593. function parseFinder(ecModel, finderInput, opt) {
  7594. var _a = preParseFinder(finderInput, opt),
  7595. mainTypeSpecified = _a.mainTypeSpecified,
  7596. queryOptionMap = _a.queryOptionMap,
  7597. others = _a.others;
  7598. var result = others;
  7599. var defaultMainType = opt ? opt.defaultMainType : null;
  7600. if (!mainTypeSpecified && defaultMainType) {
  7601. queryOptionMap.set(defaultMainType, {});
  7602. }
  7603. queryOptionMap.each(function (queryOption, mainType) {
  7604. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  7605. useDefault: defaultMainType === mainType,
  7606. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  7607. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  7608. });
  7609. result[mainType + 'Models'] = queryResult.models;
  7610. result[mainType + 'Model'] = queryResult.models[0];
  7611. });
  7612. return result;
  7613. }
  7614. function preParseFinder(finderInput, opt) {
  7615. var finder;
  7616. if (isString(finderInput)) {
  7617. var obj = {};
  7618. obj[finderInput + 'Index'] = 0;
  7619. finder = obj;
  7620. } else {
  7621. finder = finderInput;
  7622. }
  7623. var queryOptionMap = createHashMap();
  7624. var others = {};
  7625. var mainTypeSpecified = false;
  7626. each(finder, function (value, key) {
  7627. // Exclude 'dataIndex' and other illgal keys.
  7628. if (key === 'dataIndex' || key === 'dataIndexInside') {
  7629. others[key] = value;
  7630. return;
  7631. }
  7632. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  7633. var mainType = parsedKey[1];
  7634. var queryType = (parsedKey[2] || '').toLowerCase();
  7635. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  7636. return;
  7637. }
  7638. mainTypeSpecified = mainTypeSpecified || !!mainType;
  7639. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  7640. queryOption[queryType] = value;
  7641. });
  7642. return {
  7643. mainTypeSpecified: mainTypeSpecified,
  7644. queryOptionMap: queryOptionMap,
  7645. others: others
  7646. };
  7647. }
  7648. var SINGLE_REFERRING = {
  7649. useDefault: true,
  7650. enableAll: false,
  7651. enableNone: false
  7652. };
  7653. var MULTIPLE_REFERRING = {
  7654. useDefault: false,
  7655. enableAll: true,
  7656. enableNone: true
  7657. };
  7658. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  7659. opt = opt || SINGLE_REFERRING;
  7660. var indexOption = userOption.index;
  7661. var idOption = userOption.id;
  7662. var nameOption = userOption.name;
  7663. var result = {
  7664. models: null,
  7665. specified: indexOption != null || idOption != null || nameOption != null
  7666. };
  7667. if (!result.specified) {
  7668. // Use the first as default if `useDefault`.
  7669. var firstCmpt = void 0;
  7670. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  7671. return result;
  7672. }
  7673. if (indexOption === 'none' || indexOption === false) {
  7674. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  7675. result.models = [];
  7676. return result;
  7677. } // `queryComponents` will return all components if
  7678. // both all of index/id/name are null/undefined.
  7679. if (indexOption === 'all') {
  7680. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  7681. indexOption = idOption = nameOption = null;
  7682. }
  7683. result.models = ecModel.queryComponents({
  7684. mainType: mainType,
  7685. index: indexOption,
  7686. id: idOption,
  7687. name: nameOption
  7688. });
  7689. return result;
  7690. }
  7691. function setAttribute(dom, key, value) {
  7692. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  7693. }
  7694. function getAttribute(dom, key) {
  7695. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  7696. }
  7697. function getTooltipRenderMode(renderModeOption) {
  7698. if (renderModeOption === 'auto') {
  7699. // Using html when `document` exists, use richText otherwise
  7700. return env.domSupported ? 'html' : 'richText';
  7701. } else {
  7702. return renderModeOption || 'html';
  7703. }
  7704. }
  7705. /**
  7706. * Group a list by key.
  7707. */
  7708. function groupData(array, getKey // return key
  7709. ) {
  7710. var buckets = createHashMap();
  7711. var keys = [];
  7712. each(array, function (item) {
  7713. var key = getKey(item);
  7714. (buckets.get(key) || (keys.push(key), buckets.set(key, []))).push(item);
  7715. });
  7716. return {
  7717. keys: keys,
  7718. buckets: buckets
  7719. };
  7720. }
  7721. /**
  7722. * Interpolate raw values of a series with percent
  7723. *
  7724. * @param data data
  7725. * @param labelModel label model of the text element
  7726. * @param sourceValue start value. May be null/undefined when init.
  7727. * @param targetValue end value
  7728. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  7729. * @return interpolated values
  7730. * If `sourceValue` and `targetValue` are `number`, return `number`.
  7731. * If `sourceValue` and `targetValue` are `string`, return `string`.
  7732. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  7733. * Other cases do not supported.
  7734. */
  7735. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  7736. var isAutoPrecision = precision == null || precision === 'auto';
  7737. if (targetValue == null) {
  7738. return targetValue;
  7739. }
  7740. if (typeof targetValue === 'number') {
  7741. var value = interpolateNumber(sourceValue || 0, targetValue, percent);
  7742. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  7743. } else if (typeof targetValue === 'string') {
  7744. return percent < 1 ? sourceValue : targetValue;
  7745. } else {
  7746. var interpolated = [];
  7747. var leftArr = sourceValue;
  7748. var rightArr = targetValue;
  7749. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  7750. for (var i = 0; i < length_1; ++i) {
  7751. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  7752. if (info && info.type === 'ordinal') {
  7753. // In init, there is no `sourceValue`, but should better not to get undefined result.
  7754. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  7755. } else {
  7756. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  7757. var rightVal = rightArr[i];
  7758. var value = interpolateNumber(leftVal, rightVal, percent);
  7759. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  7760. }
  7761. }
  7762. return interpolated;
  7763. }
  7764. }
  7765. var TYPE_DELIMITER = '.';
  7766. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  7767. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  7768. /**
  7769. * Notice, parseClassType('') should returns {main: '', sub: ''}
  7770. * @public
  7771. */
  7772. function parseClassType(componentType) {
  7773. var ret = {
  7774. main: '',
  7775. sub: ''
  7776. };
  7777. if (componentType) {
  7778. var typeArr = componentType.split(TYPE_DELIMITER);
  7779. ret.main = typeArr[0] || '';
  7780. ret.sub = typeArr[1] || '';
  7781. }
  7782. return ret;
  7783. }
  7784. /**
  7785. * @public
  7786. */
  7787. function checkClassType(componentType) {
  7788. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  7789. }
  7790. function isExtendedClass(clz) {
  7791. return !!(clz && clz[IS_EXTENDED_CLASS]);
  7792. }
  7793. /**
  7794. * Implements `ExtendableConstructor` for `rootClz`.
  7795. *
  7796. * @usage
  7797. * ```ts
  7798. * class Xxx {}
  7799. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  7800. * enableClassExtend(Xxx as XxxConstructor);
  7801. * ```
  7802. */
  7803. function enableClassExtend(rootClz, mandatoryMethods) {
  7804. rootClz.$constructor = rootClz; // FIXME: not necessary?
  7805. rootClz.extend = function (proto) {
  7806. if ("development" !== 'production') {
  7807. each(mandatoryMethods, function (method) {
  7808. if (!proto[method]) {
  7809. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  7810. }
  7811. });
  7812. }
  7813. var superClass = this; // For backward compat, we both support ts class inheritance and this
  7814. // "extend" approach.
  7815. // The constructor should keep the same behavior as ts class inheritance:
  7816. // If this constructor/$constructor is not declared, auto invoke the super
  7817. // constructor.
  7818. // If this constructor/$constructor is declared, it is responsible for
  7819. // calling the super constructor.
  7820. function ExtendedClass() {
  7821. var args = [];
  7822. for (var _i = 0; _i < arguments.length; _i++) {
  7823. args[_i] = arguments[_i];
  7824. }
  7825. if (!proto.$constructor) {
  7826. if (!isESClass(superClass)) {
  7827. // Will throw error if superClass is an es6 native class.
  7828. superClass.apply(this, arguments);
  7829. } else {
  7830. var ins = createObject( // @ts-ignore
  7831. ExtendedClass.prototype, new (superClass.bind.apply(superClass, __spreadArray([void 0], args)))());
  7832. return ins;
  7833. }
  7834. } else {
  7835. proto.$constructor.apply(this, arguments);
  7836. }
  7837. }
  7838. ExtendedClass[IS_EXTENDED_CLASS] = true;
  7839. extend(ExtendedClass.prototype, proto);
  7840. ExtendedClass.extend = this.extend;
  7841. ExtendedClass.superCall = superCall;
  7842. ExtendedClass.superApply = superApply;
  7843. inherits(ExtendedClass, this);
  7844. ExtendedClass.superClass = superClass;
  7845. return ExtendedClass;
  7846. };
  7847. }
  7848. function isESClass(fn) {
  7849. return typeof fn === 'function' && /^class\s/.test(Function.prototype.toString.call(fn));
  7850. }
  7851. /**
  7852. * A work around to both support ts extend and this extend mechanism.
  7853. * on sub-class.
  7854. * @usage
  7855. * ```ts
  7856. * class Component { ... }
  7857. * classUtil.enableClassExtend(Component);
  7858. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  7859. *
  7860. * class Series extends Component { ... }
  7861. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  7862. * Component.markExtend(Series);
  7863. * ```
  7864. */
  7865. function mountExtend(SubClz, SupperClz) {
  7866. SubClz.extend = SupperClz.extend;
  7867. } // A random offset.
  7868. var classBase = Math.round(Math.random() * 10);
  7869. /**
  7870. * Implements `CheckableConstructor` for `target`.
  7871. * Can not use instanceof, consider different scope by
  7872. * cross domain or es module import in ec extensions.
  7873. * Mount a method "isInstance()" to Clz.
  7874. *
  7875. * @usage
  7876. * ```ts
  7877. * class Xxx {}
  7878. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  7879. * enableClassCheck(Xxx as XxxConstructor)
  7880. * ```
  7881. */
  7882. function enableClassCheck(target) {
  7883. var classAttr = ['__\0is_clz', classBase++].join('_');
  7884. target.prototype[classAttr] = true;
  7885. if ("development" !== 'production') {
  7886. assert(!target.isInstance, 'The method "is" can not be defined.');
  7887. }
  7888. target.isInstance = function (obj) {
  7889. return !!(obj && obj[classAttr]);
  7890. };
  7891. } // superCall should have class info, which can not be fetch from 'this'.
  7892. // Consider this case:
  7893. // class A has method f,
  7894. // class B inherits class A, overrides method f, f call superApply('f'),
  7895. // class C inherits class B, do not overrides method f,
  7896. // then when method of class C is called, dead loop occured.
  7897. function superCall(context, methodName) {
  7898. var args = [];
  7899. for (var _i = 2; _i < arguments.length; _i++) {
  7900. args[_i - 2] = arguments[_i];
  7901. }
  7902. return this.superClass.prototype[methodName].apply(context, args);
  7903. }
  7904. function superApply(context, methodName, args) {
  7905. return this.superClass.prototype[methodName].apply(context, args);
  7906. }
  7907. /**
  7908. * Implements `ClassManager` for `target`
  7909. *
  7910. * @usage
  7911. * ```ts
  7912. * class Xxx {}
  7913. * type XxxConstructor = typeof Xxx & ClassManager
  7914. * enableClassManagement(Xxx as XxxConstructor);
  7915. * ```
  7916. */
  7917. function enableClassManagement(target) {
  7918. /**
  7919. * Component model classes
  7920. * key: componentType,
  7921. * value:
  7922. * componentClass, when componentType is 'xxx'
  7923. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  7924. */
  7925. var storage = {};
  7926. target.registerClass = function (clz) {
  7927. // `type` should not be a "instance memeber".
  7928. // If using TS class, should better declared as `static type = 'series.pie'`.
  7929. // otherwise users have to mount `type` on prototype manually.
  7930. // For backward compat and enable instance visit type via `this.type`,
  7931. // we stil support fetch `type` from prototype.
  7932. var componentFullType = clz.type || clz.prototype.type;
  7933. if (componentFullType) {
  7934. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  7935. clz.prototype.type = componentFullType;
  7936. var componentTypeInfo = parseClassType(componentFullType);
  7937. if (!componentTypeInfo.sub) {
  7938. if ("development" !== 'production') {
  7939. if (storage[componentTypeInfo.main]) {
  7940. console.warn(componentTypeInfo.main + ' exists.');
  7941. }
  7942. }
  7943. storage[componentTypeInfo.main] = clz;
  7944. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  7945. var container = makeContainer(componentTypeInfo);
  7946. container[componentTypeInfo.sub] = clz;
  7947. }
  7948. }
  7949. return clz;
  7950. };
  7951. target.getClass = function (mainType, subType, throwWhenNotFound) {
  7952. var clz = storage[mainType];
  7953. if (clz && clz[IS_CONTAINER]) {
  7954. clz = subType ? clz[subType] : null;
  7955. }
  7956. if (throwWhenNotFound && !clz) {
  7957. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  7958. }
  7959. return clz;
  7960. };
  7961. target.getClassesByMainType = function (componentType) {
  7962. var componentTypeInfo = parseClassType(componentType);
  7963. var result = [];
  7964. var obj = storage[componentTypeInfo.main];
  7965. if (obj && obj[IS_CONTAINER]) {
  7966. each(obj, function (o, type) {
  7967. type !== IS_CONTAINER && result.push(o);
  7968. });
  7969. } else {
  7970. result.push(obj);
  7971. }
  7972. return result;
  7973. };
  7974. target.hasClass = function (componentType) {
  7975. // Just consider componentType.main.
  7976. var componentTypeInfo = parseClassType(componentType);
  7977. return !!storage[componentTypeInfo.main];
  7978. };
  7979. /**
  7980. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  7981. */
  7982. target.getAllClassMainTypes = function () {
  7983. var types = [];
  7984. each(storage, function (obj, type) {
  7985. types.push(type);
  7986. });
  7987. return types;
  7988. };
  7989. /**
  7990. * If a main type is container and has sub types
  7991. */
  7992. target.hasSubTypes = function (componentType) {
  7993. var componentTypeInfo = parseClassType(componentType);
  7994. var obj = storage[componentTypeInfo.main];
  7995. return obj && obj[IS_CONTAINER];
  7996. };
  7997. function makeContainer(componentTypeInfo) {
  7998. var container = storage[componentTypeInfo.main];
  7999. if (!container || !container[IS_CONTAINER]) {
  8000. container = storage[componentTypeInfo.main] = {};
  8001. container[IS_CONTAINER] = true;
  8002. }
  8003. return container;
  8004. }
  8005. } // /**
  8006. // * @param {string|Array.<string>} properties
  8007. // */
  8008. // export function setReadOnly(obj, properties) {
  8009. // FIXME It seems broken in IE8 simulation of IE11
  8010. // if (!zrUtil.isArray(properties)) {
  8011. // properties = properties != null ? [properties] : [];
  8012. // }
  8013. // zrUtil.each(properties, function (prop) {
  8014. // let value = obj[prop];
  8015. // Object.defineProperty
  8016. // && Object.defineProperty(obj, prop, {
  8017. // value: value, writable: false
  8018. // });
  8019. // zrUtil.isArray(obj[prop])
  8020. // && Object.freeze
  8021. // && Object.freeze(obj[prop]);
  8022. // });
  8023. // }
  8024. function makeStyleMapper(properties, ignoreParent) {
  8025. // Normalize
  8026. for (var i = 0; i < properties.length; i++) {
  8027. if (!properties[i][1]) {
  8028. properties[i][1] = properties[i][0];
  8029. }
  8030. }
  8031. ignoreParent = ignoreParent || false;
  8032. return function (model, excludes, includes) {
  8033. var style = {};
  8034. for (var i = 0; i < properties.length; i++) {
  8035. var propName = properties[i][1];
  8036. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8037. continue;
  8038. }
  8039. var val = model.getShallow(propName, ignoreParent);
  8040. if (val != null) {
  8041. style[properties[i][0]] = val;
  8042. }
  8043. } // TODO Text or image?
  8044. return style;
  8045. };
  8046. }
  8047. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8048. // So do not transfer decal directly.
  8049. ];
  8050. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8051. var AreaStyleMixin =
  8052. /** @class */
  8053. function () {
  8054. function AreaStyleMixin() {}
  8055. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8056. return getAreaStyle(this, excludes, includes);
  8057. };
  8058. return AreaStyleMixin;
  8059. }();
  8060. var globalImageCache = new LRU(50);
  8061. function findExistImage(newImageOrSrc) {
  8062. if (typeof newImageOrSrc === 'string') {
  8063. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8064. return cachedImgObj && cachedImgObj.image;
  8065. }
  8066. else {
  8067. return newImageOrSrc;
  8068. }
  8069. }
  8070. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8071. if (!newImageOrSrc) {
  8072. return image;
  8073. }
  8074. else if (typeof newImageOrSrc === 'string') {
  8075. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8076. return image;
  8077. }
  8078. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8079. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8080. if (cachedImgObj) {
  8081. image = cachedImgObj.image;
  8082. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8083. }
  8084. else {
  8085. image = new Image();
  8086. image.onload = image.onerror = imageOnLoad;
  8087. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8088. image: image,
  8089. pending: [pendingWrap]
  8090. });
  8091. image.src = image.__zrImageSrc = newImageOrSrc;
  8092. }
  8093. return image;
  8094. }
  8095. else {
  8096. return newImageOrSrc;
  8097. }
  8098. }
  8099. function imageOnLoad() {
  8100. var cachedImgObj = this.__cachedImgObj;
  8101. this.onload = this.onerror = this.__cachedImgObj = null;
  8102. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8103. var pendingWrap = cachedImgObj.pending[i];
  8104. var cb = pendingWrap.cb;
  8105. cb && cb(this, pendingWrap.cbPayload);
  8106. pendingWrap.hostEl.dirty();
  8107. }
  8108. cachedImgObj.pending.length = 0;
  8109. }
  8110. function isImageReady(image) {
  8111. return image && image.width && image.height;
  8112. }
  8113. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8114. function truncateText(text, containerWidth, font, ellipsis, options) {
  8115. if (!containerWidth) {
  8116. return '';
  8117. }
  8118. var textLines = (text + '').split('\n');
  8119. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8120. for (var i = 0, len = textLines.length; i < len; i++) {
  8121. textLines[i] = truncateSingleLine(textLines[i], options);
  8122. }
  8123. return textLines.join('\n');
  8124. }
  8125. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8126. options = options || {};
  8127. var preparedOpts = extend({}, options);
  8128. preparedOpts.font = font;
  8129. ellipsis = retrieve2(ellipsis, '...');
  8130. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8131. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8132. preparedOpts.cnCharWidth = getWidth('国', font);
  8133. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8134. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8135. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8136. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8137. contentWidth -= ascCharWidth;
  8138. }
  8139. var ellipsisWidth = getWidth(ellipsis, font);
  8140. if (ellipsisWidth > contentWidth) {
  8141. ellipsis = '';
  8142. ellipsisWidth = 0;
  8143. }
  8144. contentWidth = containerWidth - ellipsisWidth;
  8145. preparedOpts.ellipsis = ellipsis;
  8146. preparedOpts.ellipsisWidth = ellipsisWidth;
  8147. preparedOpts.contentWidth = contentWidth;
  8148. preparedOpts.containerWidth = containerWidth;
  8149. return preparedOpts;
  8150. }
  8151. function truncateSingleLine(textLine, options) {
  8152. var containerWidth = options.containerWidth;
  8153. var font = options.font;
  8154. var contentWidth = options.contentWidth;
  8155. if (!containerWidth) {
  8156. return '';
  8157. }
  8158. var lineWidth = getWidth(textLine, font);
  8159. if (lineWidth <= containerWidth) {
  8160. return textLine;
  8161. }
  8162. for (var j = 0;; j++) {
  8163. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8164. textLine += options.ellipsis;
  8165. break;
  8166. }
  8167. var subLength = j === 0
  8168. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8169. : lineWidth > 0
  8170. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8171. : 0;
  8172. textLine = textLine.substr(0, subLength);
  8173. lineWidth = getWidth(textLine, font);
  8174. }
  8175. if (textLine === '') {
  8176. textLine = options.placeholder;
  8177. }
  8178. return textLine;
  8179. }
  8180. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8181. var width = 0;
  8182. var i = 0;
  8183. for (var len = text.length; i < len && width < contentWidth; i++) {
  8184. var charCode = text.charCodeAt(i);
  8185. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8186. }
  8187. return i;
  8188. }
  8189. function parsePlainText(text, style) {
  8190. text != null && (text += '');
  8191. var overflow = style.overflow;
  8192. var padding = style.padding;
  8193. var font = style.font;
  8194. var truncate = overflow === 'truncate';
  8195. var calculatedLineHeight = getLineHeight(font);
  8196. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8197. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8198. var width = style.width;
  8199. var lines;
  8200. if (width != null && overflow === 'break' || overflow === 'breakAll') {
  8201. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8202. }
  8203. else {
  8204. lines = text ? text.split('\n') : [];
  8205. }
  8206. var contentHeight = lines.length * lineHeight;
  8207. var height = retrieve2(style.height, contentHeight);
  8208. if (contentHeight > height && truncateLineOverflow) {
  8209. var lineCount = Math.floor(height / lineHeight);
  8210. lines = lines.slice(0, lineCount);
  8211. }
  8212. var outerHeight = height;
  8213. var outerWidth = width;
  8214. if (padding) {
  8215. outerHeight += padding[0] + padding[2];
  8216. if (outerWidth != null) {
  8217. outerWidth += padding[1] + padding[3];
  8218. }
  8219. }
  8220. if (text && truncate && outerWidth != null) {
  8221. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8222. minChar: style.truncateMinChar,
  8223. placeholder: style.placeholder
  8224. });
  8225. for (var i = 0; i < lines.length; i++) {
  8226. lines[i] = truncateSingleLine(lines[i], options);
  8227. }
  8228. }
  8229. if (width == null) {
  8230. var maxWidth = 0;
  8231. for (var i = 0; i < lines.length; i++) {
  8232. maxWidth = Math.max(getWidth(lines[i], font), maxWidth);
  8233. }
  8234. width = maxWidth;
  8235. }
  8236. return {
  8237. lines: lines,
  8238. height: height,
  8239. outerHeight: outerHeight,
  8240. lineHeight: lineHeight,
  8241. calculatedLineHeight: calculatedLineHeight,
  8242. contentHeight: contentHeight,
  8243. width: width
  8244. };
  8245. }
  8246. var RichTextToken = (function () {
  8247. function RichTextToken() {
  8248. }
  8249. return RichTextToken;
  8250. }());
  8251. var RichTextLine = (function () {
  8252. function RichTextLine(tokens) {
  8253. this.tokens = [];
  8254. if (tokens) {
  8255. this.tokens = tokens;
  8256. }
  8257. }
  8258. return RichTextLine;
  8259. }());
  8260. var RichTextContentBlock = (function () {
  8261. function RichTextContentBlock() {
  8262. this.width = 0;
  8263. this.height = 0;
  8264. this.contentWidth = 0;
  8265. this.contentHeight = 0;
  8266. this.outerWidth = 0;
  8267. this.outerHeight = 0;
  8268. this.lines = [];
  8269. }
  8270. return RichTextContentBlock;
  8271. }());
  8272. function parseRichText(text, style) {
  8273. var contentBlock = new RichTextContentBlock();
  8274. text != null && (text += '');
  8275. if (!text) {
  8276. return contentBlock;
  8277. }
  8278. var topWidth = style.width;
  8279. var topHeight = style.height;
  8280. var overflow = style.overflow;
  8281. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8282. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8283. : null;
  8284. var lastIndex = STYLE_REG.lastIndex = 0;
  8285. var result;
  8286. while ((result = STYLE_REG.exec(text)) != null) {
  8287. var matchedIndex = result.index;
  8288. if (matchedIndex > lastIndex) {
  8289. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8290. }
  8291. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8292. lastIndex = STYLE_REG.lastIndex;
  8293. }
  8294. if (lastIndex < text.length) {
  8295. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8296. }
  8297. var pendingList = [];
  8298. var calculatedHeight = 0;
  8299. var calculatedWidth = 0;
  8300. var stlPadding = style.padding;
  8301. var truncate = overflow === 'truncate';
  8302. var truncateLine = style.lineOverflow === 'truncate';
  8303. function finishLine(line, lineWidth, lineHeight) {
  8304. line.width = lineWidth;
  8305. line.lineHeight = lineHeight;
  8306. calculatedHeight += lineHeight;
  8307. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8308. }
  8309. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8310. var line = contentBlock.lines[i];
  8311. var lineHeight = 0;
  8312. var lineWidth = 0;
  8313. for (var j = 0; j < line.tokens.length; j++) {
  8314. var token = line.tokens[j];
  8315. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8316. var textPadding = token.textPadding = tokenStyle.padding;
  8317. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8318. var font = token.font = tokenStyle.font || style.font;
  8319. token.contentHeight = getLineHeight(font);
  8320. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  8321. token.innerHeight = tokenHeight;
  8322. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  8323. token.height = tokenHeight;
  8324. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  8325. token.align = tokenStyle && tokenStyle.align || style.align;
  8326. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  8327. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  8328. if (j > 0) {
  8329. line.tokens = line.tokens.slice(0, j);
  8330. finishLine(line, lineWidth, lineHeight);
  8331. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  8332. }
  8333. else {
  8334. contentBlock.lines = contentBlock.lines.slice(0, i);
  8335. }
  8336. break outer;
  8337. }
  8338. var styleTokenWidth = tokenStyle.width;
  8339. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  8340. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  8341. token.percentWidth = styleTokenWidth;
  8342. pendingList.push(token);
  8343. token.contentWidth = getWidth(token.text, font);
  8344. }
  8345. else {
  8346. if (tokenWidthNotSpecified) {
  8347. var textBackgroundColor = tokenStyle.backgroundColor;
  8348. var bgImg = textBackgroundColor && textBackgroundColor.image;
  8349. if (bgImg) {
  8350. bgImg = findExistImage(bgImg);
  8351. if (isImageReady(bgImg)) {
  8352. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  8353. }
  8354. }
  8355. }
  8356. var remainTruncWidth = truncate && topWidth != null
  8357. ? topWidth - lineWidth : null;
  8358. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  8359. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  8360. token.text = '';
  8361. token.width = token.contentWidth = 0;
  8362. }
  8363. else {
  8364. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  8365. token.width = token.contentWidth = getWidth(token.text, font);
  8366. }
  8367. }
  8368. else {
  8369. token.contentWidth = getWidth(token.text, font);
  8370. }
  8371. }
  8372. token.width += paddingH;
  8373. lineWidth += token.width;
  8374. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  8375. }
  8376. finishLine(line, lineWidth, lineHeight);
  8377. }
  8378. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  8379. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  8380. contentBlock.contentHeight = calculatedHeight;
  8381. contentBlock.contentWidth = calculatedWidth;
  8382. if (stlPadding) {
  8383. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  8384. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  8385. }
  8386. for (var i = 0; i < pendingList.length; i++) {
  8387. var token = pendingList[i];
  8388. var percentWidth = token.percentWidth;
  8389. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  8390. }
  8391. return contentBlock;
  8392. }
  8393. function pushTokens(block, str, style, wrapInfo, styleName) {
  8394. var isEmptyStr = str === '';
  8395. var tokenStyle = styleName && style.rich[styleName] || {};
  8396. var lines = block.lines;
  8397. var font = tokenStyle.font || style.font;
  8398. var newLine = false;
  8399. var strLines;
  8400. var linesWidths;
  8401. if (wrapInfo) {
  8402. var tokenPadding = tokenStyle.padding;
  8403. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  8404. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  8405. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  8406. if (lines.length > 0) {
  8407. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  8408. strLines = str.split('\n');
  8409. newLine = true;
  8410. }
  8411. }
  8412. wrapInfo.accumWidth = outerWidth_1;
  8413. }
  8414. else {
  8415. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  8416. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  8417. linesWidths = res.linesWidths;
  8418. strLines = res.lines;
  8419. }
  8420. }
  8421. else {
  8422. strLines = str.split('\n');
  8423. }
  8424. for (var i = 0; i < strLines.length; i++) {
  8425. var text = strLines[i];
  8426. var token = new RichTextToken();
  8427. token.styleName = styleName;
  8428. token.text = text;
  8429. token.isLineHolder = !text && !isEmptyStr;
  8430. if (typeof tokenStyle.width === 'number') {
  8431. token.width = tokenStyle.width;
  8432. }
  8433. else {
  8434. token.width = linesWidths
  8435. ? linesWidths[i]
  8436. : getWidth(text, font);
  8437. }
  8438. if (!i && !newLine) {
  8439. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  8440. var tokensLen = tokens.length;
  8441. (tokensLen === 1 && tokens[0].isLineHolder)
  8442. ? (tokens[0] = token)
  8443. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  8444. }
  8445. else {
  8446. lines.push(new RichTextLine([token]));
  8447. }
  8448. }
  8449. }
  8450. function isLatin(ch) {
  8451. var code = ch.charCodeAt(0);
  8452. return code >= 0x21 && code <= 0xFF;
  8453. }
  8454. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  8455. obj[ch] = true;
  8456. return obj;
  8457. }, {});
  8458. function isWordBreakChar(ch) {
  8459. if (isLatin(ch)) {
  8460. if (breakCharMap[ch]) {
  8461. return true;
  8462. }
  8463. return false;
  8464. }
  8465. return true;
  8466. }
  8467. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  8468. var lines = [];
  8469. var linesWidths = [];
  8470. var line = '';
  8471. var currentWord = '';
  8472. var currentWordWidth = 0;
  8473. var accumWidth = 0;
  8474. for (var i = 0; i < text.length; i++) {
  8475. var ch = text.charAt(i);
  8476. if (ch === '\n') {
  8477. if (currentWord) {
  8478. line += currentWord;
  8479. accumWidth += currentWordWidth;
  8480. }
  8481. lines.push(line);
  8482. linesWidths.push(accumWidth);
  8483. line = '';
  8484. currentWord = '';
  8485. currentWordWidth = 0;
  8486. accumWidth = 0;
  8487. continue;
  8488. }
  8489. var chWidth = getWidth(ch, font);
  8490. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  8491. if (!lines.length
  8492. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  8493. : accumWidth + chWidth > lineWidth) {
  8494. if (!accumWidth) {
  8495. if (inWord) {
  8496. lines.push(currentWord);
  8497. linesWidths.push(currentWordWidth);
  8498. currentWord = ch;
  8499. currentWordWidth = chWidth;
  8500. }
  8501. else {
  8502. lines.push(ch);
  8503. linesWidths.push(chWidth);
  8504. }
  8505. }
  8506. else if (line || currentWord) {
  8507. if (inWord) {
  8508. if (!line) {
  8509. line = currentWord;
  8510. currentWord = '';
  8511. currentWordWidth = 0;
  8512. accumWidth = currentWordWidth;
  8513. }
  8514. lines.push(line);
  8515. linesWidths.push(accumWidth - currentWordWidth);
  8516. currentWord += ch;
  8517. currentWordWidth += chWidth;
  8518. line = '';
  8519. accumWidth = currentWordWidth;
  8520. }
  8521. else {
  8522. if (currentWord) {
  8523. line += currentWord;
  8524. accumWidth += currentWordWidth;
  8525. currentWord = '';
  8526. currentWordWidth = 0;
  8527. }
  8528. lines.push(line);
  8529. linesWidths.push(accumWidth);
  8530. line = ch;
  8531. accumWidth = chWidth;
  8532. }
  8533. }
  8534. continue;
  8535. }
  8536. accumWidth += chWidth;
  8537. if (inWord) {
  8538. currentWord += ch;
  8539. currentWordWidth += chWidth;
  8540. }
  8541. else {
  8542. if (currentWord) {
  8543. line += currentWord;
  8544. currentWord = '';
  8545. currentWordWidth = 0;
  8546. }
  8547. line += ch;
  8548. }
  8549. }
  8550. if (!lines.length && !line) {
  8551. line = text;
  8552. currentWord = '';
  8553. currentWordWidth = 0;
  8554. }
  8555. if (currentWord) {
  8556. line += currentWord;
  8557. }
  8558. if (line) {
  8559. lines.push(line);
  8560. linesWidths.push(accumWidth);
  8561. }
  8562. if (lines.length === 1) {
  8563. accumWidth += lastAccumWidth;
  8564. }
  8565. return {
  8566. accumWidth: accumWidth,
  8567. lines: lines,
  8568. linesWidths: linesWidths
  8569. };
  8570. }
  8571. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  8572. var DEFAULT_COMMON_STYLE = {
  8573. shadowBlur: 0,
  8574. shadowOffsetX: 0,
  8575. shadowOffsetY: 0,
  8576. shadowColor: '#000',
  8577. opacity: 1,
  8578. blend: 'source-over'
  8579. };
  8580. var DEFAULT_COMMON_ANIMATION_PROPS = {
  8581. style: {
  8582. shadowBlur: true,
  8583. shadowOffsetX: true,
  8584. shadowOffsetY: true,
  8585. shadowColor: true,
  8586. opacity: true
  8587. }
  8588. };
  8589. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  8590. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  8591. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  8592. var Displayable = (function (_super) {
  8593. __extends(Displayable, _super);
  8594. function Displayable(props) {
  8595. return _super.call(this, props) || this;
  8596. }
  8597. Displayable.prototype._init = function (props) {
  8598. var keysArr = keys(props);
  8599. for (var i = 0; i < keysArr.length; i++) {
  8600. var key = keysArr[i];
  8601. if (key === 'style') {
  8602. this.useStyle(props[key]);
  8603. }
  8604. else {
  8605. _super.prototype.attrKV.call(this, key, props[key]);
  8606. }
  8607. }
  8608. if (!this.style) {
  8609. this.useStyle({});
  8610. }
  8611. };
  8612. Displayable.prototype.beforeBrush = function () { };
  8613. Displayable.prototype.afterBrush = function () { };
  8614. Displayable.prototype.innerBeforeBrush = function () { };
  8615. Displayable.prototype.innerAfterBrush = function () { };
  8616. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  8617. var m = this.transform;
  8618. if (this.ignore
  8619. || this.invisible
  8620. || this.style.opacity === 0
  8621. || (this.culling
  8622. && isDisplayableCulled(this, viewWidth, viewHeight))
  8623. || (m && !m[0] && !m[3])) {
  8624. return false;
  8625. }
  8626. if (considerClipPath && this.__clipPaths) {
  8627. for (var i = 0; i < this.__clipPaths.length; ++i) {
  8628. if (this.__clipPaths[i].isZeroArea()) {
  8629. return false;
  8630. }
  8631. }
  8632. }
  8633. if (considerAncestors && this.parent) {
  8634. var parent_1 = this.parent;
  8635. while (parent_1) {
  8636. if (parent_1.ignore) {
  8637. return false;
  8638. }
  8639. parent_1 = parent_1.parent;
  8640. }
  8641. }
  8642. return true;
  8643. };
  8644. Displayable.prototype.contain = function (x, y) {
  8645. return this.rectContain(x, y);
  8646. };
  8647. Displayable.prototype.traverse = function (cb, context) {
  8648. cb.call(context, this);
  8649. };
  8650. Displayable.prototype.rectContain = function (x, y) {
  8651. var coord = this.transformCoordToLocal(x, y);
  8652. var rect = this.getBoundingRect();
  8653. return rect.contain(coord[0], coord[1]);
  8654. };
  8655. Displayable.prototype.getPaintRect = function () {
  8656. var rect = this._paintRect;
  8657. if (!this._paintRect || this.__dirty) {
  8658. var transform = this.transform;
  8659. var elRect = this.getBoundingRect();
  8660. var style = this.style;
  8661. var shadowSize = style.shadowBlur || 0;
  8662. var shadowOffsetX = style.shadowOffsetX || 0;
  8663. var shadowOffsetY = style.shadowOffsetY || 0;
  8664. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  8665. if (transform) {
  8666. BoundingRect.applyTransform(rect, elRect, transform);
  8667. }
  8668. else {
  8669. rect.copy(elRect);
  8670. }
  8671. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  8672. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  8673. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  8674. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  8675. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  8676. }
  8677. var tolerance = this.dirtyRectTolerance;
  8678. if (!rect.isZero()) {
  8679. rect.x = Math.floor(rect.x - tolerance);
  8680. rect.y = Math.floor(rect.y - tolerance);
  8681. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  8682. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  8683. }
  8684. }
  8685. return rect;
  8686. };
  8687. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  8688. if (paintRect) {
  8689. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  8690. this._prevPaintRect.copy(paintRect);
  8691. }
  8692. else {
  8693. this._prevPaintRect = null;
  8694. }
  8695. };
  8696. Displayable.prototype.getPrevPaintRect = function () {
  8697. return this._prevPaintRect;
  8698. };
  8699. Displayable.prototype.animateStyle = function (loop) {
  8700. return this.animate('style', loop);
  8701. };
  8702. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  8703. if (targetKey === 'style') {
  8704. this.dirtyStyle();
  8705. }
  8706. else {
  8707. this.markRedraw();
  8708. }
  8709. };
  8710. Displayable.prototype.attrKV = function (key, value) {
  8711. if (key !== 'style') {
  8712. _super.prototype.attrKV.call(this, key, value);
  8713. }
  8714. else {
  8715. if (!this.style) {
  8716. this.useStyle(value);
  8717. }
  8718. else {
  8719. this.setStyle(value);
  8720. }
  8721. }
  8722. };
  8723. Displayable.prototype.setStyle = function (keyOrObj, value) {
  8724. if (typeof keyOrObj === 'string') {
  8725. this.style[keyOrObj] = value;
  8726. }
  8727. else {
  8728. extend(this.style, keyOrObj);
  8729. }
  8730. this.dirtyStyle();
  8731. return this;
  8732. };
  8733. Displayable.prototype.dirtyStyle = function (notRedraw) {
  8734. if (!notRedraw) {
  8735. this.markRedraw();
  8736. }
  8737. this.__dirty |= STYLE_CHANGED_BIT;
  8738. if (this._rect) {
  8739. this._rect = null;
  8740. }
  8741. };
  8742. Displayable.prototype.dirty = function () {
  8743. this.dirtyStyle();
  8744. };
  8745. Displayable.prototype.styleChanged = function () {
  8746. return !!(this.__dirty & STYLE_CHANGED_BIT);
  8747. };
  8748. Displayable.prototype.styleUpdated = function () {
  8749. this.__dirty &= ~STYLE_CHANGED_BIT;
  8750. };
  8751. Displayable.prototype.createStyle = function (obj) {
  8752. return createObject(DEFAULT_COMMON_STYLE, obj);
  8753. };
  8754. Displayable.prototype.useStyle = function (obj) {
  8755. if (!obj[STYLE_MAGIC_KEY]) {
  8756. obj = this.createStyle(obj);
  8757. }
  8758. if (this.__inHover) {
  8759. this.__hoverStyle = obj;
  8760. }
  8761. else {
  8762. this.style = obj;
  8763. }
  8764. this.dirtyStyle();
  8765. };
  8766. Displayable.prototype.isStyleObject = function (obj) {
  8767. return obj[STYLE_MAGIC_KEY];
  8768. };
  8769. Displayable.prototype._innerSaveToNormal = function (toState) {
  8770. _super.prototype._innerSaveToNormal.call(this, toState);
  8771. var normalState = this._normalState;
  8772. if (toState.style && !normalState.style) {
  8773. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  8774. }
  8775. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  8776. };
  8777. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  8778. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  8779. var needsRestoreToNormal = !(state && keepCurrentStates);
  8780. var targetStyle;
  8781. if (state && state.style) {
  8782. if (transition) {
  8783. if (keepCurrentStates) {
  8784. targetStyle = state.style;
  8785. }
  8786. else {
  8787. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  8788. this._mergeStyle(targetStyle, state.style);
  8789. }
  8790. }
  8791. else {
  8792. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  8793. this._mergeStyle(targetStyle, state.style);
  8794. }
  8795. }
  8796. else if (needsRestoreToNormal) {
  8797. targetStyle = normalState.style;
  8798. }
  8799. if (targetStyle) {
  8800. if (transition) {
  8801. var sourceStyle = this.style;
  8802. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  8803. if (needsRestoreToNormal) {
  8804. var changedKeys = keys(sourceStyle);
  8805. for (var i = 0; i < changedKeys.length; i++) {
  8806. var key = changedKeys[i];
  8807. if (key in targetStyle) {
  8808. targetStyle[key] = targetStyle[key];
  8809. this.style[key] = sourceStyle[key];
  8810. }
  8811. }
  8812. }
  8813. var targetKeys = keys(targetStyle);
  8814. for (var i = 0; i < targetKeys.length; i++) {
  8815. var key = targetKeys[i];
  8816. this.style[key] = this.style[key];
  8817. }
  8818. this._transitionState(stateName, {
  8819. style: targetStyle
  8820. }, animationCfg, this.getAnimationStyleProps());
  8821. }
  8822. else {
  8823. this.useStyle(targetStyle);
  8824. }
  8825. }
  8826. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  8827. for (var i = 0; i < statesKeys.length; i++) {
  8828. var key = statesKeys[i];
  8829. if (state && state[key] != null) {
  8830. this[key] = state[key];
  8831. }
  8832. else if (needsRestoreToNormal) {
  8833. if (normalState[key] != null) {
  8834. this[key] = normalState[key];
  8835. }
  8836. }
  8837. }
  8838. };
  8839. Displayable.prototype._mergeStates = function (states) {
  8840. var mergedState = _super.prototype._mergeStates.call(this, states);
  8841. var mergedStyle;
  8842. for (var i = 0; i < states.length; i++) {
  8843. var state = states[i];
  8844. if (state.style) {
  8845. mergedStyle = mergedStyle || {};
  8846. this._mergeStyle(mergedStyle, state.style);
  8847. }
  8848. }
  8849. if (mergedStyle) {
  8850. mergedState.style = mergedStyle;
  8851. }
  8852. return mergedState;
  8853. };
  8854. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  8855. extend(targetStyle, sourceStyle);
  8856. return targetStyle;
  8857. };
  8858. Displayable.prototype.getAnimationStyleProps = function () {
  8859. return DEFAULT_COMMON_ANIMATION_PROPS;
  8860. };
  8861. Displayable.initDefaultProps = (function () {
  8862. var dispProto = Displayable.prototype;
  8863. dispProto.type = 'displayable';
  8864. dispProto.invisible = false;
  8865. dispProto.z = 0;
  8866. dispProto.z2 = 0;
  8867. dispProto.zlevel = 0;
  8868. dispProto.culling = false;
  8869. dispProto.cursor = 'pointer';
  8870. dispProto.rectHover = false;
  8871. dispProto.incremental = false;
  8872. dispProto._rect = null;
  8873. dispProto.dirtyRectTolerance = 0;
  8874. dispProto.__dirty = REDARAW_BIT | STYLE_CHANGED_BIT;
  8875. })();
  8876. return Displayable;
  8877. }(Element));
  8878. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8879. var viewRect = new BoundingRect(0, 0, 0, 0);
  8880. function isDisplayableCulled(el, width, height) {
  8881. tmpRect.copy(el.getBoundingRect());
  8882. if (el.transform) {
  8883. tmpRect.applyTransform(el.transform);
  8884. }
  8885. viewRect.width = width;
  8886. viewRect.height = height;
  8887. return !tmpRect.intersect(viewRect);
  8888. }
  8889. var mathPow = Math.pow;
  8890. var mathSqrt = Math.sqrt;
  8891. var EPSILON$1 = 1e-8;
  8892. var EPSILON_NUMERIC = 1e-4;
  8893. var THREE_SQRT = mathSqrt(3);
  8894. var ONE_THIRD = 1 / 3;
  8895. var _v0 = create();
  8896. var _v1 = create();
  8897. var _v2 = create();
  8898. function isAroundZero(val) {
  8899. return val > -EPSILON$1 && val < EPSILON$1;
  8900. }
  8901. function isNotAroundZero$1(val) {
  8902. return val > EPSILON$1 || val < -EPSILON$1;
  8903. }
  8904. function cubicAt(p0, p1, p2, p3, t) {
  8905. var onet = 1 - t;
  8906. return onet * onet * (onet * p0 + 3 * t * p1)
  8907. + t * t * (t * p3 + 3 * onet * p2);
  8908. }
  8909. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  8910. var onet = 1 - t;
  8911. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  8912. + (p3 - p2) * t * t);
  8913. }
  8914. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  8915. var a = p3 + 3 * (p1 - p2) - p0;
  8916. var b = 3 * (p2 - p1 * 2 + p0);
  8917. var c = 3 * (p1 - p0);
  8918. var d = p0 - val;
  8919. var A = b * b - 3 * a * c;
  8920. var B = b * c - 9 * a * d;
  8921. var C = c * c - 3 * b * d;
  8922. var n = 0;
  8923. if (isAroundZero(A) && isAroundZero(B)) {
  8924. if (isAroundZero(b)) {
  8925. roots[0] = 0;
  8926. }
  8927. else {
  8928. var t1 = -c / b;
  8929. if (t1 >= 0 && t1 <= 1) {
  8930. roots[n++] = t1;
  8931. }
  8932. }
  8933. }
  8934. else {
  8935. var disc = B * B - 4 * A * C;
  8936. if (isAroundZero(disc)) {
  8937. var K = B / A;
  8938. var t1 = -b / a + K;
  8939. var t2 = -K / 2;
  8940. if (t1 >= 0 && t1 <= 1) {
  8941. roots[n++] = t1;
  8942. }
  8943. if (t2 >= 0 && t2 <= 1) {
  8944. roots[n++] = t2;
  8945. }
  8946. }
  8947. else if (disc > 0) {
  8948. var discSqrt = mathSqrt(disc);
  8949. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  8950. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  8951. if (Y1 < 0) {
  8952. Y1 = -mathPow(-Y1, ONE_THIRD);
  8953. }
  8954. else {
  8955. Y1 = mathPow(Y1, ONE_THIRD);
  8956. }
  8957. if (Y2 < 0) {
  8958. Y2 = -mathPow(-Y2, ONE_THIRD);
  8959. }
  8960. else {
  8961. Y2 = mathPow(Y2, ONE_THIRD);
  8962. }
  8963. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  8964. if (t1 >= 0 && t1 <= 1) {
  8965. roots[n++] = t1;
  8966. }
  8967. }
  8968. else {
  8969. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  8970. var theta = Math.acos(T) / 3;
  8971. var ASqrt = mathSqrt(A);
  8972. var tmp = Math.cos(theta);
  8973. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  8974. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  8975. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  8976. if (t1 >= 0 && t1 <= 1) {
  8977. roots[n++] = t1;
  8978. }
  8979. if (t2 >= 0 && t2 <= 1) {
  8980. roots[n++] = t2;
  8981. }
  8982. if (t3 >= 0 && t3 <= 1) {
  8983. roots[n++] = t3;
  8984. }
  8985. }
  8986. }
  8987. return n;
  8988. }
  8989. function cubicExtrema(p0, p1, p2, p3, extrema) {
  8990. var b = 6 * p2 - 12 * p1 + 6 * p0;
  8991. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  8992. var c = 3 * p1 - 3 * p0;
  8993. var n = 0;
  8994. if (isAroundZero(a)) {
  8995. if (isNotAroundZero$1(b)) {
  8996. var t1 = -c / b;
  8997. if (t1 >= 0 && t1 <= 1) {
  8998. extrema[n++] = t1;
  8999. }
  9000. }
  9001. }
  9002. else {
  9003. var disc = b * b - 4 * a * c;
  9004. if (isAroundZero(disc)) {
  9005. extrema[0] = -b / (2 * a);
  9006. }
  9007. else if (disc > 0) {
  9008. var discSqrt = mathSqrt(disc);
  9009. var t1 = (-b + discSqrt) / (2 * a);
  9010. var t2 = (-b - discSqrt) / (2 * a);
  9011. if (t1 >= 0 && t1 <= 1) {
  9012. extrema[n++] = t1;
  9013. }
  9014. if (t2 >= 0 && t2 <= 1) {
  9015. extrema[n++] = t2;
  9016. }
  9017. }
  9018. }
  9019. return n;
  9020. }
  9021. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  9022. var p01 = (p1 - p0) * t + p0;
  9023. var p12 = (p2 - p1) * t + p1;
  9024. var p23 = (p3 - p2) * t + p2;
  9025. var p012 = (p12 - p01) * t + p01;
  9026. var p123 = (p23 - p12) * t + p12;
  9027. var p0123 = (p123 - p012) * t + p012;
  9028. out[0] = p0;
  9029. out[1] = p01;
  9030. out[2] = p012;
  9031. out[3] = p0123;
  9032. out[4] = p0123;
  9033. out[5] = p123;
  9034. out[6] = p23;
  9035. out[7] = p3;
  9036. }
  9037. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  9038. var t;
  9039. var interval = 0.005;
  9040. var d = Infinity;
  9041. var prev;
  9042. var next;
  9043. var d1;
  9044. var d2;
  9045. _v0[0] = x;
  9046. _v0[1] = y;
  9047. for (var _t = 0; _t < 1; _t += 0.05) {
  9048. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  9049. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  9050. d1 = distSquare(_v0, _v1);
  9051. if (d1 < d) {
  9052. t = _t;
  9053. d = d1;
  9054. }
  9055. }
  9056. d = Infinity;
  9057. for (var i = 0; i < 32; i++) {
  9058. if (interval < EPSILON_NUMERIC) {
  9059. break;
  9060. }
  9061. prev = t - interval;
  9062. next = t + interval;
  9063. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  9064. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  9065. d1 = distSquare(_v1, _v0);
  9066. if (prev >= 0 && d1 < d) {
  9067. t = prev;
  9068. d = d1;
  9069. }
  9070. else {
  9071. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  9072. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  9073. d2 = distSquare(_v2, _v0);
  9074. if (next <= 1 && d2 < d) {
  9075. t = next;
  9076. d = d2;
  9077. }
  9078. else {
  9079. interval *= 0.5;
  9080. }
  9081. }
  9082. }
  9083. if (out) {
  9084. out[0] = cubicAt(x0, x1, x2, x3, t);
  9085. out[1] = cubicAt(y0, y1, y2, y3, t);
  9086. }
  9087. return mathSqrt(d);
  9088. }
  9089. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  9090. var px = x0;
  9091. var py = y0;
  9092. var d = 0;
  9093. var step = 1 / iteration;
  9094. for (var i = 1; i <= iteration; i++) {
  9095. var t = i * step;
  9096. var x = cubicAt(x0, x1, x2, x3, t);
  9097. var y = cubicAt(y0, y1, y2, y3, t);
  9098. var dx = x - px;
  9099. var dy = y - py;
  9100. d += Math.sqrt(dx * dx + dy * dy);
  9101. px = x;
  9102. py = y;
  9103. }
  9104. return d;
  9105. }
  9106. function quadraticAt(p0, p1, p2, t) {
  9107. var onet = 1 - t;
  9108. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  9109. }
  9110. function quadraticDerivativeAt(p0, p1, p2, t) {
  9111. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  9112. }
  9113. function quadraticRootAt(p0, p1, p2, val, roots) {
  9114. var a = p0 - 2 * p1 + p2;
  9115. var b = 2 * (p1 - p0);
  9116. var c = p0 - val;
  9117. var n = 0;
  9118. if (isAroundZero(a)) {
  9119. if (isNotAroundZero$1(b)) {
  9120. var t1 = -c / b;
  9121. if (t1 >= 0 && t1 <= 1) {
  9122. roots[n++] = t1;
  9123. }
  9124. }
  9125. }
  9126. else {
  9127. var disc = b * b - 4 * a * c;
  9128. if (isAroundZero(disc)) {
  9129. var t1 = -b / (2 * a);
  9130. if (t1 >= 0 && t1 <= 1) {
  9131. roots[n++] = t1;
  9132. }
  9133. }
  9134. else if (disc > 0) {
  9135. var discSqrt = mathSqrt(disc);
  9136. var t1 = (-b + discSqrt) / (2 * a);
  9137. var t2 = (-b - discSqrt) / (2 * a);
  9138. if (t1 >= 0 && t1 <= 1) {
  9139. roots[n++] = t1;
  9140. }
  9141. if (t2 >= 0 && t2 <= 1) {
  9142. roots[n++] = t2;
  9143. }
  9144. }
  9145. }
  9146. return n;
  9147. }
  9148. function quadraticExtremum(p0, p1, p2) {
  9149. var divider = p0 + p2 - 2 * p1;
  9150. if (divider === 0) {
  9151. return 0.5;
  9152. }
  9153. else {
  9154. return (p0 - p1) / divider;
  9155. }
  9156. }
  9157. function quadraticSubdivide(p0, p1, p2, t, out) {
  9158. var p01 = (p1 - p0) * t + p0;
  9159. var p12 = (p2 - p1) * t + p1;
  9160. var p012 = (p12 - p01) * t + p01;
  9161. out[0] = p0;
  9162. out[1] = p01;
  9163. out[2] = p012;
  9164. out[3] = p012;
  9165. out[4] = p12;
  9166. out[5] = p2;
  9167. }
  9168. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  9169. var t;
  9170. var interval = 0.005;
  9171. var d = Infinity;
  9172. _v0[0] = x;
  9173. _v0[1] = y;
  9174. for (var _t = 0; _t < 1; _t += 0.05) {
  9175. _v1[0] = quadraticAt(x0, x1, x2, _t);
  9176. _v1[1] = quadraticAt(y0, y1, y2, _t);
  9177. var d1 = distSquare(_v0, _v1);
  9178. if (d1 < d) {
  9179. t = _t;
  9180. d = d1;
  9181. }
  9182. }
  9183. d = Infinity;
  9184. for (var i = 0; i < 32; i++) {
  9185. if (interval < EPSILON_NUMERIC) {
  9186. break;
  9187. }
  9188. var prev = t - interval;
  9189. var next = t + interval;
  9190. _v1[0] = quadraticAt(x0, x1, x2, prev);
  9191. _v1[1] = quadraticAt(y0, y1, y2, prev);
  9192. var d1 = distSquare(_v1, _v0);
  9193. if (prev >= 0 && d1 < d) {
  9194. t = prev;
  9195. d = d1;
  9196. }
  9197. else {
  9198. _v2[0] = quadraticAt(x0, x1, x2, next);
  9199. _v2[1] = quadraticAt(y0, y1, y2, next);
  9200. var d2 = distSquare(_v2, _v0);
  9201. if (next <= 1 && d2 < d) {
  9202. t = next;
  9203. d = d2;
  9204. }
  9205. else {
  9206. interval *= 0.5;
  9207. }
  9208. }
  9209. }
  9210. if (out) {
  9211. out[0] = quadraticAt(x0, x1, x2, t);
  9212. out[1] = quadraticAt(y0, y1, y2, t);
  9213. }
  9214. return mathSqrt(d);
  9215. }
  9216. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  9217. var px = x0;
  9218. var py = y0;
  9219. var d = 0;
  9220. var step = 1 / iteration;
  9221. for (var i = 1; i <= iteration; i++) {
  9222. var t = i * step;
  9223. var x = quadraticAt(x0, x1, x2, t);
  9224. var y = quadraticAt(y0, y1, y2, t);
  9225. var dx = x - px;
  9226. var dy = y - py;
  9227. d += Math.sqrt(dx * dx + dy * dy);
  9228. px = x;
  9229. py = y;
  9230. }
  9231. return d;
  9232. }
  9233. var mathMin$1 = Math.min;
  9234. var mathMax$1 = Math.max;
  9235. var mathSin = Math.sin;
  9236. var mathCos = Math.cos;
  9237. var PI2 = Math.PI * 2;
  9238. var start = create();
  9239. var end = create();
  9240. var extremity = create();
  9241. function fromPoints(points, min, max) {
  9242. if (points.length === 0) {
  9243. return;
  9244. }
  9245. var p = points[0];
  9246. var left = p[0];
  9247. var right = p[0];
  9248. var top = p[1];
  9249. var bottom = p[1];
  9250. for (var i = 1; i < points.length; i++) {
  9251. p = points[i];
  9252. left = mathMin$1(left, p[0]);
  9253. right = mathMax$1(right, p[0]);
  9254. top = mathMin$1(top, p[1]);
  9255. bottom = mathMax$1(bottom, p[1]);
  9256. }
  9257. min[0] = left;
  9258. min[1] = top;
  9259. max[0] = right;
  9260. max[1] = bottom;
  9261. }
  9262. function fromLine(x0, y0, x1, y1, min, max) {
  9263. min[0] = mathMin$1(x0, x1);
  9264. min[1] = mathMin$1(y0, y1);
  9265. max[0] = mathMax$1(x0, x1);
  9266. max[1] = mathMax$1(y0, y1);
  9267. }
  9268. var xDim = [];
  9269. var yDim = [];
  9270. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9271. var cubicExtrema$1 = cubicExtrema;
  9272. var cubicAt$1 = cubicAt;
  9273. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9274. min[0] = Infinity;
  9275. min[1] = Infinity;
  9276. max[0] = -Infinity;
  9277. max[1] = -Infinity;
  9278. for (var i = 0; i < n; i++) {
  9279. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9280. min[0] = mathMin$1(x, min[0]);
  9281. max[0] = mathMax$1(x, max[0]);
  9282. }
  9283. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9284. for (var i = 0; i < n; i++) {
  9285. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9286. min[1] = mathMin$1(y, min[1]);
  9287. max[1] = mathMax$1(y, max[1]);
  9288. }
  9289. min[0] = mathMin$1(x0, min[0]);
  9290. max[0] = mathMax$1(x0, max[0]);
  9291. min[0] = mathMin$1(x3, min[0]);
  9292. max[0] = mathMax$1(x3, max[0]);
  9293. min[1] = mathMin$1(y0, min[1]);
  9294. max[1] = mathMax$1(y0, max[1]);
  9295. min[1] = mathMin$1(y3, min[1]);
  9296. max[1] = mathMax$1(y3, max[1]);
  9297. }
  9298. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9299. var quadraticExtremum$1 = quadraticExtremum;
  9300. var quadraticAt$1 = quadraticAt;
  9301. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9302. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9303. var x = quadraticAt$1(x0, x1, x2, tx);
  9304. var y = quadraticAt$1(y0, y1, y2, ty);
  9305. min[0] = mathMin$1(x0, x2, x);
  9306. min[1] = mathMin$1(y0, y2, y);
  9307. max[0] = mathMax$1(x0, x2, x);
  9308. max[1] = mathMax$1(y0, y2, y);
  9309. }
  9310. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9311. var vec2Min = min;
  9312. var vec2Max = max;
  9313. var diff = Math.abs(startAngle - endAngle);
  9314. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9315. min$1[0] = x - rx;
  9316. min$1[1] = y - ry;
  9317. max$1[0] = x + rx;
  9318. max$1[1] = y + ry;
  9319. return;
  9320. }
  9321. start[0] = mathCos(startAngle) * rx + x;
  9322. start[1] = mathSin(startAngle) * ry + y;
  9323. end[0] = mathCos(endAngle) * rx + x;
  9324. end[1] = mathSin(endAngle) * ry + y;
  9325. vec2Min(min$1, start, end);
  9326. vec2Max(max$1, start, end);
  9327. startAngle = startAngle % (PI2);
  9328. if (startAngle < 0) {
  9329. startAngle = startAngle + PI2;
  9330. }
  9331. endAngle = endAngle % (PI2);
  9332. if (endAngle < 0) {
  9333. endAngle = endAngle + PI2;
  9334. }
  9335. if (startAngle > endAngle && !anticlockwise) {
  9336. endAngle += PI2;
  9337. }
  9338. else if (startAngle < endAngle && anticlockwise) {
  9339. startAngle += PI2;
  9340. }
  9341. if (anticlockwise) {
  9342. var tmp = endAngle;
  9343. endAngle = startAngle;
  9344. startAngle = tmp;
  9345. }
  9346. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9347. if (angle > startAngle) {
  9348. extremity[0] = mathCos(angle) * rx + x;
  9349. extremity[1] = mathSin(angle) * ry + y;
  9350. vec2Min(min$1, extremity, min$1);
  9351. vec2Max(max$1, extremity, max$1);
  9352. }
  9353. }
  9354. }
  9355. var CMD = {
  9356. M: 1,
  9357. L: 2,
  9358. C: 3,
  9359. Q: 4,
  9360. A: 5,
  9361. Z: 6,
  9362. R: 7
  9363. };
  9364. var tmpOutX = [];
  9365. var tmpOutY = [];
  9366. var min$1 = [];
  9367. var max$1 = [];
  9368. var min2 = [];
  9369. var max2 = [];
  9370. var mathMin$2 = Math.min;
  9371. var mathMax$2 = Math.max;
  9372. var mathCos$1 = Math.cos;
  9373. var mathSin$1 = Math.sin;
  9374. var mathSqrt$1 = Math.sqrt;
  9375. var mathAbs = Math.abs;
  9376. var PI = Math.PI;
  9377. var PI2$1 = PI * 2;
  9378. var hasTypedArray = typeof Float32Array !== 'undefined';
  9379. var tmpAngles = [];
  9380. function modPI2(radian) {
  9381. var n = Math.round(radian / PI * 1e8) / 1e8;
  9382. return (n % 2) * PI;
  9383. }
  9384. function normalizeArcAngles(angles, anticlockwise) {
  9385. var newStartAngle = modPI2(angles[0]);
  9386. if (newStartAngle < 0) {
  9387. newStartAngle += PI2$1;
  9388. }
  9389. var delta = newStartAngle - angles[0];
  9390. var newEndAngle = angles[1];
  9391. newEndAngle += delta;
  9392. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9393. newEndAngle = newStartAngle + PI2$1;
  9394. }
  9395. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9396. newEndAngle = newStartAngle - PI2$1;
  9397. }
  9398. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9399. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9400. }
  9401. else if (anticlockwise && newStartAngle < newEndAngle) {
  9402. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9403. }
  9404. angles[0] = newStartAngle;
  9405. angles[1] = newEndAngle;
  9406. }
  9407. var PathProxy = (function () {
  9408. function PathProxy(notSaveData) {
  9409. this.dpr = 1;
  9410. this._xi = 0;
  9411. this._yi = 0;
  9412. this._x0 = 0;
  9413. this._y0 = 0;
  9414. this._len = 0;
  9415. if (notSaveData) {
  9416. this._saveData = false;
  9417. }
  9418. if (this._saveData) {
  9419. this.data = [];
  9420. }
  9421. }
  9422. PathProxy.prototype.increaseVersion = function () {
  9423. this._version++;
  9424. };
  9425. PathProxy.prototype.getVersion = function () {
  9426. return this._version;
  9427. };
  9428. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9429. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9430. if (segmentIgnoreThreshold > 0) {
  9431. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9432. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9433. }
  9434. };
  9435. PathProxy.prototype.setDPR = function (dpr) {
  9436. this.dpr = dpr;
  9437. };
  9438. PathProxy.prototype.setContext = function (ctx) {
  9439. this._ctx = ctx;
  9440. };
  9441. PathProxy.prototype.getContext = function () {
  9442. return this._ctx;
  9443. };
  9444. PathProxy.prototype.beginPath = function () {
  9445. this._ctx && this._ctx.beginPath();
  9446. this.reset();
  9447. return this;
  9448. };
  9449. PathProxy.prototype.reset = function () {
  9450. if (this._saveData) {
  9451. this._len = 0;
  9452. }
  9453. if (this._lineDash) {
  9454. this._lineDash = null;
  9455. this._dashOffset = 0;
  9456. }
  9457. if (this._pathSegLen) {
  9458. this._pathSegLen = null;
  9459. this._pathLen = 0;
  9460. }
  9461. this._version++;
  9462. };
  9463. PathProxy.prototype.moveTo = function (x, y) {
  9464. this._drawPendingPt();
  9465. this.addData(CMD.M, x, y);
  9466. this._ctx && this._ctx.moveTo(x, y);
  9467. this._x0 = x;
  9468. this._y0 = y;
  9469. this._xi = x;
  9470. this._yi = y;
  9471. return this;
  9472. };
  9473. PathProxy.prototype.lineTo = function (x, y) {
  9474. var dx = mathAbs(x - this._xi);
  9475. var dy = mathAbs(y - this._yi);
  9476. var exceedUnit = dx > this._ux || dy > this._uy;
  9477. this.addData(CMD.L, x, y);
  9478. if (this._ctx && exceedUnit) {
  9479. this._needsDash ? this._dashedLineTo(x, y)
  9480. : this._ctx.lineTo(x, y);
  9481. }
  9482. if (exceedUnit) {
  9483. this._xi = x;
  9484. this._yi = y;
  9485. this._pendingPtDist = 0;
  9486. }
  9487. else {
  9488. var d2 = dx * dx + dy * dy;
  9489. if (d2 > this._pendingPtDist) {
  9490. this._pendingPtX = x;
  9491. this._pendingPtY = y;
  9492. this._pendingPtDist = d2;
  9493. }
  9494. }
  9495. return this;
  9496. };
  9497. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9498. this._drawPendingPt();
  9499. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9500. if (this._ctx) {
  9501. this._needsDash ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  9502. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9503. }
  9504. this._xi = x3;
  9505. this._yi = y3;
  9506. return this;
  9507. };
  9508. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9509. this._drawPendingPt();
  9510. this.addData(CMD.Q, x1, y1, x2, y2);
  9511. if (this._ctx) {
  9512. this._needsDash ? this._dashedQuadraticTo(x1, y1, x2, y2)
  9513. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9514. }
  9515. this._xi = x2;
  9516. this._yi = y2;
  9517. return this;
  9518. };
  9519. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9520. this._drawPendingPt();
  9521. tmpAngles[0] = startAngle;
  9522. tmpAngles[1] = endAngle;
  9523. normalizeArcAngles(tmpAngles, anticlockwise);
  9524. startAngle = tmpAngles[0];
  9525. endAngle = tmpAngles[1];
  9526. var delta = endAngle - startAngle;
  9527. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9528. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9529. this._xi = mathCos$1(endAngle) * r + cx;
  9530. this._yi = mathSin$1(endAngle) * r + cy;
  9531. return this;
  9532. };
  9533. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9534. this._drawPendingPt();
  9535. if (this._ctx) {
  9536. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9537. }
  9538. return this;
  9539. };
  9540. PathProxy.prototype.rect = function (x, y, w, h) {
  9541. this._drawPendingPt();
  9542. this._ctx && this._ctx.rect(x, y, w, h);
  9543. this.addData(CMD.R, x, y, w, h);
  9544. return this;
  9545. };
  9546. PathProxy.prototype.closePath = function () {
  9547. this._drawPendingPt();
  9548. this.addData(CMD.Z);
  9549. var ctx = this._ctx;
  9550. var x0 = this._x0;
  9551. var y0 = this._y0;
  9552. if (ctx) {
  9553. this._needsDash && this._dashedLineTo(x0, y0);
  9554. ctx.closePath();
  9555. }
  9556. this._xi = x0;
  9557. this._yi = y0;
  9558. return this;
  9559. };
  9560. PathProxy.prototype.fill = function (ctx) {
  9561. ctx && ctx.fill();
  9562. this.toStatic();
  9563. };
  9564. PathProxy.prototype.stroke = function (ctx) {
  9565. ctx && ctx.stroke();
  9566. this.toStatic();
  9567. };
  9568. PathProxy.prototype.setLineDash = function (lineDash) {
  9569. if (lineDash instanceof Array) {
  9570. this._lineDash = lineDash;
  9571. this._dashIdx = 0;
  9572. var lineDashSum = 0;
  9573. for (var i = 0; i < lineDash.length; i++) {
  9574. lineDashSum += lineDash[i];
  9575. }
  9576. this._dashSum = lineDashSum;
  9577. this._needsDash = true;
  9578. }
  9579. else {
  9580. this._lineDash = null;
  9581. this._needsDash = false;
  9582. }
  9583. return this;
  9584. };
  9585. PathProxy.prototype.setLineDashOffset = function (offset) {
  9586. this._dashOffset = offset;
  9587. return this;
  9588. };
  9589. PathProxy.prototype.len = function () {
  9590. return this._len;
  9591. };
  9592. PathProxy.prototype.setData = function (data) {
  9593. var len = data.length;
  9594. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9595. this.data = new Float32Array(len);
  9596. }
  9597. for (var i = 0; i < len; i++) {
  9598. this.data[i] = data[i];
  9599. }
  9600. this._len = len;
  9601. };
  9602. PathProxy.prototype.appendPath = function (path) {
  9603. if (!(path instanceof Array)) {
  9604. path = [path];
  9605. }
  9606. var len = path.length;
  9607. var appendSize = 0;
  9608. var offset = this._len;
  9609. for (var i = 0; i < len; i++) {
  9610. appendSize += path[i].len();
  9611. }
  9612. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9613. this.data = new Float32Array(offset + appendSize);
  9614. }
  9615. for (var i = 0; i < len; i++) {
  9616. var appendPathData = path[i].data;
  9617. for (var k = 0; k < appendPathData.length; k++) {
  9618. this.data[offset++] = appendPathData[k];
  9619. }
  9620. }
  9621. this._len = offset;
  9622. };
  9623. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9624. if (!this._saveData) {
  9625. return;
  9626. }
  9627. var data = this.data;
  9628. if (this._len + arguments.length > data.length) {
  9629. this._expandData();
  9630. data = this.data;
  9631. }
  9632. for (var i = 0; i < arguments.length; i++) {
  9633. data[this._len++] = arguments[i];
  9634. }
  9635. };
  9636. PathProxy.prototype._drawPendingPt = function () {
  9637. if (this._pendingPtDist > 0) {
  9638. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  9639. this._pendingPtDist = 0;
  9640. }
  9641. };
  9642. PathProxy.prototype._expandData = function () {
  9643. if (!(this.data instanceof Array)) {
  9644. var newData = [];
  9645. for (var i = 0; i < this._len; i++) {
  9646. newData[i] = this.data[i];
  9647. }
  9648. this.data = newData;
  9649. }
  9650. };
  9651. PathProxy.prototype._dashedLineTo = function (x1, y1) {
  9652. var dashSum = this._dashSum;
  9653. var lineDash = this._lineDash;
  9654. var ctx = this._ctx;
  9655. var offset = this._dashOffset;
  9656. var x0 = this._xi;
  9657. var y0 = this._yi;
  9658. var dx = x1 - x0;
  9659. var dy = y1 - y0;
  9660. var dist = mathSqrt$1(dx * dx + dy * dy);
  9661. var x = x0;
  9662. var y = y0;
  9663. var nDash = lineDash.length;
  9664. var dash;
  9665. var idx;
  9666. dx /= dist;
  9667. dy /= dist;
  9668. if (offset < 0) {
  9669. offset = dashSum + offset;
  9670. }
  9671. offset %= dashSum;
  9672. x -= offset * dx;
  9673. y -= offset * dy;
  9674. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  9675. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  9676. idx = this._dashIdx;
  9677. dash = lineDash[idx];
  9678. x += dx * dash;
  9679. y += dy * dash;
  9680. this._dashIdx = (idx + 1) % nDash;
  9681. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  9682. continue;
  9683. }
  9684. ctx[idx % 2 ? 'moveTo' : 'lineTo'](dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1), dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1));
  9685. }
  9686. dx = x - x1;
  9687. dy = y - y1;
  9688. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  9689. };
  9690. PathProxy.prototype._dashedBezierTo = function (x1, y1, x2, y2, x3, y3) {
  9691. var ctx = this._ctx;
  9692. var dashSum = this._dashSum;
  9693. var offset = this._dashOffset;
  9694. var lineDash = this._lineDash;
  9695. var x0 = this._xi;
  9696. var y0 = this._yi;
  9697. var bezierLen = 0;
  9698. var idx = this._dashIdx;
  9699. var nDash = lineDash.length;
  9700. var t;
  9701. var dx;
  9702. var dy;
  9703. var x;
  9704. var y;
  9705. var tmpLen = 0;
  9706. if (offset < 0) {
  9707. offset = dashSum + offset;
  9708. }
  9709. offset %= dashSum;
  9710. for (t = 0; t < 1; t += 0.1) {
  9711. dx = cubicAt(x0, x1, x2, x3, t + 0.1)
  9712. - cubicAt(x0, x1, x2, x3, t);
  9713. dy = cubicAt(y0, y1, y2, y3, t + 0.1)
  9714. - cubicAt(y0, y1, y2, y3, t);
  9715. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  9716. }
  9717. for (; idx < nDash; idx++) {
  9718. tmpLen += lineDash[idx];
  9719. if (tmpLen > offset) {
  9720. break;
  9721. }
  9722. }
  9723. t = (tmpLen - offset) / bezierLen;
  9724. while (t <= 1) {
  9725. x = cubicAt(x0, x1, x2, x3, t);
  9726. y = cubicAt(y0, y1, y2, y3, t);
  9727. idx % 2 ? ctx.moveTo(x, y)
  9728. : ctx.lineTo(x, y);
  9729. t += lineDash[idx] / bezierLen;
  9730. idx = (idx + 1) % nDash;
  9731. }
  9732. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  9733. dx = x3 - x;
  9734. dy = y3 - y;
  9735. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  9736. };
  9737. PathProxy.prototype._dashedQuadraticTo = function (x1, y1, x2, y2) {
  9738. var x3 = x2;
  9739. var y3 = y2;
  9740. x2 = (x2 + 2 * x1) / 3;
  9741. y2 = (y2 + 2 * y1) / 3;
  9742. x1 = (this._xi + 2 * x1) / 3;
  9743. y1 = (this._yi + 2 * y1) / 3;
  9744. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  9745. };
  9746. PathProxy.prototype.toStatic = function () {
  9747. if (!this._saveData) {
  9748. return;
  9749. }
  9750. this._drawPendingPt();
  9751. var data = this.data;
  9752. if (data instanceof Array) {
  9753. data.length = this._len;
  9754. if (hasTypedArray && this._len > 11) {
  9755. this.data = new Float32Array(data);
  9756. }
  9757. }
  9758. };
  9759. PathProxy.prototype.getBoundingRect = function () {
  9760. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9761. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9762. var data = this.data;
  9763. var xi = 0;
  9764. var yi = 0;
  9765. var x0 = 0;
  9766. var y0 = 0;
  9767. var i;
  9768. for (i = 0; i < this._len;) {
  9769. var cmd = data[i++];
  9770. var isFirst = i === 1;
  9771. if (isFirst) {
  9772. xi = data[i];
  9773. yi = data[i + 1];
  9774. x0 = xi;
  9775. y0 = yi;
  9776. }
  9777. switch (cmd) {
  9778. case CMD.M:
  9779. xi = x0 = data[i++];
  9780. yi = y0 = data[i++];
  9781. min2[0] = x0;
  9782. min2[1] = y0;
  9783. max2[0] = x0;
  9784. max2[1] = y0;
  9785. break;
  9786. case CMD.L:
  9787. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  9788. xi = data[i++];
  9789. yi = data[i++];
  9790. break;
  9791. case CMD.C:
  9792. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9793. xi = data[i++];
  9794. yi = data[i++];
  9795. break;
  9796. case CMD.Q:
  9797. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9798. xi = data[i++];
  9799. yi = data[i++];
  9800. break;
  9801. case CMD.A:
  9802. var cx = data[i++];
  9803. var cy = data[i++];
  9804. var rx = data[i++];
  9805. var ry = data[i++];
  9806. var startAngle = data[i++];
  9807. var endAngle = data[i++] + startAngle;
  9808. i += 1;
  9809. var anticlockwise = !data[i++];
  9810. if (isFirst) {
  9811. x0 = mathCos$1(startAngle) * rx + cx;
  9812. y0 = mathSin$1(startAngle) * ry + cy;
  9813. }
  9814. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  9815. xi = mathCos$1(endAngle) * rx + cx;
  9816. yi = mathSin$1(endAngle) * ry + cy;
  9817. break;
  9818. case CMD.R:
  9819. x0 = xi = data[i++];
  9820. y0 = yi = data[i++];
  9821. var width = data[i++];
  9822. var height = data[i++];
  9823. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  9824. break;
  9825. case CMD.Z:
  9826. xi = x0;
  9827. yi = y0;
  9828. break;
  9829. }
  9830. min(min$1, min$1, min2);
  9831. max(max$1, max$1, max2);
  9832. }
  9833. if (i === 0) {
  9834. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  9835. }
  9836. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  9837. };
  9838. PathProxy.prototype._calculateLength = function () {
  9839. var data = this.data;
  9840. var len = this._len;
  9841. var ux = this._ux;
  9842. var uy = this._uy;
  9843. var xi = 0;
  9844. var yi = 0;
  9845. var x0 = 0;
  9846. var y0 = 0;
  9847. if (!this._pathSegLen) {
  9848. this._pathSegLen = [];
  9849. }
  9850. var pathSegLen = this._pathSegLen;
  9851. var pathTotalLen = 0;
  9852. var segCount = 0;
  9853. for (var i = 0; i < len;) {
  9854. var cmd = data[i++];
  9855. var isFirst = i === 1;
  9856. if (isFirst) {
  9857. xi = data[i];
  9858. yi = data[i + 1];
  9859. x0 = xi;
  9860. y0 = yi;
  9861. }
  9862. var l = -1;
  9863. switch (cmd) {
  9864. case CMD.M:
  9865. xi = x0 = data[i++];
  9866. yi = y0 = data[i++];
  9867. break;
  9868. case CMD.L: {
  9869. var x2 = data[i++];
  9870. var y2 = data[i++];
  9871. var dx = x2 - xi;
  9872. var dy = y2 - yi;
  9873. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  9874. l = Math.sqrt(dx * dx + dy * dy);
  9875. xi = x2;
  9876. yi = y2;
  9877. }
  9878. break;
  9879. }
  9880. case CMD.C: {
  9881. var x1 = data[i++];
  9882. var y1 = data[i++];
  9883. var x2 = data[i++];
  9884. var y2 = data[i++];
  9885. var x3 = data[i++];
  9886. var y3 = data[i++];
  9887. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  9888. xi = x3;
  9889. yi = y3;
  9890. break;
  9891. }
  9892. case CMD.Q: {
  9893. var x1 = data[i++];
  9894. var y1 = data[i++];
  9895. var x2 = data[i++];
  9896. var y2 = data[i++];
  9897. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  9898. xi = x2;
  9899. yi = y2;
  9900. break;
  9901. }
  9902. case CMD.A:
  9903. var cx = data[i++];
  9904. var cy = data[i++];
  9905. var rx = data[i++];
  9906. var ry = data[i++];
  9907. var startAngle = data[i++];
  9908. var delta = data[i++];
  9909. var endAngle = delta + startAngle;
  9910. i += 1;
  9911. var anticlockwise = !data[i++];
  9912. if (isFirst) {
  9913. x0 = mathCos$1(startAngle) * rx + cx;
  9914. y0 = mathSin$1(startAngle) * ry + cy;
  9915. }
  9916. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  9917. xi = mathCos$1(endAngle) * rx + cx;
  9918. yi = mathSin$1(endAngle) * ry + cy;
  9919. break;
  9920. case CMD.R: {
  9921. x0 = xi = data[i++];
  9922. y0 = yi = data[i++];
  9923. var width = data[i++];
  9924. var height = data[i++];
  9925. l = width * 2 + height * 2;
  9926. break;
  9927. }
  9928. case CMD.Z: {
  9929. var dx = x0 - xi;
  9930. var dy = y0 - yi;
  9931. l = Math.sqrt(dx * dx + dy * dy);
  9932. xi = x0;
  9933. yi = y0;
  9934. break;
  9935. }
  9936. }
  9937. if (l >= 0) {
  9938. pathSegLen[segCount++] = l;
  9939. pathTotalLen += l;
  9940. }
  9941. }
  9942. this._pathLen = pathTotalLen;
  9943. return pathTotalLen;
  9944. };
  9945. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  9946. var d = this.data;
  9947. var ux = this._ux;
  9948. var uy = this._uy;
  9949. var len = this._len;
  9950. var x0;
  9951. var y0;
  9952. var xi;
  9953. var yi;
  9954. var x;
  9955. var y;
  9956. var drawPart = percent < 1;
  9957. var pathSegLen;
  9958. var pathTotalLen;
  9959. var accumLength = 0;
  9960. var segCount = 0;
  9961. var displayedLength;
  9962. var pendingPtDist = 0;
  9963. var pendingPtX;
  9964. var pendingPtY;
  9965. if (drawPart) {
  9966. if (!this._pathSegLen) {
  9967. this._calculateLength();
  9968. }
  9969. pathSegLen = this._pathSegLen;
  9970. pathTotalLen = this._pathLen;
  9971. displayedLength = percent * pathTotalLen;
  9972. if (!displayedLength) {
  9973. return;
  9974. }
  9975. }
  9976. lo: for (var i = 0; i < len;) {
  9977. var cmd = d[i++];
  9978. var isFirst = i === 1;
  9979. if (isFirst) {
  9980. xi = d[i];
  9981. yi = d[i + 1];
  9982. x0 = xi;
  9983. y0 = yi;
  9984. }
  9985. if (cmd !== CMD.L && pendingPtDist > 0) {
  9986. ctx.lineTo(pendingPtX, pendingPtY);
  9987. pendingPtDist = 0;
  9988. }
  9989. switch (cmd) {
  9990. case CMD.M:
  9991. x0 = xi = d[i++];
  9992. y0 = yi = d[i++];
  9993. ctx.moveTo(xi, yi);
  9994. break;
  9995. case CMD.L: {
  9996. x = d[i++];
  9997. y = d[i++];
  9998. var dx = mathAbs(x - xi);
  9999. var dy = mathAbs(y - yi);
  10000. if (dx > ux || dy > uy) {
  10001. if (drawPart) {
  10002. var l = pathSegLen[segCount++];
  10003. if (accumLength + l > displayedLength) {
  10004. var t = (displayedLength - accumLength) / l;
  10005. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10006. break lo;
  10007. }
  10008. accumLength += l;
  10009. }
  10010. ctx.lineTo(x, y);
  10011. xi = x;
  10012. yi = y;
  10013. pendingPtDist = 0;
  10014. }
  10015. else {
  10016. var d2 = dx * dx + dy * dy;
  10017. if (d2 > pendingPtDist) {
  10018. pendingPtX = x;
  10019. pendingPtY = y;
  10020. pendingPtDist = d2;
  10021. }
  10022. }
  10023. break;
  10024. }
  10025. case CMD.C: {
  10026. var x1 = d[i++];
  10027. var y1 = d[i++];
  10028. var x2 = d[i++];
  10029. var y2 = d[i++];
  10030. var x3 = d[i++];
  10031. var y3 = d[i++];
  10032. if (drawPart) {
  10033. var l = pathSegLen[segCount++];
  10034. if (accumLength + l > displayedLength) {
  10035. var t = (displayedLength - accumLength) / l;
  10036. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10037. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10038. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10039. break lo;
  10040. }
  10041. accumLength += l;
  10042. }
  10043. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10044. xi = x3;
  10045. yi = y3;
  10046. break;
  10047. }
  10048. case CMD.Q: {
  10049. var x1 = d[i++];
  10050. var y1 = d[i++];
  10051. var x2 = d[i++];
  10052. var y2 = d[i++];
  10053. if (drawPart) {
  10054. var l = pathSegLen[segCount++];
  10055. if (accumLength + l > displayedLength) {
  10056. var t = (displayedLength - accumLength) / l;
  10057. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10058. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10059. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10060. break lo;
  10061. }
  10062. accumLength += l;
  10063. }
  10064. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10065. xi = x2;
  10066. yi = y2;
  10067. break;
  10068. }
  10069. case CMD.A:
  10070. var cx = d[i++];
  10071. var cy = d[i++];
  10072. var rx = d[i++];
  10073. var ry = d[i++];
  10074. var startAngle = d[i++];
  10075. var delta = d[i++];
  10076. var psi = d[i++];
  10077. var anticlockwise = !d[i++];
  10078. var r = (rx > ry) ? rx : ry;
  10079. var isEllipse = mathAbs(rx - ry) > 1e-3;
  10080. var endAngle = startAngle + delta;
  10081. var breakBuild = false;
  10082. if (drawPart) {
  10083. var l = pathSegLen[segCount++];
  10084. if (accumLength + l > displayedLength) {
  10085. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10086. breakBuild = true;
  10087. }
  10088. accumLength += l;
  10089. }
  10090. if (isEllipse && ctx.ellipse) {
  10091. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10092. }
  10093. else {
  10094. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10095. }
  10096. if (breakBuild) {
  10097. break lo;
  10098. }
  10099. if (isFirst) {
  10100. x0 = mathCos$1(startAngle) * rx + cx;
  10101. y0 = mathSin$1(startAngle) * ry + cy;
  10102. }
  10103. xi = mathCos$1(endAngle) * rx + cx;
  10104. yi = mathSin$1(endAngle) * ry + cy;
  10105. break;
  10106. case CMD.R:
  10107. x0 = xi = d[i];
  10108. y0 = yi = d[i + 1];
  10109. x = d[i++];
  10110. y = d[i++];
  10111. var width = d[i++];
  10112. var height = d[i++];
  10113. if (drawPart) {
  10114. var l = pathSegLen[segCount++];
  10115. if (accumLength + l > displayedLength) {
  10116. var d_1 = displayedLength - accumLength;
  10117. ctx.moveTo(x, y);
  10118. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10119. d_1 -= width;
  10120. if (d_1 > 0) {
  10121. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10122. }
  10123. d_1 -= height;
  10124. if (d_1 > 0) {
  10125. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10126. }
  10127. d_1 -= width;
  10128. if (d_1 > 0) {
  10129. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10130. }
  10131. break lo;
  10132. }
  10133. accumLength += l;
  10134. }
  10135. ctx.rect(x, y, width, height);
  10136. break;
  10137. case CMD.Z:
  10138. if (drawPart) {
  10139. var l = pathSegLen[segCount++];
  10140. if (accumLength + l > displayedLength) {
  10141. var t = (displayedLength - accumLength) / l;
  10142. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10143. break lo;
  10144. }
  10145. accumLength += l;
  10146. }
  10147. ctx.closePath();
  10148. xi = x0;
  10149. yi = y0;
  10150. }
  10151. }
  10152. };
  10153. PathProxy.prototype.clone = function () {
  10154. var newProxy = new PathProxy();
  10155. var data = this.data;
  10156. newProxy.data = data.slice ? data.slice()
  10157. : Array.prototype.slice.call(data);
  10158. newProxy._len = this._len;
  10159. return newProxy;
  10160. };
  10161. PathProxy.CMD = CMD;
  10162. PathProxy.initDefaultProps = (function () {
  10163. var proto = PathProxy.prototype;
  10164. proto._saveData = true;
  10165. proto._needsDash = false;
  10166. proto._dashOffset = 0;
  10167. proto._dashIdx = 0;
  10168. proto._dashSum = 0;
  10169. proto._ux = 0;
  10170. proto._uy = 0;
  10171. proto._pendingPtDist = 0;
  10172. proto._version = 0;
  10173. })();
  10174. return PathProxy;
  10175. }());
  10176. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10177. if (lineWidth === 0) {
  10178. return false;
  10179. }
  10180. var _l = lineWidth;
  10181. var _a = 0;
  10182. var _b = x0;
  10183. if ((y > y0 + _l && y > y1 + _l)
  10184. || (y < y0 - _l && y < y1 - _l)
  10185. || (x > x0 + _l && x > x1 + _l)
  10186. || (x < x0 - _l && x < x1 - _l)) {
  10187. return false;
  10188. }
  10189. if (x0 !== x1) {
  10190. _a = (y0 - y1) / (x0 - x1);
  10191. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10192. }
  10193. else {
  10194. return Math.abs(x - x0) <= _l / 2;
  10195. }
  10196. var tmp = _a * x - y + _b;
  10197. var _s = tmp * tmp / (_a * _a + 1);
  10198. return _s <= _l / 2 * _l / 2;
  10199. }
  10200. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10201. if (lineWidth === 0) {
  10202. return false;
  10203. }
  10204. var _l = lineWidth;
  10205. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10206. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10207. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10208. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10209. return false;
  10210. }
  10211. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10212. return d <= _l / 2;
  10213. }
  10214. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10215. if (lineWidth === 0) {
  10216. return false;
  10217. }
  10218. var _l = lineWidth;
  10219. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10220. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10221. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10222. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10223. return false;
  10224. }
  10225. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10226. return d <= _l / 2;
  10227. }
  10228. var PI2$2 = Math.PI * 2;
  10229. function normalizeRadian(angle) {
  10230. angle %= PI2$2;
  10231. if (angle < 0) {
  10232. angle += PI2$2;
  10233. }
  10234. return angle;
  10235. }
  10236. var PI2$3 = Math.PI * 2;
  10237. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10238. if (lineWidth === 0) {
  10239. return false;
  10240. }
  10241. var _l = lineWidth;
  10242. x -= cx;
  10243. y -= cy;
  10244. var d = Math.sqrt(x * x + y * y);
  10245. if ((d - _l > r) || (d + _l < r)) {
  10246. return false;
  10247. }
  10248. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10249. return true;
  10250. }
  10251. if (anticlockwise) {
  10252. var tmp = startAngle;
  10253. startAngle = normalizeRadian(endAngle);
  10254. endAngle = normalizeRadian(tmp);
  10255. }
  10256. else {
  10257. startAngle = normalizeRadian(startAngle);
  10258. endAngle = normalizeRadian(endAngle);
  10259. }
  10260. if (startAngle > endAngle) {
  10261. endAngle += PI2$3;
  10262. }
  10263. var angle = Math.atan2(y, x);
  10264. if (angle < 0) {
  10265. angle += PI2$3;
  10266. }
  10267. return (angle >= startAngle && angle <= endAngle)
  10268. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10269. }
  10270. function windingLine(x0, y0, x1, y1, x, y) {
  10271. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10272. return 0;
  10273. }
  10274. if (y1 === y0) {
  10275. return 0;
  10276. }
  10277. var t = (y - y0) / (y1 - y0);
  10278. var dir = y1 < y0 ? 1 : -1;
  10279. if (t === 1 || t === 0) {
  10280. dir = y1 < y0 ? 0.5 : -0.5;
  10281. }
  10282. var x_ = t * (x1 - x0) + x0;
  10283. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10284. }
  10285. var CMD$1 = PathProxy.CMD;
  10286. var PI2$4 = Math.PI * 2;
  10287. var EPSILON$2 = 1e-4;
  10288. function isAroundEqual(a, b) {
  10289. return Math.abs(a - b) < EPSILON$2;
  10290. }
  10291. var roots = [-1, -1, -1];
  10292. var extrema = [-1, -1];
  10293. function swapExtrema() {
  10294. var tmp = extrema[0];
  10295. extrema[0] = extrema[1];
  10296. extrema[1] = tmp;
  10297. }
  10298. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10299. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10300. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10301. return 0;
  10302. }
  10303. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10304. if (nRoots === 0) {
  10305. return 0;
  10306. }
  10307. else {
  10308. var w = 0;
  10309. var nExtrema = -1;
  10310. var y0_ = void 0;
  10311. var y1_ = void 0;
  10312. for (var i = 0; i < nRoots; i++) {
  10313. var t = roots[i];
  10314. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10315. var x_ = cubicAt(x0, x1, x2, x3, t);
  10316. if (x_ < x) {
  10317. continue;
  10318. }
  10319. if (nExtrema < 0) {
  10320. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10321. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10322. swapExtrema();
  10323. }
  10324. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10325. if (nExtrema > 1) {
  10326. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10327. }
  10328. }
  10329. if (nExtrema === 2) {
  10330. if (t < extrema[0]) {
  10331. w += y0_ < y0 ? unit : -unit;
  10332. }
  10333. else if (t < extrema[1]) {
  10334. w += y1_ < y0_ ? unit : -unit;
  10335. }
  10336. else {
  10337. w += y3 < y1_ ? unit : -unit;
  10338. }
  10339. }
  10340. else {
  10341. if (t < extrema[0]) {
  10342. w += y0_ < y0 ? unit : -unit;
  10343. }
  10344. else {
  10345. w += y3 < y0_ ? unit : -unit;
  10346. }
  10347. }
  10348. }
  10349. return w;
  10350. }
  10351. }
  10352. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10353. if ((y > y0 && y > y1 && y > y2)
  10354. || (y < y0 && y < y1 && y < y2)) {
  10355. return 0;
  10356. }
  10357. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10358. if (nRoots === 0) {
  10359. return 0;
  10360. }
  10361. else {
  10362. var t = quadraticExtremum(y0, y1, y2);
  10363. if (t >= 0 && t <= 1) {
  10364. var w = 0;
  10365. var y_ = quadraticAt(y0, y1, y2, t);
  10366. for (var i = 0; i < nRoots; i++) {
  10367. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10368. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10369. if (x_ < x) {
  10370. continue;
  10371. }
  10372. if (roots[i] < t) {
  10373. w += y_ < y0 ? unit : -unit;
  10374. }
  10375. else {
  10376. w += y2 < y_ ? unit : -unit;
  10377. }
  10378. }
  10379. return w;
  10380. }
  10381. else {
  10382. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10383. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10384. if (x_ < x) {
  10385. return 0;
  10386. }
  10387. return y2 < y0 ? unit : -unit;
  10388. }
  10389. }
  10390. }
  10391. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10392. y -= cy;
  10393. if (y > r || y < -r) {
  10394. return 0;
  10395. }
  10396. var tmp = Math.sqrt(r * r - y * y);
  10397. roots[0] = -tmp;
  10398. roots[1] = tmp;
  10399. var dTheta = Math.abs(startAngle - endAngle);
  10400. if (dTheta < 1e-4) {
  10401. return 0;
  10402. }
  10403. if (dTheta >= PI2$4 - 1e-4) {
  10404. startAngle = 0;
  10405. endAngle = PI2$4;
  10406. var dir = anticlockwise ? 1 : -1;
  10407. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10408. return dir;
  10409. }
  10410. else {
  10411. return 0;
  10412. }
  10413. }
  10414. if (startAngle > endAngle) {
  10415. var tmp_1 = startAngle;
  10416. startAngle = endAngle;
  10417. endAngle = tmp_1;
  10418. }
  10419. if (startAngle < 0) {
  10420. startAngle += PI2$4;
  10421. endAngle += PI2$4;
  10422. }
  10423. var w = 0;
  10424. for (var i = 0; i < 2; i++) {
  10425. var x_ = roots[i];
  10426. if (x_ + cx > x) {
  10427. var angle = Math.atan2(y, x_);
  10428. var dir = anticlockwise ? 1 : -1;
  10429. if (angle < 0) {
  10430. angle = PI2$4 + angle;
  10431. }
  10432. if ((angle >= startAngle && angle <= endAngle)
  10433. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10434. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10435. dir = -dir;
  10436. }
  10437. w += dir;
  10438. }
  10439. }
  10440. }
  10441. return w;
  10442. }
  10443. function containPath(path, lineWidth, isStroke, x, y) {
  10444. var data = path.data;
  10445. var len = path.len();
  10446. var w = 0;
  10447. var xi = 0;
  10448. var yi = 0;
  10449. var x0 = 0;
  10450. var y0 = 0;
  10451. var x1;
  10452. var y1;
  10453. for (var i = 0; i < len;) {
  10454. var cmd = data[i++];
  10455. var isFirst = i === 1;
  10456. if (cmd === CMD$1.M && i > 1) {
  10457. if (!isStroke) {
  10458. w += windingLine(xi, yi, x0, y0, x, y);
  10459. }
  10460. }
  10461. if (isFirst) {
  10462. xi = data[i];
  10463. yi = data[i + 1];
  10464. x0 = xi;
  10465. y0 = yi;
  10466. }
  10467. switch (cmd) {
  10468. case CMD$1.M:
  10469. x0 = data[i++];
  10470. y0 = data[i++];
  10471. xi = x0;
  10472. yi = y0;
  10473. break;
  10474. case CMD$1.L:
  10475. if (isStroke) {
  10476. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10477. return true;
  10478. }
  10479. }
  10480. else {
  10481. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10482. }
  10483. xi = data[i++];
  10484. yi = data[i++];
  10485. break;
  10486. case CMD$1.C:
  10487. if (isStroke) {
  10488. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10489. return true;
  10490. }
  10491. }
  10492. else {
  10493. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10494. }
  10495. xi = data[i++];
  10496. yi = data[i++];
  10497. break;
  10498. case CMD$1.Q:
  10499. if (isStroke) {
  10500. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10501. return true;
  10502. }
  10503. }
  10504. else {
  10505. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10506. }
  10507. xi = data[i++];
  10508. yi = data[i++];
  10509. break;
  10510. case CMD$1.A:
  10511. var cx = data[i++];
  10512. var cy = data[i++];
  10513. var rx = data[i++];
  10514. var ry = data[i++];
  10515. var theta = data[i++];
  10516. var dTheta = data[i++];
  10517. i += 1;
  10518. var anticlockwise = !!(1 - data[i++]);
  10519. x1 = Math.cos(theta) * rx + cx;
  10520. y1 = Math.sin(theta) * ry + cy;
  10521. if (!isFirst) {
  10522. w += windingLine(xi, yi, x1, y1, x, y);
  10523. }
  10524. else {
  10525. x0 = x1;
  10526. y0 = y1;
  10527. }
  10528. var _x = (x - cx) * ry / rx + cx;
  10529. if (isStroke) {
  10530. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10531. return true;
  10532. }
  10533. }
  10534. else {
  10535. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10536. }
  10537. xi = Math.cos(theta + dTheta) * rx + cx;
  10538. yi = Math.sin(theta + dTheta) * ry + cy;
  10539. break;
  10540. case CMD$1.R:
  10541. x0 = xi = data[i++];
  10542. y0 = yi = data[i++];
  10543. var width = data[i++];
  10544. var height = data[i++];
  10545. x1 = x0 + width;
  10546. y1 = y0 + height;
  10547. if (isStroke) {
  10548. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10549. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10550. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10551. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10552. return true;
  10553. }
  10554. }
  10555. else {
  10556. w += windingLine(x1, y0, x1, y1, x, y);
  10557. w += windingLine(x0, y1, x0, y0, x, y);
  10558. }
  10559. break;
  10560. case CMD$1.Z:
  10561. if (isStroke) {
  10562. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10563. return true;
  10564. }
  10565. }
  10566. else {
  10567. w += windingLine(xi, yi, x0, y0, x, y);
  10568. }
  10569. xi = x0;
  10570. yi = y0;
  10571. break;
  10572. }
  10573. }
  10574. if (!isStroke && !isAroundEqual(yi, y0)) {
  10575. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10576. }
  10577. return w !== 0;
  10578. }
  10579. function contain(pathProxy, x, y) {
  10580. return containPath(pathProxy, 0, false, x, y);
  10581. }
  10582. function containStroke$4(pathProxy, lineWidth, x, y) {
  10583. return containPath(pathProxy, lineWidth, true, x, y);
  10584. }
  10585. var DEFAULT_PATH_STYLE = defaults({
  10586. fill: '#000',
  10587. stroke: null,
  10588. strokePercent: 1,
  10589. fillOpacity: 1,
  10590. strokeOpacity: 1,
  10591. lineDashOffset: 0,
  10592. lineWidth: 1,
  10593. lineCap: 'butt',
  10594. miterLimit: 10,
  10595. strokeNoScale: false,
  10596. strokeFirst: false
  10597. }, DEFAULT_COMMON_STYLE);
  10598. var DEFAULT_PATH_ANIMATION_PROPS = {
  10599. style: defaults({
  10600. fill: true,
  10601. stroke: true,
  10602. strokePercent: true,
  10603. fillOpacity: true,
  10604. strokeOpacity: true,
  10605. lineDashOffset: true,
  10606. lineWidth: true,
  10607. miterLimit: true
  10608. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10609. };
  10610. var pathCopyParams = [
  10611. 'x', 'y', 'rotation', 'scaleX', 'scaleY', 'originX', 'originY', 'invisible',
  10612. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10613. ];
  10614. var Path = (function (_super) {
  10615. __extends(Path, _super);
  10616. function Path(opts) {
  10617. return _super.call(this, opts) || this;
  10618. }
  10619. Path.prototype.update = function () {
  10620. var _this = this;
  10621. _super.prototype.update.call(this);
  10622. var style = this.style;
  10623. if (style.decal) {
  10624. var decalEl = this._decalEl = this._decalEl || new Path();
  10625. if (decalEl.buildPath === Path.prototype.buildPath) {
  10626. decalEl.buildPath = function (ctx) {
  10627. _this.buildPath(ctx, _this.shape);
  10628. };
  10629. }
  10630. decalEl.silent = true;
  10631. var decalElStyle = decalEl.style;
  10632. for (var key in style) {
  10633. if (decalElStyle[key] !== style[key]) {
  10634. decalElStyle[key] = style[key];
  10635. }
  10636. }
  10637. decalElStyle.fill = style.fill ? style.decal : null;
  10638. decalElStyle.decal = null;
  10639. decalElStyle.shadowColor = null;
  10640. style.strokeFirst && (decalElStyle.stroke = null);
  10641. for (var i = 0; i < pathCopyParams.length; ++i) {
  10642. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10643. }
  10644. decalEl.__dirty |= REDARAW_BIT;
  10645. }
  10646. else if (this._decalEl) {
  10647. this._decalEl = null;
  10648. }
  10649. };
  10650. Path.prototype.getDecalElement = function () {
  10651. return this._decalEl;
  10652. };
  10653. Path.prototype._init = function (props) {
  10654. var keysArr = keys(props);
  10655. this.shape = this.getDefaultShape();
  10656. var defaultStyle = this.getDefaultStyle();
  10657. if (defaultStyle) {
  10658. this.useStyle(defaultStyle);
  10659. }
  10660. for (var i = 0; i < keysArr.length; i++) {
  10661. var key = keysArr[i];
  10662. var value = props[key];
  10663. if (key === 'style') {
  10664. if (!this.style) {
  10665. this.useStyle(value);
  10666. }
  10667. else {
  10668. extend(this.style, value);
  10669. }
  10670. }
  10671. else if (key === 'shape') {
  10672. extend(this.shape, value);
  10673. }
  10674. else {
  10675. _super.prototype.attrKV.call(this, key, value);
  10676. }
  10677. }
  10678. if (!this.style) {
  10679. this.useStyle({});
  10680. }
  10681. };
  10682. Path.prototype.getDefaultStyle = function () {
  10683. return null;
  10684. };
  10685. Path.prototype.getDefaultShape = function () {
  10686. return {};
  10687. };
  10688. Path.prototype.canBeInsideText = function () {
  10689. return this.hasFill();
  10690. };
  10691. Path.prototype.getInsideTextFill = function () {
  10692. var pathFill = this.style.fill;
  10693. if (pathFill !== 'none') {
  10694. if (isString(pathFill)) {
  10695. var fillLum = lum(pathFill, 0);
  10696. if (fillLum > 0.5) {
  10697. return DARK_LABEL_COLOR;
  10698. }
  10699. else if (fillLum > 0.2) {
  10700. return LIGHTER_LABEL_COLOR;
  10701. }
  10702. return LIGHT_LABEL_COLOR;
  10703. }
  10704. else if (pathFill) {
  10705. return LIGHT_LABEL_COLOR;
  10706. }
  10707. }
  10708. return DARK_LABEL_COLOR;
  10709. };
  10710. Path.prototype.getInsideTextStroke = function (textFill) {
  10711. var pathFill = this.style.fill;
  10712. if (isString(pathFill)) {
  10713. var zr = this.__zr;
  10714. var isDarkMode = !!(zr && zr.isDarkMode());
  10715. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10716. if (isDarkMode === isDarkLabel) {
  10717. return pathFill;
  10718. }
  10719. }
  10720. };
  10721. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  10722. Path.prototype.pathUpdated = function () {
  10723. this.__dirty &= ~SHAPE_CHANGED_BIT;
  10724. };
  10725. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  10726. !this.path && this.createPathProxy();
  10727. this.path.beginPath();
  10728. this.buildPath(this.path, this.shape, inBatch);
  10729. return this.path;
  10730. };
  10731. Path.prototype.createPathProxy = function () {
  10732. this.path = new PathProxy(false);
  10733. };
  10734. Path.prototype.hasStroke = function () {
  10735. var style = this.style;
  10736. var stroke = style.stroke;
  10737. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10738. };
  10739. Path.prototype.hasFill = function () {
  10740. var style = this.style;
  10741. var fill = style.fill;
  10742. return fill != null && fill !== 'none';
  10743. };
  10744. Path.prototype.getBoundingRect = function () {
  10745. var rect = this._rect;
  10746. var style = this.style;
  10747. var needsUpdateRect = !rect;
  10748. if (needsUpdateRect) {
  10749. var firstInvoke = false;
  10750. if (!this.path) {
  10751. firstInvoke = true;
  10752. this.createPathProxy();
  10753. }
  10754. var path = this.path;
  10755. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  10756. path.beginPath();
  10757. this.buildPath(path, this.shape, false);
  10758. this.pathUpdated();
  10759. }
  10760. rect = path.getBoundingRect();
  10761. }
  10762. this._rect = rect;
  10763. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10764. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  10765. if (this.__dirty || needsUpdateRect) {
  10766. rectWithStroke.copy(rect);
  10767. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10768. var w = style.lineWidth;
  10769. if (!this.hasFill()) {
  10770. var strokeContainThreshold = this.strokeContainThreshold;
  10771. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10772. }
  10773. if (lineScale > 1e-10) {
  10774. rectWithStroke.width += w / lineScale;
  10775. rectWithStroke.height += w / lineScale;
  10776. rectWithStroke.x -= w / lineScale / 2;
  10777. rectWithStroke.y -= w / lineScale / 2;
  10778. }
  10779. }
  10780. return rectWithStroke;
  10781. }
  10782. return rect;
  10783. };
  10784. Path.prototype.contain = function (x, y) {
  10785. var localPos = this.transformCoordToLocal(x, y);
  10786. var rect = this.getBoundingRect();
  10787. var style = this.style;
  10788. x = localPos[0];
  10789. y = localPos[1];
  10790. if (rect.contain(x, y)) {
  10791. var pathProxy = this.path;
  10792. if (this.hasStroke()) {
  10793. var lineWidth = style.lineWidth;
  10794. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10795. if (lineScale > 1e-10) {
  10796. if (!this.hasFill()) {
  10797. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  10798. }
  10799. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  10800. return true;
  10801. }
  10802. }
  10803. }
  10804. if (this.hasFill()) {
  10805. return contain(pathProxy, x, y);
  10806. }
  10807. }
  10808. return false;
  10809. };
  10810. Path.prototype.dirtyShape = function () {
  10811. this.__dirty |= SHAPE_CHANGED_BIT;
  10812. if (this._rect) {
  10813. this._rect = null;
  10814. }
  10815. if (this._decalEl) {
  10816. this._decalEl.dirtyShape();
  10817. }
  10818. this.markRedraw();
  10819. };
  10820. Path.prototype.dirty = function () {
  10821. this.dirtyStyle();
  10822. this.dirtyShape();
  10823. };
  10824. Path.prototype.animateShape = function (loop) {
  10825. return this.animate('shape', loop);
  10826. };
  10827. Path.prototype.updateDuringAnimation = function (targetKey) {
  10828. if (targetKey === 'style') {
  10829. this.dirtyStyle();
  10830. }
  10831. else if (targetKey === 'shape') {
  10832. this.dirtyShape();
  10833. }
  10834. else {
  10835. this.markRedraw();
  10836. }
  10837. };
  10838. Path.prototype.attrKV = function (key, value) {
  10839. if (key === 'shape') {
  10840. this.setShape(value);
  10841. }
  10842. else {
  10843. _super.prototype.attrKV.call(this, key, value);
  10844. }
  10845. };
  10846. Path.prototype.setShape = function (keyOrObj, value) {
  10847. var shape = this.shape;
  10848. if (!shape) {
  10849. shape = this.shape = {};
  10850. }
  10851. if (typeof keyOrObj === 'string') {
  10852. shape[keyOrObj] = value;
  10853. }
  10854. else {
  10855. extend(shape, keyOrObj);
  10856. }
  10857. this.dirtyShape();
  10858. return this;
  10859. };
  10860. Path.prototype.shapeChanged = function () {
  10861. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  10862. };
  10863. Path.prototype.createStyle = function (obj) {
  10864. return createObject(DEFAULT_PATH_STYLE, obj);
  10865. };
  10866. Path.prototype._innerSaveToNormal = function (toState) {
  10867. _super.prototype._innerSaveToNormal.call(this, toState);
  10868. var normalState = this._normalState;
  10869. if (toState.shape && !normalState.shape) {
  10870. normalState.shape = extend({}, this.shape);
  10871. }
  10872. };
  10873. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  10874. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  10875. var needsRestoreToNormal = !(state && keepCurrentStates);
  10876. var targetShape;
  10877. if (state && state.shape) {
  10878. if (transition) {
  10879. if (keepCurrentStates) {
  10880. targetShape = state.shape;
  10881. }
  10882. else {
  10883. targetShape = extend({}, normalState.shape);
  10884. extend(targetShape, state.shape);
  10885. }
  10886. }
  10887. else {
  10888. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  10889. extend(targetShape, state.shape);
  10890. }
  10891. }
  10892. else if (needsRestoreToNormal) {
  10893. targetShape = normalState.shape;
  10894. }
  10895. if (targetShape) {
  10896. if (transition) {
  10897. this.shape = extend({}, this.shape);
  10898. var targetShapePrimaryProps = {};
  10899. var shapeKeys = keys(targetShape);
  10900. for (var i = 0; i < shapeKeys.length; i++) {
  10901. var key = shapeKeys[i];
  10902. if (typeof targetShape[key] === 'object') {
  10903. this.shape[key] = targetShape[key];
  10904. }
  10905. else {
  10906. targetShapePrimaryProps[key] = targetShape[key];
  10907. }
  10908. }
  10909. this._transitionState(stateName, {
  10910. shape: targetShapePrimaryProps
  10911. }, animationCfg);
  10912. }
  10913. else {
  10914. this.shape = targetShape;
  10915. this.dirtyShape();
  10916. }
  10917. }
  10918. };
  10919. Path.prototype._mergeStates = function (states) {
  10920. var mergedState = _super.prototype._mergeStates.call(this, states);
  10921. var mergedShape;
  10922. for (var i = 0; i < states.length; i++) {
  10923. var state = states[i];
  10924. if (state.shape) {
  10925. mergedShape = mergedShape || {};
  10926. this._mergeStyle(mergedShape, state.shape);
  10927. }
  10928. }
  10929. if (mergedShape) {
  10930. mergedState.shape = mergedShape;
  10931. }
  10932. return mergedState;
  10933. };
  10934. Path.prototype.getAnimationStyleProps = function () {
  10935. return DEFAULT_PATH_ANIMATION_PROPS;
  10936. };
  10937. Path.prototype.isZeroArea = function () {
  10938. return false;
  10939. };
  10940. Path.extend = function (defaultProps) {
  10941. var Sub = (function (_super) {
  10942. __extends(Sub, _super);
  10943. function Sub(opts) {
  10944. var _this = _super.call(this, opts) || this;
  10945. defaultProps.init && defaultProps.init.call(_this, opts);
  10946. return _this;
  10947. }
  10948. Sub.prototype.getDefaultStyle = function () {
  10949. return clone(defaultProps.style);
  10950. };
  10951. Sub.prototype.getDefaultShape = function () {
  10952. return clone(defaultProps.shape);
  10953. };
  10954. return Sub;
  10955. }(Path));
  10956. for (var key in defaultProps) {
  10957. if (typeof defaultProps[key] === 'function') {
  10958. Sub.prototype[key] = defaultProps[key];
  10959. }
  10960. }
  10961. return Sub;
  10962. };
  10963. Path.initDefaultProps = (function () {
  10964. var pathProto = Path.prototype;
  10965. pathProto.type = 'path';
  10966. pathProto.strokeContainThreshold = 5;
  10967. pathProto.segmentIgnoreThreshold = 0;
  10968. pathProto.subPixelOptimize = false;
  10969. pathProto.autoBatch = false;
  10970. pathProto.__dirty = REDARAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  10971. })();
  10972. return Path;
  10973. }(Displayable));
  10974. var DEFAULT_TSPAN_STYLE = defaults({
  10975. strokeFirst: true,
  10976. font: DEFAULT_FONT,
  10977. x: 0,
  10978. y: 0,
  10979. textAlign: 'left',
  10980. textBaseline: 'top',
  10981. miterLimit: 2
  10982. }, DEFAULT_PATH_STYLE);
  10983. var TSpan = (function (_super) {
  10984. __extends(TSpan, _super);
  10985. function TSpan() {
  10986. return _super !== null && _super.apply(this, arguments) || this;
  10987. }
  10988. TSpan.prototype.hasStroke = function () {
  10989. var style = this.style;
  10990. var stroke = style.stroke;
  10991. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  10992. };
  10993. TSpan.prototype.hasFill = function () {
  10994. var style = this.style;
  10995. var fill = style.fill;
  10996. return fill != null && fill !== 'none';
  10997. };
  10998. TSpan.prototype.createStyle = function (obj) {
  10999. return createObject(DEFAULT_TSPAN_STYLE, obj);
  11000. };
  11001. TSpan.prototype.setBoundingRect = function (rect) {
  11002. this._rect = rect;
  11003. };
  11004. TSpan.prototype.getBoundingRect = function () {
  11005. var style = this.style;
  11006. if (!this._rect) {
  11007. var text = style.text;
  11008. text != null ? (text += '') : (text = '');
  11009. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  11010. rect.x += style.x || 0;
  11011. rect.y += style.y || 0;
  11012. if (this.hasStroke()) {
  11013. var w = style.lineWidth;
  11014. rect.x -= w / 2;
  11015. rect.y -= w / 2;
  11016. rect.width += w;
  11017. rect.height += w;
  11018. }
  11019. this._rect = rect;
  11020. }
  11021. return this._rect;
  11022. };
  11023. TSpan.initDefaultProps = (function () {
  11024. var tspanProto = TSpan.prototype;
  11025. tspanProto.dirtyRectTolerance = 10;
  11026. })();
  11027. return TSpan;
  11028. }(Displayable));
  11029. TSpan.prototype.type = 'tspan';
  11030. var DEFAULT_IMAGE_STYLE = defaults({
  11031. x: 0,
  11032. y: 0
  11033. }, DEFAULT_COMMON_STYLE);
  11034. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11035. style: defaults({
  11036. x: true,
  11037. y: true,
  11038. width: true,
  11039. height: true,
  11040. sx: true,
  11041. sy: true,
  11042. sWidth: true,
  11043. sHeight: true
  11044. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11045. };
  11046. function isImageLike(source) {
  11047. return !!(source
  11048. && typeof source !== 'string'
  11049. && source.width && source.height);
  11050. }
  11051. var ZRImage = (function (_super) {
  11052. __extends(ZRImage, _super);
  11053. function ZRImage() {
  11054. return _super !== null && _super.apply(this, arguments) || this;
  11055. }
  11056. ZRImage.prototype.createStyle = function (obj) {
  11057. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11058. };
  11059. ZRImage.prototype._getSize = function (dim) {
  11060. var style = this.style;
  11061. var size = style[dim];
  11062. if (size != null) {
  11063. return size;
  11064. }
  11065. var imageSource = isImageLike(style.image)
  11066. ? style.image : this.__image;
  11067. if (!imageSource) {
  11068. return 0;
  11069. }
  11070. var otherDim = dim === 'width' ? 'height' : 'width';
  11071. var otherDimSize = style[otherDim];
  11072. if (otherDimSize == null) {
  11073. return imageSource[dim];
  11074. }
  11075. else {
  11076. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11077. }
  11078. };
  11079. ZRImage.prototype.getWidth = function () {
  11080. return this._getSize('width');
  11081. };
  11082. ZRImage.prototype.getHeight = function () {
  11083. return this._getSize('height');
  11084. };
  11085. ZRImage.prototype.getAnimationStyleProps = function () {
  11086. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11087. };
  11088. ZRImage.prototype.getBoundingRect = function () {
  11089. var style = this.style;
  11090. if (!this._rect) {
  11091. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11092. }
  11093. return this._rect;
  11094. };
  11095. return ZRImage;
  11096. }(Displayable));
  11097. ZRImage.prototype.type = 'image';
  11098. function buildPath(ctx, shape) {
  11099. var x = shape.x;
  11100. var y = shape.y;
  11101. var width = shape.width;
  11102. var height = shape.height;
  11103. var r = shape.r;
  11104. var r1;
  11105. var r2;
  11106. var r3;
  11107. var r4;
  11108. if (width < 0) {
  11109. x = x + width;
  11110. width = -width;
  11111. }
  11112. if (height < 0) {
  11113. y = y + height;
  11114. height = -height;
  11115. }
  11116. if (typeof r === 'number') {
  11117. r1 = r2 = r3 = r4 = r;
  11118. }
  11119. else if (r instanceof Array) {
  11120. if (r.length === 1) {
  11121. r1 = r2 = r3 = r4 = r[0];
  11122. }
  11123. else if (r.length === 2) {
  11124. r1 = r3 = r[0];
  11125. r2 = r4 = r[1];
  11126. }
  11127. else if (r.length === 3) {
  11128. r1 = r[0];
  11129. r2 = r4 = r[1];
  11130. r3 = r[2];
  11131. }
  11132. else {
  11133. r1 = r[0];
  11134. r2 = r[1];
  11135. r3 = r[2];
  11136. r4 = r[3];
  11137. }
  11138. }
  11139. else {
  11140. r1 = r2 = r3 = r4 = 0;
  11141. }
  11142. var total;
  11143. if (r1 + r2 > width) {
  11144. total = r1 + r2;
  11145. r1 *= width / total;
  11146. r2 *= width / total;
  11147. }
  11148. if (r3 + r4 > width) {
  11149. total = r3 + r4;
  11150. r3 *= width / total;
  11151. r4 *= width / total;
  11152. }
  11153. if (r2 + r3 > height) {
  11154. total = r2 + r3;
  11155. r2 *= height / total;
  11156. r3 *= height / total;
  11157. }
  11158. if (r1 + r4 > height) {
  11159. total = r1 + r4;
  11160. r1 *= height / total;
  11161. r4 *= height / total;
  11162. }
  11163. ctx.moveTo(x + r1, y);
  11164. ctx.lineTo(x + width - r2, y);
  11165. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11166. ctx.lineTo(x + width, y + height - r3);
  11167. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11168. ctx.lineTo(x + r4, y + height);
  11169. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11170. ctx.lineTo(x, y + r1);
  11171. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11172. }
  11173. var round$1 = Math.round;
  11174. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11175. if (!inputShape) {
  11176. return;
  11177. }
  11178. var x1 = inputShape.x1;
  11179. var x2 = inputShape.x2;
  11180. var y1 = inputShape.y1;
  11181. var y2 = inputShape.y2;
  11182. outputShape.x1 = x1;
  11183. outputShape.x2 = x2;
  11184. outputShape.y1 = y1;
  11185. outputShape.y2 = y2;
  11186. var lineWidth = style && style.lineWidth;
  11187. if (!lineWidth) {
  11188. return outputShape;
  11189. }
  11190. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11191. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11192. }
  11193. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11194. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11195. }
  11196. return outputShape;
  11197. }
  11198. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11199. if (!inputShape) {
  11200. return;
  11201. }
  11202. var originX = inputShape.x;
  11203. var originY = inputShape.y;
  11204. var originWidth = inputShape.width;
  11205. var originHeight = inputShape.height;
  11206. outputShape.x = originX;
  11207. outputShape.y = originY;
  11208. outputShape.width = originWidth;
  11209. outputShape.height = originHeight;
  11210. var lineWidth = style && style.lineWidth;
  11211. if (!lineWidth) {
  11212. return outputShape;
  11213. }
  11214. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11215. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11216. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11217. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11218. return outputShape;
  11219. }
  11220. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11221. if (!lineWidth) {
  11222. return position;
  11223. }
  11224. var doubledPosition = round$1(position * 2);
  11225. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11226. ? doubledPosition / 2
  11227. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11228. }
  11229. var RectShape = (function () {
  11230. function RectShape() {
  11231. this.x = 0;
  11232. this.y = 0;
  11233. this.width = 0;
  11234. this.height = 0;
  11235. }
  11236. return RectShape;
  11237. }());
  11238. var subPixelOptimizeOutputShape = {};
  11239. var Rect = (function (_super) {
  11240. __extends(Rect, _super);
  11241. function Rect(opts) {
  11242. return _super.call(this, opts) || this;
  11243. }
  11244. Rect.prototype.getDefaultShape = function () {
  11245. return new RectShape();
  11246. };
  11247. Rect.prototype.buildPath = function (ctx, shape) {
  11248. var x;
  11249. var y;
  11250. var width;
  11251. var height;
  11252. if (this.subPixelOptimize) {
  11253. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11254. x = optimizedShape.x;
  11255. y = optimizedShape.y;
  11256. width = optimizedShape.width;
  11257. height = optimizedShape.height;
  11258. optimizedShape.r = shape.r;
  11259. shape = optimizedShape;
  11260. }
  11261. else {
  11262. x = shape.x;
  11263. y = shape.y;
  11264. width = shape.width;
  11265. height = shape.height;
  11266. }
  11267. if (!shape.r) {
  11268. ctx.rect(x, y, width, height);
  11269. }
  11270. else {
  11271. buildPath(ctx, shape);
  11272. }
  11273. };
  11274. Rect.prototype.isZeroArea = function () {
  11275. return !this.shape.width || !this.shape.height;
  11276. };
  11277. return Rect;
  11278. }(Path));
  11279. Rect.prototype.type = 'rect';
  11280. var DEFAULT_RICH_TEXT_COLOR = {
  11281. fill: '#000'
  11282. };
  11283. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11284. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11285. style: defaults({
  11286. fill: true,
  11287. stroke: true,
  11288. fillOpacity: true,
  11289. strokeOpacity: true,
  11290. lineWidth: true,
  11291. fontSize: true,
  11292. lineHeight: true,
  11293. width: true,
  11294. height: true,
  11295. textShadowColor: true,
  11296. textShadowBlur: true,
  11297. textShadowOffsetX: true,
  11298. textShadowOffsetY: true,
  11299. backgroundColor: true,
  11300. padding: true,
  11301. borderColor: true,
  11302. borderWidth: true,
  11303. borderRadius: true
  11304. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11305. };
  11306. var ZRText = (function (_super) {
  11307. __extends(ZRText, _super);
  11308. function ZRText(opts) {
  11309. var _this = _super.call(this) || this;
  11310. _this.type = 'text';
  11311. _this._children = [];
  11312. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11313. _this.attr(opts);
  11314. return _this;
  11315. }
  11316. ZRText.prototype.childrenRef = function () {
  11317. return this._children;
  11318. };
  11319. ZRText.prototype.update = function () {
  11320. _super.prototype.update.call(this);
  11321. if (this.styleChanged()) {
  11322. this._updateSubTexts();
  11323. }
  11324. for (var i = 0; i < this._children.length; i++) {
  11325. var child = this._children[i];
  11326. child.zlevel = this.zlevel;
  11327. child.z = this.z;
  11328. child.z2 = this.z2;
  11329. child.culling = this.culling;
  11330. child.cursor = this.cursor;
  11331. child.invisible = this.invisible;
  11332. }
  11333. };
  11334. ZRText.prototype.updateTransform = function () {
  11335. var innerTransformable = this.innerTransformable;
  11336. if (innerTransformable) {
  11337. innerTransformable.updateTransform();
  11338. if (innerTransformable.transform) {
  11339. this.transform = innerTransformable.transform;
  11340. }
  11341. }
  11342. else {
  11343. _super.prototype.updateTransform.call(this);
  11344. }
  11345. };
  11346. ZRText.prototype.getLocalTransform = function (m) {
  11347. var innerTransformable = this.innerTransformable;
  11348. return innerTransformable
  11349. ? innerTransformable.getLocalTransform(m)
  11350. : _super.prototype.getLocalTransform.call(this, m);
  11351. };
  11352. ZRText.prototype.getComputedTransform = function () {
  11353. if (this.__hostTarget) {
  11354. this.__hostTarget.getComputedTransform();
  11355. this.__hostTarget.updateInnerText(true);
  11356. }
  11357. return _super.prototype.getComputedTransform.call(this);
  11358. };
  11359. ZRText.prototype._updateSubTexts = function () {
  11360. this._childCursor = 0;
  11361. normalizeTextStyle(this.style);
  11362. this.style.rich
  11363. ? this._updateRichTexts()
  11364. : this._updatePlainTexts();
  11365. this._children.length = this._childCursor;
  11366. this.styleUpdated();
  11367. };
  11368. ZRText.prototype.addSelfToZr = function (zr) {
  11369. _super.prototype.addSelfToZr.call(this, zr);
  11370. for (var i = 0; i < this._children.length; i++) {
  11371. this._children[i].__zr = zr;
  11372. }
  11373. };
  11374. ZRText.prototype.removeSelfFromZr = function (zr) {
  11375. _super.prototype.removeSelfFromZr.call(this, zr);
  11376. for (var i = 0; i < this._children.length; i++) {
  11377. this._children[i].__zr = null;
  11378. }
  11379. };
  11380. ZRText.prototype.getBoundingRect = function () {
  11381. if (this.styleChanged()) {
  11382. this._updateSubTexts();
  11383. }
  11384. if (!this._rect) {
  11385. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11386. var children = this._children;
  11387. var tmpMat = [];
  11388. var rect = null;
  11389. for (var i = 0; i < children.length; i++) {
  11390. var child = children[i];
  11391. var childRect = child.getBoundingRect();
  11392. var transform = child.getLocalTransform(tmpMat);
  11393. if (transform) {
  11394. tmpRect.copy(childRect);
  11395. tmpRect.applyTransform(transform);
  11396. rect = rect || tmpRect.clone();
  11397. rect.union(tmpRect);
  11398. }
  11399. else {
  11400. rect = rect || childRect.clone();
  11401. rect.union(childRect);
  11402. }
  11403. }
  11404. this._rect = rect || tmpRect;
  11405. }
  11406. return this._rect;
  11407. };
  11408. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11409. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11410. };
  11411. ZRText.prototype.setTextContent = function (textContent) {
  11412. throw new Error('Can\'t attach text on another text');
  11413. };
  11414. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11415. if (!sourceStyle) {
  11416. return targetStyle;
  11417. }
  11418. var sourceRich = sourceStyle.rich;
  11419. var targetRich = targetStyle.rich || (sourceRich && {});
  11420. extend(targetStyle, sourceStyle);
  11421. if (sourceRich && targetRich) {
  11422. this._mergeRich(targetRich, sourceRich);
  11423. targetStyle.rich = targetRich;
  11424. }
  11425. else if (targetRich) {
  11426. targetStyle.rich = targetRich;
  11427. }
  11428. return targetStyle;
  11429. };
  11430. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11431. var richNames = keys(sourceRich);
  11432. for (var i = 0; i < richNames.length; i++) {
  11433. var richName = richNames[i];
  11434. targetRich[richName] = targetRich[richName] || {};
  11435. extend(targetRich[richName], sourceRich[richName]);
  11436. }
  11437. };
  11438. ZRText.prototype.getAnimationStyleProps = function () {
  11439. return DEFAULT_TEXT_ANIMATION_PROPS;
  11440. };
  11441. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11442. var child = this._children[this._childCursor];
  11443. if (!child || !(child instanceof Ctor)) {
  11444. child = new Ctor();
  11445. }
  11446. this._children[this._childCursor++] = child;
  11447. child.__zr = this.__zr;
  11448. child.parent = this;
  11449. return child;
  11450. };
  11451. ZRText.prototype._updatePlainTexts = function () {
  11452. var style = this.style;
  11453. var textFont = style.font || DEFAULT_FONT;
  11454. var textPadding = style.padding;
  11455. var text = getStyleText(style);
  11456. var contentBlock = parsePlainText(text, style);
  11457. var needDrawBg = needDrawBackground(style);
  11458. var bgColorDrawn = !!(style.backgroundColor);
  11459. var outerHeight = contentBlock.outerHeight;
  11460. var textLines = contentBlock.lines;
  11461. var lineHeight = contentBlock.lineHeight;
  11462. var defaultStyle = this._defaultStyle;
  11463. var baseX = style.x || 0;
  11464. var baseY = style.y || 0;
  11465. var textAlign = style.align || defaultStyle.align || 'left';
  11466. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11467. var textX = baseX;
  11468. var textY = adjustTextY(baseY, contentBlock.contentHeight, verticalAlign);
  11469. if (needDrawBg || textPadding) {
  11470. var outerWidth_1 = contentBlock.width;
  11471. textPadding && (outerWidth_1 += textPadding[1] + textPadding[3]);
  11472. var boxX = adjustTextX(baseX, outerWidth_1, textAlign);
  11473. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11474. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth_1, outerHeight);
  11475. }
  11476. textY += lineHeight / 2;
  11477. if (textPadding) {
  11478. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11479. if (verticalAlign === 'top') {
  11480. textY += textPadding[0];
  11481. }
  11482. else if (verticalAlign === 'bottom') {
  11483. textY -= textPadding[2];
  11484. }
  11485. }
  11486. var defaultLineWidth = 0;
  11487. var useDefaultFill = false;
  11488. var textFill = getFill('fill' in style
  11489. ? style.fill
  11490. : (useDefaultFill = true, defaultStyle.fill));
  11491. var textStroke = getStroke('stroke' in style
  11492. ? style.stroke
  11493. : (!bgColorDrawn
  11494. && (!defaultStyle.autoStroke || useDefaultFill))
  11495. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11496. : null);
  11497. var hasShadow = style.textShadowBlur > 0;
  11498. var fixedBoundingRect = style.width != null
  11499. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11500. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11501. for (var i = 0; i < textLines.length; i++) {
  11502. var el = this._getOrCreateChild(TSpan);
  11503. var subElStyle = el.createStyle();
  11504. el.useStyle(subElStyle);
  11505. subElStyle.text = textLines[i];
  11506. subElStyle.x = textX;
  11507. subElStyle.y = textY;
  11508. if (textAlign) {
  11509. subElStyle.textAlign = textAlign;
  11510. }
  11511. subElStyle.textBaseline = 'middle';
  11512. subElStyle.opacity = style.opacity;
  11513. subElStyle.strokeFirst = true;
  11514. if (hasShadow) {
  11515. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11516. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11517. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11518. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11519. }
  11520. if (textStroke) {
  11521. subElStyle.stroke = textStroke;
  11522. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11523. subElStyle.lineDash = style.lineDash;
  11524. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11525. }
  11526. if (textFill) {
  11527. subElStyle.fill = textFill;
  11528. }
  11529. subElStyle.font = textFont;
  11530. textY += lineHeight;
  11531. if (fixedBoundingRect) {
  11532. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), style.width, calculatedLineHeight));
  11533. }
  11534. }
  11535. };
  11536. ZRText.prototype._updateRichTexts = function () {
  11537. var style = this.style;
  11538. var text = getStyleText(style);
  11539. var contentBlock = parseRichText(text, style);
  11540. var contentWidth = contentBlock.width;
  11541. var outerWidth = contentBlock.outerWidth;
  11542. var outerHeight = contentBlock.outerHeight;
  11543. var textPadding = style.padding;
  11544. var baseX = style.x || 0;
  11545. var baseY = style.y || 0;
  11546. var defaultStyle = this._defaultStyle;
  11547. var textAlign = style.align || defaultStyle.align;
  11548. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11549. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11550. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11551. var xLeft = boxX;
  11552. var lineTop = boxY;
  11553. if (textPadding) {
  11554. xLeft += textPadding[3];
  11555. lineTop += textPadding[0];
  11556. }
  11557. var xRight = xLeft + contentWidth;
  11558. if (needDrawBackground(style)) {
  11559. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11560. }
  11561. var bgColorDrawn = !!(style.backgroundColor);
  11562. for (var i = 0; i < contentBlock.lines.length; i++) {
  11563. var line = contentBlock.lines[i];
  11564. var tokens = line.tokens;
  11565. var tokenCount = tokens.length;
  11566. var lineHeight = line.lineHeight;
  11567. var remainedWidth = line.width;
  11568. var leftIndex = 0;
  11569. var lineXLeft = xLeft;
  11570. var lineXRight = xRight;
  11571. var rightIndex = tokenCount - 1;
  11572. var token = void 0;
  11573. while (leftIndex < tokenCount
  11574. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11575. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11576. remainedWidth -= token.width;
  11577. lineXLeft += token.width;
  11578. leftIndex++;
  11579. }
  11580. while (rightIndex >= 0
  11581. && (token = tokens[rightIndex], token.align === 'right')) {
  11582. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11583. remainedWidth -= token.width;
  11584. lineXRight -= token.width;
  11585. rightIndex--;
  11586. }
  11587. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11588. while (leftIndex <= rightIndex) {
  11589. token = tokens[leftIndex];
  11590. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11591. lineXLeft += token.width;
  11592. leftIndex++;
  11593. }
  11594. lineTop += lineHeight;
  11595. }
  11596. };
  11597. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11598. var tokenStyle = style.rich[token.styleName] || {};
  11599. tokenStyle.text = token.text;
  11600. var verticalAlign = token.verticalAlign;
  11601. var y = lineTop + lineHeight / 2;
  11602. if (verticalAlign === 'top') {
  11603. y = lineTop + token.height / 2;
  11604. }
  11605. else if (verticalAlign === 'bottom') {
  11606. y = lineTop + lineHeight - token.height / 2;
  11607. }
  11608. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11609. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11610. ? x - token.width
  11611. : textAlign === 'center'
  11612. ? x - token.width / 2
  11613. : x, y - token.height / 2, token.width, token.height);
  11614. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11615. var textPadding = token.textPadding;
  11616. if (textPadding) {
  11617. x = getTextXForPadding(x, textAlign, textPadding);
  11618. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11619. }
  11620. var el = this._getOrCreateChild(TSpan);
  11621. var subElStyle = el.createStyle();
  11622. el.useStyle(subElStyle);
  11623. var defaultStyle = this._defaultStyle;
  11624. var useDefaultFill = false;
  11625. var defaultLineWidth = 0;
  11626. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11627. : 'fill' in style ? style.fill
  11628. : (useDefaultFill = true, defaultStyle.fill));
  11629. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11630. : 'stroke' in style ? style.stroke
  11631. : (!bgColorDrawn
  11632. && !parentBgColorDrawn
  11633. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11634. : null);
  11635. var hasShadow = tokenStyle.textShadowBlur > 0
  11636. || style.textShadowBlur > 0;
  11637. subElStyle.text = token.text;
  11638. subElStyle.x = x;
  11639. subElStyle.y = y;
  11640. if (hasShadow) {
  11641. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11642. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11643. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11644. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11645. }
  11646. subElStyle.textAlign = textAlign;
  11647. subElStyle.textBaseline = 'middle';
  11648. subElStyle.font = token.font || DEFAULT_FONT;
  11649. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11650. if (textStroke) {
  11651. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11652. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11653. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11654. subElStyle.stroke = textStroke;
  11655. }
  11656. if (textFill) {
  11657. subElStyle.fill = textFill;
  11658. }
  11659. var textWidth = token.contentWidth;
  11660. var textHeight = token.contentHeight;
  11661. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11662. };
  11663. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11664. var textBackgroundColor = style.backgroundColor;
  11665. var textBorderWidth = style.borderWidth;
  11666. var textBorderColor = style.borderColor;
  11667. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11668. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11669. var textBorderRadius = style.borderRadius;
  11670. var self = this;
  11671. var rectEl;
  11672. var imgEl;
  11673. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11674. rectEl = this._getOrCreateChild(Rect);
  11675. rectEl.useStyle(rectEl.createStyle());
  11676. rectEl.style.fill = null;
  11677. var rectShape = rectEl.shape;
  11678. rectShape.x = x;
  11679. rectShape.y = y;
  11680. rectShape.width = width;
  11681. rectShape.height = height;
  11682. rectShape.r = textBorderRadius;
  11683. rectEl.dirtyShape();
  11684. }
  11685. if (isPlainOrGradientBg) {
  11686. var rectStyle = rectEl.style;
  11687. rectStyle.fill = textBackgroundColor || null;
  11688. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11689. }
  11690. else if (isImageBg) {
  11691. imgEl = this._getOrCreateChild(ZRImage);
  11692. imgEl.onload = function () {
  11693. self.dirtyStyle();
  11694. };
  11695. var imgStyle = imgEl.style;
  11696. imgStyle.image = textBackgroundColor.image;
  11697. imgStyle.x = x;
  11698. imgStyle.y = y;
  11699. imgStyle.width = width;
  11700. imgStyle.height = height;
  11701. }
  11702. if (textBorderWidth && textBorderColor) {
  11703. var rectStyle = rectEl.style;
  11704. rectStyle.lineWidth = textBorderWidth;
  11705. rectStyle.stroke = textBorderColor;
  11706. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11707. rectStyle.lineDash = style.borderDash;
  11708. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11709. rectEl.strokeContainThreshold = 0;
  11710. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11711. rectStyle.strokeFirst = true;
  11712. rectStyle.lineWidth *= 2;
  11713. }
  11714. }
  11715. var commonStyle = (rectEl || imgEl).style;
  11716. commonStyle.shadowBlur = style.shadowBlur || 0;
  11717. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11718. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11719. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11720. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11721. };
  11722. ZRText.makeFont = function (style) {
  11723. var font = '';
  11724. if (style.fontSize || style.fontFamily || style.fontWeight) {
  11725. var fontSize = '';
  11726. if (typeof style.fontSize === 'string'
  11727. && (style.fontSize.indexOf('px') !== -1
  11728. || style.fontSize.indexOf('rem') !== -1
  11729. || style.fontSize.indexOf('em') !== -1)) {
  11730. fontSize = style.fontSize;
  11731. }
  11732. else if (!isNaN(+style.fontSize)) {
  11733. fontSize = style.fontSize + 'px';
  11734. }
  11735. else {
  11736. fontSize = '12px';
  11737. }
  11738. font = [
  11739. style.fontStyle,
  11740. style.fontWeight,
  11741. fontSize,
  11742. style.fontFamily || 'sans-serif'
  11743. ].join(' ');
  11744. }
  11745. return font && trim(font) || style.textFont || style.font;
  11746. };
  11747. return ZRText;
  11748. }(Displayable));
  11749. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11750. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11751. function normalizeTextStyle(style) {
  11752. normalizeStyle(style);
  11753. each(style.rich, normalizeStyle);
  11754. return style;
  11755. }
  11756. function normalizeStyle(style) {
  11757. if (style) {
  11758. style.font = ZRText.makeFont(style);
  11759. var textAlign = style.align;
  11760. textAlign === 'middle' && (textAlign = 'center');
  11761. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11762. var verticalAlign = style.verticalAlign;
  11763. verticalAlign === 'center' && (verticalAlign = 'middle');
  11764. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11765. var textPadding = style.padding;
  11766. if (textPadding) {
  11767. style.padding = normalizeCssArray(style.padding);
  11768. }
  11769. }
  11770. }
  11771. function getStroke(stroke, lineWidth) {
  11772. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11773. ? null
  11774. : (stroke.image || stroke.colorStops)
  11775. ? '#000'
  11776. : stroke;
  11777. }
  11778. function getFill(fill) {
  11779. return (fill == null || fill === 'none')
  11780. ? null
  11781. : (fill.image || fill.colorStops)
  11782. ? '#000'
  11783. : fill;
  11784. }
  11785. function getTextXForPadding(x, textAlign, textPadding) {
  11786. return textAlign === 'right'
  11787. ? (x - textPadding[1])
  11788. : textAlign === 'center'
  11789. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  11790. : (x + textPadding[3]);
  11791. }
  11792. function getStyleText(style) {
  11793. var text = style.text;
  11794. text != null && (text += '');
  11795. return text;
  11796. }
  11797. function needDrawBackground(style) {
  11798. return !!(style.backgroundColor
  11799. || style.lineHeight
  11800. || (style.borderWidth && style.borderColor));
  11801. }
  11802. var getECData = makeInner();
  11803. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  11804. if (el) {
  11805. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  11806. // Useful in tooltip
  11807. ecData.dataIndex = dataIdx;
  11808. ecData.dataType = dataType;
  11809. ecData.seriesIndex = seriesIndex; // TODO: not store dataIndex on children.
  11810. if (el.type === 'group') {
  11811. el.traverse(function (child) {
  11812. var childECData = getECData(child);
  11813. childECData.seriesIndex = seriesIndex;
  11814. childECData.dataIndex = dataIdx;
  11815. childECData.dataType = dataType;
  11816. });
  11817. }
  11818. }
  11819. };
  11820. var _highlightNextDigit = 1;
  11821. var _highlightKeyMap = {};
  11822. var getSavedStates = makeInner();
  11823. var HOVER_STATE_NORMAL = 0;
  11824. var HOVER_STATE_BLUR = 1;
  11825. var HOVER_STATE_EMPHASIS = 2;
  11826. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  11827. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  11828. var Z2_EMPHASIS_LIFT = 10;
  11829. var Z2_SELECT_LIFT = 9;
  11830. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  11831. var DOWNPLAY_ACTION_TYPE = 'downplay';
  11832. var SELECT_ACTION_TYPE = 'select';
  11833. var UNSELECT_ACTION_TYPE = 'unselect';
  11834. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  11835. function hasFillOrStroke(fillOrStroke) {
  11836. return fillOrStroke != null && fillOrStroke !== 'none';
  11837. } // Most lifted color are duplicated.
  11838. var liftedColorCache = new LRU(100);
  11839. function liftColor(color$1) {
  11840. if (typeof color$1 !== 'string') {
  11841. return color$1;
  11842. }
  11843. var liftedColor = liftedColorCache.get(color$1);
  11844. if (!liftedColor) {
  11845. liftedColor = lift(color$1, -0.1);
  11846. liftedColorCache.put(color$1, liftedColor);
  11847. }
  11848. return liftedColor;
  11849. }
  11850. function doChangeHoverState(el, stateName, hoverStateEnum) {
  11851. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  11852. el.onHoverStateChange(stateName);
  11853. }
  11854. el.hoverState = hoverStateEnum;
  11855. }
  11856. function singleEnterEmphasis(el) {
  11857. // Only mark the flag.
  11858. // States will be applied in the echarts.ts in next frame.
  11859. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  11860. }
  11861. function singleLeaveEmphasis(el) {
  11862. // Only mark the flag.
  11863. // States will be applied in the echarts.ts in next frame.
  11864. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  11865. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11866. }
  11867. }
  11868. function singleEnterBlur(el) {
  11869. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  11870. }
  11871. function singleLeaveBlur(el) {
  11872. if (el.hoverState === HOVER_STATE_BLUR) {
  11873. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11874. }
  11875. }
  11876. function singleEnterSelect(el) {
  11877. el.selected = true;
  11878. }
  11879. function singleLeaveSelect(el) {
  11880. el.selected = false;
  11881. }
  11882. function updateElementState(el, updater, commonParam) {
  11883. updater(el, commonParam);
  11884. }
  11885. function traverseUpdateState(el, updater, commonParam) {
  11886. updateElementState(el, updater, commonParam);
  11887. el.isGroup && el.traverse(function (child) {
  11888. updateElementState(child, updater, commonParam);
  11889. });
  11890. }
  11891. function setStatesFlag(el, stateName) {
  11892. switch (stateName) {
  11893. case 'emphasis':
  11894. el.hoverState = HOVER_STATE_EMPHASIS;
  11895. break;
  11896. case 'normal':
  11897. el.hoverState = HOVER_STATE_NORMAL;
  11898. break;
  11899. case 'blur':
  11900. el.hoverState = HOVER_STATE_BLUR;
  11901. break;
  11902. case 'select':
  11903. el.selected = true;
  11904. }
  11905. }
  11906. function getFromStateStyle(el, props, toStateName, defaultValue) {
  11907. var style = el.style;
  11908. var fromState = {};
  11909. for (var i = 0; i < props.length; i++) {
  11910. var propName = props[i];
  11911. var val = style[propName];
  11912. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  11913. }
  11914. for (var i = 0; i < el.animators.length; i++) {
  11915. var animator = el.animators[i];
  11916. if (animator.__fromStateTransition // Dont consider the animation to emphasis state.
  11917. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  11918. animator.saveFinalToTarget(fromState, props);
  11919. }
  11920. }
  11921. return fromState;
  11922. }
  11923. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  11924. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  11925. var cloned = false;
  11926. if (el instanceof Path) {
  11927. var store = getSavedStates(el);
  11928. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  11929. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  11930. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  11931. state = state || {};
  11932. var emphasisStyle = state.style || {}; // inherit case
  11933. if (emphasisStyle.fill === 'inherit') {
  11934. cloned = true;
  11935. state = extend({}, state);
  11936. emphasisStyle = extend({}, emphasisStyle);
  11937. emphasisStyle.fill = fromFill;
  11938. } // Apply default color lift
  11939. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  11940. cloned = true; // Not modify the original value.
  11941. state = extend({}, state);
  11942. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  11943. emphasisStyle.fill = liftColor(fromFill);
  11944. } // Not highlight stroke if fill has been highlighted.
  11945. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  11946. if (!cloned) {
  11947. state = extend({}, state);
  11948. emphasisStyle = extend({}, emphasisStyle);
  11949. }
  11950. emphasisStyle.stroke = liftColor(fromStroke);
  11951. }
  11952. state.style = emphasisStyle;
  11953. }
  11954. }
  11955. if (state) {
  11956. // TODO Share with textContent?
  11957. if (state.z2 == null) {
  11958. if (!cloned) {
  11959. state = extend({}, state);
  11960. }
  11961. var z2EmphasisLift = el.z2EmphasisLift;
  11962. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  11963. }
  11964. }
  11965. return state;
  11966. }
  11967. function createSelectDefaultState(el, stateName, state) {
  11968. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  11969. if (state) {
  11970. // TODO Share with textContent?
  11971. if (state.z2 == null) {
  11972. state = extend({}, state);
  11973. var z2SelectLift = el.z2SelectLift;
  11974. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  11975. }
  11976. }
  11977. return state;
  11978. }
  11979. function createBlurDefaultState(el, stateName, state) {
  11980. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  11981. var currentOpacity = el.style.opacity;
  11982. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  11983. opacity: 1
  11984. }) : null;
  11985. state = state || {};
  11986. var blurStyle = state.style || {};
  11987. if (blurStyle.opacity == null) {
  11988. // clone state
  11989. state = extend({}, state);
  11990. blurStyle = extend({
  11991. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  11992. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  11993. }, blurStyle);
  11994. state.style = blurStyle;
  11995. }
  11996. return state;
  11997. }
  11998. function elementStateProxy(stateName, targetStates) {
  11999. var state = this.states[stateName];
  12000. if (this.style) {
  12001. if (stateName === 'emphasis') {
  12002. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12003. } else if (stateName === 'blur') {
  12004. return createBlurDefaultState(this, stateName, state);
  12005. } else if (stateName === 'select') {
  12006. return createSelectDefaultState(this, stateName, state);
  12007. }
  12008. }
  12009. return state;
  12010. }
  12011. /**FI
  12012. * Set hover style (namely "emphasis style") of element.
  12013. * @param el Should not be `zrender/graphic/Group`.
  12014. * @param focus 'self' | 'selfInSeries' | 'series'
  12015. */
  12016. function setDefaultStateProxy(el) {
  12017. el.stateProxy = elementStateProxy;
  12018. var textContent = el.getTextContent();
  12019. var textGuide = el.getTextGuideLine();
  12020. if (textContent) {
  12021. textContent.stateProxy = elementStateProxy;
  12022. }
  12023. if (textGuide) {
  12024. textGuide.stateProxy = elementStateProxy;
  12025. }
  12026. }
  12027. function enterEmphasisWhenMouseOver(el, e) {
  12028. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12029. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12030. }
  12031. function leaveEmphasisWhenMouseOut(el, e) {
  12032. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12033. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12034. }
  12035. function enterEmphasis(el, highlightDigit) {
  12036. el.__highByOuter |= 1 << (highlightDigit || 0);
  12037. traverseUpdateState(el, singleEnterEmphasis);
  12038. }
  12039. function leaveEmphasis(el, highlightDigit) {
  12040. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12041. }
  12042. function enterBlur(el) {
  12043. traverseUpdateState(el, singleEnterBlur);
  12044. }
  12045. function leaveBlur(el) {
  12046. traverseUpdateState(el, singleLeaveBlur);
  12047. }
  12048. function enterSelect(el) {
  12049. traverseUpdateState(el, singleEnterSelect);
  12050. }
  12051. function leaveSelect(el) {
  12052. traverseUpdateState(el, singleLeaveSelect);
  12053. }
  12054. function shouldSilent(el, e) {
  12055. return el.__highDownSilentOnTouch && e.zrByTouch;
  12056. }
  12057. function allLeaveBlur(api) {
  12058. var model = api.getModel();
  12059. model.eachComponent(function (componentType, componentModel) {
  12060. var view = componentType === 'series' ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel); // Leave blur anyway
  12061. view.group.traverse(function (child) {
  12062. singleLeaveBlur(child);
  12063. });
  12064. });
  12065. }
  12066. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12067. var ecModel = api.getModel();
  12068. blurScope = blurScope || 'coordinateSystem';
  12069. function leaveBlurOfIndices(data, dataIndices) {
  12070. for (var i = 0; i < dataIndices.length; i++) {
  12071. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12072. itemEl && leaveBlur(itemEl);
  12073. }
  12074. }
  12075. if (targetSeriesIndex == null) {
  12076. return;
  12077. }
  12078. if (!focus || focus === 'none') {
  12079. return;
  12080. }
  12081. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12082. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12083. if (targetCoordSys && targetCoordSys.master) {
  12084. targetCoordSys = targetCoordSys.master;
  12085. }
  12086. var blurredSeries = [];
  12087. ecModel.eachSeries(function (seriesModel) {
  12088. var sameSeries = targetSeriesModel === seriesModel;
  12089. var coordSys = seriesModel.coordinateSystem;
  12090. if (coordSys && coordSys.master) {
  12091. coordSys = coordSys.master;
  12092. }
  12093. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12094. if (!( // Not blur other series if blurScope series
  12095. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  12096. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  12097. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  12098. )) {
  12099. var view = api.getViewOfSeriesModel(seriesModel);
  12100. view.group.traverse(function (child) {
  12101. singleEnterBlur(child);
  12102. });
  12103. if (isArrayLike(focus)) {
  12104. leaveBlurOfIndices(seriesModel.getData(), focus);
  12105. } else if (isObject(focus)) {
  12106. var dataTypes = keys(focus);
  12107. for (var d = 0; d < dataTypes.length; d++) {
  12108. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12109. }
  12110. }
  12111. blurredSeries.push(seriesModel);
  12112. }
  12113. });
  12114. ecModel.eachComponent(function (componentType, componentModel) {
  12115. if (componentType === 'series') {
  12116. return;
  12117. }
  12118. var view = api.getViewOfComponentModel(componentModel);
  12119. if (view && view.blurSeries) {
  12120. view.blurSeries(blurredSeries, ecModel);
  12121. }
  12122. });
  12123. }
  12124. function blurComponent(componentMainType, componentIndex, api) {
  12125. if (componentMainType == null || componentIndex == null) {
  12126. return;
  12127. }
  12128. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12129. if (!componentModel) {
  12130. return;
  12131. }
  12132. var view = api.getViewOfComponentModel(componentModel);
  12133. if (!view || !view.focusBlurEnabled) {
  12134. return;
  12135. }
  12136. view.group.traverse(function (child) {
  12137. singleEnterBlur(child);
  12138. });
  12139. }
  12140. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12141. var seriesIndex = seriesModel.seriesIndex;
  12142. var data = seriesModel.getData(payload.dataType);
  12143. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  12144. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12145. var el = data.getItemGraphicEl(dataIndex);
  12146. if (!el) {
  12147. var count = data.count();
  12148. var current = 0; // If data on dataIndex is NaN.
  12149. while (!el && current < count) {
  12150. el = data.getItemGraphicEl(current++);
  12151. }
  12152. }
  12153. if (el) {
  12154. var ecData = getECData(el);
  12155. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12156. } else {
  12157. // If there is no element put on the data. Try getting it from raw option
  12158. // TODO Should put it on seriesModel?
  12159. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12160. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12161. if (focus_1 != null) {
  12162. blurSeries(seriesIndex, focus_1, blurScope, api);
  12163. }
  12164. }
  12165. }
  12166. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12167. var ret = {
  12168. focusSelf: false,
  12169. dispatchers: null
  12170. };
  12171. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12172. return ret;
  12173. }
  12174. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12175. if (!componentModel) {
  12176. return ret;
  12177. }
  12178. var view = api.getViewOfComponentModel(componentModel);
  12179. if (!view || !view.findHighDownDispatchers) {
  12180. return ret;
  12181. }
  12182. var dispatchers = view.findHighDownDispatchers(name); // At presnet, the component (like Geo) only blur inside itself.
  12183. // So we do not use `blurScope` in component.
  12184. var focusSelf;
  12185. for (var i = 0; i < dispatchers.length; i++) {
  12186. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12187. error('param should be highDownDispatcher');
  12188. }
  12189. if (getECData(dispatchers[i]).focus === 'self') {
  12190. focusSelf = true;
  12191. break;
  12192. }
  12193. }
  12194. return {
  12195. focusSelf: focusSelf,
  12196. dispatchers: dispatchers
  12197. };
  12198. }
  12199. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12200. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12201. error('param should be highDownDispatcher');
  12202. }
  12203. var ecData = getECData(dispatcher);
  12204. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12205. dispatchers = _a.dispatchers,
  12206. focusSelf = _a.focusSelf; // If `findHighDownDispatchers` is supported on the component,
  12207. // highlight/downplay elements with the same name.
  12208. if (dispatchers) {
  12209. if (focusSelf) {
  12210. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12211. }
  12212. each(dispatchers, function (dispatcher) {
  12213. return enterEmphasisWhenMouseOver(dispatcher, e);
  12214. });
  12215. } else {
  12216. // Try blur all in the related series. Then emphasis the hoverred.
  12217. // TODO. progressive mode.
  12218. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12219. if (ecData.focus === 'self') {
  12220. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12221. } // Other than series, component that not support `findHighDownDispatcher` will
  12222. // also use it. But in this case, highlight/downplay are only supported in
  12223. // mouse hover but not in dispatchAction.
  12224. enterEmphasisWhenMouseOver(dispatcher, e);
  12225. }
  12226. }
  12227. function handleGlboalMouseOutForHighDown(dispatcher, e, api) {
  12228. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12229. error('param should be highDownDispatcher');
  12230. }
  12231. allLeaveBlur(api);
  12232. var ecData = getECData(dispatcher);
  12233. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12234. if (dispatchers) {
  12235. each(dispatchers, function (dispatcher) {
  12236. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12237. });
  12238. } else {
  12239. leaveEmphasisWhenMouseOut(dispatcher, e);
  12240. }
  12241. }
  12242. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12243. if (!isSelectChangePayload(payload)) {
  12244. return;
  12245. }
  12246. var dataType = payload.dataType;
  12247. var data = seriesModel.getData(dataType);
  12248. var dataIndex = queryDataIndex(data, payload);
  12249. if (!isArray(dataIndex)) {
  12250. dataIndex = [dataIndex];
  12251. }
  12252. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12253. }
  12254. function updateSeriesElementSelection(seriesModel) {
  12255. var allData = seriesModel.getAllData();
  12256. each(allData, function (_a) {
  12257. var data = _a.data,
  12258. type = _a.type;
  12259. data.eachItemGraphicEl(function (el, idx) {
  12260. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12261. });
  12262. });
  12263. }
  12264. function getAllSelectedIndices(ecModel) {
  12265. var ret = [];
  12266. ecModel.eachSeries(function (seriesModel) {
  12267. var allData = seriesModel.getAllData();
  12268. each(allData, function (_a) {
  12269. var data = _a.data,
  12270. type = _a.type;
  12271. var dataIndices = seriesModel.getSelectedDataIndices();
  12272. if (dataIndices.length > 0) {
  12273. var item = {
  12274. dataIndex: dataIndices,
  12275. seriesIndex: seriesModel.seriesIndex
  12276. };
  12277. if (type != null) {
  12278. item.dataType = type;
  12279. }
  12280. ret.push(item);
  12281. }
  12282. });
  12283. });
  12284. return ret;
  12285. }
  12286. /**
  12287. * Enable the function that mouseover will trigger the emphasis state.
  12288. *
  12289. * NOTE:
  12290. * This function should be used on the element with dataIndex, seriesIndex.
  12291. *
  12292. */
  12293. function enableHoverEmphasis(el, focus, blurScope) {
  12294. setAsHighDownDispatcher(el, true);
  12295. traverseUpdateState(el, setDefaultStateProxy);
  12296. enableHoverFocus(el, focus, blurScope);
  12297. }
  12298. function enableHoverFocus(el, focus, blurScope) {
  12299. var ecData = getECData(el);
  12300. if (focus != null) {
  12301. // TODO dataIndex may be set after this function. This check is not useful.
  12302. // if (ecData.dataIndex == null) {
  12303. // if (__DEV__) {
  12304. // console.warn('focus can only been set on element with dataIndex');
  12305. // }
  12306. // }
  12307. // else {
  12308. ecData.focus = focus;
  12309. ecData.blurScope = blurScope; // }
  12310. } else if (ecData.focus) {
  12311. ecData.focus = null;
  12312. }
  12313. }
  12314. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12315. var defaultStyleGetterMap = {
  12316. itemStyle: 'getItemStyle',
  12317. lineStyle: 'getLineStyle',
  12318. areaStyle: 'getAreaStyle'
  12319. };
  12320. /**
  12321. * Set emphasis/blur/selected states of element.
  12322. */
  12323. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  12324. getter) {
  12325. styleType = styleType || 'itemStyle';
  12326. for (var i = 0; i < OTHER_STATES.length; i++) {
  12327. var stateName = OTHER_STATES[i];
  12328. var model = itemModel.getModel([stateName, styleType]);
  12329. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12330. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12331. }
  12332. }
  12333. /**
  12334. * @parame el
  12335. * @param el.highDownSilentOnTouch
  12336. * In touch device, mouseover event will be trigger on touchstart event
  12337. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12338. * conveniently use hoverStyle when tap on touch screen without additional
  12339. * code for compatibility.
  12340. * But if the chart/component has select feature, which usually also use
  12341. * hoverStyle, there might be conflict between 'select-highlight' and
  12342. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12343. * In this case, `highDownSilentOnTouch` should be used to disable
  12344. * hover-highlight on touch device.
  12345. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12346. */
  12347. function setAsHighDownDispatcher(el, asDispatcher) {
  12348. var disable = asDispatcher === false;
  12349. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12350. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12351. if (el.highDownSilentOnTouch) {
  12352. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12353. } // Simple optimize, since this method might be
  12354. // called for each elements of a group in some cases.
  12355. if (!disable || extendedEl.__highDownDispatcher) {
  12356. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12357. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12358. // Also keep previous record.
  12359. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12360. extendedEl.__highDownDispatcher = !disable;
  12361. }
  12362. }
  12363. function isHighDownDispatcher(el) {
  12364. return !!(el && el.__highDownDispatcher);
  12365. }
  12366. /**
  12367. * Enable component highlight/downplay features:
  12368. * + hover link (within the same name)
  12369. * + focus blur in component
  12370. */
  12371. function enableComponentHighDownFeatures(el, componentModel, componentHighDownName) {
  12372. var ecData = getECData(el);
  12373. ecData.componentMainType = componentModel.mainType;
  12374. ecData.componentIndex = componentModel.componentIndex;
  12375. ecData.componentHighDownName = componentHighDownName;
  12376. }
  12377. /**
  12378. * Support hightlight/downplay record on each elements.
  12379. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12380. * user triggerred hightlight/downplay should not conflict.
  12381. * Only all of the highlightDigit cleared, return to normal.
  12382. * @param {string} highlightKey
  12383. * @return {number} highlightDigit
  12384. */
  12385. function getHighlightDigit(highlightKey) {
  12386. var highlightDigit = _highlightKeyMap[highlightKey];
  12387. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12388. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12389. }
  12390. return highlightDigit;
  12391. }
  12392. function isSelectChangePayload(payload) {
  12393. var payloadType = payload.type;
  12394. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12395. }
  12396. function isHighDownPayload(payload) {
  12397. var payloadType = payload.type;
  12398. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12399. }
  12400. function savePathStates(el) {
  12401. var store = getSavedStates(el);
  12402. store.normalFill = el.style.fill;
  12403. store.normalStroke = el.style.stroke;
  12404. var selectState = el.states.select || {};
  12405. store.selectFill = selectState.style && selectState.style.fill || null;
  12406. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12407. }
  12408. var CMD$2 = PathProxy.CMD;
  12409. var points = [[], [], []];
  12410. var mathSqrt$2 = Math.sqrt;
  12411. var mathAtan2 = Math.atan2;
  12412. function transformPath(path, m) {
  12413. if (!m) {
  12414. return;
  12415. }
  12416. var data = path.data;
  12417. var len = path.len();
  12418. var cmd;
  12419. var nPoint;
  12420. var i;
  12421. var j;
  12422. var k;
  12423. var p;
  12424. var M = CMD$2.M;
  12425. var C = CMD$2.C;
  12426. var L = CMD$2.L;
  12427. var R = CMD$2.R;
  12428. var A = CMD$2.A;
  12429. var Q = CMD$2.Q;
  12430. for (i = 0, j = 0; i < len;) {
  12431. cmd = data[i++];
  12432. j = i;
  12433. nPoint = 0;
  12434. switch (cmd) {
  12435. case M:
  12436. nPoint = 1;
  12437. break;
  12438. case L:
  12439. nPoint = 1;
  12440. break;
  12441. case C:
  12442. nPoint = 3;
  12443. break;
  12444. case Q:
  12445. nPoint = 2;
  12446. break;
  12447. case A:
  12448. var x = m[4];
  12449. var y = m[5];
  12450. var sx = mathSqrt$2(m[0] * m[0] + m[1] * m[1]);
  12451. var sy = mathSqrt$2(m[2] * m[2] + m[3] * m[3]);
  12452. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12453. data[i] *= sx;
  12454. data[i++] += x;
  12455. data[i] *= sy;
  12456. data[i++] += y;
  12457. data[i++] *= sx;
  12458. data[i++] *= sy;
  12459. data[i++] += angle;
  12460. data[i++] += angle;
  12461. i += 2;
  12462. j = i;
  12463. break;
  12464. case R:
  12465. p[0] = data[i++];
  12466. p[1] = data[i++];
  12467. applyTransform(p, p, m);
  12468. data[j++] = p[0];
  12469. data[j++] = p[1];
  12470. p[0] += data[i++];
  12471. p[1] += data[i++];
  12472. applyTransform(p, p, m);
  12473. data[j++] = p[0];
  12474. data[j++] = p[1];
  12475. }
  12476. for (k = 0; k < nPoint; k++) {
  12477. var p_1 = points[k];
  12478. p_1[0] = data[i++];
  12479. p_1[1] = data[i++];
  12480. applyTransform(p_1, p_1, m);
  12481. data[j++] = p_1[0];
  12482. data[j++] = p_1[1];
  12483. }
  12484. }
  12485. path.increaseVersion();
  12486. }
  12487. var mathSqrt$3 = Math.sqrt;
  12488. var mathSin$2 = Math.sin;
  12489. var mathCos$2 = Math.cos;
  12490. var PI$1 = Math.PI;
  12491. function vMag(v) {
  12492. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12493. }
  12494. function vRatio(u, v) {
  12495. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12496. }
  12497. function vAngle(u, v) {
  12498. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12499. * Math.acos(vRatio(u, v));
  12500. }
  12501. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12502. var psi = psiDeg * (PI$1 / 180.0);
  12503. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12504. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12505. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12506. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12507. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12508. if (lambda > 1) {
  12509. rx *= mathSqrt$3(lambda);
  12510. ry *= mathSqrt$3(lambda);
  12511. }
  12512. var f = (fa === fs ? -1 : 1)
  12513. * mathSqrt$3((((rx * rx) * (ry * ry))
  12514. - ((rx * rx) * (yp * yp))
  12515. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12516. + (ry * ry) * (xp * xp))) || 0;
  12517. var cxp = f * rx * yp / ry;
  12518. var cyp = f * -ry * xp / rx;
  12519. var cx = (x1 + x2) / 2.0
  12520. + mathCos$2(psi) * cxp
  12521. - mathSin$2(psi) * cyp;
  12522. var cy = (y1 + y2) / 2.0
  12523. + mathSin$2(psi) * cxp
  12524. + mathCos$2(psi) * cyp;
  12525. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12526. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12527. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12528. var dTheta = vAngle(u, v);
  12529. if (vRatio(u, v) <= -1) {
  12530. dTheta = PI$1;
  12531. }
  12532. if (vRatio(u, v) >= 1) {
  12533. dTheta = 0;
  12534. }
  12535. if (dTheta < 0) {
  12536. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12537. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12538. }
  12539. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12540. }
  12541. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12542. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12543. function createPathProxyFromString(data) {
  12544. var path = new PathProxy();
  12545. if (!data) {
  12546. return path;
  12547. }
  12548. var cpx = 0;
  12549. var cpy = 0;
  12550. var subpathX = cpx;
  12551. var subpathY = cpy;
  12552. var prevCmd;
  12553. var CMD = PathProxy.CMD;
  12554. var cmdList = data.match(commandReg);
  12555. if (!cmdList) {
  12556. return path;
  12557. }
  12558. for (var l = 0; l < cmdList.length; l++) {
  12559. var cmdText = cmdList[l];
  12560. var cmdStr = cmdText.charAt(0);
  12561. var cmd = void 0;
  12562. var p = cmdText.match(numberReg) || [];
  12563. var pLen = p.length;
  12564. for (var i = 0; i < pLen; i++) {
  12565. p[i] = parseFloat(p[i]);
  12566. }
  12567. var off = 0;
  12568. while (off < pLen) {
  12569. var ctlPtx = void 0;
  12570. var ctlPty = void 0;
  12571. var rx = void 0;
  12572. var ry = void 0;
  12573. var psi = void 0;
  12574. var fa = void 0;
  12575. var fs = void 0;
  12576. var x1 = cpx;
  12577. var y1 = cpy;
  12578. var len = void 0;
  12579. var pathData = void 0;
  12580. switch (cmdStr) {
  12581. case 'l':
  12582. cpx += p[off++];
  12583. cpy += p[off++];
  12584. cmd = CMD.L;
  12585. path.addData(cmd, cpx, cpy);
  12586. break;
  12587. case 'L':
  12588. cpx = p[off++];
  12589. cpy = p[off++];
  12590. cmd = CMD.L;
  12591. path.addData(cmd, cpx, cpy);
  12592. break;
  12593. case 'm':
  12594. cpx += p[off++];
  12595. cpy += p[off++];
  12596. cmd = CMD.M;
  12597. path.addData(cmd, cpx, cpy);
  12598. subpathX = cpx;
  12599. subpathY = cpy;
  12600. cmdStr = 'l';
  12601. break;
  12602. case 'M':
  12603. cpx = p[off++];
  12604. cpy = p[off++];
  12605. cmd = CMD.M;
  12606. path.addData(cmd, cpx, cpy);
  12607. subpathX = cpx;
  12608. subpathY = cpy;
  12609. cmdStr = 'L';
  12610. break;
  12611. case 'h':
  12612. cpx += p[off++];
  12613. cmd = CMD.L;
  12614. path.addData(cmd, cpx, cpy);
  12615. break;
  12616. case 'H':
  12617. cpx = p[off++];
  12618. cmd = CMD.L;
  12619. path.addData(cmd, cpx, cpy);
  12620. break;
  12621. case 'v':
  12622. cpy += p[off++];
  12623. cmd = CMD.L;
  12624. path.addData(cmd, cpx, cpy);
  12625. break;
  12626. case 'V':
  12627. cpy = p[off++];
  12628. cmd = CMD.L;
  12629. path.addData(cmd, cpx, cpy);
  12630. break;
  12631. case 'C':
  12632. cmd = CMD.C;
  12633. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12634. cpx = p[off - 2];
  12635. cpy = p[off - 1];
  12636. break;
  12637. case 'c':
  12638. cmd = CMD.C;
  12639. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12640. cpx += p[off - 2];
  12641. cpy += p[off - 1];
  12642. break;
  12643. case 'S':
  12644. ctlPtx = cpx;
  12645. ctlPty = cpy;
  12646. len = path.len();
  12647. pathData = path.data;
  12648. if (prevCmd === CMD.C) {
  12649. ctlPtx += cpx - pathData[len - 4];
  12650. ctlPty += cpy - pathData[len - 3];
  12651. }
  12652. cmd = CMD.C;
  12653. x1 = p[off++];
  12654. y1 = p[off++];
  12655. cpx = p[off++];
  12656. cpy = p[off++];
  12657. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12658. break;
  12659. case 's':
  12660. ctlPtx = cpx;
  12661. ctlPty = cpy;
  12662. len = path.len();
  12663. pathData = path.data;
  12664. if (prevCmd === CMD.C) {
  12665. ctlPtx += cpx - pathData[len - 4];
  12666. ctlPty += cpy - pathData[len - 3];
  12667. }
  12668. cmd = CMD.C;
  12669. x1 = cpx + p[off++];
  12670. y1 = cpy + p[off++];
  12671. cpx += p[off++];
  12672. cpy += p[off++];
  12673. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12674. break;
  12675. case 'Q':
  12676. x1 = p[off++];
  12677. y1 = p[off++];
  12678. cpx = p[off++];
  12679. cpy = p[off++];
  12680. cmd = CMD.Q;
  12681. path.addData(cmd, x1, y1, cpx, cpy);
  12682. break;
  12683. case 'q':
  12684. x1 = p[off++] + cpx;
  12685. y1 = p[off++] + cpy;
  12686. cpx += p[off++];
  12687. cpy += p[off++];
  12688. cmd = CMD.Q;
  12689. path.addData(cmd, x1, y1, cpx, cpy);
  12690. break;
  12691. case 'T':
  12692. ctlPtx = cpx;
  12693. ctlPty = cpy;
  12694. len = path.len();
  12695. pathData = path.data;
  12696. if (prevCmd === CMD.Q) {
  12697. ctlPtx += cpx - pathData[len - 4];
  12698. ctlPty += cpy - pathData[len - 3];
  12699. }
  12700. cpx = p[off++];
  12701. cpy = p[off++];
  12702. cmd = CMD.Q;
  12703. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12704. break;
  12705. case 't':
  12706. ctlPtx = cpx;
  12707. ctlPty = cpy;
  12708. len = path.len();
  12709. pathData = path.data;
  12710. if (prevCmd === CMD.Q) {
  12711. ctlPtx += cpx - pathData[len - 4];
  12712. ctlPty += cpy - pathData[len - 3];
  12713. }
  12714. cpx += p[off++];
  12715. cpy += p[off++];
  12716. cmd = CMD.Q;
  12717. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12718. break;
  12719. case 'A':
  12720. rx = p[off++];
  12721. ry = p[off++];
  12722. psi = p[off++];
  12723. fa = p[off++];
  12724. fs = p[off++];
  12725. x1 = cpx, y1 = cpy;
  12726. cpx = p[off++];
  12727. cpy = p[off++];
  12728. cmd = CMD.A;
  12729. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12730. break;
  12731. case 'a':
  12732. rx = p[off++];
  12733. ry = p[off++];
  12734. psi = p[off++];
  12735. fa = p[off++];
  12736. fs = p[off++];
  12737. x1 = cpx, y1 = cpy;
  12738. cpx += p[off++];
  12739. cpy += p[off++];
  12740. cmd = CMD.A;
  12741. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12742. break;
  12743. }
  12744. }
  12745. if (cmdStr === 'z' || cmdStr === 'Z') {
  12746. cmd = CMD.Z;
  12747. path.addData(cmd);
  12748. cpx = subpathX;
  12749. cpy = subpathY;
  12750. }
  12751. prevCmd = cmd;
  12752. }
  12753. path.toStatic();
  12754. return path;
  12755. }
  12756. var SVGPath = (function (_super) {
  12757. __extends(SVGPath, _super);
  12758. function SVGPath() {
  12759. return _super !== null && _super.apply(this, arguments) || this;
  12760. }
  12761. SVGPath.prototype.applyTransform = function (m) { };
  12762. return SVGPath;
  12763. }(Path));
  12764. function isPathProxy(path) {
  12765. return path.setData != null;
  12766. }
  12767. function createPathOptions(str, opts) {
  12768. var pathProxy = createPathProxyFromString(str);
  12769. var innerOpts = extend({}, opts);
  12770. innerOpts.buildPath = function (path) {
  12771. if (isPathProxy(path)) {
  12772. path.setData(pathProxy.data);
  12773. var ctx = path.getContext();
  12774. if (ctx) {
  12775. path.rebuildPath(ctx, 1);
  12776. }
  12777. }
  12778. else {
  12779. var ctx = path;
  12780. pathProxy.rebuildPath(ctx, 1);
  12781. }
  12782. };
  12783. innerOpts.applyTransform = function (m) {
  12784. transformPath(pathProxy, m);
  12785. this.dirtyShape();
  12786. };
  12787. return innerOpts;
  12788. }
  12789. function createFromString(str, opts) {
  12790. return new SVGPath(createPathOptions(str, opts));
  12791. }
  12792. function extendFromString(str, defaultOpts) {
  12793. var innerOpts = createPathOptions(str, defaultOpts);
  12794. var Sub = (function (_super) {
  12795. __extends(Sub, _super);
  12796. function Sub(opts) {
  12797. var _this = _super.call(this, opts) || this;
  12798. _this.applyTransform = innerOpts.applyTransform;
  12799. _this.buildPath = innerOpts.buildPath;
  12800. return _this;
  12801. }
  12802. return Sub;
  12803. }(SVGPath));
  12804. return Sub;
  12805. }
  12806. function mergePath(pathEls, opts) {
  12807. var pathList = [];
  12808. var len = pathEls.length;
  12809. for (var i = 0; i < len; i++) {
  12810. var pathEl = pathEls[i];
  12811. pathList.push(pathEl.getUpdatedPathProxy(true));
  12812. }
  12813. var pathBundle = new Path(opts);
  12814. pathBundle.createPathProxy();
  12815. pathBundle.buildPath = function (path) {
  12816. if (isPathProxy(path)) {
  12817. path.appendPath(pathList);
  12818. var ctx = path.getContext();
  12819. if (ctx) {
  12820. path.rebuildPath(ctx, 1);
  12821. }
  12822. }
  12823. };
  12824. return pathBundle;
  12825. }
  12826. function clonePath(sourcePath, opts) {
  12827. opts = opts || {};
  12828. var path = new Path();
  12829. if (sourcePath.shape) {
  12830. path.setShape(sourcePath.shape);
  12831. }
  12832. path.setStyle(sourcePath.style);
  12833. if (opts.bakeTransform) {
  12834. transformPath(path.path, sourcePath.getComputedTransform());
  12835. }
  12836. else {
  12837. if (opts.toLocal) {
  12838. path.setLocalTransform(sourcePath.getComputedTransform());
  12839. }
  12840. else {
  12841. path.copyTransform(sourcePath);
  12842. }
  12843. }
  12844. path.buildPath = sourcePath.buildPath;
  12845. path.applyTransform = path.applyTransform;
  12846. path.z = sourcePath.z;
  12847. path.z2 = sourcePath.z2;
  12848. path.zlevel = sourcePath.zlevel;
  12849. return path;
  12850. }
  12851. var CircleShape = (function () {
  12852. function CircleShape() {
  12853. this.cx = 0;
  12854. this.cy = 0;
  12855. this.r = 0;
  12856. }
  12857. return CircleShape;
  12858. }());
  12859. var Circle = (function (_super) {
  12860. __extends(Circle, _super);
  12861. function Circle(opts) {
  12862. return _super.call(this, opts) || this;
  12863. }
  12864. Circle.prototype.getDefaultShape = function () {
  12865. return new CircleShape();
  12866. };
  12867. Circle.prototype.buildPath = function (ctx, shape, inBundle) {
  12868. if (inBundle) {
  12869. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12870. }
  12871. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  12872. };
  12873. return Circle;
  12874. }(Path));
  12875. Circle.prototype.type = 'circle';
  12876. var EllipseShape = (function () {
  12877. function EllipseShape() {
  12878. this.cx = 0;
  12879. this.cy = 0;
  12880. this.rx = 0;
  12881. this.ry = 0;
  12882. }
  12883. return EllipseShape;
  12884. }());
  12885. var Ellipse = (function (_super) {
  12886. __extends(Ellipse, _super);
  12887. function Ellipse(opts) {
  12888. return _super.call(this, opts) || this;
  12889. }
  12890. Ellipse.prototype.getDefaultShape = function () {
  12891. return new EllipseShape();
  12892. };
  12893. Ellipse.prototype.buildPath = function (ctx, shape) {
  12894. var k = 0.5522848;
  12895. var x = shape.cx;
  12896. var y = shape.cy;
  12897. var a = shape.rx;
  12898. var b = shape.ry;
  12899. var ox = a * k;
  12900. var oy = b * k;
  12901. ctx.moveTo(x - a, y);
  12902. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  12903. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  12904. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  12905. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  12906. ctx.closePath();
  12907. };
  12908. return Ellipse;
  12909. }(Path));
  12910. Ellipse.prototype.type = 'ellipse';
  12911. var PI$2 = Math.PI;
  12912. var PI2$5 = PI$2 * 2;
  12913. var mathSin$3 = Math.sin;
  12914. var mathCos$3 = Math.cos;
  12915. var mathACos = Math.acos;
  12916. var mathATan2 = Math.atan2;
  12917. var mathAbs$1 = Math.abs;
  12918. var mathSqrt$4 = Math.sqrt;
  12919. var mathMax$3 = Math.max;
  12920. var mathMin$3 = Math.min;
  12921. var e = 1e-4;
  12922. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  12923. var x10 = x1 - x0;
  12924. var y10 = y1 - y0;
  12925. var x32 = x3 - x2;
  12926. var y32 = y3 - y2;
  12927. var t = y32 * x10 - x32 * y10;
  12928. if (t * t < e) {
  12929. return;
  12930. }
  12931. t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
  12932. return [x0 + t * x10, y0 + t * y10];
  12933. }
  12934. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  12935. var x01 = x0 - x1;
  12936. var y01 = y0 - y1;
  12937. var lo = (clockwise ? cr : -cr) / mathSqrt$4(x01 * x01 + y01 * y01);
  12938. var ox = lo * y01;
  12939. var oy = -lo * x01;
  12940. var x11 = x0 + ox;
  12941. var y11 = y0 + oy;
  12942. var x10 = x1 + ox;
  12943. var y10 = y1 + oy;
  12944. var x00 = (x11 + x10) / 2;
  12945. var y00 = (y11 + y10) / 2;
  12946. var dx = x10 - x11;
  12947. var dy = y10 - y11;
  12948. var d2 = dx * dx + dy * dy;
  12949. var r = radius - cr;
  12950. var s = x11 * y10 - x10 * y11;
  12951. var d = (dy < 0 ? -1 : 1) * mathSqrt$4(mathMax$3(0, r * r * d2 - s * s));
  12952. var cx0 = (s * dy - dx * d) / d2;
  12953. var cy0 = (-s * dx - dy * d) / d2;
  12954. var cx1 = (s * dy + dx * d) / d2;
  12955. var cy1 = (-s * dx + dy * d) / d2;
  12956. var dx0 = cx0 - x00;
  12957. var dy0 = cy0 - y00;
  12958. var dx1 = cx1 - x00;
  12959. var dy1 = cy1 - y00;
  12960. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  12961. cx0 = cx1;
  12962. cy0 = cy1;
  12963. }
  12964. return {
  12965. cx: cx0,
  12966. cy: cy0,
  12967. x01: -ox,
  12968. y01: -oy,
  12969. x11: cx0 * (radius / r - 1),
  12970. y11: cy0 * (radius / r - 1)
  12971. };
  12972. }
  12973. function buildPath$1(ctx, shape) {
  12974. var radius = mathMax$3(shape.r, 0);
  12975. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  12976. var hasRadius = radius > 0;
  12977. var hasInnerRadius = innerRadius > 0;
  12978. if (!hasRadius && !hasInnerRadius) {
  12979. return;
  12980. }
  12981. if (!hasRadius) {
  12982. radius = innerRadius;
  12983. innerRadius = 0;
  12984. }
  12985. if (innerRadius > radius) {
  12986. var tmp = radius;
  12987. radius = innerRadius;
  12988. innerRadius = tmp;
  12989. }
  12990. var clockwise = !!shape.clockwise;
  12991. var startAngle = shape.startAngle;
  12992. var endAngle = shape.endAngle;
  12993. var arc;
  12994. if (startAngle === endAngle) {
  12995. arc = 0;
  12996. }
  12997. else {
  12998. var tmpAngles = [startAngle, endAngle];
  12999. normalizeArcAngles(tmpAngles, !clockwise);
  13000. arc = mathAbs$1(tmpAngles[0] - tmpAngles[1]);
  13001. }
  13002. var x = shape.cx;
  13003. var y = shape.cy;
  13004. var cornerRadius = shape.cornerRadius || 0;
  13005. var innerCornerRadius = shape.innerCornerRadius || 0;
  13006. if (!(radius > e)) {
  13007. ctx.moveTo(x, y);
  13008. }
  13009. else if (arc > PI2$5 - e) {
  13010. ctx.moveTo(x + radius * mathCos$3(startAngle), y + radius * mathSin$3(startAngle));
  13011. ctx.arc(x, y, radius, startAngle, endAngle, !clockwise);
  13012. if (innerRadius > e) {
  13013. ctx.moveTo(x + innerRadius * mathCos$3(endAngle), y + innerRadius * mathSin$3(endAngle));
  13014. ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise);
  13015. }
  13016. }
  13017. else {
  13018. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  13019. var cr = mathMin$3(halfRd, cornerRadius);
  13020. var icr = mathMin$3(halfRd, innerCornerRadius);
  13021. var cr0 = icr;
  13022. var cr1 = cr;
  13023. var xrs = radius * mathCos$3(startAngle);
  13024. var yrs = radius * mathSin$3(startAngle);
  13025. var xire = innerRadius * mathCos$3(endAngle);
  13026. var yire = innerRadius * mathSin$3(endAngle);
  13027. var xre = void 0;
  13028. var yre = void 0;
  13029. var xirs = void 0;
  13030. var yirs = void 0;
  13031. if (cr > e || icr > e) {
  13032. xre = radius * mathCos$3(endAngle);
  13033. yre = radius * mathSin$3(endAngle);
  13034. xirs = innerRadius * mathCos$3(startAngle);
  13035. yirs = innerRadius * mathSin$3(startAngle);
  13036. if (arc < PI$2) {
  13037. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13038. if (it_1) {
  13039. var x0 = xrs - it_1[0];
  13040. var y0 = yrs - it_1[1];
  13041. var x1 = xre - it_1[0];
  13042. var y1 = yre - it_1[1];
  13043. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$4(x0 * x0 + y0 * y0) * mathSqrt$4(x1 * x1 + y1 * y1))) / 2);
  13044. var b = mathSqrt$4(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13045. cr0 = mathMin$3(icr, (innerRadius - b) / (a - 1));
  13046. cr1 = mathMin$3(cr, (radius - b) / (a + 1));
  13047. }
  13048. }
  13049. }
  13050. if (!(arc > e)) {
  13051. ctx.moveTo(x + xrs, y + yrs);
  13052. }
  13053. else if (cr1 > e) {
  13054. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, cr1, clockwise);
  13055. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, cr1, clockwise);
  13056. ctx.moveTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01);
  13057. if (cr1 < cr) {
  13058. ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise);
  13059. }
  13060. else {
  13061. ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise);
  13062. ctx.arc(x, y, radius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), !clockwise);
  13063. ctx.arc(x + ct1.cx, y + ct1.cy, cr1, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise);
  13064. }
  13065. }
  13066. else {
  13067. ctx.moveTo(x + xrs, y + yrs);
  13068. ctx.arc(x, y, radius, startAngle, endAngle, !clockwise);
  13069. }
  13070. if (!(innerRadius > e) || !(arc > e)) {
  13071. ctx.lineTo(x + xire, y + yire);
  13072. }
  13073. else if (cr0 > e) {
  13074. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -cr0, clockwise);
  13075. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -cr0, clockwise);
  13076. ctx.lineTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01);
  13077. if (cr0 < icr) {
  13078. ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise);
  13079. }
  13080. else {
  13081. ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise);
  13082. ctx.arc(x, y, innerRadius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), clockwise);
  13083. ctx.arc(x + ct1.cx, y + ct1.cy, cr0, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise);
  13084. }
  13085. }
  13086. else {
  13087. ctx.lineTo(x + xire, y + yire);
  13088. ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise);
  13089. }
  13090. }
  13091. ctx.closePath();
  13092. }
  13093. var SectorShape = (function () {
  13094. function SectorShape() {
  13095. this.cx = 0;
  13096. this.cy = 0;
  13097. this.r0 = 0;
  13098. this.r = 0;
  13099. this.startAngle = 0;
  13100. this.endAngle = Math.PI * 2;
  13101. this.clockwise = true;
  13102. this.cornerRadius = 0;
  13103. this.innerCornerRadius = 0;
  13104. }
  13105. return SectorShape;
  13106. }());
  13107. var Sector = (function (_super) {
  13108. __extends(Sector, _super);
  13109. function Sector(opts) {
  13110. return _super.call(this, opts) || this;
  13111. }
  13112. Sector.prototype.getDefaultShape = function () {
  13113. return new SectorShape();
  13114. };
  13115. Sector.prototype.buildPath = function (ctx, shape) {
  13116. buildPath$1(ctx, shape);
  13117. };
  13118. Sector.prototype.isZeroArea = function () {
  13119. return this.shape.startAngle === this.shape.endAngle
  13120. || this.shape.r === this.shape.r0;
  13121. };
  13122. return Sector;
  13123. }(Path));
  13124. Sector.prototype.type = 'sector';
  13125. var RingShape = (function () {
  13126. function RingShape() {
  13127. this.cx = 0;
  13128. this.cy = 0;
  13129. this.r = 0;
  13130. this.r0 = 0;
  13131. }
  13132. return RingShape;
  13133. }());
  13134. var Ring = (function (_super) {
  13135. __extends(Ring, _super);
  13136. function Ring(opts) {
  13137. return _super.call(this, opts) || this;
  13138. }
  13139. Ring.prototype.getDefaultShape = function () {
  13140. return new RingShape();
  13141. };
  13142. Ring.prototype.buildPath = function (ctx, shape) {
  13143. var x = shape.cx;
  13144. var y = shape.cy;
  13145. var PI2 = Math.PI * 2;
  13146. ctx.moveTo(x + shape.r, y);
  13147. ctx.arc(x, y, shape.r, 0, PI2, false);
  13148. ctx.moveTo(x + shape.r0, y);
  13149. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13150. };
  13151. return Ring;
  13152. }(Path));
  13153. Ring.prototype.type = 'ring';
  13154. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13155. var v0 = (p2 - p0) * 0.5;
  13156. var v1 = (p3 - p1) * 0.5;
  13157. return (2 * (p1 - p2) + v0 + v1) * t3
  13158. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13159. + v0 * t + p1;
  13160. }
  13161. function smoothSpline(points, isLoop) {
  13162. var len = points.length;
  13163. var ret = [];
  13164. var distance$1 = 0;
  13165. for (var i = 1; i < len; i++) {
  13166. distance$1 += distance(points[i - 1], points[i]);
  13167. }
  13168. var segs = distance$1 / 2;
  13169. segs = segs < len ? len : segs;
  13170. for (var i = 0; i < segs; i++) {
  13171. var pos = i / (segs - 1) * (isLoop ? len : len - 1);
  13172. var idx = Math.floor(pos);
  13173. var w = pos - idx;
  13174. var p0 = void 0;
  13175. var p1 = points[idx % len];
  13176. var p2 = void 0;
  13177. var p3 = void 0;
  13178. if (!isLoop) {
  13179. p0 = points[idx === 0 ? idx : idx - 1];
  13180. p2 = points[idx > len - 2 ? len - 1 : idx + 1];
  13181. p3 = points[idx > len - 3 ? len - 1 : idx + 2];
  13182. }
  13183. else {
  13184. p0 = points[(idx - 1 + len) % len];
  13185. p2 = points[(idx + 1) % len];
  13186. p3 = points[(idx + 2) % len];
  13187. }
  13188. var w2 = w * w;
  13189. var w3 = w * w2;
  13190. ret.push([
  13191. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13192. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13193. ]);
  13194. }
  13195. return ret;
  13196. }
  13197. function smoothBezier(points, smooth, isLoop, constraint) {
  13198. var cps = [];
  13199. var v = [];
  13200. var v1 = [];
  13201. var v2 = [];
  13202. var prevPoint;
  13203. var nextPoint;
  13204. var min$1;
  13205. var max$1;
  13206. if (constraint) {
  13207. min$1 = [Infinity, Infinity];
  13208. max$1 = [-Infinity, -Infinity];
  13209. for (var i = 0, len = points.length; i < len; i++) {
  13210. min(min$1, min$1, points[i]);
  13211. max(max$1, max$1, points[i]);
  13212. }
  13213. min(min$1, min$1, constraint[0]);
  13214. max(max$1, max$1, constraint[1]);
  13215. }
  13216. for (var i = 0, len = points.length; i < len; i++) {
  13217. var point = points[i];
  13218. if (isLoop) {
  13219. prevPoint = points[i ? i - 1 : len - 1];
  13220. nextPoint = points[(i + 1) % len];
  13221. }
  13222. else {
  13223. if (i === 0 || i === len - 1) {
  13224. cps.push(clone$1(points[i]));
  13225. continue;
  13226. }
  13227. else {
  13228. prevPoint = points[i - 1];
  13229. nextPoint = points[i + 1];
  13230. }
  13231. }
  13232. sub(v, nextPoint, prevPoint);
  13233. scale(v, v, smooth);
  13234. var d0 = distance(point, prevPoint);
  13235. var d1 = distance(point, nextPoint);
  13236. var sum = d0 + d1;
  13237. if (sum !== 0) {
  13238. d0 /= sum;
  13239. d1 /= sum;
  13240. }
  13241. scale(v1, v, -d0);
  13242. scale(v2, v, d1);
  13243. var cp0 = add([], point, v1);
  13244. var cp1 = add([], point, v2);
  13245. if (constraint) {
  13246. max(cp0, cp0, min$1);
  13247. min(cp0, cp0, max$1);
  13248. max(cp1, cp1, min$1);
  13249. min(cp1, cp1, max$1);
  13250. }
  13251. cps.push(cp0);
  13252. cps.push(cp1);
  13253. }
  13254. if (isLoop) {
  13255. cps.push(cps.shift());
  13256. }
  13257. return cps;
  13258. }
  13259. function buildPath$2(ctx, shape, closePath) {
  13260. var smooth = shape.smooth;
  13261. var points = shape.points;
  13262. if (points && points.length >= 2) {
  13263. if (smooth && smooth !== 'spline') {
  13264. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13265. ctx.moveTo(points[0][0], points[0][1]);
  13266. var len = points.length;
  13267. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13268. var cp1 = controlPoints[i * 2];
  13269. var cp2 = controlPoints[i * 2 + 1];
  13270. var p = points[(i + 1) % len];
  13271. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13272. }
  13273. }
  13274. else {
  13275. if (smooth === 'spline') {
  13276. points = smoothSpline(points, closePath);
  13277. }
  13278. ctx.moveTo(points[0][0], points[0][1]);
  13279. for (var i = 1, l = points.length; i < l; i++) {
  13280. ctx.lineTo(points[i][0], points[i][1]);
  13281. }
  13282. }
  13283. closePath && ctx.closePath();
  13284. }
  13285. }
  13286. var PolygonShape = (function () {
  13287. function PolygonShape() {
  13288. this.points = null;
  13289. this.smooth = 0;
  13290. this.smoothConstraint = null;
  13291. }
  13292. return PolygonShape;
  13293. }());
  13294. var Polygon = (function (_super) {
  13295. __extends(Polygon, _super);
  13296. function Polygon(opts) {
  13297. return _super.call(this, opts) || this;
  13298. }
  13299. Polygon.prototype.getDefaultShape = function () {
  13300. return new PolygonShape();
  13301. };
  13302. Polygon.prototype.buildPath = function (ctx, shape) {
  13303. buildPath$2(ctx, shape, true);
  13304. };
  13305. return Polygon;
  13306. }(Path));
  13307. Polygon.prototype.type = 'polygon';
  13308. var PolylineShape = (function () {
  13309. function PolylineShape() {
  13310. this.points = null;
  13311. this.percent = 1;
  13312. this.smooth = 0;
  13313. this.smoothConstraint = null;
  13314. }
  13315. return PolylineShape;
  13316. }());
  13317. var Polyline = (function (_super) {
  13318. __extends(Polyline, _super);
  13319. function Polyline(opts) {
  13320. return _super.call(this, opts) || this;
  13321. }
  13322. Polyline.prototype.getDefaultStyle = function () {
  13323. return {
  13324. stroke: '#000',
  13325. fill: null
  13326. };
  13327. };
  13328. Polyline.prototype.getDefaultShape = function () {
  13329. return new PolylineShape();
  13330. };
  13331. Polyline.prototype.buildPath = function (ctx, shape) {
  13332. buildPath$2(ctx, shape, false);
  13333. };
  13334. return Polyline;
  13335. }(Path));
  13336. Polyline.prototype.type = 'polyline';
  13337. var subPixelOptimizeOutputShape$1 = {};
  13338. var LineShape = (function () {
  13339. function LineShape() {
  13340. this.x1 = 0;
  13341. this.y1 = 0;
  13342. this.x2 = 0;
  13343. this.y2 = 0;
  13344. this.percent = 1;
  13345. }
  13346. return LineShape;
  13347. }());
  13348. var Line = (function (_super) {
  13349. __extends(Line, _super);
  13350. function Line(opts) {
  13351. return _super.call(this, opts) || this;
  13352. }
  13353. Line.prototype.getDefaultStyle = function () {
  13354. return {
  13355. stroke: '#000',
  13356. fill: null
  13357. };
  13358. };
  13359. Line.prototype.getDefaultShape = function () {
  13360. return new LineShape();
  13361. };
  13362. Line.prototype.buildPath = function (ctx, shape) {
  13363. var x1;
  13364. var y1;
  13365. var x2;
  13366. var y2;
  13367. if (this.subPixelOptimize) {
  13368. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13369. x1 = optimizedShape.x1;
  13370. y1 = optimizedShape.y1;
  13371. x2 = optimizedShape.x2;
  13372. y2 = optimizedShape.y2;
  13373. }
  13374. else {
  13375. x1 = shape.x1;
  13376. y1 = shape.y1;
  13377. x2 = shape.x2;
  13378. y2 = shape.y2;
  13379. }
  13380. var percent = shape.percent;
  13381. if (percent === 0) {
  13382. return;
  13383. }
  13384. ctx.moveTo(x1, y1);
  13385. if (percent < 1) {
  13386. x2 = x1 * (1 - percent) + x2 * percent;
  13387. y2 = y1 * (1 - percent) + y2 * percent;
  13388. }
  13389. ctx.lineTo(x2, y2);
  13390. };
  13391. Line.prototype.pointAt = function (p) {
  13392. var shape = this.shape;
  13393. return [
  13394. shape.x1 * (1 - p) + shape.x2 * p,
  13395. shape.y1 * (1 - p) + shape.y2 * p
  13396. ];
  13397. };
  13398. return Line;
  13399. }(Path));
  13400. Line.prototype.type = 'line';
  13401. var out = [];
  13402. var BezierCurveShape = (function () {
  13403. function BezierCurveShape() {
  13404. this.x1 = 0;
  13405. this.y1 = 0;
  13406. this.x2 = 0;
  13407. this.y2 = 0;
  13408. this.cpx1 = 0;
  13409. this.cpy1 = 0;
  13410. this.percent = 1;
  13411. }
  13412. return BezierCurveShape;
  13413. }());
  13414. function someVectorAt(shape, t, isTangent) {
  13415. var cpx2 = shape.cpx2;
  13416. var cpy2 = shape.cpy2;
  13417. if (cpx2 === null || cpy2 === null) {
  13418. return [
  13419. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13420. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13421. ];
  13422. }
  13423. else {
  13424. return [
  13425. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13426. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13427. ];
  13428. }
  13429. }
  13430. var BezierCurve = (function (_super) {
  13431. __extends(BezierCurve, _super);
  13432. function BezierCurve(opts) {
  13433. return _super.call(this, opts) || this;
  13434. }
  13435. BezierCurve.prototype.getDefaultStyle = function () {
  13436. return {
  13437. stroke: '#000',
  13438. fill: null
  13439. };
  13440. };
  13441. BezierCurve.prototype.getDefaultShape = function () {
  13442. return new BezierCurveShape();
  13443. };
  13444. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13445. var x1 = shape.x1;
  13446. var y1 = shape.y1;
  13447. var x2 = shape.x2;
  13448. var y2 = shape.y2;
  13449. var cpx1 = shape.cpx1;
  13450. var cpy1 = shape.cpy1;
  13451. var cpx2 = shape.cpx2;
  13452. var cpy2 = shape.cpy2;
  13453. var percent = shape.percent;
  13454. if (percent === 0) {
  13455. return;
  13456. }
  13457. ctx.moveTo(x1, y1);
  13458. if (cpx2 == null || cpy2 == null) {
  13459. if (percent < 1) {
  13460. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13461. cpx1 = out[1];
  13462. x2 = out[2];
  13463. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13464. cpy1 = out[1];
  13465. y2 = out[2];
  13466. }
  13467. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13468. }
  13469. else {
  13470. if (percent < 1) {
  13471. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13472. cpx1 = out[1];
  13473. cpx2 = out[2];
  13474. x2 = out[3];
  13475. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13476. cpy1 = out[1];
  13477. cpy2 = out[2];
  13478. y2 = out[3];
  13479. }
  13480. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13481. }
  13482. };
  13483. BezierCurve.prototype.pointAt = function (t) {
  13484. return someVectorAt(this.shape, t, false);
  13485. };
  13486. BezierCurve.prototype.tangentAt = function (t) {
  13487. var p = someVectorAt(this.shape, t, true);
  13488. return normalize(p, p);
  13489. };
  13490. return BezierCurve;
  13491. }(Path));
  13492. BezierCurve.prototype.type = 'bezier-curve';
  13493. var ArcShape = (function () {
  13494. function ArcShape() {
  13495. this.cx = 0;
  13496. this.cy = 0;
  13497. this.r = 0;
  13498. this.startAngle = 0;
  13499. this.endAngle = Math.PI * 2;
  13500. this.clockwise = true;
  13501. }
  13502. return ArcShape;
  13503. }());
  13504. var Arc = (function (_super) {
  13505. __extends(Arc, _super);
  13506. function Arc(opts) {
  13507. return _super.call(this, opts) || this;
  13508. }
  13509. Arc.prototype.getDefaultStyle = function () {
  13510. return {
  13511. stroke: '#000',
  13512. fill: null
  13513. };
  13514. };
  13515. Arc.prototype.getDefaultShape = function () {
  13516. return new ArcShape();
  13517. };
  13518. Arc.prototype.buildPath = function (ctx, shape) {
  13519. var x = shape.cx;
  13520. var y = shape.cy;
  13521. var r = Math.max(shape.r, 0);
  13522. var startAngle = shape.startAngle;
  13523. var endAngle = shape.endAngle;
  13524. var clockwise = shape.clockwise;
  13525. var unitX = Math.cos(startAngle);
  13526. var unitY = Math.sin(startAngle);
  13527. ctx.moveTo(unitX * r + x, unitY * r + y);
  13528. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13529. };
  13530. return Arc;
  13531. }(Path));
  13532. Arc.prototype.type = 'arc';
  13533. var CompoundPath = (function (_super) {
  13534. __extends(CompoundPath, _super);
  13535. function CompoundPath() {
  13536. var _this = _super !== null && _super.apply(this, arguments) || this;
  13537. _this.type = 'compound';
  13538. return _this;
  13539. }
  13540. CompoundPath.prototype._updatePathDirty = function () {
  13541. var paths = this.shape.paths;
  13542. var dirtyPath = this.shapeChanged();
  13543. for (var i = 0; i < paths.length; i++) {
  13544. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13545. }
  13546. if (dirtyPath) {
  13547. this.dirtyShape();
  13548. }
  13549. };
  13550. CompoundPath.prototype.beforeBrush = function () {
  13551. this._updatePathDirty();
  13552. var paths = this.shape.paths || [];
  13553. var scale = this.getGlobalScale();
  13554. for (var i = 0; i < paths.length; i++) {
  13555. if (!paths[i].path) {
  13556. paths[i].createPathProxy();
  13557. }
  13558. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13559. }
  13560. };
  13561. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13562. var paths = shape.paths || [];
  13563. for (var i = 0; i < paths.length; i++) {
  13564. paths[i].buildPath(ctx, paths[i].shape, true);
  13565. }
  13566. };
  13567. CompoundPath.prototype.afterBrush = function () {
  13568. var paths = this.shape.paths || [];
  13569. for (var i = 0; i < paths.length; i++) {
  13570. paths[i].pathUpdated();
  13571. }
  13572. };
  13573. CompoundPath.prototype.getBoundingRect = function () {
  13574. this._updatePathDirty.call(this);
  13575. return Path.prototype.getBoundingRect.call(this);
  13576. };
  13577. return CompoundPath;
  13578. }(Path));
  13579. var Gradient = (function () {
  13580. function Gradient(colorStops) {
  13581. this.colorStops = colorStops || [];
  13582. }
  13583. Gradient.prototype.addColorStop = function (offset, color) {
  13584. this.colorStops.push({
  13585. offset: offset,
  13586. color: color
  13587. });
  13588. };
  13589. return Gradient;
  13590. }());
  13591. var LinearGradient = (function (_super) {
  13592. __extends(LinearGradient, _super);
  13593. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13594. var _this = _super.call(this, colorStops) || this;
  13595. _this.x = x == null ? 0 : x;
  13596. _this.y = y == null ? 0 : y;
  13597. _this.x2 = x2 == null ? 1 : x2;
  13598. _this.y2 = y2 == null ? 0 : y2;
  13599. _this.type = 'linear';
  13600. _this.global = globalCoord || false;
  13601. return _this;
  13602. }
  13603. return LinearGradient;
  13604. }(Gradient));
  13605. var RadialGradient = (function (_super) {
  13606. __extends(RadialGradient, _super);
  13607. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13608. var _this = _super.call(this, colorStops) || this;
  13609. _this.x = x == null ? 0.5 : x;
  13610. _this.y = y == null ? 0.5 : y;
  13611. _this.r = r == null ? 0.5 : r;
  13612. _this.type = 'radial';
  13613. _this.global = globalCoord || false;
  13614. return _this;
  13615. }
  13616. return RadialGradient;
  13617. }(Gradient));
  13618. var extent = [0, 0];
  13619. var extent2 = [0, 0];
  13620. var minTv$1 = new Point();
  13621. var maxTv$1 = new Point();
  13622. var OrientedBoundingRect = (function () {
  13623. function OrientedBoundingRect(rect, transform) {
  13624. this._corners = [];
  13625. this._axes = [];
  13626. this._origin = [0, 0];
  13627. for (var i = 0; i < 4; i++) {
  13628. this._corners[i] = new Point();
  13629. }
  13630. for (var i = 0; i < 2; i++) {
  13631. this._axes[i] = new Point();
  13632. }
  13633. if (rect) {
  13634. this.fromBoundingRect(rect, transform);
  13635. }
  13636. }
  13637. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13638. var corners = this._corners;
  13639. var axes = this._axes;
  13640. var x = rect.x;
  13641. var y = rect.y;
  13642. var x2 = x + rect.width;
  13643. var y2 = y + rect.height;
  13644. corners[0].set(x, y);
  13645. corners[1].set(x2, y);
  13646. corners[2].set(x2, y2);
  13647. corners[3].set(x, y2);
  13648. if (transform) {
  13649. for (var i = 0; i < 4; i++) {
  13650. corners[i].transform(transform);
  13651. }
  13652. }
  13653. Point.sub(axes[0], corners[1], corners[0]);
  13654. Point.sub(axes[1], corners[3], corners[0]);
  13655. axes[0].normalize();
  13656. axes[1].normalize();
  13657. for (var i = 0; i < 2; i++) {
  13658. this._origin[i] = axes[i].dot(corners[0]);
  13659. }
  13660. };
  13661. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13662. var overlapped = true;
  13663. var noMtv = !mtv;
  13664. minTv$1.set(Infinity, Infinity);
  13665. maxTv$1.set(0, 0);
  13666. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13667. overlapped = false;
  13668. if (noMtv) {
  13669. return overlapped;
  13670. }
  13671. }
  13672. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13673. overlapped = false;
  13674. if (noMtv) {
  13675. return overlapped;
  13676. }
  13677. }
  13678. if (!noMtv) {
  13679. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13680. }
  13681. return overlapped;
  13682. };
  13683. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13684. var overlapped = true;
  13685. for (var i = 0; i < 2; i++) {
  13686. var axis = this._axes[i];
  13687. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13688. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13689. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13690. overlapped = false;
  13691. if (noMtv) {
  13692. return overlapped;
  13693. }
  13694. var dist0 = Math.abs(extent2[0] - extent[1]);
  13695. var dist1 = Math.abs(extent[0] - extent2[1]);
  13696. if (Math.min(dist0, dist1) > maxTv.len()) {
  13697. if (dist0 < dist1) {
  13698. Point.scale(maxTv, axis, -dist0 * inverse);
  13699. }
  13700. else {
  13701. Point.scale(maxTv, axis, dist1 * inverse);
  13702. }
  13703. }
  13704. }
  13705. else if (minTv) {
  13706. var dist0 = Math.abs(extent2[0] - extent[1]);
  13707. var dist1 = Math.abs(extent[0] - extent2[1]);
  13708. if (Math.min(dist0, dist1) < minTv.len()) {
  13709. if (dist0 < dist1) {
  13710. Point.scale(minTv, axis, dist0 * inverse);
  13711. }
  13712. else {
  13713. Point.scale(minTv, axis, -dist1 * inverse);
  13714. }
  13715. }
  13716. }
  13717. }
  13718. return overlapped;
  13719. };
  13720. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13721. var axis = this._axes[dim];
  13722. var origin = this._origin;
  13723. var proj = corners[0].dot(axis) + origin[dim];
  13724. var min = proj;
  13725. var max = proj;
  13726. for (var i = 1; i < corners.length; i++) {
  13727. var proj_1 = corners[i].dot(axis) + origin[dim];
  13728. min = Math.min(proj_1, min);
  13729. max = Math.max(proj_1, max);
  13730. }
  13731. out[0] = min;
  13732. out[1] = max;
  13733. };
  13734. return OrientedBoundingRect;
  13735. }());
  13736. var m = [];
  13737. var IncrementalDisplayable = (function (_super) {
  13738. __extends(IncrementalDisplayable, _super);
  13739. function IncrementalDisplayable() {
  13740. var _this = _super !== null && _super.apply(this, arguments) || this;
  13741. _this.notClear = true;
  13742. _this.incremental = true;
  13743. _this._displayables = [];
  13744. _this._temporaryDisplayables = [];
  13745. _this._cursor = 0;
  13746. return _this;
  13747. }
  13748. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  13749. cb.call(context, this);
  13750. };
  13751. IncrementalDisplayable.prototype.useStyle = function () {
  13752. this.style = {};
  13753. };
  13754. IncrementalDisplayable.prototype.getCursor = function () {
  13755. return this._cursor;
  13756. };
  13757. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  13758. this._cursor = this._displayables.length;
  13759. };
  13760. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  13761. this._displayables = [];
  13762. this._temporaryDisplayables = [];
  13763. this._cursor = 0;
  13764. this.markRedraw();
  13765. this.notClear = false;
  13766. };
  13767. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  13768. this._temporaryDisplayables = [];
  13769. };
  13770. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  13771. if (notPersistent) {
  13772. this._temporaryDisplayables.push(displayable);
  13773. }
  13774. else {
  13775. this._displayables.push(displayable);
  13776. }
  13777. this.markRedraw();
  13778. };
  13779. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  13780. notPersistent = notPersistent || false;
  13781. for (var i = 0; i < displayables.length; i++) {
  13782. this.addDisplayable(displayables[i], notPersistent);
  13783. }
  13784. };
  13785. IncrementalDisplayable.prototype.getDisplayables = function () {
  13786. return this._displayables;
  13787. };
  13788. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  13789. return this._temporaryDisplayables;
  13790. };
  13791. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  13792. for (var i = this._cursor; i < this._displayables.length; i++) {
  13793. cb && cb(this._displayables[i]);
  13794. }
  13795. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13796. cb && cb(this._temporaryDisplayables[i]);
  13797. }
  13798. };
  13799. IncrementalDisplayable.prototype.update = function () {
  13800. this.updateTransform();
  13801. for (var i = this._cursor; i < this._displayables.length; i++) {
  13802. var displayable = this._displayables[i];
  13803. displayable.parent = this;
  13804. displayable.update();
  13805. displayable.parent = null;
  13806. }
  13807. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13808. var displayable = this._temporaryDisplayables[i];
  13809. displayable.parent = this;
  13810. displayable.update();
  13811. displayable.parent = null;
  13812. }
  13813. };
  13814. IncrementalDisplayable.prototype.getBoundingRect = function () {
  13815. if (!this._rect) {
  13816. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13817. for (var i = 0; i < this._displayables.length; i++) {
  13818. var displayable = this._displayables[i];
  13819. var childRect = displayable.getBoundingRect().clone();
  13820. if (displayable.needLocalTransform()) {
  13821. childRect.applyTransform(displayable.getLocalTransform(m));
  13822. }
  13823. rect.union(childRect);
  13824. }
  13825. this._rect = rect;
  13826. }
  13827. return this._rect;
  13828. };
  13829. IncrementalDisplayable.prototype.contain = function (x, y) {
  13830. var localPos = this.transformCoordToLocal(x, y);
  13831. var rect = this.getBoundingRect();
  13832. if (rect.contain(localPos[0], localPos[1])) {
  13833. for (var i = 0; i < this._displayables.length; i++) {
  13834. var displayable = this._displayables[i];
  13835. if (displayable.contain(x, y)) {
  13836. return true;
  13837. }
  13838. }
  13839. }
  13840. return false;
  13841. };
  13842. return IncrementalDisplayable;
  13843. }(Displayable));
  13844. var transitionStore = makeInner();
  13845. /**
  13846. * Return null if animation is disabled.
  13847. */
  13848. function getAnimationConfig(animationType, animatableModel, dataIndex, // Extra opts can override the option in animatable model.
  13849. extraOpts, // TODO It's only for pictorial bar now.
  13850. extraDelayParams) {
  13851. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  13852. // If animation is enabled. Will use this animation config in payload.
  13853. // If animation is disabled. Just ignore it.
  13854. if (animatableModel && animatableModel.ecModel) {
  13855. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  13856. animationPayload = updatePayload && updatePayload.animation;
  13857. }
  13858. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  13859. var isUpdate = animationType === 'update';
  13860. if (animationEnabled) {
  13861. var duration = void 0;
  13862. var easing = void 0;
  13863. var delay = void 0;
  13864. if (extraOpts) {
  13865. duration = retrieve2(extraOpts.duration, 200);
  13866. easing = retrieve2(extraOpts.easing, 'cubicOut');
  13867. delay = 0;
  13868. } else {
  13869. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  13870. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  13871. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  13872. } // animation from payload has highest priority.
  13873. if (animationPayload) {
  13874. animationPayload.duration != null && (duration = animationPayload.duration);
  13875. animationPayload.easing != null && (easing = animationPayload.easing);
  13876. animationPayload.delay != null && (delay = animationPayload.delay);
  13877. }
  13878. if (typeof delay === 'function') {
  13879. delay = delay(dataIndex, extraDelayParams);
  13880. }
  13881. if (typeof duration === 'function') {
  13882. duration = duration(dataIndex);
  13883. }
  13884. var config = {
  13885. duration: duration || 0,
  13886. delay: delay,
  13887. easing: easing
  13888. };
  13889. return config;
  13890. } else {
  13891. return null;
  13892. }
  13893. }
  13894. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  13895. var isFrom = false;
  13896. var removeOpt;
  13897. if (typeof dataIndex === 'function') {
  13898. during = cb;
  13899. cb = dataIndex;
  13900. dataIndex = null;
  13901. } else if (isObject(dataIndex)) {
  13902. cb = dataIndex.cb;
  13903. during = dataIndex.during;
  13904. isFrom = dataIndex.isFrom;
  13905. removeOpt = dataIndex.removeOpt;
  13906. dataIndex = dataIndex.dataIndex;
  13907. }
  13908. var isRemove = animationType === 'remove';
  13909. if (!isRemove) {
  13910. // Must stop the remove animation.
  13911. el.stopAnimation('remove');
  13912. }
  13913. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  13914. if (animationConfig && animationConfig.duration > 0) {
  13915. var duration = animationConfig.duration;
  13916. var animationDelay = animationConfig.delay;
  13917. var animationEasing = animationConfig.easing;
  13918. var animateConfig = {
  13919. duration: duration,
  13920. delay: animationDelay || 0,
  13921. easing: animationEasing,
  13922. done: cb,
  13923. force: !!cb || !!during,
  13924. // Set to final state in update/init animation.
  13925. // So the post processing based on the path shape can be done correctly.
  13926. setToFinal: !isRemove,
  13927. scope: animationType,
  13928. during: during
  13929. };
  13930. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  13931. } else {
  13932. el.stopAnimation(); // If `isFrom`, the props is the "from" props.
  13933. !isFrom && el.attr(props); // Call during at least once.
  13934. during && during(1);
  13935. cb && cb();
  13936. }
  13937. }
  13938. /**
  13939. * Update graphic element properties with or without animation according to the
  13940. * configuration in series.
  13941. *
  13942. * Caution: this method will stop previous animation.
  13943. * So do not use this method to one element twice before
  13944. * animation starts, unless you know what you are doing.
  13945. * @example
  13946. * graphic.updateProps(el, {
  13947. * position: [100, 100]
  13948. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  13949. * // Or
  13950. * graphic.updateProps(el, {
  13951. * position: [100, 100]
  13952. * }, seriesModel, function () { console.log('Animation done!'); });
  13953. */
  13954. function updateProps(el, props, // TODO: TYPE AnimatableModel
  13955. animatableModel, dataIndex, cb, during) {
  13956. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  13957. }
  13958. /**
  13959. * Init graphic element properties with or without animation according to the
  13960. * configuration in series.
  13961. *
  13962. * Caution: this method will stop previous animation.
  13963. * So do not use this method to one element twice before
  13964. * animation starts, unless you know what you are doing.
  13965. */
  13966. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  13967. animateOrSetProps('init', el, props, animatableModel, dataIndex, cb, during);
  13968. }
  13969. /**
  13970. * If element is removed.
  13971. * It can determine if element is having remove animation.
  13972. */
  13973. function isElementRemoved(el) {
  13974. if (!el.__zr) {
  13975. return true;
  13976. }
  13977. for (var i = 0; i < el.animators.length; i++) {
  13978. var animator = el.animators[i];
  13979. if (animator.scope === 'remove') {
  13980. return true;
  13981. }
  13982. }
  13983. return false;
  13984. }
  13985. /**
  13986. * Remove graphic element
  13987. */
  13988. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  13989. // Don't do remove animation twice.
  13990. if (isElementRemoved(el)) {
  13991. return;
  13992. }
  13993. animateOrSetProps('remove', el, props, animatableModel, dataIndex, cb, during);
  13994. }
  13995. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  13996. el.removeTextContent();
  13997. el.removeTextGuideLine();
  13998. removeElement(el, {
  13999. style: {
  14000. opacity: 0
  14001. }
  14002. }, animatableModel, dataIndex, done);
  14003. }
  14004. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14005. function doRemove() {
  14006. el.parent && el.parent.remove(el);
  14007. } // Hide label and labelLine first
  14008. // TODO Also use fade out animation?
  14009. if (!el.isGroup) {
  14010. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14011. } else {
  14012. el.traverse(function (disp) {
  14013. if (!disp.isGroup) {
  14014. // Can invoke doRemove multiple times.
  14015. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14016. }
  14017. });
  14018. }
  14019. }
  14020. /**
  14021. * Save old style for style transition in universalTransition module.
  14022. * It's used when element will be reused in each render.
  14023. * For chart like map, heatmap, which will always create new element.
  14024. * We don't need to save this because universalTransition can get old style from the old element
  14025. */
  14026. function saveOldStyle(el) {
  14027. transitionStore(el).oldStyle = el.style;
  14028. }
  14029. function getOldStyle(el) {
  14030. return transitionStore(el).oldStyle;
  14031. }
  14032. var mathMax$4 = Math.max;
  14033. var mathMin$4 = Math.min;
  14034. var _customShapeMap = {};
  14035. /**
  14036. * Extend shape with parameters
  14037. */
  14038. function extendShape(opts) {
  14039. return Path.extend(opts);
  14040. }
  14041. var extendPathFromString = extendFromString;
  14042. /**
  14043. * Extend path
  14044. */
  14045. function extendPath(pathData, opts) {
  14046. return extendPathFromString(pathData, opts);
  14047. }
  14048. /**
  14049. * Register a user defined shape.
  14050. * The shape class can be fetched by `getShapeClass`
  14051. * This method will overwrite the registered shapes, including
  14052. * the registered built-in shapes, if using the same `name`.
  14053. * The shape can be used in `custom series` and
  14054. * `graphic component` by declaring `{type: name}`.
  14055. *
  14056. * @param name
  14057. * @param ShapeClass Can be generated by `extendShape`.
  14058. */
  14059. function registerShape(name, ShapeClass) {
  14060. _customShapeMap[name] = ShapeClass;
  14061. }
  14062. /**
  14063. * Find shape class registered by `registerShape`. Usually used in
  14064. * fetching user defined shape.
  14065. *
  14066. * [Caution]:
  14067. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14068. * to use user registered shapes.
  14069. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14070. * `registerShape` by default. That enables users to get both built-in
  14071. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14072. * the built-in shapes by using names like 'circle', 'rect' via calling
  14073. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14074. * in case that it is overwritten by users, except that some features, like
  14075. * `custom series`, `graphic component`, do it deliberately.
  14076. *
  14077. * (2) In the features like `custom series`, `graphic component`, the user input
  14078. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14079. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14080. * are reserved names, that is, if some user register a shape named `'image'`,
  14081. * the shape will not be used. If we intending to add some more reserved names
  14082. * in feature, that might bring break changes (disable some existing user shape
  14083. * names). But that case probably rearly happen. So we dont make more mechanism
  14084. * to resolve this issue here.
  14085. *
  14086. * @param name
  14087. * @return The shape class. If not found, return nothing.
  14088. */
  14089. function getShapeClass(name) {
  14090. if (_customShapeMap.hasOwnProperty(name)) {
  14091. return _customShapeMap[name];
  14092. }
  14093. }
  14094. /**
  14095. * Create a path element from path data string
  14096. * @param pathData
  14097. * @param opts
  14098. * @param rect
  14099. * @param layout 'center' or 'cover' default to be cover
  14100. */
  14101. function makePath(pathData, opts, rect, layout) {
  14102. var path = createFromString(pathData, opts);
  14103. if (rect) {
  14104. if (layout === 'center') {
  14105. rect = centerGraphic(rect, path.getBoundingRect());
  14106. }
  14107. resizePath(path, rect);
  14108. }
  14109. return path;
  14110. }
  14111. /**
  14112. * Create a image element from image url
  14113. * @param imageUrl image url
  14114. * @param opts options
  14115. * @param rect constrain rect
  14116. * @param layout 'center' or 'cover'. Default to be 'cover'
  14117. */
  14118. function makeImage(imageUrl, rect, layout) {
  14119. var zrImg = new ZRImage({
  14120. style: {
  14121. image: imageUrl,
  14122. x: rect.x,
  14123. y: rect.y,
  14124. width: rect.width,
  14125. height: rect.height
  14126. },
  14127. onload: function (img) {
  14128. if (layout === 'center') {
  14129. var boundingRect = {
  14130. width: img.width,
  14131. height: img.height
  14132. };
  14133. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14134. }
  14135. }
  14136. });
  14137. return zrImg;
  14138. }
  14139. /**
  14140. * Get position of centered element in bounding box.
  14141. *
  14142. * @param rect element local bounding box
  14143. * @param boundingRect constraint bounding box
  14144. * @return element position containing x, y, width, and height
  14145. */
  14146. function centerGraphic(rect, boundingRect) {
  14147. // Set rect to center, keep width / height ratio.
  14148. var aspect = boundingRect.width / boundingRect.height;
  14149. var width = rect.height * aspect;
  14150. var height;
  14151. if (width <= rect.width) {
  14152. height = rect.height;
  14153. } else {
  14154. width = rect.width;
  14155. height = width / aspect;
  14156. }
  14157. var cx = rect.x + rect.width / 2;
  14158. var cy = rect.y + rect.height / 2;
  14159. return {
  14160. x: cx - width / 2,
  14161. y: cy - height / 2,
  14162. width: width,
  14163. height: height
  14164. };
  14165. }
  14166. var mergePath$1 = mergePath;
  14167. /**
  14168. * Resize a path to fit the rect
  14169. * @param path
  14170. * @param rect
  14171. */
  14172. function resizePath(path, rect) {
  14173. if (!path.applyTransform) {
  14174. return;
  14175. }
  14176. var pathRect = path.getBoundingRect();
  14177. var m = pathRect.calculateTransform(rect);
  14178. path.applyTransform(m);
  14179. }
  14180. /**
  14181. * Sub pixel optimize line for canvas
  14182. */
  14183. function subPixelOptimizeLine$1(param) {
  14184. subPixelOptimizeLine(param.shape, param.shape, param.style);
  14185. return param;
  14186. }
  14187. /**
  14188. * Sub pixel optimize rect for canvas
  14189. */
  14190. function subPixelOptimizeRect$1(param) {
  14191. subPixelOptimizeRect(param.shape, param.shape, param.style);
  14192. return param;
  14193. }
  14194. /**
  14195. * Sub pixel optimize for canvas
  14196. *
  14197. * @param position Coordinate, such as x, y
  14198. * @param lineWidth Should be nonnegative integer.
  14199. * @param positiveOrNegative Default false (negative).
  14200. * @return Optimized position.
  14201. */
  14202. var subPixelOptimize$1 = subPixelOptimize;
  14203. /**
  14204. * Get transform matrix of target (param target),
  14205. * in coordinate of its ancestor (param ancestor)
  14206. *
  14207. * @param target
  14208. * @param [ancestor]
  14209. */
  14210. function getTransform(target, ancestor) {
  14211. var mat = identity([]);
  14212. while (target && target !== ancestor) {
  14213. mul$1(mat, target.getLocalTransform(), mat);
  14214. target = target.parent;
  14215. }
  14216. return mat;
  14217. }
  14218. /**
  14219. * Apply transform to an vertex.
  14220. * @param target [x, y]
  14221. * @param transform Can be:
  14222. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14223. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14224. * @param invert Whether use invert matrix.
  14225. * @return [x, y]
  14226. */
  14227. function applyTransform$1(target, transform, invert$1) {
  14228. if (transform && !isArrayLike(transform)) {
  14229. transform = Transformable.getLocalTransform(transform);
  14230. }
  14231. if (invert$1) {
  14232. transform = invert([], transform);
  14233. }
  14234. return applyTransform([], target, transform);
  14235. }
  14236. /**
  14237. * @param direction 'left' 'right' 'top' 'bottom'
  14238. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14239. * @param invert Whether use invert matrix.
  14240. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  14241. */
  14242. function transformDirection(direction, transform, invert) {
  14243. // Pick a base, ensure that transform result will not be (0, 0).
  14244. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14245. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14246. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14247. vertex = applyTransform$1(vertex, transform, invert);
  14248. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14249. }
  14250. function isNotGroup(el) {
  14251. return !el.isGroup;
  14252. }
  14253. function isPath(el) {
  14254. return el.shape != null;
  14255. }
  14256. /**
  14257. * Apply group transition animation from g1 to g2.
  14258. * If no animatableModel, no animation.
  14259. */
  14260. function groupTransition(g1, g2, animatableModel) {
  14261. if (!g1 || !g2) {
  14262. return;
  14263. }
  14264. function getElMap(g) {
  14265. var elMap = {};
  14266. g.traverse(function (el) {
  14267. if (isNotGroup(el) && el.anid) {
  14268. elMap[el.anid] = el;
  14269. }
  14270. });
  14271. return elMap;
  14272. }
  14273. function getAnimatableProps(el) {
  14274. var obj = {
  14275. x: el.x,
  14276. y: el.y,
  14277. rotation: el.rotation
  14278. };
  14279. if (isPath(el)) {
  14280. obj.shape = extend({}, el.shape);
  14281. }
  14282. return obj;
  14283. }
  14284. var elMap1 = getElMap(g1);
  14285. g2.traverse(function (el) {
  14286. if (isNotGroup(el) && el.anid) {
  14287. var oldEl = elMap1[el.anid];
  14288. if (oldEl) {
  14289. var newProp = getAnimatableProps(el);
  14290. el.attr(getAnimatableProps(oldEl));
  14291. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14292. }
  14293. }
  14294. });
  14295. }
  14296. function clipPointsByRect(points, rect) {
  14297. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  14298. // and when element have border.
  14299. return map(points, function (point) {
  14300. var x = point[0];
  14301. x = mathMax$4(x, rect.x);
  14302. x = mathMin$4(x, rect.x + rect.width);
  14303. var y = point[1];
  14304. y = mathMax$4(y, rect.y);
  14305. y = mathMin$4(y, rect.y + rect.height);
  14306. return [x, y];
  14307. });
  14308. }
  14309. /**
  14310. * Return a new clipped rect. If rect size are negative, return undefined.
  14311. */
  14312. function clipRectByRect(targetRect, rect) {
  14313. var x = mathMax$4(targetRect.x, rect.x);
  14314. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14315. var y = mathMax$4(targetRect.y, rect.y);
  14316. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14317. // should be painted. So return undefined.
  14318. if (x2 >= x && y2 >= y) {
  14319. return {
  14320. x: x,
  14321. y: y,
  14322. width: x2 - x,
  14323. height: y2 - y
  14324. };
  14325. }
  14326. }
  14327. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  14328. opt, rect) {
  14329. var innerOpts = extend({
  14330. rectHover: true
  14331. }, opt);
  14332. var style = innerOpts.style = {
  14333. strokeNoScale: true
  14334. };
  14335. rect = rect || {
  14336. x: -1,
  14337. y: -1,
  14338. width: 2,
  14339. height: 2
  14340. };
  14341. if (iconStr) {
  14342. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14343. }
  14344. }
  14345. /**
  14346. * Return `true` if the given line (line `a`) and the given polygon
  14347. * are intersect.
  14348. * Note that we do not count colinear as intersect here because no
  14349. * requirement for that. We could do that if required in future.
  14350. */
  14351. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14352. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14353. var p = points[i];
  14354. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14355. return true;
  14356. }
  14357. p2 = p;
  14358. }
  14359. }
  14360. /**
  14361. * Return `true` if the given two lines (line `a` and line `b`)
  14362. * are intersect.
  14363. * Note that we do not count colinear as intersect here because no
  14364. * requirement for that. We could do that if required in future.
  14365. */
  14366. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14367. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14368. var mx = a2x - a1x;
  14369. var my = a2y - a1y;
  14370. var nx = b2x - b1x;
  14371. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  14372. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14373. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14374. if (nearZero(nmCrossProduct)) {
  14375. return false;
  14376. } // `vec_m` and `vec_n` are intersect iff
  14377. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14378. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14379. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14380. var b1a1x = a1x - b1x;
  14381. var b1a1y = a1y - b1y;
  14382. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14383. if (q < 0 || q > 1) {
  14384. return false;
  14385. }
  14386. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14387. if (p < 0 || p > 1) {
  14388. return false;
  14389. }
  14390. return true;
  14391. }
  14392. /**
  14393. * Cross product of 2-dimension vector.
  14394. */
  14395. function crossProduct2d(x1, y1, x2, y2) {
  14396. return x1 * y2 - x2 * y1;
  14397. }
  14398. function nearZero(val) {
  14399. return val <= 1e-6 && val >= -1e-6;
  14400. }
  14401. function setTooltipConfig(opt) {
  14402. var itemTooltipOption = opt.itemTooltipOption;
  14403. var componentModel = opt.componentModel;
  14404. var itemName = opt.itemName;
  14405. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14406. formatter: itemTooltipOption
  14407. } : itemTooltipOption;
  14408. var mainType = componentModel.mainType;
  14409. var componentIndex = componentModel.componentIndex;
  14410. var formatterParams = {
  14411. componentType: mainType,
  14412. name: itemName,
  14413. $vars: ['name']
  14414. };
  14415. formatterParams[mainType + 'Index'] = componentIndex;
  14416. var formatterParamsExtra = opt.formatterParamsExtra;
  14417. if (formatterParamsExtra) {
  14418. each(keys(formatterParamsExtra), function (key) {
  14419. if (!hasOwn(formatterParams, key)) {
  14420. formatterParams[key] = formatterParamsExtra[key];
  14421. formatterParams.$vars.push(key);
  14422. }
  14423. });
  14424. }
  14425. var ecData = getECData(opt.el);
  14426. ecData.componentMainType = mainType;
  14427. ecData.componentIndex = componentIndex;
  14428. ecData.tooltipConfig = {
  14429. name: itemName,
  14430. option: defaults({
  14431. content: itemName,
  14432. formatterParams: formatterParams
  14433. }, itemTooltipOptionObj)
  14434. };
  14435. } // Register built-in shapes. These shapes might be overwirtten
  14436. // by users, although we do not recommend that.
  14437. registerShape('circle', Circle);
  14438. registerShape('ellipse', Ellipse);
  14439. registerShape('sector', Sector);
  14440. registerShape('ring', Ring);
  14441. registerShape('polygon', Polygon);
  14442. registerShape('polyline', Polyline);
  14443. registerShape('rect', Rect);
  14444. registerShape('line', Line);
  14445. registerShape('bezierCurve', BezierCurve);
  14446. registerShape('arc', Arc);
  14447. var graphic = /*#__PURE__*/Object.freeze({
  14448. __proto__: null,
  14449. updateProps: updateProps,
  14450. initProps: initProps,
  14451. removeElement: removeElement,
  14452. removeElementWithFadeOut: removeElementWithFadeOut,
  14453. isElementRemoved: isElementRemoved,
  14454. extendShape: extendShape,
  14455. extendPath: extendPath,
  14456. registerShape: registerShape,
  14457. getShapeClass: getShapeClass,
  14458. makePath: makePath,
  14459. makeImage: makeImage,
  14460. mergePath: mergePath$1,
  14461. resizePath: resizePath,
  14462. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14463. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14464. subPixelOptimize: subPixelOptimize$1,
  14465. getTransform: getTransform,
  14466. applyTransform: applyTransform$1,
  14467. transformDirection: transformDirection,
  14468. groupTransition: groupTransition,
  14469. clipPointsByRect: clipPointsByRect,
  14470. clipRectByRect: clipRectByRect,
  14471. createIcon: createIcon,
  14472. linePolygonIntersect: linePolygonIntersect,
  14473. lineLineIntersect: lineLineIntersect,
  14474. setTooltipConfig: setTooltipConfig,
  14475. Group: Group,
  14476. Image: ZRImage,
  14477. Text: ZRText,
  14478. Circle: Circle,
  14479. Ellipse: Ellipse,
  14480. Sector: Sector,
  14481. Ring: Ring,
  14482. Polygon: Polygon,
  14483. Polyline: Polyline,
  14484. Rect: Rect,
  14485. Line: Line,
  14486. BezierCurve: BezierCurve,
  14487. Arc: Arc,
  14488. IncrementalDisplayable: IncrementalDisplayable,
  14489. CompoundPath: CompoundPath,
  14490. LinearGradient: LinearGradient,
  14491. RadialGradient: RadialGradient,
  14492. BoundingRect: BoundingRect,
  14493. OrientedBoundingRect: OrientedBoundingRect,
  14494. Point: Point,
  14495. Path: Path
  14496. });
  14497. var EMPTY_OBJ = {};
  14498. function setLabelText(label, labelTexts) {
  14499. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14500. var stateName = SPECIAL_STATES[i];
  14501. var text = labelTexts[stateName];
  14502. var state = label.ensureState(stateName);
  14503. state.style = state.style || {};
  14504. state.style.text = text;
  14505. }
  14506. var oldStates = label.currentStates.slice();
  14507. label.clearStates(true);
  14508. label.setStyle({
  14509. text: labelTexts.normal
  14510. });
  14511. label.useStates(oldStates, true);
  14512. }
  14513. function getLabelText(opt, stateModels, interpolatedValue) {
  14514. var labelFetcher = opt.labelFetcher;
  14515. var labelDataIndex = opt.labelDataIndex;
  14516. var labelDimIndex = opt.labelDimIndex;
  14517. var normalModel = stateModels.normal;
  14518. var baseText;
  14519. if (labelFetcher) {
  14520. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14521. interpolatedValue: interpolatedValue
  14522. } : null);
  14523. }
  14524. if (baseText == null) {
  14525. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14526. }
  14527. var statesText = {
  14528. normal: baseText
  14529. };
  14530. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14531. var stateName = SPECIAL_STATES[i];
  14532. var stateModel = stateModels[stateName];
  14533. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14534. }
  14535. return statesText;
  14536. }
  14537. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  14538. ) {
  14539. opt = opt || EMPTY_OBJ;
  14540. var isSetOnText = targetEl instanceof ZRText;
  14541. var needsCreateText = false;
  14542. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14543. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14544. if (stateModel && stateModel.getShallow('show')) {
  14545. needsCreateText = true;
  14546. break;
  14547. }
  14548. }
  14549. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14550. if (needsCreateText) {
  14551. if (!isSetOnText) {
  14552. // Reuse the previous
  14553. if (!textContent) {
  14554. textContent = new ZRText();
  14555. targetEl.setTextContent(textContent);
  14556. } // Use same state proxy
  14557. if (targetEl.stateProxy) {
  14558. textContent.stateProxy = targetEl.stateProxy;
  14559. }
  14560. }
  14561. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14562. var normalModel = labelStatesModels.normal;
  14563. var showNormal = !!normalModel.getShallow('show');
  14564. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14565. normalStyle.text = labelStatesTexts.normal;
  14566. if (!isSetOnText) {
  14567. // Always create new
  14568. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14569. }
  14570. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14571. var stateName = SPECIAL_STATES[i];
  14572. var stateModel = labelStatesModels[stateName];
  14573. if (stateModel) {
  14574. var stateObj = textContent.ensureState(stateName);
  14575. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14576. if (stateShow !== showNormal) {
  14577. stateObj.ignore = !stateShow;
  14578. }
  14579. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14580. stateObj.style.text = labelStatesTexts[stateName];
  14581. if (!isSetOnText) {
  14582. var targetElEmphasisState = targetEl.ensureState(stateName);
  14583. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14584. }
  14585. }
  14586. } // PENDING: if there is many requirements that emphasis position
  14587. // need to be different from normal position, we might consider
  14588. // auto slient is those cases.
  14589. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14590. if (textContent.style.x != null) {
  14591. normalStyle.x = textContent.style.x;
  14592. }
  14593. if (textContent.style.y != null) {
  14594. normalStyle.y = textContent.style.y;
  14595. }
  14596. textContent.ignore = !showNormal; // Always create new style.
  14597. textContent.useStyle(normalStyle);
  14598. textContent.dirty();
  14599. if (opt.enableTextSetter) {
  14600. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14601. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14602. setLabelText(textContent, labelStatesTexts);
  14603. };
  14604. }
  14605. } else if (textContent) {
  14606. // Not display rich text.
  14607. textContent.ignore = true;
  14608. }
  14609. targetEl.dirty();
  14610. }
  14611. function getLabelStatesModels(itemModel, labelName) {
  14612. labelName = labelName || 'label';
  14613. var statesModels = {
  14614. normal: itemModel.getModel(labelName)
  14615. };
  14616. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14617. var stateName = SPECIAL_STATES[i];
  14618. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14619. }
  14620. return statesModels;
  14621. }
  14622. /**
  14623. * Set basic textStyle properties.
  14624. */
  14625. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14626. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14627. ) {
  14628. var textStyle = {};
  14629. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14630. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14631. return textStyle;
  14632. }
  14633. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14634. opt = opt || {};
  14635. var textConfig = {};
  14636. var labelPosition;
  14637. var labelRotate = textStyleModel.getShallow('rotate');
  14638. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14639. var labelOffset = textStyleModel.getShallow('offset');
  14640. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14641. // in bar series, and magric type should be considered.
  14642. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14643. if (labelPosition != null) {
  14644. textConfig.position = labelPosition;
  14645. }
  14646. if (labelOffset != null) {
  14647. textConfig.offset = labelOffset;
  14648. }
  14649. if (labelRotate != null) {
  14650. labelRotate *= Math.PI / 180;
  14651. textConfig.rotation = labelRotate;
  14652. }
  14653. if (labelDistance != null) {
  14654. textConfig.distance = labelDistance;
  14655. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14656. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14657. return textConfig;
  14658. }
  14659. /**
  14660. * The uniform entry of set text style, that is, retrieve style definitions
  14661. * from `model` and set to `textStyle` object.
  14662. *
  14663. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14664. * properties will be set. (Consider the states of normal and emphasis and
  14665. * default value can be adopted, merge would make the logic too complicated
  14666. * to manage.)
  14667. */
  14668. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14669. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14670. opt = opt || EMPTY_OBJ;
  14671. var ecModel = textStyleModel.ecModel;
  14672. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14673. // {
  14674. // data: [{
  14675. // value: 12,
  14676. // label: {
  14677. // rich: {
  14678. // // no 'a' here but using parent 'a'.
  14679. // }
  14680. // }
  14681. // }],
  14682. // rich: {
  14683. // a: { ... }
  14684. // }
  14685. // }
  14686. var richItemNames = getRichItemNames(textStyleModel);
  14687. var richResult;
  14688. if (richItemNames) {
  14689. richResult = {};
  14690. for (var name_1 in richItemNames) {
  14691. if (richItemNames.hasOwnProperty(name_1)) {
  14692. // Cascade is supported in rich.
  14693. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14694. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14695. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14696. // That might confuses users. So probably we should put `textStyleModel` as the
  14697. // root ancestor of the `richTextStyle`. But that would be a break change.
  14698. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14699. }
  14700. }
  14701. }
  14702. if (richResult) {
  14703. textStyle.rich = richResult;
  14704. }
  14705. var overflow = textStyleModel.get('overflow');
  14706. if (overflow) {
  14707. textStyle.overflow = overflow;
  14708. }
  14709. var margin = textStyleModel.get('minMargin');
  14710. if (margin != null) {
  14711. textStyle.margin = margin;
  14712. }
  14713. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  14714. } // Consider case:
  14715. // {
  14716. // data: [{
  14717. // value: 12,
  14718. // label: {
  14719. // rich: {
  14720. // // no 'a' here but using parent 'a'.
  14721. // }
  14722. // }
  14723. // }],
  14724. // rich: {
  14725. // a: { ... }
  14726. // }
  14727. // }
  14728. // TODO TextStyleModel
  14729. function getRichItemNames(textStyleModel) {
  14730. // Use object to remove duplicated names.
  14731. var richItemNameMap;
  14732. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14733. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14734. if (rich) {
  14735. richItemNameMap = richItemNameMap || {};
  14736. var richKeys = keys(rich);
  14737. for (var i = 0; i < richKeys.length; i++) {
  14738. var richKey = richKeys[i];
  14739. richItemNameMap[richKey] = 1;
  14740. }
  14741. }
  14742. textStyleModel = textStyleModel.parentModel;
  14743. }
  14744. return richItemNameMap;
  14745. }
  14746. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  14747. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign'];
  14748. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  14749. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  14750. // In merge mode, default value should not be given.
  14751. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  14752. var inheritColor = opt && opt.inheritColor;
  14753. var fillColor = textStyleModel.getShallow('color');
  14754. var strokeColor = textStyleModel.getShallow('textBorderColor');
  14755. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  14756. if (fillColor === 'inherit' || fillColor === 'auto') {
  14757. if ("development" !== 'production') {
  14758. if (fillColor === 'auto') {
  14759. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14760. }
  14761. }
  14762. if (inheritColor) {
  14763. fillColor = inheritColor;
  14764. } else {
  14765. fillColor = null;
  14766. }
  14767. }
  14768. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  14769. if ("development" !== 'production') {
  14770. if (strokeColor === 'auto') {
  14771. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14772. }
  14773. }
  14774. if (inheritColor) {
  14775. strokeColor = inheritColor;
  14776. } else {
  14777. strokeColor = null;
  14778. }
  14779. }
  14780. if (!isAttached) {
  14781. // Only use default global textStyle.color if text is individual.
  14782. // Otherwise it will use the strategy of attached text color because text may be on a path.
  14783. fillColor = fillColor || globalTextStyle.color;
  14784. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  14785. }
  14786. if (fillColor != null) {
  14787. textStyle.fill = fillColor;
  14788. }
  14789. if (strokeColor != null) {
  14790. textStyle.stroke = strokeColor;
  14791. }
  14792. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14793. if (textBorderWidth != null) {
  14794. textStyle.lineWidth = textBorderWidth;
  14795. }
  14796. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  14797. if (textBorderType != null) {
  14798. textStyle.lineDash = textBorderType;
  14799. }
  14800. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  14801. if (textBorderDashOffset != null) {
  14802. textStyle.lineDashOffset = textBorderDashOffset;
  14803. }
  14804. if (!isNotNormal && opacity == null && !inRich) {
  14805. opacity = opt && opt.defaultOpacity;
  14806. }
  14807. if (opacity != null) {
  14808. textStyle.opacity = opacity;
  14809. } // TODO
  14810. if (!isNotNormal && !isAttached) {
  14811. // Set default finally.
  14812. if (textStyle.fill == null && opt.inheritColor) {
  14813. textStyle.fill = opt.inheritColor;
  14814. }
  14815. } // Do not use `getFont` here, because merge should be supported, where
  14816. // part of these properties may be changed in emphasis style, and the
  14817. // others should remain their original value got from normal style.
  14818. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  14819. var key = TEXT_PROPS_WITH_GLOBAL[i];
  14820. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  14821. if (val != null) {
  14822. textStyle[key] = val;
  14823. }
  14824. }
  14825. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  14826. var key = TEXT_PROPS_SELF[i];
  14827. var val = textStyleModel.getShallow(key);
  14828. if (val != null) {
  14829. textStyle[key] = val;
  14830. }
  14831. }
  14832. if (textStyle.verticalAlign == null) {
  14833. var baseline = textStyleModel.getShallow('baseline');
  14834. if (baseline != null) {
  14835. textStyle.verticalAlign = baseline;
  14836. }
  14837. }
  14838. if (!isBlock || !opt.disableBox) {
  14839. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  14840. var key = TEXT_PROPS_BOX[i];
  14841. var val = textStyleModel.getShallow(key);
  14842. if (val != null) {
  14843. textStyle[key] = val;
  14844. }
  14845. }
  14846. var borderType = textStyleModel.getShallow('borderType');
  14847. if (borderType != null) {
  14848. textStyle.borderDash = borderType;
  14849. }
  14850. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  14851. if ("development" !== 'production') {
  14852. if (textStyle.backgroundColor === 'auto') {
  14853. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  14854. }
  14855. }
  14856. textStyle.backgroundColor = inheritColor;
  14857. }
  14858. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  14859. if ("development" !== 'production') {
  14860. if (textStyle.borderColor === 'auto') {
  14861. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  14862. }
  14863. }
  14864. textStyle.borderColor = inheritColor;
  14865. }
  14866. }
  14867. }
  14868. function getFont(opt, ecModel) {
  14869. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  14870. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  14871. 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(' '));
  14872. }
  14873. var labelInner = makeInner();
  14874. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  14875. if (!label) {
  14876. return;
  14877. }
  14878. var obj = labelInner(label);
  14879. obj.prevValue = obj.value;
  14880. obj.value = value;
  14881. var normalLabelModel = labelStatesModels.normal;
  14882. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  14883. if (obj.valueAnimation) {
  14884. obj.precision = normalLabelModel.get('precision');
  14885. obj.defaultInterpolatedText = getDefaultText;
  14886. obj.statesModels = labelStatesModels;
  14887. }
  14888. }
  14889. function animateLabelValue(textEl, dataIndex, data, animatableModel, labelFetcher) {
  14890. var labelInnerStore = labelInner(textEl);
  14891. if (!labelInnerStore.valueAnimation) {
  14892. return;
  14893. }
  14894. var defaultInterpolatedText = labelInnerStore.defaultInterpolatedText; // Consider the case that being animating, do not use the `obj.value`,
  14895. // Otherwise it will jump to the `obj.value` when this new animation started.
  14896. var currValue = retrieve2(labelInnerStore.interpolatedValue, labelInnerStore.prevValue);
  14897. var targetValue = labelInnerStore.value;
  14898. function during(percent) {
  14899. var interpolated = interpolateRawValues(data, labelInnerStore.precision, currValue, targetValue, percent);
  14900. labelInnerStore.interpolatedValue = percent === 1 ? null : interpolated;
  14901. var labelText = getLabelText({
  14902. labelDataIndex: dataIndex,
  14903. labelFetcher: labelFetcher,
  14904. defaultText: defaultInterpolatedText ? defaultInterpolatedText(interpolated) : interpolated + ''
  14905. }, labelInnerStore.statesModels, interpolated);
  14906. setLabelText(textEl, labelText);
  14907. }
  14908. (labelInnerStore.prevValue == null ? initProps : updateProps)(textEl, {}, animatableModel, dataIndex, null, during);
  14909. }
  14910. var PATH_COLOR = ['textStyle', 'color']; // TODO Performance improvement?
  14911. var tmpRichText = new ZRText();
  14912. var TextStyleMixin =
  14913. /** @class */
  14914. function () {
  14915. function TextStyleMixin() {}
  14916. /**
  14917. * Get color property or get color from option.textStyle.color
  14918. */
  14919. // TODO Callback
  14920. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  14921. var ecModel = this.ecModel;
  14922. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  14923. };
  14924. /**
  14925. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14926. * @return {string}
  14927. */
  14928. TextStyleMixin.prototype.getFont = function () {
  14929. return getFont({
  14930. fontStyle: this.getShallow('fontStyle'),
  14931. fontWeight: this.getShallow('fontWeight'),
  14932. fontSize: this.getShallow('fontSize'),
  14933. fontFamily: this.getShallow('fontFamily')
  14934. }, this.ecModel);
  14935. };
  14936. TextStyleMixin.prototype.getTextRect = function (text) {
  14937. tmpRichText.useStyle({
  14938. text: text,
  14939. fontStyle: this.getShallow('fontStyle'),
  14940. fontWeight: this.getShallow('fontWeight'),
  14941. fontSize: this.getShallow('fontSize'),
  14942. fontFamily: this.getShallow('fontFamily'),
  14943. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14944. padding: this.getShallow('padding'),
  14945. lineHeight: this.getShallow('lineHeight'),
  14946. rich: this.getShallow('rich')
  14947. });
  14948. tmpRichText.update();
  14949. return tmpRichText.getBoundingRect();
  14950. };
  14951. return TextStyleMixin;
  14952. }();
  14953. 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`.
  14954. // So do not transfer decal directly.
  14955. ];
  14956. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  14957. var LineStyleMixin =
  14958. /** @class */
  14959. function () {
  14960. function LineStyleMixin() {}
  14961. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  14962. return getLineStyle(this, excludes);
  14963. };
  14964. return LineStyleMixin;
  14965. }();
  14966. 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`.
  14967. // So do not transfer decal directly.
  14968. ];
  14969. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  14970. var ItemStyleMixin =
  14971. /** @class */
  14972. function () {
  14973. function ItemStyleMixin() {}
  14974. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  14975. return getItemStyle(this, excludes, includes);
  14976. };
  14977. return ItemStyleMixin;
  14978. }();
  14979. var Model =
  14980. /** @class */
  14981. function () {
  14982. function Model(option, parentModel, ecModel) {
  14983. this.parentModel = parentModel;
  14984. this.ecModel = ecModel;
  14985. this.option = option; // Simple optimization
  14986. // if (this.init) {
  14987. // if (arguments.length <= 4) {
  14988. // this.init(option, parentModel, ecModel, extraOpt);
  14989. // }
  14990. // else {
  14991. // this.init.apply(this, arguments);
  14992. // }
  14993. // }
  14994. }
  14995. Model.prototype.init = function (option, parentModel, ecModel) {
  14996. var rest = [];
  14997. for (var _i = 3; _i < arguments.length; _i++) {
  14998. rest[_i - 3] = arguments[_i];
  14999. }
  15000. };
  15001. /**
  15002. * Merge the input option to me.
  15003. */
  15004. Model.prototype.mergeOption = function (option, ecModel) {
  15005. merge(this.option, option, true);
  15006. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `ModelOption`
  15007. // TODO: TYPE strict key check?
  15008. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15009. Model.prototype.get = function (path, ignoreParent) {
  15010. if (path == null) {
  15011. return this.option;
  15012. }
  15013. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15014. };
  15015. Model.prototype.getShallow = function (key, ignoreParent) {
  15016. var option = this.option;
  15017. var val = option == null ? option : option[key];
  15018. if (val == null && !ignoreParent) {
  15019. var parentModel = this.parentModel;
  15020. if (parentModel) {
  15021. // FIXME:TS do not know how to make it works
  15022. val = parentModel.getShallow(key);
  15023. }
  15024. }
  15025. return val;
  15026. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `Model<ModelOption>`
  15027. // getModel(path: string | string[], parentModel?: Model): Model;
  15028. // TODO 'xxx.yyy.zzz' is deprecated
  15029. Model.prototype.getModel = function (path, parentModel) {
  15030. var hasPath = path != null;
  15031. var pathFinal = hasPath ? this.parsePath(path) : null;
  15032. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15033. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15034. return new Model(obj, parentModel, this.ecModel);
  15035. };
  15036. /**
  15037. * Squash option stack into one.
  15038. * parentModel will be removed after squashed.
  15039. *
  15040. * NOTE: resolveParentPath will not be applied here for simplicity. DON'T use this function
  15041. * if resolveParentPath is modified.
  15042. *
  15043. * @param deepMerge If do deep merge. Default to be false.
  15044. */
  15045. // squash(
  15046. // deepMerge?: boolean,
  15047. // handleCallback?: (func: () => object) => object
  15048. // ) {
  15049. // const optionStack = [];
  15050. // let model: Model = this;
  15051. // while (model) {
  15052. // if (model.option) {
  15053. // optionStack.push(model.option);
  15054. // }
  15055. // model = model.parentModel;
  15056. // }
  15057. // const newOption = {} as Opt;
  15058. // let option;
  15059. // while (option = optionStack.pop()) { // Top down merge
  15060. // if (isFunction(option) && handleCallback) {
  15061. // option = handleCallback(option);
  15062. // }
  15063. // if (deepMerge) {
  15064. // merge(newOption, option);
  15065. // }
  15066. // else {
  15067. // extend(newOption, option);
  15068. // }
  15069. // }
  15070. // // Remove parentModel
  15071. // this.option = newOption;
  15072. // this.parentModel = null;
  15073. // }
  15074. /**
  15075. * If model has option
  15076. */
  15077. Model.prototype.isEmpty = function () {
  15078. return this.option == null;
  15079. };
  15080. Model.prototype.restoreData = function () {}; // Pending
  15081. Model.prototype.clone = function () {
  15082. var Ctor = this.constructor;
  15083. return new Ctor(clone(this.option));
  15084. }; // setReadOnly(properties): void {
  15085. // clazzUtil.setReadOnly(this, properties);
  15086. // }
  15087. // If path is null/undefined, return null/undefined.
  15088. Model.prototype.parsePath = function (path) {
  15089. if (typeof path === 'string') {
  15090. return path.split('.');
  15091. }
  15092. return path;
  15093. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  15094. // Default to be a identity resolver.
  15095. // Can be modified to a different resolver.
  15096. Model.prototype.resolveParentPath = function (path) {
  15097. return path;
  15098. }; // FIXME:TS check whether put this method here
  15099. Model.prototype.isAnimationEnabled = function () {
  15100. if (!env.node && this.option) {
  15101. if (this.option.animation != null) {
  15102. return !!this.option.animation;
  15103. } else if (this.parentModel) {
  15104. return this.parentModel.isAnimationEnabled();
  15105. }
  15106. }
  15107. };
  15108. Model.prototype._doGet = function (pathArr, parentModel) {
  15109. var obj = this.option;
  15110. if (!pathArr) {
  15111. return obj;
  15112. }
  15113. for (var i = 0; i < pathArr.length; i++) {
  15114. // Ignore empty
  15115. if (!pathArr[i]) {
  15116. continue;
  15117. } // obj could be number/string/... (like 0)
  15118. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15119. if (obj == null) {
  15120. break;
  15121. }
  15122. }
  15123. if (obj == null && parentModel) {
  15124. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15125. }
  15126. return obj;
  15127. };
  15128. return Model;
  15129. }();
  15130. enableClassExtend(Model);
  15131. enableClassCheck(Model);
  15132. mixin(Model, LineStyleMixin);
  15133. mixin(Model, ItemStyleMixin);
  15134. mixin(Model, AreaStyleMixin);
  15135. mixin(Model, TextStyleMixin);
  15136. var base = Math.round(Math.random() * 10);
  15137. /**
  15138. * @public
  15139. * @param {string} type
  15140. * @return {string}
  15141. */
  15142. function getUID(type) {
  15143. // Considering the case of crossing js context,
  15144. // use Math.random to make id as unique as possible.
  15145. return [type || '', base++].join('_');
  15146. }
  15147. /**
  15148. * Implements `SubTypeDefaulterManager` for `target`.
  15149. */
  15150. function enableSubTypeDefaulter(target) {
  15151. var subTypeDefaulters = {};
  15152. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  15153. var componentTypeInfo = parseClassType(componentType);
  15154. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  15155. };
  15156. target.determineSubType = function (componentType, option) {
  15157. var type = option.type;
  15158. if (!type) {
  15159. var componentTypeMain = parseClassType(componentType).main;
  15160. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15161. type = subTypeDefaulters[componentTypeMain](option);
  15162. }
  15163. }
  15164. return type;
  15165. };
  15166. }
  15167. /**
  15168. * Implements `TopologicalTravelable<any>` for `entity`.
  15169. *
  15170. * Topological travel on Activity Network (Activity On Vertices).
  15171. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15172. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15173. * If there is circular dependencey, Error will be thrown.
  15174. */
  15175. function enableTopologicalTravel(entity, dependencyGetter) {
  15176. /**
  15177. * @param targetNameList Target Component type list.
  15178. * Can be ['aa', 'bb', 'aa.xx']
  15179. * @param fullNameList By which we can build dependency graph.
  15180. * @param callback Params: componentType, dependencies.
  15181. * @param context Scope of callback.
  15182. */
  15183. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15184. if (!targetNameList.length) {
  15185. return;
  15186. }
  15187. var result = makeDepndencyGraph(fullNameList);
  15188. var graph = result.graph;
  15189. var noEntryList = result.noEntryList;
  15190. var targetNameSet = {};
  15191. each(targetNameList, function (name) {
  15192. targetNameSet[name] = true;
  15193. });
  15194. while (noEntryList.length) {
  15195. var currComponentType = noEntryList.pop();
  15196. var currVertex = graph[currComponentType];
  15197. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15198. if (isInTargetNameSet) {
  15199. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15200. delete targetNameSet[currComponentType];
  15201. }
  15202. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15203. }
  15204. each(targetNameSet, function () {
  15205. var errMsg = '';
  15206. if ("development" !== 'production') {
  15207. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  15208. }
  15209. throw new Error(errMsg);
  15210. });
  15211. function removeEdge(succComponentType) {
  15212. graph[succComponentType].entryCount--;
  15213. if (graph[succComponentType].entryCount === 0) {
  15214. noEntryList.push(succComponentType);
  15215. }
  15216. } // Consider this case: legend depends on series, and we call
  15217. // chart.setOption({series: [...]}), where only series is in option.
  15218. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15219. // not be called, but only sereis.mergeOption is called. Thus legend
  15220. // have no chance to update its local record about series (like which
  15221. // name of series is available in legend).
  15222. function removeEdgeAndAdd(succComponentType) {
  15223. targetNameSet[succComponentType] = true;
  15224. removeEdge(succComponentType);
  15225. }
  15226. };
  15227. function makeDepndencyGraph(fullNameList) {
  15228. var graph = {};
  15229. var noEntryList = [];
  15230. each(fullNameList, function (name) {
  15231. var thisItem = createDependencyGraphItem(graph, name);
  15232. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15233. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15234. thisItem.entryCount = availableDeps.length;
  15235. if (thisItem.entryCount === 0) {
  15236. noEntryList.push(name);
  15237. }
  15238. each(availableDeps, function (dependentName) {
  15239. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15240. thisItem.predecessor.push(dependentName);
  15241. }
  15242. var thatItem = createDependencyGraphItem(graph, dependentName);
  15243. if (indexOf(thatItem.successor, dependentName) < 0) {
  15244. thatItem.successor.push(name);
  15245. }
  15246. });
  15247. });
  15248. return {
  15249. graph: graph,
  15250. noEntryList: noEntryList
  15251. };
  15252. }
  15253. function createDependencyGraphItem(graph, name) {
  15254. if (!graph[name]) {
  15255. graph[name] = {
  15256. predecessor: [],
  15257. successor: []
  15258. };
  15259. }
  15260. return graph[name];
  15261. }
  15262. function getAvailableDependencies(originalDeps, fullNameList) {
  15263. var availableDeps = [];
  15264. each(originalDeps, function (dep) {
  15265. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15266. });
  15267. return availableDeps;
  15268. }
  15269. }
  15270. function inheritDefaultOption(superOption, subOption) {
  15271. // See also `model/Component.ts#getDefaultOption`
  15272. return merge(merge({}, superOption, true), subOption, true);
  15273. }
  15274. /*
  15275. * Licensed to the Apache Software Foundation (ASF) under one
  15276. * or more contributor license agreements. See the NOTICE file
  15277. * distributed with this work for additional information
  15278. * regarding copyright ownership. The ASF licenses this file
  15279. * to you under the Apache License, Version 2.0 (the
  15280. * "License"); you may not use this file except in compliance
  15281. * with the License. You may obtain a copy of the License at
  15282. *
  15283. * http://www.apache.org/licenses/LICENSE-2.0
  15284. *
  15285. * Unless required by applicable law or agreed to in writing,
  15286. * software distributed under the License is distributed on an
  15287. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15288. * KIND, either express or implied. See the License for the
  15289. * specific language governing permissions and limitations
  15290. * under the License.
  15291. */
  15292. /**
  15293. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15294. */
  15295. /*
  15296. * Licensed to the Apache Software Foundation (ASF) under one
  15297. * or more contributor license agreements. See the NOTICE file
  15298. * distributed with this work for additional information
  15299. * regarding copyright ownership. The ASF licenses this file
  15300. * to you under the Apache License, Version 2.0 (the
  15301. * "License"); you may not use this file except in compliance
  15302. * with the License. You may obtain a copy of the License at
  15303. *
  15304. * http://www.apache.org/licenses/LICENSE-2.0
  15305. *
  15306. * Unless required by applicable law or agreed to in writing,
  15307. * software distributed under the License is distributed on an
  15308. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15309. * KIND, either express or implied. See the License for the
  15310. * specific language governing permissions and limitations
  15311. * under the License.
  15312. */
  15313. /**
  15314. * Language: English.
  15315. */
  15316. var langEN = {
  15317. time: {
  15318. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  15319. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  15320. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  15321. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  15322. },
  15323. legend: {
  15324. selector: {
  15325. all: 'All',
  15326. inverse: 'Inv'
  15327. }
  15328. },
  15329. toolbox: {
  15330. brush: {
  15331. title: {
  15332. rect: 'Box Select',
  15333. polygon: 'Lasso Select',
  15334. lineX: 'Horizontally Select',
  15335. lineY: 'Vertically Select',
  15336. keep: 'Keep Selections',
  15337. clear: 'Clear Selections'
  15338. }
  15339. },
  15340. dataView: {
  15341. title: 'Data View',
  15342. lang: ['Data View', 'Close', 'Refresh']
  15343. },
  15344. dataZoom: {
  15345. title: {
  15346. zoom: 'Zoom',
  15347. back: 'Zoom Reset'
  15348. }
  15349. },
  15350. magicType: {
  15351. title: {
  15352. line: 'Switch to Line Chart',
  15353. bar: 'Switch to Bar Chart',
  15354. stack: 'Stack',
  15355. tiled: 'Tile'
  15356. }
  15357. },
  15358. restore: {
  15359. title: 'Restore'
  15360. },
  15361. saveAsImage: {
  15362. title: 'Save as Image',
  15363. lang: ['Right Click to Save Image']
  15364. }
  15365. },
  15366. series: {
  15367. typeNames: {
  15368. pie: 'Pie chart',
  15369. bar: 'Bar chart',
  15370. line: 'Line chart',
  15371. scatter: 'Scatter plot',
  15372. effectScatter: 'Ripple scatter plot',
  15373. radar: 'Radar chart',
  15374. tree: 'Tree',
  15375. treemap: 'Treemap',
  15376. boxplot: 'Boxplot',
  15377. candlestick: 'Candlestick',
  15378. k: 'K line chart',
  15379. heatmap: 'Heat map',
  15380. map: 'Map',
  15381. parallel: 'Parallel coordinate map',
  15382. lines: 'Line graph',
  15383. graph: 'Relationship graph',
  15384. sankey: 'Sankey diagram',
  15385. funnel: 'Funnel chart',
  15386. gauge: 'Gauge',
  15387. pictorialBar: 'Pictorial bar',
  15388. themeRiver: 'Theme River Map',
  15389. sunburst: 'Sunburst'
  15390. }
  15391. },
  15392. aria: {
  15393. general: {
  15394. withTitle: 'This is a chart about "{title}"',
  15395. withoutTitle: 'This is a chart'
  15396. },
  15397. series: {
  15398. single: {
  15399. prefix: '',
  15400. withName: ' with type {seriesType} named {seriesName}.',
  15401. withoutName: ' with type {seriesType}.'
  15402. },
  15403. multiple: {
  15404. prefix: '. It consists of {seriesCount} series count.',
  15405. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15406. withoutName: ' The {seriesId} series is a {seriesType}.',
  15407. separator: {
  15408. middle: '',
  15409. end: ''
  15410. }
  15411. }
  15412. },
  15413. data: {
  15414. allData: 'The data is as follows: ',
  15415. partialData: 'The first {displayCnt} items are: ',
  15416. withName: 'the data for {name} is {value}',
  15417. withoutName: '{value}',
  15418. separator: {
  15419. middle: ', ',
  15420. end: '. '
  15421. }
  15422. }
  15423. }
  15424. };
  15425. /*
  15426. * Licensed to the Apache Software Foundation (ASF) under one
  15427. * or more contributor license agreements. See the NOTICE file
  15428. * distributed with this work for additional information
  15429. * regarding copyright ownership. The ASF licenses this file
  15430. * to you under the Apache License, Version 2.0 (the
  15431. * "License"); you may not use this file except in compliance
  15432. * with the License. You may obtain a copy of the License at
  15433. *
  15434. * http://www.apache.org/licenses/LICENSE-2.0
  15435. *
  15436. * Unless required by applicable law or agreed to in writing,
  15437. * software distributed under the License is distributed on an
  15438. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15439. * KIND, either express or implied. See the License for the
  15440. * specific language governing permissions and limitations
  15441. * under the License.
  15442. */
  15443. /**
  15444. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15445. */
  15446. /*
  15447. * Licensed to the Apache Software Foundation (ASF) under one
  15448. * or more contributor license agreements. See the NOTICE file
  15449. * distributed with this work for additional information
  15450. * regarding copyright ownership. The ASF licenses this file
  15451. * to you under the Apache License, Version 2.0 (the
  15452. * "License"); you may not use this file except in compliance
  15453. * with the License. You may obtain a copy of the License at
  15454. *
  15455. * http://www.apache.org/licenses/LICENSE-2.0
  15456. *
  15457. * Unless required by applicable law or agreed to in writing,
  15458. * software distributed under the License is distributed on an
  15459. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15460. * KIND, either express or implied. See the License for the
  15461. * specific language governing permissions and limitations
  15462. * under the License.
  15463. */
  15464. var langZH = {
  15465. time: {
  15466. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15467. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15468. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15469. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15470. },
  15471. legend: {
  15472. selector: {
  15473. all: '全选',
  15474. inverse: '反选'
  15475. }
  15476. },
  15477. toolbox: {
  15478. brush: {
  15479. title: {
  15480. rect: '矩形选择',
  15481. polygon: '圈选',
  15482. lineX: '横向选择',
  15483. lineY: '纵向选择',
  15484. keep: '保持选择',
  15485. clear: '清除选择'
  15486. }
  15487. },
  15488. dataView: {
  15489. title: '数据视图',
  15490. lang: ['数据视图', '关闭', '刷新']
  15491. },
  15492. dataZoom: {
  15493. title: {
  15494. zoom: '区域缩放',
  15495. back: '区域缩放还原'
  15496. }
  15497. },
  15498. magicType: {
  15499. title: {
  15500. line: '切换为折线图',
  15501. bar: '切换为柱状图',
  15502. stack: '切换为堆叠',
  15503. tiled: '切换为平铺'
  15504. }
  15505. },
  15506. restore: {
  15507. title: '还原'
  15508. },
  15509. saveAsImage: {
  15510. title: '保存为图片',
  15511. lang: ['右键另存为图片']
  15512. }
  15513. },
  15514. series: {
  15515. typeNames: {
  15516. pie: '饼图',
  15517. bar: '柱状图',
  15518. line: '折线图',
  15519. scatter: '散点图',
  15520. effectScatter: '涟漪散点图',
  15521. radar: '雷达图',
  15522. tree: '树图',
  15523. treemap: '矩形树图',
  15524. boxplot: '箱型图',
  15525. candlestick: 'K线图',
  15526. k: 'K线图',
  15527. heatmap: '热力图',
  15528. map: '地图',
  15529. parallel: '平行坐标图',
  15530. lines: '线图',
  15531. graph: '关系图',
  15532. sankey: '桑基图',
  15533. funnel: '漏斗图',
  15534. gauge: '仪表盘图',
  15535. pictorialBar: '象形柱图',
  15536. themeRiver: '主题河流图',
  15537. sunburst: '旭日图'
  15538. }
  15539. },
  15540. aria: {
  15541. general: {
  15542. withTitle: '这是一个关于“{title}”的图表。',
  15543. withoutTitle: '这是一个图表,'
  15544. },
  15545. series: {
  15546. single: {
  15547. prefix: '',
  15548. withName: '图表类型是{seriesType},表示{seriesName}。',
  15549. withoutName: '图表类型是{seriesType}。'
  15550. },
  15551. multiple: {
  15552. prefix: '它由{seriesCount}个图表系列组成。',
  15553. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15554. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15555. separator: {
  15556. middle: ';',
  15557. end: '。'
  15558. }
  15559. }
  15560. },
  15561. data: {
  15562. allData: '其数据是——',
  15563. partialData: '其中,前{displayCnt}项是——',
  15564. withName: '{name}的数据是{value}',
  15565. withoutName: '{value}',
  15566. separator: {
  15567. middle: ',',
  15568. end: ''
  15569. }
  15570. }
  15571. }
  15572. };
  15573. var LOCALE_ZH = 'ZH';
  15574. var LOCALE_EN = 'EN';
  15575. var DEFAULT_LOCALE = LOCALE_EN;
  15576. var localeStorage = {};
  15577. var localeModels = {};
  15578. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15579. var langStr = (
  15580. /* eslint-disable-next-line */
  15581. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15582. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15583. }();
  15584. function registerLocale(locale, localeObj) {
  15585. locale = locale.toUpperCase();
  15586. localeModels[locale] = new Model(localeObj);
  15587. localeStorage[locale] = localeObj;
  15588. } // export function getLocale(locale: string) {
  15589. // return localeStorage[locale];
  15590. // }
  15591. function createLocaleObject(locale) {
  15592. if (isString(locale)) {
  15593. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15594. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15595. return clone(localeObj);
  15596. } else {
  15597. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15598. }
  15599. } else {
  15600. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15601. }
  15602. }
  15603. function getLocaleModel(lang) {
  15604. return localeModels[lang];
  15605. }
  15606. function getDefaultLocaleModel() {
  15607. return localeModels[DEFAULT_LOCALE];
  15608. } // Default locale
  15609. registerLocale(LOCALE_EN, langEN);
  15610. registerLocale(LOCALE_ZH, langZH);
  15611. var ONE_SECOND = 1000;
  15612. var ONE_MINUTE = ONE_SECOND * 60;
  15613. var ONE_HOUR = ONE_MINUTE * 60;
  15614. var ONE_DAY = ONE_HOUR * 24;
  15615. var ONE_YEAR = ONE_DAY * 365;
  15616. var defaultLeveledFormatter = {
  15617. year: '{yyyy}',
  15618. month: '{MMM}',
  15619. day: '{d}',
  15620. hour: '{HH}:{mm}',
  15621. minute: '{HH}:{mm}',
  15622. second: '{HH}:{mm}:{ss}',
  15623. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15624. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15625. };
  15626. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15627. var fullLeveledFormatter = {
  15628. year: '{yyyy}',
  15629. month: '{yyyy}-{MM}',
  15630. day: fullDayFormatter,
  15631. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15632. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15633. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15634. millisecond: defaultLeveledFormatter.none
  15635. };
  15636. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15637. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15638. function pad(str, len) {
  15639. str += '';
  15640. return '0000'.substr(0, len - str.length) + str;
  15641. }
  15642. function getPrimaryTimeUnit(timeUnit) {
  15643. switch (timeUnit) {
  15644. case 'half-year':
  15645. case 'quarter':
  15646. return 'month';
  15647. case 'week':
  15648. case 'half-week':
  15649. return 'day';
  15650. case 'half-day':
  15651. case 'quarter-day':
  15652. return 'hour';
  15653. default:
  15654. // year, minutes, second, milliseconds
  15655. return timeUnit;
  15656. }
  15657. }
  15658. function isPrimaryTimeUnit(timeUnit) {
  15659. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15660. }
  15661. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15662. switch (timeUnit) {
  15663. case 'year':
  15664. case 'month':
  15665. return 'day';
  15666. case 'millisecond':
  15667. return 'millisecond';
  15668. default:
  15669. // Also for day, hour, minute, second
  15670. return 'second';
  15671. }
  15672. }
  15673. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15674. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15675. time, template, isUTC, lang) {
  15676. var date = parseDate(time);
  15677. var y = date[fullYearGetterName(isUTC)]();
  15678. var M = date[monthGetterName(isUTC)]() + 1;
  15679. var q = Math.floor((M - 1) / 4) + 1;
  15680. var d = date[dateGetterName(isUTC)]();
  15681. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15682. var H = date[hoursGetterName(isUTC)]();
  15683. var h = (H - 1) % 12 + 1;
  15684. var m = date[minutesGetterName(isUTC)]();
  15685. var s = date[secondsGetterName(isUTC)]();
  15686. var S = date[millisecondsGetterName(isUTC)]();
  15687. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15688. var timeModel = localeModel.getModel('time');
  15689. var month = timeModel.get('month');
  15690. var monthAbbr = timeModel.get('monthAbbr');
  15691. var dayOfWeek = timeModel.get('dayOfWeek');
  15692. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15693. 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 + '');
  15694. }
  15695. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15696. var template = null;
  15697. if (typeof formatter === 'string') {
  15698. // Single formatter for all units at all levels
  15699. template = formatter;
  15700. } else if (typeof formatter === 'function') {
  15701. // Callback formatter
  15702. template = formatter(tick.value, idx, {
  15703. level: tick.level
  15704. });
  15705. } else {
  15706. var defaults$1 = extend({}, defaultLeveledFormatter);
  15707. if (tick.level > 0) {
  15708. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15709. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15710. }
  15711. }
  15712. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15713. : defaults(formatter, defaults$1) : defaults$1;
  15714. var unit = getUnitFromValue(tick.value, isUTC);
  15715. if (mergedFormatter[unit]) {
  15716. template = mergedFormatter[unit];
  15717. } else if (mergedFormatter.inherit) {
  15718. // Unit formatter is not defined and should inherit from bigger units
  15719. var targetId = timeUnits.indexOf(unit);
  15720. for (var i = targetId - 1; i >= 0; --i) {
  15721. if (mergedFormatter[unit]) {
  15722. template = mergedFormatter[unit];
  15723. break;
  15724. }
  15725. }
  15726. template = template || defaults$1.none;
  15727. }
  15728. if (isArray(template)) {
  15729. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15730. levelId = Math.min(levelId, template.length - 1);
  15731. template = template[levelId];
  15732. }
  15733. }
  15734. return format(new Date(tick.value), template, isUTC, lang);
  15735. }
  15736. function getUnitFromValue(value, isUTC) {
  15737. var date = parseDate(value);
  15738. var M = date[monthGetterName(isUTC)]() + 1;
  15739. var d = date[dateGetterName(isUTC)]();
  15740. var h = date[hoursGetterName(isUTC)]();
  15741. var m = date[minutesGetterName(isUTC)]();
  15742. var s = date[secondsGetterName(isUTC)]();
  15743. var S = date[millisecondsGetterName(isUTC)]();
  15744. var isSecond = S === 0;
  15745. var isMinute = isSecond && s === 0;
  15746. var isHour = isMinute && m === 0;
  15747. var isDay = isHour && h === 0;
  15748. var isMonth = isDay && d === 1;
  15749. var isYear = isMonth && M === 1;
  15750. if (isYear) {
  15751. return 'year';
  15752. } else if (isMonth) {
  15753. return 'month';
  15754. } else if (isDay) {
  15755. return 'day';
  15756. } else if (isHour) {
  15757. return 'hour';
  15758. } else if (isMinute) {
  15759. return 'minute';
  15760. } else if (isSecond) {
  15761. return 'second';
  15762. } else {
  15763. return 'millisecond';
  15764. }
  15765. }
  15766. function getUnitValue(value, unit, isUTC) {
  15767. var date = typeof value === 'number' ? parseDate(value) : value;
  15768. unit = unit || getUnitFromValue(value, isUTC);
  15769. switch (unit) {
  15770. case 'year':
  15771. return date[fullYearGetterName(isUTC)]();
  15772. case 'half-year':
  15773. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  15774. case 'quarter':
  15775. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  15776. case 'month':
  15777. return date[monthGetterName(isUTC)]();
  15778. case 'day':
  15779. return date[dateGetterName(isUTC)]();
  15780. case 'half-day':
  15781. return date[hoursGetterName(isUTC)]() / 24;
  15782. case 'hour':
  15783. return date[hoursGetterName(isUTC)]();
  15784. case 'minute':
  15785. return date[minutesGetterName(isUTC)]();
  15786. case 'second':
  15787. return date[secondsGetterName(isUTC)]();
  15788. case 'millisecond':
  15789. return date[millisecondsGetterName(isUTC)]();
  15790. }
  15791. }
  15792. function fullYearGetterName(isUTC) {
  15793. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  15794. }
  15795. function monthGetterName(isUTC) {
  15796. return isUTC ? 'getUTCMonth' : 'getMonth';
  15797. }
  15798. function dateGetterName(isUTC) {
  15799. return isUTC ? 'getUTCDate' : 'getDate';
  15800. }
  15801. function hoursGetterName(isUTC) {
  15802. return isUTC ? 'getUTCHours' : 'getHours';
  15803. }
  15804. function minutesGetterName(isUTC) {
  15805. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  15806. }
  15807. function secondsGetterName(isUTC) {
  15808. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15809. }
  15810. function millisecondsGetterName(isUTC) {
  15811. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  15812. }
  15813. function fullYearSetterName(isUTC) {
  15814. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  15815. }
  15816. function monthSetterName(isUTC) {
  15817. return isUTC ? 'setUTCMonth' : 'setMonth';
  15818. }
  15819. function dateSetterName(isUTC) {
  15820. return isUTC ? 'setUTCDate' : 'setDate';
  15821. }
  15822. function hoursSetterName(isUTC) {
  15823. return isUTC ? 'setUTCHours' : 'setHours';
  15824. }
  15825. function minutesSetterName(isUTC) {
  15826. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  15827. }
  15828. function secondsSetterName(isUTC) {
  15829. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15830. }
  15831. function millisecondsSetterName(isUTC) {
  15832. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  15833. }
  15834. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  15835. deprecateLog('getTextRect is deprecated.');
  15836. var textEl = new ZRText({
  15837. style: {
  15838. text: text,
  15839. font: font,
  15840. align: align,
  15841. verticalAlign: verticalAlign,
  15842. padding: padding,
  15843. rich: rich,
  15844. overflow: truncate ? 'truncate' : null,
  15845. lineHeight: lineHeight
  15846. }
  15847. });
  15848. return textEl.getBoundingRect();
  15849. }
  15850. /**
  15851. * Add a comma each three digit.
  15852. */
  15853. function addCommas(x) {
  15854. if (!isNumeric(x)) {
  15855. return isString(x) ? x : '-';
  15856. }
  15857. var parts = (x + '').split('.');
  15858. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  15859. }
  15860. function toCamelCase(str, upperCaseFirst) {
  15861. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  15862. return group1.toUpperCase();
  15863. });
  15864. if (upperCaseFirst && str) {
  15865. str = str.charAt(0).toUpperCase() + str.slice(1);
  15866. }
  15867. return str;
  15868. }
  15869. var normalizeCssArray$1 = normalizeCssArray;
  15870. var replaceReg = /([&<>"'])/g;
  15871. var replaceMap = {
  15872. '&': '&amp;',
  15873. '<': '&lt;',
  15874. '>': '&gt;',
  15875. '"': '&quot;',
  15876. '\'': '&#39;'
  15877. };
  15878. function encodeHTML(source) {
  15879. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  15880. return replaceMap[c];
  15881. });
  15882. }
  15883. /**
  15884. * Make value user readable for tooltip and label.
  15885. * "User readable":
  15886. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  15887. * Avoid to display an empty string, which users can not recognize there is
  15888. * a value and it might look like a bug.
  15889. */
  15890. function makeValueReadable(value, valueType, useUTC) {
  15891. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}';
  15892. function stringToUserReadable(str) {
  15893. return str && trim(str) ? str : '-';
  15894. }
  15895. function isNumberUserReadable(num) {
  15896. return !!(num != null && !isNaN(num) && isFinite(num));
  15897. }
  15898. var isTypeTime = valueType === 'time';
  15899. var isValueDate = value instanceof Date;
  15900. if (isTypeTime || isValueDate) {
  15901. var date = isTypeTime ? parseDate(value) : value;
  15902. if (!isNaN(+date)) {
  15903. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  15904. } else if (isValueDate) {
  15905. return '-';
  15906. } // In other cases, continue to try to display the value in the following code.
  15907. }
  15908. if (valueType === 'ordinal') {
  15909. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  15910. } // By default.
  15911. var numericResult = numericToNumber(value);
  15912. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : '-';
  15913. }
  15914. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15915. var wrapVar = function (varName, seriesIdx) {
  15916. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15917. };
  15918. /**
  15919. * Template formatter
  15920. * @param {Array.<Object>|Object} paramsList
  15921. */
  15922. function formatTpl(tpl, paramsList, encode) {
  15923. if (!isArray(paramsList)) {
  15924. paramsList = [paramsList];
  15925. }
  15926. var seriesLen = paramsList.length;
  15927. if (!seriesLen) {
  15928. return '';
  15929. }
  15930. var $vars = paramsList[0].$vars || [];
  15931. for (var i = 0; i < $vars.length; i++) {
  15932. var alias = TPL_VAR_ALIAS[i];
  15933. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15934. }
  15935. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15936. for (var k = 0; k < $vars.length; k++) {
  15937. var val = paramsList[seriesIdx][$vars[k]];
  15938. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  15939. }
  15940. }
  15941. return tpl;
  15942. }
  15943. /**
  15944. * simple Template formatter
  15945. */
  15946. function formatTplSimple(tpl, param, encode) {
  15947. each(param, function (value, key) {
  15948. tpl = tpl.replace('{' + key + '}', encode ? encodeHTML(value) : value);
  15949. });
  15950. return tpl;
  15951. }
  15952. function getTooltipMarker(inOpt, extraCssText) {
  15953. var opt = isString(inOpt) ? {
  15954. color: inOpt,
  15955. extraCssText: extraCssText
  15956. } : inOpt || {};
  15957. var color = opt.color;
  15958. var type = opt.type;
  15959. extraCssText = opt.extraCssText;
  15960. var renderMode = opt.renderMode || 'html';
  15961. if (!color) {
  15962. return '';
  15963. }
  15964. if (renderMode === 'html') {
  15965. 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
  15966. + 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>';
  15967. } else {
  15968. // Should better not to auto generate style name by auto-increment number here.
  15969. // Because this util is usually called in tooltip formatter, which is probably
  15970. // called repeatly when mouse move and the auto-increment number increases fast.
  15971. // Users can make their own style name by theirselves, make it unique and readable.
  15972. var markerId = opt.markerId || 'markerX';
  15973. return {
  15974. renderMode: renderMode,
  15975. content: '{' + markerId + '|} ',
  15976. style: type === 'subItem' ? {
  15977. width: 4,
  15978. height: 4,
  15979. borderRadius: 2,
  15980. backgroundColor: color
  15981. } : {
  15982. width: 10,
  15983. height: 10,
  15984. borderRadius: 5,
  15985. backgroundColor: color
  15986. }
  15987. };
  15988. }
  15989. }
  15990. /**
  15991. * @deprecated Use `time/format` instead.
  15992. * ISO Date format
  15993. * @param {string} tpl
  15994. * @param {number} value
  15995. * @param {boolean} [isUTC=false] Default in local time.
  15996. * see `module:echarts/scale/Time`
  15997. * and `module:echarts/util/number#parseDate`.
  15998. * @inner
  15999. */
  16000. function formatTime(tpl, value, isUTC) {
  16001. if ("development" !== 'production') {
  16002. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  16003. }
  16004. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  16005. tpl = 'MM-dd\nyyyy';
  16006. }
  16007. var date = parseDate(value);
  16008. var utc = isUTC ? 'UTC' : '';
  16009. var y = date['get' + utc + 'FullYear']();
  16010. var M = date['get' + utc + 'Month']() + 1;
  16011. var d = date['get' + utc + 'Date']();
  16012. var h = date['get' + utc + 'Hours']();
  16013. var m = date['get' + utc + 'Minutes']();
  16014. var s = date['get' + utc + 'Seconds']();
  16015. var S = date['get' + utc + 'Milliseconds']();
  16016. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', y % 100 + '').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));
  16017. return tpl;
  16018. }
  16019. /**
  16020. * Capital first
  16021. * @param {string} str
  16022. * @return {string}
  16023. */
  16024. function capitalFirst(str) {
  16025. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16026. }
  16027. /**
  16028. * @return Never be null/undefined.
  16029. */
  16030. function convertToColorString(color, defaultColor) {
  16031. defaultColor = defaultColor || 'transparent';
  16032. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  16033. }
  16034. /**
  16035. * open new tab
  16036. * @param link url
  16037. * @param target blank or self
  16038. */
  16039. function windowOpen(link, target) {
  16040. /* global window */
  16041. if (target === '_blank' || target === 'blank') {
  16042. var blank = window.open();
  16043. blank.opener = null;
  16044. blank.location.href = link;
  16045. } else {
  16046. window.open(link, target);
  16047. }
  16048. }
  16049. var each$1 = each;
  16050. /**
  16051. * @public
  16052. */
  16053. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16054. /**
  16055. * @public
  16056. */
  16057. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16058. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16059. var x = 0;
  16060. var y = 0;
  16061. if (maxWidth == null) {
  16062. maxWidth = Infinity;
  16063. }
  16064. if (maxHeight == null) {
  16065. maxHeight = Infinity;
  16066. }
  16067. var currentLineMaxSize = 0;
  16068. group.eachChild(function (child, idx) {
  16069. var rect = child.getBoundingRect();
  16070. var nextChild = group.childAt(idx + 1);
  16071. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16072. var nextX;
  16073. var nextY;
  16074. if (orient === 'horizontal') {
  16075. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16076. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  16077. // FIXME compare before adding gap?
  16078. if (nextX > maxWidth || child.newline) {
  16079. x = 0;
  16080. nextX = moveX;
  16081. y += currentLineMaxSize + gap;
  16082. currentLineMaxSize = rect.height;
  16083. } else {
  16084. // FIXME: consider rect.y is not `0`?
  16085. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16086. }
  16087. } else {
  16088. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16089. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  16090. if (nextY > maxHeight || child.newline) {
  16091. x += currentLineMaxSize + gap;
  16092. y = 0;
  16093. nextY = moveY;
  16094. currentLineMaxSize = rect.width;
  16095. } else {
  16096. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16097. }
  16098. }
  16099. if (child.newline) {
  16100. return;
  16101. }
  16102. child.x = x;
  16103. child.y = y;
  16104. child.markRedraw();
  16105. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16106. });
  16107. }
  16108. /**
  16109. * VBox or HBox layouting
  16110. * @param {string} orient
  16111. * @param {module:zrender/graphic/Group} group
  16112. * @param {number} gap
  16113. * @param {number} [width=Infinity]
  16114. * @param {number} [height=Infinity]
  16115. */
  16116. var box = boxLayout;
  16117. /**
  16118. * VBox layouting
  16119. * @param {module:zrender/graphic/Group} group
  16120. * @param {number} gap
  16121. * @param {number} [width=Infinity]
  16122. * @param {number} [height=Infinity]
  16123. */
  16124. var vbox = curry(boxLayout, 'vertical');
  16125. /**
  16126. * HBox layouting
  16127. * @param {module:zrender/graphic/Group} group
  16128. * @param {number} gap
  16129. * @param {number} [width=Infinity]
  16130. * @param {number} [height=Infinity]
  16131. */
  16132. var hbox = curry(boxLayout, 'horizontal');
  16133. /**
  16134. * If x or x2 is not specified or 'center' 'left' 'right',
  16135. * the width would be as long as possible.
  16136. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16137. * the height would be as long as possible.
  16138. */
  16139. function getAvailableSize(positionInfo, containerRect, margin) {
  16140. var containerWidth = containerRect.width;
  16141. var containerHeight = containerRect.height;
  16142. var x = parsePercent$1(positionInfo.left, containerWidth);
  16143. var y = parsePercent$1(positionInfo.top, containerHeight);
  16144. var x2 = parsePercent$1(positionInfo.right, containerWidth);
  16145. var y2 = parsePercent$1(positionInfo.bottom, containerHeight);
  16146. (isNaN(x) || isNaN(parseFloat(positionInfo.left))) && (x = 0);
  16147. (isNaN(x2) || isNaN(parseFloat(positionInfo.right))) && (x2 = containerWidth);
  16148. (isNaN(y) || isNaN(parseFloat(positionInfo.top))) && (y = 0);
  16149. (isNaN(y2) || isNaN(parseFloat(positionInfo.bottom))) && (y2 = containerHeight);
  16150. margin = normalizeCssArray$1(margin || 0);
  16151. return {
  16152. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16153. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16154. };
  16155. }
  16156. /**
  16157. * Parse position info.
  16158. */
  16159. function getLayoutRect(positionInfo, containerRect, margin) {
  16160. margin = normalizeCssArray$1(margin || 0);
  16161. var containerWidth = containerRect.width;
  16162. var containerHeight = containerRect.height;
  16163. var left = parsePercent$1(positionInfo.left, containerWidth);
  16164. var top = parsePercent$1(positionInfo.top, containerHeight);
  16165. var right = parsePercent$1(positionInfo.right, containerWidth);
  16166. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16167. var width = parsePercent$1(positionInfo.width, containerWidth);
  16168. var height = parsePercent$1(positionInfo.height, containerHeight);
  16169. var verticalMargin = margin[2] + margin[0];
  16170. var horizontalMargin = margin[1] + margin[3];
  16171. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  16172. if (isNaN(width)) {
  16173. width = containerWidth - right - horizontalMargin - left;
  16174. }
  16175. if (isNaN(height)) {
  16176. height = containerHeight - bottom - verticalMargin - top;
  16177. }
  16178. if (aspect != null) {
  16179. // If width and height are not given
  16180. // 1. Graph should not exceeds the container
  16181. // 2. Aspect must be keeped
  16182. // 3. Graph should take the space as more as possible
  16183. // FIXME
  16184. // Margin is not considered, because there is no case that both
  16185. // using margin and aspect so far.
  16186. if (isNaN(width) && isNaN(height)) {
  16187. if (aspect > containerWidth / containerHeight) {
  16188. width = containerWidth * 0.8;
  16189. } else {
  16190. height = containerHeight * 0.8;
  16191. }
  16192. } // Calculate width or height with given aspect
  16193. if (isNaN(width)) {
  16194. width = aspect * height;
  16195. }
  16196. if (isNaN(height)) {
  16197. height = width / aspect;
  16198. }
  16199. } // If left is not specified, calculate left from right and width
  16200. if (isNaN(left)) {
  16201. left = containerWidth - right - width - horizontalMargin;
  16202. }
  16203. if (isNaN(top)) {
  16204. top = containerHeight - bottom - height - verticalMargin;
  16205. } // Align left and top
  16206. switch (positionInfo.left || positionInfo.right) {
  16207. case 'center':
  16208. left = containerWidth / 2 - width / 2 - margin[3];
  16209. break;
  16210. case 'right':
  16211. left = containerWidth - width - horizontalMargin;
  16212. break;
  16213. }
  16214. switch (positionInfo.top || positionInfo.bottom) {
  16215. case 'middle':
  16216. case 'center':
  16217. top = containerHeight / 2 - height / 2 - margin[0];
  16218. break;
  16219. case 'bottom':
  16220. top = containerHeight - height - verticalMargin;
  16221. break;
  16222. } // If something is wrong and left, top, width, height are calculated as NaN
  16223. left = left || 0;
  16224. top = top || 0;
  16225. if (isNaN(width)) {
  16226. // Width may be NaN if only one value is given except width
  16227. width = containerWidth - horizontalMargin - left - (right || 0);
  16228. }
  16229. if (isNaN(height)) {
  16230. // Height may be NaN if only one value is given except height
  16231. height = containerHeight - verticalMargin - top - (bottom || 0);
  16232. }
  16233. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16234. rect.margin = margin;
  16235. return rect;
  16236. }
  16237. /**
  16238. * Position a zr element in viewport
  16239. * Group position is specified by either
  16240. * {left, top}, {right, bottom}
  16241. * If all properties exists, right and bottom will be igonred.
  16242. *
  16243. * Logic:
  16244. * 1. Scale (against origin point in parent coord)
  16245. * 2. Rotate (against origin point in parent coord)
  16246. * 3. Traslate (with el.position by this method)
  16247. * So this method only fixes the last step 'Traslate', which does not affect
  16248. * scaling and rotating.
  16249. *
  16250. * If be called repeatly with the same input el, the same result will be gotten.
  16251. *
  16252. * @param el Should have `getBoundingRect` method.
  16253. * @param positionInfo
  16254. * @param positionInfo.left
  16255. * @param positionInfo.top
  16256. * @param positionInfo.right
  16257. * @param positionInfo.bottom
  16258. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  16259. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  16260. * @param containerRect
  16261. * @param margin
  16262. * @param opt
  16263. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  16264. * @param opt.boundingMode
  16265. * Specify how to calculate boundingRect when locating.
  16266. * 'all': Position the boundingRect that is transformed and uioned
  16267. * both itself and its descendants.
  16268. * This mode simplies confine the elements in the bounding
  16269. * of their container (e.g., using 'right: 0').
  16270. * 'raw': Position the boundingRect that is not transformed and only itself.
  16271. * This mode is useful when you want a element can overflow its
  16272. * container. (Consider a rotated circle needs to be located in a corner.)
  16273. * In this mode positionInfo.width/height can only be number.
  16274. */
  16275. function positionElement(el, positionInfo, containerRect, margin, opt) {
  16276. var h = !opt || !opt.hv || opt.hv[0];
  16277. var v = !opt || !opt.hv || opt.hv[1];
  16278. var boundingMode = opt && opt.boundingMode || 'all';
  16279. if (!h && !v) {
  16280. return;
  16281. }
  16282. var rect;
  16283. if (boundingMode === 'raw') {
  16284. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  16285. } else {
  16286. rect = el.getBoundingRect();
  16287. if (el.needLocalTransform()) {
  16288. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  16289. // which should not be modified.
  16290. rect = rect.clone();
  16291. rect.applyTransform(transform);
  16292. }
  16293. } // The real width and height can not be specified but calculated by the given el.
  16294. var layoutRect = getLayoutRect(defaults({
  16295. width: rect.width,
  16296. height: rect.height
  16297. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  16298. // (see zrender/core/Transformable#getLocalTransform),
  16299. // we can just only modify el.position to get final result.
  16300. var dx = h ? layoutRect.x - rect.x : 0;
  16301. var dy = v ? layoutRect.y - rect.y : 0;
  16302. if (boundingMode === 'raw') {
  16303. el.x = dx;
  16304. el.y = dy;
  16305. } else {
  16306. el.x += dx;
  16307. el.y += dy;
  16308. }
  16309. el.markRedraw();
  16310. }
  16311. /**
  16312. * @param option Contains some of the properties in HV_NAMES.
  16313. * @param hvIdx 0: horizontal; 1: vertical.
  16314. */
  16315. function sizeCalculable(option, hvIdx) {
  16316. return option[HV_NAMES[hvIdx][0]] != null || option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null;
  16317. }
  16318. function fetchLayoutMode(ins) {
  16319. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  16320. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  16321. type: layoutMode
  16322. } : null;
  16323. }
  16324. /**
  16325. * Consider Case:
  16326. * When default option has {left: 0, width: 100}, and we set {right: 0}
  16327. * through setOption or media query, using normal zrUtil.merge will cause
  16328. * {right: 0} does not take effect.
  16329. *
  16330. * @example
  16331. * ComponentModel.extend({
  16332. * init: function () {
  16333. * ...
  16334. * let inputPositionParams = layout.getLayoutParams(option);
  16335. * this.mergeOption(inputPositionParams);
  16336. * },
  16337. * mergeOption: function (newOption) {
  16338. * newOption && zrUtil.merge(thisOption, newOption, true);
  16339. * layout.mergeLayoutParam(thisOption, newOption);
  16340. * }
  16341. * });
  16342. *
  16343. * @param targetOption
  16344. * @param newOption
  16345. * @param opt
  16346. */
  16347. function mergeLayoutParam(targetOption, newOption, opt) {
  16348. var ignoreSize = opt && opt.ignoreSize;
  16349. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16350. var hResult = merge(HV_NAMES[0], 0);
  16351. var vResult = merge(HV_NAMES[1], 1);
  16352. copy(HV_NAMES[0], targetOption, hResult);
  16353. copy(HV_NAMES[1], targetOption, vResult);
  16354. function merge(names, hvIdx) {
  16355. var newParams = {};
  16356. var newValueCount = 0;
  16357. var merged = {};
  16358. var mergedValueCount = 0;
  16359. var enoughParamNumber = 2;
  16360. each$1(names, function (name) {
  16361. merged[name] = targetOption[name];
  16362. });
  16363. each$1(names, function (name) {
  16364. // Consider case: newOption.width is null, which is
  16365. // set by user for removing width setting.
  16366. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16367. hasValue(newParams, name) && newValueCount++;
  16368. hasValue(merged, name) && mergedValueCount++;
  16369. });
  16370. if (ignoreSize[hvIdx]) {
  16371. // Only one of left/right is premitted to exist.
  16372. if (hasValue(newOption, names[1])) {
  16373. merged[names[2]] = null;
  16374. } else if (hasValue(newOption, names[2])) {
  16375. merged[names[1]] = null;
  16376. }
  16377. return merged;
  16378. } // Case: newOption: {width: ..., right: ...},
  16379. // or targetOption: {right: ...} and newOption: {width: ...},
  16380. // There is no conflict when merged only has params count
  16381. // little than enoughParamNumber.
  16382. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16383. return merged;
  16384. } // Case: newOption: {width: ..., right: ...},
  16385. // Than we can make sure user only want those two, and ignore
  16386. // all origin params in targetOption.
  16387. else if (newValueCount >= enoughParamNumber) {
  16388. return newParams;
  16389. } else {
  16390. // Chose another param from targetOption by priority.
  16391. for (var i = 0; i < names.length; i++) {
  16392. var name_1 = names[i];
  16393. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16394. newParams[name_1] = targetOption[name_1];
  16395. break;
  16396. }
  16397. }
  16398. return newParams;
  16399. }
  16400. }
  16401. function hasProp(obj, name) {
  16402. return obj.hasOwnProperty(name);
  16403. }
  16404. function hasValue(obj, name) {
  16405. return obj[name] != null && obj[name] !== 'auto';
  16406. }
  16407. function copy(names, target, source) {
  16408. each$1(names, function (name) {
  16409. target[name] = source[name];
  16410. });
  16411. }
  16412. }
  16413. /**
  16414. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16415. */
  16416. function getLayoutParams(source) {
  16417. return copyLayoutParams({}, source);
  16418. }
  16419. /**
  16420. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16421. * @param {Object} source
  16422. * @return {Object} Result contains those props.
  16423. */
  16424. function copyLayoutParams(target, source) {
  16425. source && target && each$1(LOCATION_PARAMS, function (name) {
  16426. source.hasOwnProperty(name) && (target[name] = source[name]);
  16427. });
  16428. return target;
  16429. }
  16430. var inner = makeInner();
  16431. var ComponentModel =
  16432. /** @class */
  16433. function (_super) {
  16434. __extends(ComponentModel, _super);
  16435. function ComponentModel(option, parentModel, ecModel) {
  16436. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16437. _this.uid = getUID('ec_cpt_model');
  16438. return _this;
  16439. }
  16440. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16441. this.mergeDefaultAndTheme(option, ecModel);
  16442. };
  16443. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16444. var layoutMode = fetchLayoutMode(this);
  16445. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16446. var themeModel = ecModel.getTheme();
  16447. merge(option, themeModel.get(this.mainType));
  16448. merge(option, this.getDefaultOption());
  16449. if (layoutMode) {
  16450. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16451. }
  16452. };
  16453. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16454. merge(this.option, option, true);
  16455. var layoutMode = fetchLayoutMode(this);
  16456. if (layoutMode) {
  16457. mergeLayoutParam(this.option, option, layoutMode);
  16458. }
  16459. };
  16460. /**
  16461. * Called immediately after `init` or `mergeOption` of this instance called.
  16462. */
  16463. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16464. /**
  16465. * [How to declare defaultOption]:
  16466. *
  16467. * (A) If using class declaration in typescript (since echarts 5):
  16468. * ```ts
  16469. * import {ComponentOption} from '../model/option';
  16470. * export interface XxxOption extends ComponentOption {
  16471. * aaa: number
  16472. * }
  16473. * export class XxxModel extends Component {
  16474. * static type = 'xxx';
  16475. * static defaultOption: XxxOption = {
  16476. * aaa: 123
  16477. * }
  16478. * }
  16479. * Component.registerClass(XxxModel);
  16480. * ```
  16481. * ```ts
  16482. * import {inheritDefaultOption} from '../util/component';
  16483. * import {XxxModel, XxxOption} from './XxxModel';
  16484. * export interface XxxSubOption extends XxxOption {
  16485. * bbb: number
  16486. * }
  16487. * class XxxSubModel extends XxxModel {
  16488. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16489. * bbb: 456
  16490. * })
  16491. * fn() {
  16492. * let opt = this.getDefaultOption();
  16493. * // opt is {aaa: 123, bbb: 456}
  16494. * }
  16495. * }
  16496. * ```
  16497. *
  16498. * (B) If using class extend (previous approach in echarts 3 & 4):
  16499. * ```js
  16500. * let XxxComponent = Component.extend({
  16501. * defaultOption: {
  16502. * xx: 123
  16503. * }
  16504. * })
  16505. * ```
  16506. * ```js
  16507. * let XxxSubComponent = XxxComponent.extend({
  16508. * defaultOption: {
  16509. * yy: 456
  16510. * },
  16511. * fn: function () {
  16512. * let opt = this.getDefaultOption();
  16513. * // opt is {xx: 123, yy: 456}
  16514. * }
  16515. * })
  16516. * ```
  16517. */
  16518. ComponentModel.prototype.getDefaultOption = function () {
  16519. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  16520. // in legacy env and auto merge defaultOption. So if using class
  16521. // declaration, defaultOption should be merged manually.
  16522. if (!isExtendedClass(ctor)) {
  16523. // When using ts class, defaultOption must be declared as static.
  16524. return ctor.defaultOption;
  16525. } // FIXME: remove this approach?
  16526. var fields = inner(this);
  16527. if (!fields.defaultOption) {
  16528. var optList = [];
  16529. var clz = ctor;
  16530. while (clz) {
  16531. var opt = clz.prototype.defaultOption;
  16532. opt && optList.push(opt);
  16533. clz = clz.superClass;
  16534. }
  16535. var defaultOption = {};
  16536. for (var i = optList.length - 1; i >= 0; i--) {
  16537. defaultOption = merge(defaultOption, optList[i], true);
  16538. }
  16539. fields.defaultOption = defaultOption;
  16540. }
  16541. return fields.defaultOption;
  16542. };
  16543. /**
  16544. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16545. * The same behavior as `modelUtil.parseFinder`.
  16546. *
  16547. * @param useDefault In many cases like series refer axis and axis refer grid,
  16548. * If axis index / axis id not specified, use the first target as default.
  16549. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16550. */
  16551. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16552. var indexKey = mainType + 'Index';
  16553. var idKey = mainType + 'Id';
  16554. return queryReferringComponents(this.ecModel, mainType, {
  16555. index: this.get(indexKey, true),
  16556. id: this.get(idKey, true)
  16557. }, opt);
  16558. };
  16559. ComponentModel.prototype.getBoxLayoutParams = function () {
  16560. // Consider itself having box layout configs.
  16561. var boxLayoutModel = this;
  16562. return {
  16563. left: boxLayoutModel.get('left'),
  16564. top: boxLayoutModel.get('top'),
  16565. right: boxLayoutModel.get('right'),
  16566. bottom: boxLayoutModel.get('bottom'),
  16567. width: boxLayoutModel.get('width'),
  16568. height: boxLayoutModel.get('height')
  16569. };
  16570. };
  16571. ComponentModel.protoInitialize = function () {
  16572. var proto = ComponentModel.prototype;
  16573. proto.type = 'component';
  16574. proto.id = '';
  16575. proto.name = '';
  16576. proto.mainType = '';
  16577. proto.subType = '';
  16578. proto.componentIndex = 0;
  16579. }();
  16580. return ComponentModel;
  16581. }(Model);
  16582. mountExtend(ComponentModel, Model);
  16583. enableClassManagement(ComponentModel);
  16584. enableSubTypeDefaulter(ComponentModel);
  16585. enableTopologicalTravel(ComponentModel, getDependencies);
  16586. function getDependencies(componentType) {
  16587. var deps = [];
  16588. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16589. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16590. }); // Ensure main type.
  16591. deps = map(deps, function (type) {
  16592. return parseClassType(type).main;
  16593. }); // Hack dataset for convenience.
  16594. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16595. deps.unshift('dataset');
  16596. }
  16597. return deps;
  16598. }
  16599. /*
  16600. * Licensed to the Apache Software Foundation (ASF) under one
  16601. * or more contributor license agreements. See the NOTICE file
  16602. * distributed with this work for additional information
  16603. * regarding copyright ownership. The ASF licenses this file
  16604. * to you under the Apache License, Version 2.0 (the
  16605. * "License"); you may not use this file except in compliance
  16606. * with the License. You may obtain a copy of the License at
  16607. *
  16608. * http://www.apache.org/licenses/LICENSE-2.0
  16609. *
  16610. * Unless required by applicable law or agreed to in writing,
  16611. * software distributed under the License is distributed on an
  16612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16613. * KIND, either express or implied. See the License for the
  16614. * specific language governing permissions and limitations
  16615. * under the License.
  16616. */
  16617. /**
  16618. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16619. */
  16620. /*
  16621. * Licensed to the Apache Software Foundation (ASF) under one
  16622. * or more contributor license agreements. See the NOTICE file
  16623. * distributed with this work for additional information
  16624. * regarding copyright ownership. The ASF licenses this file
  16625. * to you under the Apache License, Version 2.0 (the
  16626. * "License"); you may not use this file except in compliance
  16627. * with the License. You may obtain a copy of the License at
  16628. *
  16629. * http://www.apache.org/licenses/LICENSE-2.0
  16630. *
  16631. * Unless required by applicable law or agreed to in writing,
  16632. * software distributed under the License is distributed on an
  16633. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16634. * KIND, either express or implied. See the License for the
  16635. * specific language governing permissions and limitations
  16636. * under the License.
  16637. */
  16638. var platform = ''; // Navigator not exists in node
  16639. if (typeof navigator !== 'undefined') {
  16640. /* global navigator */
  16641. platform = navigator.platform || '';
  16642. }
  16643. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16644. var globalDefault = {
  16645. darkMode: 'auto',
  16646. // backgroundColor: 'rgba(0,0,0,0)',
  16647. colorBy: 'series',
  16648. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16649. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16650. aria: {
  16651. decal: {
  16652. decals: [{
  16653. color: decalColor,
  16654. dashArrayX: [1, 0],
  16655. dashArrayY: [2, 5],
  16656. symbolSize: 1,
  16657. rotation: Math.PI / 6
  16658. }, {
  16659. color: decalColor,
  16660. symbol: 'circle',
  16661. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16662. dashArrayY: [6, 0],
  16663. symbolSize: 0.8
  16664. }, {
  16665. color: decalColor,
  16666. dashArrayX: [1, 0],
  16667. dashArrayY: [4, 3],
  16668. rotation: -Math.PI / 4
  16669. }, {
  16670. color: decalColor,
  16671. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16672. dashArrayY: [6, 0]
  16673. }, {
  16674. color: decalColor,
  16675. dashArrayX: [[1, 0], [1, 6]],
  16676. dashArrayY: [1, 0, 6, 0],
  16677. rotation: Math.PI / 4
  16678. }, {
  16679. color: decalColor,
  16680. symbol: 'triangle',
  16681. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16682. dashArrayY: [7, 2],
  16683. symbolSize: 0.75
  16684. }]
  16685. }
  16686. },
  16687. // If xAxis and yAxis declared, grid is created by default.
  16688. // grid: {},
  16689. textStyle: {
  16690. // color: '#000',
  16691. // decoration: 'none',
  16692. // PENDING
  16693. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16694. // fontFamily: 'Arial, Verdana, sans-serif',
  16695. fontSize: 12,
  16696. fontStyle: 'normal',
  16697. fontWeight: 'normal'
  16698. },
  16699. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16700. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16701. // Default is source-over
  16702. blendMode: null,
  16703. stateAnimation: {
  16704. duration: 300,
  16705. easing: 'cubicOut'
  16706. },
  16707. animation: 'auto',
  16708. animationDuration: 1000,
  16709. animationDurationUpdate: 500,
  16710. animationEasing: 'cubicInOut',
  16711. animationEasingUpdate: 'cubicInOut',
  16712. animationThreshold: 2000,
  16713. // Configuration for progressive/incremental rendering
  16714. progressiveThreshold: 3000,
  16715. progressive: 400,
  16716. // Threshold of if use single hover layer to optimize.
  16717. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16718. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16719. // which is unexpected.
  16720. // see example <echarts/test/heatmap-large.html>.
  16721. hoverLayerThreshold: 3000,
  16722. // See: module:echarts/scale/Time
  16723. useUTC: false
  16724. };
  16725. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'seriesName']);
  16726. var SOURCE_FORMAT_ORIGINAL = 'original';
  16727. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16728. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16729. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16730. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16731. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16732. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16733. var SERIES_LAYOUT_BY_ROW = 'row';
  16734. var BE_ORDINAL = {
  16735. Must: 1,
  16736. Might: 2,
  16737. Not: 3 // Other cases
  16738. };
  16739. var innerGlobalModel = makeInner();
  16740. /**
  16741. * MUST be called before mergeOption of all series.
  16742. */
  16743. function resetSourceDefaulter(ecModel) {
  16744. // `datasetMap` is used to make default encode.
  16745. innerGlobalModel(ecModel).datasetMap = createHashMap();
  16746. }
  16747. /**
  16748. * [The strategy of the arrengment of data dimensions for dataset]:
  16749. * "value way": all axes are non-category axes. So series one by one take
  16750. * several (the number is coordSysDims.length) dimensions from dataset.
  16751. * The result of data arrengment of data dimensions like:
  16752. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  16753. * "category way": at least one axis is category axis. So the the first data
  16754. * dimension is always mapped to the first category axis and shared by
  16755. * all of the series. The other data dimensions are taken by series like
  16756. * "value way" does.
  16757. * The result of data arrengment of data dimensions like:
  16758. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  16759. *
  16760. * @return encode Never be `null/undefined`.
  16761. */
  16762. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  16763. var encode = {};
  16764. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16765. if (!datasetModel || !coordDimensions) {
  16766. return encode;
  16767. }
  16768. var encodeItemName = [];
  16769. var encodeSeriesName = [];
  16770. var ecModel = seriesModel.ecModel;
  16771. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  16772. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  16773. var baseCategoryDimIndex;
  16774. var categoryWayValueDimStart;
  16775. coordDimensions = coordDimensions.slice();
  16776. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  16777. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  16778. name: coordDimInfoLoose
  16779. };
  16780. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  16781. baseCategoryDimIndex = coordDimIdx;
  16782. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  16783. }
  16784. encode[coordDimInfo.name] = [];
  16785. });
  16786. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  16787. categoryWayDim: categoryWayValueDimStart,
  16788. valueWayDim: 0
  16789. }); // TODO
  16790. // Auto detect first time axis and do arrangement.
  16791. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  16792. var coordDimName = coordDimInfo.name;
  16793. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  16794. if (baseCategoryDimIndex == null) {
  16795. var start = datasetRecord.valueWayDim;
  16796. pushDim(encode[coordDimName], start, count);
  16797. pushDim(encodeSeriesName, start, count);
  16798. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  16799. // especially when encode x y specified.
  16800. // consider: when mutiple series share one dimension
  16801. // category axis, series name should better use
  16802. // the other dimsion name. On the other hand, use
  16803. // both dimensions name.
  16804. } // In category way, the first category axis.
  16805. else if (baseCategoryDimIndex === coordDimIdx) {
  16806. pushDim(encode[coordDimName], 0, count);
  16807. pushDim(encodeItemName, 0, count);
  16808. } // In category way, the other axis.
  16809. else {
  16810. var start = datasetRecord.categoryWayDim;
  16811. pushDim(encode[coordDimName], start, count);
  16812. pushDim(encodeSeriesName, start, count);
  16813. datasetRecord.categoryWayDim += count;
  16814. }
  16815. });
  16816. function pushDim(dimIdxArr, idxFrom, idxCount) {
  16817. for (var i = 0; i < idxCount; i++) {
  16818. dimIdxArr.push(idxFrom + i);
  16819. }
  16820. }
  16821. function getDataDimCountOnCoordDim(coordDimInfo) {
  16822. var dimsDef = coordDimInfo.dimsDef;
  16823. return dimsDef ? dimsDef.length : 1;
  16824. }
  16825. encodeItemName.length && (encode.itemName = encodeItemName);
  16826. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16827. return encode;
  16828. }
  16829. /**
  16830. * Work for data like [{name: ..., value: ...}, ...].
  16831. *
  16832. * @return encode Never be `null/undefined`.
  16833. */
  16834. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  16835. var encode = {};
  16836. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16837. if (!datasetModel) {
  16838. return encode;
  16839. }
  16840. var sourceFormat = source.sourceFormat;
  16841. var dimensionsDefine = source.dimensionsDefine;
  16842. var potentialNameDimIndex;
  16843. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16844. each(dimensionsDefine, function (dim, idx) {
  16845. if ((isObject(dim) ? dim.name : dim) === 'name') {
  16846. potentialNameDimIndex = idx;
  16847. }
  16848. });
  16849. }
  16850. var idxResult = function () {
  16851. var idxRes0 = {};
  16852. var idxRes1 = {};
  16853. var guessRecords = []; // 5 is an experience value.
  16854. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  16855. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  16856. guessRecords.push(guessResult);
  16857. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  16858. // and then find a name dim with the priority:
  16859. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  16860. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  16861. idxRes0.v = i;
  16862. }
  16863. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  16864. idxRes0.n = i;
  16865. }
  16866. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  16867. return idxRes0;
  16868. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  16869. // find the first BE_ORDINAL.Might as the value dim,
  16870. // and then find a name dim with the priority:
  16871. // "other dim" > "the value dim itself".
  16872. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  16873. // treated as number.
  16874. if (!isPureNumber) {
  16875. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  16876. idxRes1.v = i;
  16877. }
  16878. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  16879. idxRes1.n = i;
  16880. }
  16881. }
  16882. }
  16883. function fulfilled(idxResult) {
  16884. return idxResult.v != null && idxResult.n != null;
  16885. }
  16886. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  16887. }();
  16888. if (idxResult) {
  16889. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  16890. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label use itemName in charts.
  16891. // So we dont set encodeLabel here.
  16892. encode.itemName = [nameDimIndex];
  16893. encode.seriesName = [nameDimIndex];
  16894. }
  16895. return encode;
  16896. }
  16897. /**
  16898. * @return If return null/undefined, indicate that should not use datasetModel.
  16899. */
  16900. function querySeriesUpstreamDatasetModel(seriesModel) {
  16901. // Caution: consider the scenario:
  16902. // A dataset is declared and a series is not expected to use the dataset,
  16903. // and at the beginning `setOption({series: { noData })` (just prepare other
  16904. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16905. // the user should set an empty array to avoid that dataset is used by default.
  16906. var thisData = seriesModel.get('data', true);
  16907. if (!thisData) {
  16908. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  16909. index: seriesModel.get('datasetIndex', true),
  16910. id: seriesModel.get('datasetId', true)
  16911. }, SINGLE_REFERRING).models[0];
  16912. }
  16913. }
  16914. /**
  16915. * @return Always return an array event empty.
  16916. */
  16917. function queryDatasetUpstreamDatasetModels(datasetModel) {
  16918. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  16919. // Otherwise, no reference.
  16920. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  16921. return [];
  16922. }
  16923. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  16924. index: datasetModel.get('fromDatasetIndex', true),
  16925. id: datasetModel.get('fromDatasetId', true)
  16926. }, SINGLE_REFERRING).models;
  16927. }
  16928. /**
  16929. * The rule should not be complex, otherwise user might not
  16930. * be able to known where the data is wrong.
  16931. * The code is ugly, but how to make it neat?
  16932. */
  16933. function guessOrdinal(source, dimIndex) {
  16934. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  16935. } // dimIndex may be overflow source data.
  16936. // return {BE_ORDINAL}
  16937. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  16938. var result; // Experience value.
  16939. var maxLoop = 5;
  16940. if (isTypedArray(data)) {
  16941. return BE_ORDINAL.Not;
  16942. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16943. // always exists in source.
  16944. var dimName;
  16945. var dimType;
  16946. if (dimensionsDefine) {
  16947. var dimDefItem = dimensionsDefine[dimIndex];
  16948. if (isObject(dimDefItem)) {
  16949. dimName = dimDefItem.name;
  16950. dimType = dimDefItem.type;
  16951. } else if (isString(dimDefItem)) {
  16952. dimName = dimDefItem;
  16953. }
  16954. }
  16955. if (dimType != null) {
  16956. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  16957. }
  16958. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16959. var dataArrayRows = data;
  16960. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16961. var sample = dataArrayRows[dimIndex];
  16962. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16963. if ((result = detectValue(sample[startIndex + i])) != null) {
  16964. return result;
  16965. }
  16966. }
  16967. } else {
  16968. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  16969. var row = dataArrayRows[startIndex + i];
  16970. if (row && (result = detectValue(row[dimIndex])) != null) {
  16971. return result;
  16972. }
  16973. }
  16974. }
  16975. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16976. var dataObjectRows = data;
  16977. if (!dimName) {
  16978. return BE_ORDINAL.Not;
  16979. }
  16980. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  16981. var item = dataObjectRows[i];
  16982. if (item && (result = detectValue(item[dimName])) != null) {
  16983. return result;
  16984. }
  16985. }
  16986. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16987. var dataKeyedColumns = data;
  16988. if (!dimName) {
  16989. return BE_ORDINAL.Not;
  16990. }
  16991. var sample = dataKeyedColumns[dimName];
  16992. if (!sample || isTypedArray(sample)) {
  16993. return BE_ORDINAL.Not;
  16994. }
  16995. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16996. if ((result = detectValue(sample[i])) != null) {
  16997. return result;
  16998. }
  16999. }
  17000. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17001. var dataOriginal = data;
  17002. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  17003. var item = dataOriginal[i];
  17004. var val = getDataItemValue(item);
  17005. if (!isArray(val)) {
  17006. return BE_ORDINAL.Not;
  17007. }
  17008. if ((result = detectValue(val[dimIndex])) != null) {
  17009. return result;
  17010. }
  17011. }
  17012. }
  17013. function detectValue(val) {
  17014. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  17015. // `isFinit('')` get `true`.
  17016. if (val != null && isFinite(val) && val !== '') {
  17017. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  17018. } else if (beStr && val !== '-') {
  17019. return BE_ORDINAL.Must;
  17020. }
  17021. }
  17022. return BE_ORDINAL.Not;
  17023. }
  17024. var internalOptionCreatorMap = createHashMap();
  17025. function registerInternalOptionCreator(mainType, creator) {
  17026. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  17027. internalOptionCreatorMap.set(mainType, creator);
  17028. }
  17029. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  17030. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  17031. if (!internalOptionCreator) {
  17032. return newCmptOptionList;
  17033. }
  17034. var internalOptions = internalOptionCreator(ecModel);
  17035. if (!internalOptions) {
  17036. return newCmptOptionList;
  17037. }
  17038. if ("development" !== 'production') {
  17039. for (var i = 0; i < internalOptions.length; i++) {
  17040. assert(isComponentIdInternal(internalOptions[i]));
  17041. }
  17042. }
  17043. return newCmptOptionList.concat(internalOptions);
  17044. }
  17045. var innerColor = makeInner();
  17046. var innerDecal = makeInner();
  17047. var PaletteMixin =
  17048. /** @class */
  17049. function () {
  17050. function PaletteMixin() {}
  17051. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  17052. var defaultPalette = normalizeToArray(this.get('color', true));
  17053. var layeredPalette = this.get('colorLayer', true);
  17054. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  17055. };
  17056. PaletteMixin.prototype.clearColorPalette = function () {
  17057. clearPalette(this, innerColor);
  17058. };
  17059. return PaletteMixin;
  17060. }();
  17061. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  17062. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  17063. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  17064. }
  17065. function getNearestPalette(palettes, requestColorNum) {
  17066. var paletteNum = palettes.length; // TODO palettes must be in order
  17067. for (var i = 0; i < paletteNum; i++) {
  17068. if (palettes[i].length > requestColorNum) {
  17069. return palettes[i];
  17070. }
  17071. }
  17072. return palettes[paletteNum - 1];
  17073. }
  17074. /**
  17075. * @param name MUST NOT be null/undefined. Otherwise call this function
  17076. * twise with the same parameters will get different result.
  17077. * @param scope default this.
  17078. * @return Can be null/undefined
  17079. */
  17080. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  17081. scope = scope || that;
  17082. var scopeFields = inner(scope);
  17083. var paletteIdx = scopeFields.paletteIdx || 0;
  17084. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17085. if (paletteNameMap.hasOwnProperty(name)) {
  17086. return paletteNameMap[name];
  17087. }
  17088. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  17089. palette = palette || defaultPalette;
  17090. if (!palette || !palette.length) {
  17091. return;
  17092. }
  17093. var pickedPaletteItem = palette[paletteIdx];
  17094. if (name) {
  17095. paletteNameMap[name] = pickedPaletteItem;
  17096. }
  17097. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  17098. return pickedPaletteItem;
  17099. }
  17100. function clearPalette(that, inner) {
  17101. inner(that).paletteIdx = 0;
  17102. inner(that).paletteNameMap = {};
  17103. }
  17104. // Internal method names:
  17105. // -----------------------
  17106. var reCreateSeriesIndices;
  17107. var assertSeriesInitialized;
  17108. var initBase;
  17109. var OPTION_INNER_KEY = '\0_ec_inner';
  17110. var OPTION_INNER_VALUE = 1;
  17111. var BUITIN_COMPONENTS_MAP = {
  17112. grid: 'GridComponent',
  17113. polar: 'PolarComponent',
  17114. geo: 'GeoComponent',
  17115. singleAxis: 'SingleAxisComponent',
  17116. parallel: 'ParallelComponent',
  17117. calendar: 'CalendarComponent',
  17118. graphic: 'GraphicComponent',
  17119. toolbox: 'ToolboxComponent',
  17120. tooltip: 'TooltipComponent',
  17121. axisPointer: 'AxisPointerComponent',
  17122. brush: 'BrushComponent',
  17123. title: 'TitleComponent',
  17124. timeline: 'TimelineComponent',
  17125. markPoint: 'MarkPointComponent',
  17126. markLine: 'MarkLineComponent',
  17127. markArea: 'MarkAreaComponent',
  17128. legend: 'LegendComponent',
  17129. dataZoom: 'DataZoomComponent',
  17130. visualMap: 'VisualMapComponent',
  17131. // aria: 'AriaComponent',
  17132. // dataset: 'DatasetComponent',
  17133. // Dependencies
  17134. xAxis: 'GridComponent',
  17135. yAxis: 'GridComponent',
  17136. angleAxis: 'PolarComponent',
  17137. radiusAxis: 'PolarComponent'
  17138. };
  17139. var BUILTIN_CHARTS_MAP = {
  17140. line: 'LineChart',
  17141. bar: 'BarChart',
  17142. pie: 'PieChart',
  17143. scatter: 'ScatterChart',
  17144. radar: 'RadarChart',
  17145. map: 'MapChart',
  17146. tree: 'TreeChart',
  17147. treemap: 'TreemapChart',
  17148. graph: 'GraphChart',
  17149. gauge: 'GaugeChart',
  17150. funnel: 'FunnelChart',
  17151. parallel: 'ParallelChart',
  17152. sankey: 'SankeyChart',
  17153. boxplot: 'BoxplotChart',
  17154. candlestick: 'CandlestickChart',
  17155. effectScatter: 'EffectScatterChart',
  17156. lines: 'LinesChart',
  17157. heatmap: 'HeatmapChart',
  17158. pictorialBar: 'PictorialBarChart',
  17159. themeRiver: 'ThemeRiverChart',
  17160. sunburst: 'SunburstChart',
  17161. custom: 'CustomChart'
  17162. };
  17163. var componetsMissingLogPrinted = {};
  17164. function checkMissingComponents(option) {
  17165. each(option, function (componentOption, mainType) {
  17166. if (!ComponentModel.hasClass(mainType)) {
  17167. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  17168. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  17169. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  17170. componetsMissingLogPrinted[componentImportName] = true;
  17171. }
  17172. }
  17173. });
  17174. }
  17175. var GlobalModel =
  17176. /** @class */
  17177. function (_super) {
  17178. __extends(GlobalModel, _super);
  17179. function GlobalModel() {
  17180. return _super !== null && _super.apply(this, arguments) || this;
  17181. }
  17182. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  17183. theme = theme || {};
  17184. this.option = null; // Mark as not initialized.
  17185. this._theme = new Model(theme);
  17186. this._locale = new Model(locale);
  17187. this._optionManager = optionManager;
  17188. };
  17189. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  17190. if ("development" !== 'production') {
  17191. assert(option != null, 'option is null/undefined');
  17192. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  17193. }
  17194. var innerOpt = normalizeSetOptionInput(opts);
  17195. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  17196. this._resetOption(null, innerOpt);
  17197. };
  17198. /**
  17199. * @param type null/undefined: reset all.
  17200. * 'recreate': force recreate all.
  17201. * 'timeline': only reset timeline option
  17202. * 'media': only reset media query option
  17203. * @return Whether option changed.
  17204. */
  17205. GlobalModel.prototype.resetOption = function (type, opt) {
  17206. return this._resetOption(type, normalizeSetOptionInput(opt));
  17207. };
  17208. GlobalModel.prototype._resetOption = function (type, opt) {
  17209. var optionChanged = false;
  17210. var optionManager = this._optionManager;
  17211. if (!type || type === 'recreate') {
  17212. var baseOption = optionManager.mountOption(type === 'recreate');
  17213. if ("development" !== 'production') {
  17214. checkMissingComponents(baseOption);
  17215. }
  17216. if (!this.option || type === 'recreate') {
  17217. initBase(this, baseOption);
  17218. } else {
  17219. this.restoreData();
  17220. this._mergeOption(baseOption, opt);
  17221. }
  17222. optionChanged = true;
  17223. }
  17224. if (type === 'timeline' || type === 'media') {
  17225. this.restoreData();
  17226. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  17227. // it should better not have the same props with `MediaUnit['option']`.
  17228. // Becuase either `option2` or `MediaUnit['option']` will be always merged to "current option"
  17229. // rather than original "baseOption". If they both override a prop, the result might be
  17230. // unexpected when media state changed after `setOption` called.
  17231. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  17232. // (`{baseOption, media}`) in `setOption`.
  17233. // For `timeline`, the case is the same.
  17234. if (!type || type === 'recreate' || type === 'timeline') {
  17235. var timelineOption = optionManager.getTimelineOption(this);
  17236. if (timelineOption) {
  17237. optionChanged = true;
  17238. this._mergeOption(timelineOption, opt);
  17239. }
  17240. }
  17241. if (!type || type === 'recreate' || type === 'media') {
  17242. var mediaOptions = optionManager.getMediaOption(this);
  17243. if (mediaOptions.length) {
  17244. each(mediaOptions, function (mediaOption) {
  17245. optionChanged = true;
  17246. this._mergeOption(mediaOption, opt);
  17247. }, this);
  17248. }
  17249. }
  17250. return optionChanged;
  17251. };
  17252. GlobalModel.prototype.mergeOption = function (option) {
  17253. this._mergeOption(option, null);
  17254. };
  17255. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  17256. var option = this.option;
  17257. var componentsMap = this._componentsMap;
  17258. var componentsCount = this._componentsCount;
  17259. var newCmptTypes = [];
  17260. var newCmptTypeMap = createHashMap();
  17261. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  17262. resetSourceDefaulter(this); // If no component class, merge directly.
  17263. // For example: color, animaiton options, etc.
  17264. each(newOption, function (componentOption, mainType) {
  17265. if (componentOption == null) {
  17266. return;
  17267. }
  17268. if (!ComponentModel.hasClass(mainType)) {
  17269. // globalSettingTask.dirty();
  17270. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17271. } else if (mainType) {
  17272. newCmptTypes.push(mainType);
  17273. newCmptTypeMap.set(mainType, true);
  17274. }
  17275. });
  17276. if (replaceMergeMainTypeMap) {
  17277. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  17278. // we trade it as it is declared in option as `{xxx: []}`. Because:
  17279. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  17280. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  17281. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  17282. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  17283. newCmptTypes.push(mainTypeInReplaceMerge);
  17284. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  17285. }
  17286. });
  17287. }
  17288. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17289. function visitComponent(mainType) {
  17290. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  17291. var oldCmptList = componentsMap.get(mainType);
  17292. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  17293. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  17294. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  17295. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  17296. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  17297. // components, which is probably incorrect logic.
  17298. option[mainType] = null;
  17299. componentsMap.set(mainType, null);
  17300. componentsCount.set(mainType, 0);
  17301. var optionsByMainType = [];
  17302. var cmptsByMainType = [];
  17303. var cmptsCountByMainType = 0;
  17304. each(mappingResult, function (resultItem, index) {
  17305. var componentModel = resultItem.existing;
  17306. var newCmptOption = resultItem.newOption;
  17307. if (!newCmptOption) {
  17308. if (componentModel) {
  17309. // Consider where is no new option and should be merged using {},
  17310. // see removeEdgeAndAdd in topologicalTravel and
  17311. // ComponentModel.getAllClassMainTypes.
  17312. componentModel.mergeOption({}, this);
  17313. componentModel.optionUpdated({}, false);
  17314. } // If no both `resultItem.exist` and `resultItem.option`,
  17315. // either it is in `replaceMerge` and not matched by any id,
  17316. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  17317. } else {
  17318. var isSeriesType = mainType === 'series';
  17319. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  17320. );
  17321. if (!ComponentModelClass) {
  17322. if ("development" !== 'production') {
  17323. var subType = resultItem.keyInfo.subType;
  17324. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  17325. if (!componetsMissingLogPrinted[subType]) {
  17326. componetsMissingLogPrinted[subType] = true;
  17327. if (seriesImportName) {
  17328. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  17329. } else {
  17330. error("Unkown series " + subType);
  17331. }
  17332. }
  17333. }
  17334. return;
  17335. }
  17336. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17337. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  17338. componentModel.mergeOption(newCmptOption, this);
  17339. componentModel.optionUpdated(newCmptOption, false);
  17340. } else {
  17341. // PENDING Global as parent ?
  17342. var extraOpt = extend({
  17343. componentIndex: index
  17344. }, resultItem.keyInfo);
  17345. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  17346. extend(componentModel, extraOpt);
  17347. if (resultItem.brandNew) {
  17348. componentModel.__requireNewView = true;
  17349. }
  17350. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  17351. // newCmptOption has been used as componentModel.option
  17352. // and may be merged with theme and default, so pass null
  17353. // to avoid confusion.
  17354. componentModel.optionUpdated(null, true);
  17355. }
  17356. }
  17357. if (componentModel) {
  17358. optionsByMainType.push(componentModel.option);
  17359. cmptsByMainType.push(componentModel);
  17360. cmptsCountByMainType++;
  17361. } else {
  17362. // Always do assign to avoid elided item in array.
  17363. optionsByMainType.push(void 0);
  17364. cmptsByMainType.push(void 0);
  17365. }
  17366. }, this);
  17367. option[mainType] = optionsByMainType;
  17368. componentsMap.set(mainType, cmptsByMainType);
  17369. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  17370. if (mainType === 'series') {
  17371. reCreateSeriesIndices(this);
  17372. }
  17373. } // If no series declared, ensure `_seriesIndices` initialized.
  17374. if (!this._seriesIndices) {
  17375. reCreateSeriesIndices(this);
  17376. }
  17377. };
  17378. /**
  17379. * Get option for output (cloned option and inner info removed)
  17380. */
  17381. GlobalModel.prototype.getOption = function () {
  17382. var option = clone(this.option);
  17383. each(option, function (optInMainType, mainType) {
  17384. if (ComponentModel.hasClass(mainType)) {
  17385. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  17386. // Inner cmpts might not be at last since ec5.0, but still
  17387. // compatible for users: if inner cmpt at last, splice the returned array.
  17388. var realLen = opts.length;
  17389. var metNonInner = false;
  17390. for (var i = realLen - 1; i >= 0; i--) {
  17391. // Remove options with inner id.
  17392. if (opts[i] && !isComponentIdInternal(opts[i])) {
  17393. metNonInner = true;
  17394. } else {
  17395. opts[i] = null;
  17396. !metNonInner && realLen--;
  17397. }
  17398. }
  17399. opts.length = realLen;
  17400. option[mainType] = opts;
  17401. }
  17402. });
  17403. delete option[OPTION_INNER_KEY];
  17404. return option;
  17405. };
  17406. GlobalModel.prototype.getTheme = function () {
  17407. return this._theme;
  17408. };
  17409. GlobalModel.prototype.getLocaleModel = function () {
  17410. return this._locale;
  17411. };
  17412. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17413. this._payload = payload;
  17414. };
  17415. GlobalModel.prototype.getUpdatePayload = function () {
  17416. return this._payload;
  17417. };
  17418. /**
  17419. * @param idx If not specified, return the first one.
  17420. */
  17421. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17422. var list = this._componentsMap.get(mainType);
  17423. if (list) {
  17424. var cmpt = list[idx || 0];
  17425. if (cmpt) {
  17426. return cmpt;
  17427. } else if (idx == null) {
  17428. for (var i = 0; i < list.length; i++) {
  17429. if (list[i]) {
  17430. return list[i];
  17431. }
  17432. }
  17433. }
  17434. }
  17435. };
  17436. /**
  17437. * @return Never be null/undefined.
  17438. */
  17439. GlobalModel.prototype.queryComponents = function (condition) {
  17440. var mainType = condition.mainType;
  17441. if (!mainType) {
  17442. return [];
  17443. }
  17444. var index = condition.index;
  17445. var id = condition.id;
  17446. var name = condition.name;
  17447. var cmpts = this._componentsMap.get(mainType);
  17448. if (!cmpts || !cmpts.length) {
  17449. return [];
  17450. }
  17451. var result;
  17452. if (index != null) {
  17453. result = [];
  17454. each(normalizeToArray(index), function (idx) {
  17455. cmpts[idx] && result.push(cmpts[idx]);
  17456. });
  17457. } else if (id != null) {
  17458. result = queryByIdOrName('id', id, cmpts);
  17459. } else if (name != null) {
  17460. result = queryByIdOrName('name', name, cmpts);
  17461. } else {
  17462. // Return all non-empty components in that mainType
  17463. result = filter(cmpts, function (cmpt) {
  17464. return !!cmpt;
  17465. });
  17466. }
  17467. return filterBySubType(result, condition);
  17468. };
  17469. /**
  17470. * The interface is different from queryComponents,
  17471. * which is convenient for inner usage.
  17472. *
  17473. * @usage
  17474. * let result = findComponents(
  17475. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17476. * );
  17477. * let result = findComponents(
  17478. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17479. * );
  17480. * let result = findComponents(
  17481. * {mainType: 'series',
  17482. * filter: function (model, index) {...}}
  17483. * );
  17484. * // result like [component0, componnet1, ...]
  17485. */
  17486. GlobalModel.prototype.findComponents = function (condition) {
  17487. var query = condition.query;
  17488. var mainType = condition.mainType;
  17489. var queryCond = getQueryCond(query);
  17490. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  17491. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17492. return !!cmpt;
  17493. });
  17494. return doFilter(filterBySubType(result, condition));
  17495. function getQueryCond(q) {
  17496. var indexAttr = mainType + 'Index';
  17497. var idAttr = mainType + 'Id';
  17498. var nameAttr = mainType + 'Name';
  17499. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17500. mainType: mainType,
  17501. // subType will be filtered finally.
  17502. index: q[indexAttr],
  17503. id: q[idAttr],
  17504. name: q[nameAttr]
  17505. } : null;
  17506. }
  17507. function doFilter(res) {
  17508. return condition.filter ? filter(res, condition.filter) : res;
  17509. }
  17510. };
  17511. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17512. var componentsMap = this._componentsMap;
  17513. if (isFunction(mainType)) {
  17514. var ctxForAll_1 = cb;
  17515. var cbForAll_1 = mainType;
  17516. componentsMap.each(function (cmpts, componentType) {
  17517. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17518. var cmpt = cmpts[i];
  17519. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17520. }
  17521. });
  17522. } else {
  17523. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17524. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17525. var cmpt = cmpts[i];
  17526. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17527. }
  17528. }
  17529. };
  17530. /**
  17531. * Get series list before filtered by name.
  17532. */
  17533. GlobalModel.prototype.getSeriesByName = function (name) {
  17534. var nameStr = convertOptionIdName(name, null);
  17535. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17536. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17537. });
  17538. };
  17539. /**
  17540. * Get series list before filtered by index.
  17541. */
  17542. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17543. return this._componentsMap.get('series')[seriesIndex];
  17544. };
  17545. /**
  17546. * Get series list before filtered by type.
  17547. * FIXME: rename to getRawSeriesByType?
  17548. */
  17549. GlobalModel.prototype.getSeriesByType = function (subType) {
  17550. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17551. return !!oneSeries && oneSeries.subType === subType;
  17552. });
  17553. };
  17554. /**
  17555. * Get all series before filtered.
  17556. */
  17557. GlobalModel.prototype.getSeries = function () {
  17558. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17559. return !!oneSeries;
  17560. });
  17561. };
  17562. /**
  17563. * Count series before filtered.
  17564. */
  17565. GlobalModel.prototype.getSeriesCount = function () {
  17566. return this._componentsCount.get('series');
  17567. };
  17568. /**
  17569. * After filtering, series may be different
  17570. * frome raw series.
  17571. */
  17572. GlobalModel.prototype.eachSeries = function (cb, context) {
  17573. assertSeriesInitialized(this);
  17574. each(this._seriesIndices, function (rawSeriesIndex) {
  17575. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17576. cb.call(context, series, rawSeriesIndex);
  17577. }, this);
  17578. };
  17579. /**
  17580. * Iterate raw series before filtered.
  17581. *
  17582. * @param {Function} cb
  17583. * @param {*} context
  17584. */
  17585. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17586. each(this._componentsMap.get('series'), function (series) {
  17587. series && cb.call(context, series, series.componentIndex);
  17588. });
  17589. };
  17590. /**
  17591. * After filtering, series may be different.
  17592. * frome raw series.
  17593. */
  17594. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17595. assertSeriesInitialized(this);
  17596. each(this._seriesIndices, function (rawSeriesIndex) {
  17597. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17598. if (series.subType === subType) {
  17599. cb.call(context, series, rawSeriesIndex);
  17600. }
  17601. }, this);
  17602. };
  17603. /**
  17604. * Iterate raw series before filtered of given type.
  17605. */
  17606. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17607. return each(this.getSeriesByType(subType), cb, context);
  17608. };
  17609. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17610. assertSeriesInitialized(this);
  17611. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17612. };
  17613. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17614. return (this._seriesIndices || []).slice();
  17615. };
  17616. GlobalModel.prototype.filterSeries = function (cb, context) {
  17617. assertSeriesInitialized(this);
  17618. var newSeriesIndices = [];
  17619. each(this._seriesIndices, function (seriesRawIdx) {
  17620. var series = this._componentsMap.get('series')[seriesRawIdx];
  17621. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17622. }, this);
  17623. this._seriesIndices = newSeriesIndices;
  17624. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17625. };
  17626. GlobalModel.prototype.restoreData = function (payload) {
  17627. reCreateSeriesIndices(this);
  17628. var componentsMap = this._componentsMap;
  17629. var componentTypes = [];
  17630. componentsMap.each(function (components, componentType) {
  17631. if (ComponentModel.hasClass(componentType)) {
  17632. componentTypes.push(componentType);
  17633. }
  17634. });
  17635. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17636. each(componentsMap.get(componentType), function (component) {
  17637. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17638. component.restoreData();
  17639. }
  17640. });
  17641. });
  17642. };
  17643. GlobalModel.internalField = function () {
  17644. reCreateSeriesIndices = function (ecModel) {
  17645. var seriesIndices = ecModel._seriesIndices = [];
  17646. each(ecModel._componentsMap.get('series'), function (series) {
  17647. // series may have been removed by `replaceMerge`.
  17648. series && seriesIndices.push(series.componentIndex);
  17649. });
  17650. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17651. };
  17652. assertSeriesInitialized = function (ecModel) {
  17653. // Components that use _seriesIndices should depends on series component,
  17654. // which make sure that their initialization is after series.
  17655. if ("development" !== 'production') {
  17656. if (!ecModel._seriesIndices) {
  17657. throw new Error('Option should contains series.');
  17658. }
  17659. }
  17660. };
  17661. initBase = function (ecModel, baseOption) {
  17662. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17663. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17664. ecModel.option = {};
  17665. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  17666. // before series initialized.
  17667. ecModel._componentsMap = createHashMap({
  17668. series: []
  17669. });
  17670. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  17671. // performed before theme and globalDefault merge.
  17672. var airaOption = baseOption.aria;
  17673. if (isObject(airaOption) && airaOption.enabled == null) {
  17674. airaOption.enabled = true;
  17675. }
  17676. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  17677. merge(baseOption, globalDefault, false);
  17678. ecModel._mergeOption(baseOption, null);
  17679. };
  17680. }();
  17681. return GlobalModel;
  17682. }(Model);
  17683. function isNotTargetSeries(seriesModel, payload) {
  17684. if (payload) {
  17685. var index = payload.seriesIndex;
  17686. var id = payload.seriesId;
  17687. var name_1 = payload.seriesName;
  17688. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17689. }
  17690. }
  17691. function mergeTheme(option, theme) {
  17692. // PENDING
  17693. // NOT use `colorLayer` in theme if option has `color`
  17694. var notMergeColorLayer = option.color && !option.colorLayer;
  17695. each(theme, function (themeItem, name) {
  17696. if (name === 'colorLayer' && notMergeColorLayer) {
  17697. return;
  17698. } // If it is component model mainType, the model handles that merge later.
  17699. // otherwise, merge them here.
  17700. if (!ComponentModel.hasClass(name)) {
  17701. if (typeof themeItem === 'object') {
  17702. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17703. } else {
  17704. if (option[name] == null) {
  17705. option[name] = themeItem;
  17706. }
  17707. }
  17708. }
  17709. });
  17710. }
  17711. function queryByIdOrName(attr, idOrName, cmpts) {
  17712. // Here is a break from echarts4: string and number are
  17713. // treated as equal.
  17714. if (isArray(idOrName)) {
  17715. var keyMap_1 = createHashMap();
  17716. each(idOrName, function (idOrNameItem) {
  17717. if (idOrNameItem != null) {
  17718. var idName = convertOptionIdName(idOrNameItem, null);
  17719. idName != null && keyMap_1.set(idOrNameItem, true);
  17720. }
  17721. });
  17722. return filter(cmpts, function (cmpt) {
  17723. return cmpt && keyMap_1.get(cmpt[attr]);
  17724. });
  17725. } else {
  17726. var idName_1 = convertOptionIdName(idOrName, null);
  17727. return filter(cmpts, function (cmpt) {
  17728. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  17729. });
  17730. }
  17731. }
  17732. function filterBySubType(components, condition) {
  17733. // Using hasOwnProperty for restrict. Consider
  17734. // subType is undefined in user payload.
  17735. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  17736. return cmpt && cmpt.subType === condition.subType;
  17737. }) : components;
  17738. }
  17739. function normalizeSetOptionInput(opts) {
  17740. var replaceMergeMainTypeMap = createHashMap();
  17741. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  17742. if ("development" !== 'production') {
  17743. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  17744. }
  17745. replaceMergeMainTypeMap.set(mainType, true);
  17746. });
  17747. return {
  17748. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  17749. };
  17750. }
  17751. mixin(GlobalModel, PaletteMixin);
  17752. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  17753. 'getOption', // 'getViewOfComponentModel',
  17754. // 'getViewOfSeriesModel',
  17755. 'getId', 'updateLabelLayout'];
  17756. var ExtensionAPI =
  17757. /** @class */
  17758. function () {
  17759. function ExtensionAPI(ecInstance) {
  17760. each(availableMethods, function (methodName) {
  17761. this[methodName] = bind(ecInstance[methodName], ecInstance);
  17762. }, this);
  17763. }
  17764. return ExtensionAPI;
  17765. }();
  17766. var coordinateSystemCreators = {};
  17767. var CoordinateSystemManager =
  17768. /** @class */
  17769. function () {
  17770. function CoordinateSystemManager() {
  17771. this._coordinateSystems = [];
  17772. }
  17773. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  17774. var coordinateSystems = [];
  17775. each(coordinateSystemCreators, function (creater, type) {
  17776. var list = creater.create(ecModel, api);
  17777. coordinateSystems = coordinateSystems.concat(list || []);
  17778. });
  17779. this._coordinateSystems = coordinateSystems;
  17780. };
  17781. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  17782. each(this._coordinateSystems, function (coordSys) {
  17783. coordSys.update && coordSys.update(ecModel, api);
  17784. });
  17785. };
  17786. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  17787. return this._coordinateSystems.slice();
  17788. };
  17789. CoordinateSystemManager.register = function (type, creator) {
  17790. coordinateSystemCreators[type] = creator;
  17791. };
  17792. CoordinateSystemManager.get = function (type) {
  17793. return coordinateSystemCreators[type];
  17794. };
  17795. return CoordinateSystemManager;
  17796. }();
  17797. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  17798. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  17799. /**
  17800. * TERM EXPLANATIONS:
  17801. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  17802. */
  17803. var OptionManager =
  17804. /** @class */
  17805. function () {
  17806. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17807. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17808. // rawOption cloned and backuped when timeline changed, which does no
  17809. // good to performance. What's more, that both timeline and setOption
  17810. // method supply 'notMerge' brings complex and some problems.
  17811. // Consider this case:
  17812. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17813. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17814. function OptionManager(api) {
  17815. this._timelineOptions = [];
  17816. this._mediaList = [];
  17817. /**
  17818. * -1, means default.
  17819. * empty means no media.
  17820. */
  17821. this._currentMediaIndices = [];
  17822. this._api = api;
  17823. }
  17824. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  17825. if (rawOption) {
  17826. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17827. each(normalizeToArray(rawOption.series), function (series) {
  17828. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17829. });
  17830. each(normalizeToArray(rawOption.dataset), function (dataset) {
  17831. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  17832. });
  17833. } // Caution: some series modify option data, if do not clone,
  17834. // it should ensure that the repeat modify correctly
  17835. // (create a new object when modify itself).
  17836. rawOption = clone(rawOption); // FIXME
  17837. // If some property is set in timeline options or media option but
  17838. // not set in baseOption, a warning should be given.
  17839. var optionBackup = this._optionBackup;
  17840. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  17841. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  17842. if (optionBackup) {
  17843. // FIXME
  17844. // the restore merge solution is essentially incorrect.
  17845. // the mapping can not be 100% consistent with ecModel, which probably brings
  17846. // potential bug!
  17847. // The first merge is delayed, becuase in most cases, users do not call `setOption` twice.
  17848. // let fakeCmptsMap = this._fakeCmptsMap;
  17849. // if (!fakeCmptsMap) {
  17850. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  17851. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  17852. // }
  17853. // mergeToBackupOption(
  17854. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  17855. // );
  17856. // For simplicity, timeline options and media options do not support merge,
  17857. // that is, if you `setOption` twice and both has timeline options, the latter
  17858. // timeline opitons will not be merged to the formers, but just substitude them.
  17859. if (newParsedOption.timelineOptions.length) {
  17860. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  17861. }
  17862. if (newParsedOption.mediaList.length) {
  17863. optionBackup.mediaList = newParsedOption.mediaList;
  17864. }
  17865. if (newParsedOption.mediaDefault) {
  17866. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  17867. }
  17868. } else {
  17869. this._optionBackup = newParsedOption;
  17870. }
  17871. };
  17872. OptionManager.prototype.mountOption = function (isRecreate) {
  17873. var optionBackup = this._optionBackup;
  17874. this._timelineOptions = optionBackup.timelineOptions;
  17875. this._mediaList = optionBackup.mediaList;
  17876. this._mediaDefault = optionBackup.mediaDefault;
  17877. this._currentMediaIndices = [];
  17878. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  17879. // called, and is merged into every new option by inner method `mergeToBackupOption`
  17880. // each time `setOption` called, can be only used in `isRecreate`, because
  17881. // its reliability is under suspicion. In other cases option merge is
  17882. // performed by `model.mergeOption`.
  17883. ? optionBackup.baseOption : this._newBaseOption);
  17884. };
  17885. OptionManager.prototype.getTimelineOption = function (ecModel) {
  17886. var option;
  17887. var timelineOptions = this._timelineOptions;
  17888. if (timelineOptions.length) {
  17889. // getTimelineOption can only be called after ecModel inited,
  17890. // so we can get currentIndex from timelineModel.
  17891. var timelineModel = ecModel.getComponent('timeline');
  17892. if (timelineModel) {
  17893. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  17894. timelineOptions[timelineModel.getCurrentIndex()]);
  17895. }
  17896. }
  17897. return option;
  17898. };
  17899. OptionManager.prototype.getMediaOption = function (ecModel) {
  17900. var ecWidth = this._api.getWidth();
  17901. var ecHeight = this._api.getHeight();
  17902. var mediaList = this._mediaList;
  17903. var mediaDefault = this._mediaDefault;
  17904. var indices = [];
  17905. var result = []; // No media defined.
  17906. if (!mediaList.length && !mediaDefault) {
  17907. return result;
  17908. } // Multi media may be applied, the latter defined media has higher priority.
  17909. for (var i = 0, len = mediaList.length; i < len; i++) {
  17910. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17911. indices.push(i);
  17912. }
  17913. } // FIXME
  17914. // Whether mediaDefault should force users to provide? Otherwise
  17915. // the change by media query can not be recorvered.
  17916. if (!indices.length && mediaDefault) {
  17917. indices = [-1];
  17918. }
  17919. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17920. result = map(indices, function (index) {
  17921. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  17922. });
  17923. } // Otherwise return nothing.
  17924. this._currentMediaIndices = indices;
  17925. return result;
  17926. };
  17927. return OptionManager;
  17928. }();
  17929. /**
  17930. * [RAW_OPTION_PATTERNS]
  17931. * (Note: "series: []" represents all other props in `ECUnitOption`)
  17932. *
  17933. * (1) No prop "baseOption" declared:
  17934. * Root option is used as "baseOption" (except prop "options" and "media").
  17935. * ```js
  17936. * option = {
  17937. * series: [],
  17938. * timeline: {},
  17939. * options: [],
  17940. * };
  17941. * option = {
  17942. * series: [],
  17943. * media: {},
  17944. * };
  17945. * option = {
  17946. * series: [],
  17947. * timeline: {},
  17948. * options: [],
  17949. * media: {},
  17950. * }
  17951. * ```
  17952. *
  17953. * (2) Prop "baseOption" declared:
  17954. * If "baseOption" declared, `ECUnitOption` props can only be declared
  17955. * inside "baseOption" except prop "timeline" (compat ec2).
  17956. * ```js
  17957. * option = {
  17958. * baseOption: {
  17959. * timeline: {},
  17960. * series: [],
  17961. * },
  17962. * options: []
  17963. * };
  17964. * option = {
  17965. * baseOption: {
  17966. * series: [],
  17967. * },
  17968. * media: []
  17969. * };
  17970. * option = {
  17971. * baseOption: {
  17972. * timeline: {},
  17973. * series: [],
  17974. * },
  17975. * options: []
  17976. * media: []
  17977. * };
  17978. * option = {
  17979. * // ec3 compat ec2: allow (only) `timeline` declared
  17980. * // outside baseOption. Keep this setting for compat.
  17981. * timeline: {},
  17982. * baseOption: {
  17983. * series: [],
  17984. * },
  17985. * options: [],
  17986. * media: []
  17987. * };
  17988. * ```
  17989. */
  17990. function parseRawOption( // `rawOption` May be modified
  17991. rawOption, optionPreprocessorFuncs, isNew) {
  17992. var mediaList = [];
  17993. var mediaDefault;
  17994. var baseOption;
  17995. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  17996. var timelineOnRoot = rawOption.timeline;
  17997. var timelineOptionsOnRoot = rawOption.options;
  17998. var mediaOnRoot = rawOption.media;
  17999. var hasMedia = !!rawOption.media;
  18000. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  18001. if (declaredBaseOption) {
  18002. baseOption = declaredBaseOption; // For merge option.
  18003. if (!baseOption.timeline) {
  18004. baseOption.timeline = timelineOnRoot;
  18005. }
  18006. } // For convenience, enable to use the root option as the `baseOption`:
  18007. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  18008. else {
  18009. if (hasTimeline || hasMedia) {
  18010. rawOption.options = rawOption.media = null;
  18011. }
  18012. baseOption = rawOption;
  18013. }
  18014. if (hasMedia) {
  18015. if (isArray(mediaOnRoot)) {
  18016. each(mediaOnRoot, function (singleMedia) {
  18017. if ("development" !== 'production') {
  18018. // Real case of wrong config.
  18019. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  18020. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  18021. }
  18022. }
  18023. if (singleMedia && singleMedia.option) {
  18024. if (singleMedia.query) {
  18025. mediaList.push(singleMedia);
  18026. } else if (!mediaDefault) {
  18027. // Use the first media default.
  18028. mediaDefault = singleMedia;
  18029. }
  18030. }
  18031. });
  18032. } else {
  18033. if ("development" !== 'production') {
  18034. // Real case of wrong config.
  18035. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  18036. }
  18037. }
  18038. }
  18039. doPreprocess(baseOption);
  18040. each(timelineOptionsOnRoot, function (option) {
  18041. return doPreprocess(option);
  18042. });
  18043. each(mediaList, function (media) {
  18044. return doPreprocess(media.option);
  18045. });
  18046. function doPreprocess(option) {
  18047. each(optionPreprocessorFuncs, function (preProcess) {
  18048. preProcess(option, isNew);
  18049. });
  18050. }
  18051. return {
  18052. baseOption: baseOption,
  18053. timelineOptions: timelineOptionsOnRoot || [],
  18054. mediaDefault: mediaDefault,
  18055. mediaList: mediaList
  18056. };
  18057. }
  18058. /**
  18059. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18060. * Support: width, height, aspectRatio
  18061. * Can use max or min as prefix.
  18062. */
  18063. function applyMediaQuery(query, ecWidth, ecHeight) {
  18064. var realMap = {
  18065. width: ecWidth,
  18066. height: ecHeight,
  18067. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18068. };
  18069. var applicatable = true;
  18070. each(query, function (value, attr) {
  18071. var matched = attr.match(QUERY_REG);
  18072. if (!matched || !matched[1] || !matched[2]) {
  18073. return;
  18074. }
  18075. var operator = matched[1];
  18076. var realAttr = matched[2].toLowerCase();
  18077. if (!compare(realMap[realAttr], value, operator)) {
  18078. applicatable = false;
  18079. }
  18080. });
  18081. return applicatable;
  18082. }
  18083. function compare(real, expect, operator) {
  18084. if (operator === 'min') {
  18085. return real >= expect;
  18086. } else if (operator === 'max') {
  18087. return real <= expect;
  18088. } else {
  18089. // Equals
  18090. return real === expect;
  18091. }
  18092. }
  18093. function indicesEquals(indices1, indices2) {
  18094. // indices is always order by asc and has only finite number.
  18095. return indices1.join(',') === indices2.join(',');
  18096. }
  18097. var each$2 = each;
  18098. var isObject$1 = isObject;
  18099. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18100. function compatEC2ItemStyle(opt) {
  18101. var itemStyleOpt = opt && opt.itemStyle;
  18102. if (!itemStyleOpt) {
  18103. return;
  18104. }
  18105. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18106. var styleName = POSSIBLE_STYLES[i];
  18107. var normalItemStyleOpt = itemStyleOpt.normal;
  18108. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18109. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18110. if ("development" !== 'production') {
  18111. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  18112. }
  18113. opt[styleName] = opt[styleName] || {};
  18114. if (!opt[styleName].normal) {
  18115. opt[styleName].normal = normalItemStyleOpt[styleName];
  18116. } else {
  18117. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18118. }
  18119. normalItemStyleOpt[styleName] = null;
  18120. }
  18121. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18122. if ("development" !== 'production') {
  18123. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  18124. }
  18125. opt[styleName] = opt[styleName] || {};
  18126. if (!opt[styleName].emphasis) {
  18127. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18128. } else {
  18129. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18130. }
  18131. emphasisItemStyleOpt[styleName] = null;
  18132. }
  18133. }
  18134. }
  18135. function convertNormalEmphasis(opt, optType, useExtend) {
  18136. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18137. var normalOpt = opt[optType].normal;
  18138. var emphasisOpt = opt[optType].emphasis;
  18139. if (normalOpt) {
  18140. if ("development" !== 'production') {
  18141. // eslint-disable-next-line max-len
  18142. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  18143. } // Timeline controlStyle has other properties besides normal and emphasis
  18144. if (useExtend) {
  18145. opt[optType].normal = opt[optType].emphasis = null;
  18146. defaults(opt[optType], normalOpt);
  18147. } else {
  18148. opt[optType] = normalOpt;
  18149. }
  18150. }
  18151. if (emphasisOpt) {
  18152. if ("development" !== 'production') {
  18153. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  18154. }
  18155. opt.emphasis = opt.emphasis || {};
  18156. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  18157. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  18158. if (emphasisOpt.focus) {
  18159. opt.emphasis.focus = emphasisOpt.focus;
  18160. }
  18161. if (emphasisOpt.blurScope) {
  18162. opt.emphasis.blurScope = emphasisOpt.blurScope;
  18163. }
  18164. }
  18165. }
  18166. }
  18167. function removeEC3NormalStatus(opt) {
  18168. convertNormalEmphasis(opt, 'itemStyle');
  18169. convertNormalEmphasis(opt, 'lineStyle');
  18170. convertNormalEmphasis(opt, 'areaStyle');
  18171. convertNormalEmphasis(opt, 'label');
  18172. convertNormalEmphasis(opt, 'labelLine'); // treemap
  18173. convertNormalEmphasis(opt, 'upperLabel'); // graph
  18174. convertNormalEmphasis(opt, 'edgeLabel');
  18175. }
  18176. function compatTextStyle(opt, propName) {
  18177. // Check whether is not object (string\null\undefined ...)
  18178. var labelOptSingle = isObject$1(opt) && opt[propName];
  18179. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  18180. if (textStyle) {
  18181. if ("development" !== 'production') {
  18182. // eslint-disable-next-line max-len
  18183. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  18184. }
  18185. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18186. var textPropName = TEXT_STYLE_OPTIONS[i];
  18187. if (textStyle.hasOwnProperty(textPropName)) {
  18188. labelOptSingle[textPropName] = textStyle[textPropName];
  18189. }
  18190. }
  18191. }
  18192. }
  18193. function compatEC3CommonStyles(opt) {
  18194. if (opt) {
  18195. removeEC3NormalStatus(opt);
  18196. compatTextStyle(opt, 'label');
  18197. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18198. }
  18199. }
  18200. function processSeries(seriesOpt) {
  18201. if (!isObject$1(seriesOpt)) {
  18202. return;
  18203. }
  18204. compatEC2ItemStyle(seriesOpt);
  18205. removeEC3NormalStatus(seriesOpt);
  18206. compatTextStyle(seriesOpt, 'label'); // treemap
  18207. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  18208. compatTextStyle(seriesOpt, 'edgeLabel');
  18209. if (seriesOpt.emphasis) {
  18210. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  18211. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  18212. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18213. }
  18214. var markPoint = seriesOpt.markPoint;
  18215. if (markPoint) {
  18216. compatEC2ItemStyle(markPoint);
  18217. compatEC3CommonStyles(markPoint);
  18218. }
  18219. var markLine = seriesOpt.markLine;
  18220. if (markLine) {
  18221. compatEC2ItemStyle(markLine);
  18222. compatEC3CommonStyles(markLine);
  18223. }
  18224. var markArea = seriesOpt.markArea;
  18225. if (markArea) {
  18226. compatEC3CommonStyles(markArea);
  18227. }
  18228. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  18229. // then the backward compat based on option type will not be performed.
  18230. if (seriesOpt.type === 'graph') {
  18231. data = data || seriesOpt.nodes;
  18232. var edgeData = seriesOpt.links || seriesOpt.edges;
  18233. if (edgeData && !isTypedArray(edgeData)) {
  18234. for (var i = 0; i < edgeData.length; i++) {
  18235. compatEC3CommonStyles(edgeData[i]);
  18236. }
  18237. }
  18238. each(seriesOpt.categories, function (opt) {
  18239. removeEC3NormalStatus(opt);
  18240. });
  18241. }
  18242. if (data && !isTypedArray(data)) {
  18243. for (var i = 0; i < data.length; i++) {
  18244. compatEC3CommonStyles(data[i]);
  18245. }
  18246. } // mark point data
  18247. markPoint = seriesOpt.markPoint;
  18248. if (markPoint && markPoint.data) {
  18249. var mpData = markPoint.data;
  18250. for (var i = 0; i < mpData.length; i++) {
  18251. compatEC3CommonStyles(mpData[i]);
  18252. }
  18253. } // mark line data
  18254. markLine = seriesOpt.markLine;
  18255. if (markLine && markLine.data) {
  18256. var mlData = markLine.data;
  18257. for (var i = 0; i < mlData.length; i++) {
  18258. if (isArray(mlData[i])) {
  18259. compatEC3CommonStyles(mlData[i][0]);
  18260. compatEC3CommonStyles(mlData[i][1]);
  18261. } else {
  18262. compatEC3CommonStyles(mlData[i]);
  18263. }
  18264. }
  18265. } // Series
  18266. if (seriesOpt.type === 'gauge') {
  18267. compatTextStyle(seriesOpt, 'axisLabel');
  18268. compatTextStyle(seriesOpt, 'title');
  18269. compatTextStyle(seriesOpt, 'detail');
  18270. } else if (seriesOpt.type === 'treemap') {
  18271. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18272. each(seriesOpt.levels, function (opt) {
  18273. removeEC3NormalStatus(opt);
  18274. });
  18275. } else if (seriesOpt.type === 'tree') {
  18276. removeEC3NormalStatus(seriesOpt.leaves);
  18277. } // sunburst starts from ec4, so it does not need to compat levels.
  18278. }
  18279. function toArr(o) {
  18280. return isArray(o) ? o : o ? [o] : [];
  18281. }
  18282. function toObj(o) {
  18283. return (isArray(o) ? o[0] : o) || {};
  18284. }
  18285. function globalCompatStyle(option, isTheme) {
  18286. each$2(toArr(option.series), function (seriesOpt) {
  18287. isObject$1(seriesOpt) && processSeries(seriesOpt);
  18288. });
  18289. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18290. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18291. each$2(axes, function (axisName) {
  18292. each$2(toArr(option[axisName]), function (axisOpt) {
  18293. if (axisOpt) {
  18294. compatTextStyle(axisOpt, 'axisLabel');
  18295. compatTextStyle(axisOpt.axisPointer, 'label');
  18296. }
  18297. });
  18298. });
  18299. each$2(toArr(option.parallel), function (parallelOpt) {
  18300. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18301. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18302. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18303. });
  18304. each$2(toArr(option.calendar), function (calendarOpt) {
  18305. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18306. compatTextStyle(calendarOpt, 'dayLabel');
  18307. compatTextStyle(calendarOpt, 'monthLabel');
  18308. compatTextStyle(calendarOpt, 'yearLabel');
  18309. }); // radar.name.textStyle
  18310. each$2(toArr(option.radar), function (radarOpt) {
  18311. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  18312. if (radarOpt.name && radarOpt.axisName == null) {
  18313. radarOpt.axisName = radarOpt.name;
  18314. delete radarOpt.name;
  18315. if ("development" !== 'production') {
  18316. deprecateLog('name property in radar component has been changed to axisName');
  18317. }
  18318. }
  18319. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  18320. radarOpt.axisNameGap = radarOpt.nameGap;
  18321. delete radarOpt.nameGap;
  18322. if ("development" !== 'production') {
  18323. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  18324. }
  18325. }
  18326. });
  18327. each$2(toArr(option.geo), function (geoOpt) {
  18328. if (isObject$1(geoOpt)) {
  18329. compatEC3CommonStyles(geoOpt);
  18330. each$2(toArr(geoOpt.regions), function (regionObj) {
  18331. compatEC3CommonStyles(regionObj);
  18332. });
  18333. }
  18334. });
  18335. each$2(toArr(option.timeline), function (timelineOpt) {
  18336. compatEC3CommonStyles(timelineOpt);
  18337. convertNormalEmphasis(timelineOpt, 'label');
  18338. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18339. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18340. var data = timelineOpt.data;
  18341. isArray(data) && each(data, function (item) {
  18342. if (isObject(item)) {
  18343. convertNormalEmphasis(item, 'label');
  18344. convertNormalEmphasis(item, 'itemStyle');
  18345. }
  18346. });
  18347. });
  18348. each$2(toArr(option.toolbox), function (toolboxOpt) {
  18349. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18350. each$2(toolboxOpt.feature, function (featureOpt) {
  18351. convertNormalEmphasis(featureOpt, 'iconStyle');
  18352. });
  18353. });
  18354. compatTextStyle(toObj(option.axisPointer), 'label');
  18355. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  18356. // storedLogs = {};
  18357. }
  18358. function get(opt, path) {
  18359. var pathArr = path.split(',');
  18360. var obj = opt;
  18361. for (var i = 0; i < pathArr.length; i++) {
  18362. obj = obj && obj[pathArr[i]];
  18363. if (obj == null) {
  18364. break;
  18365. }
  18366. }
  18367. return obj;
  18368. }
  18369. function set$1(opt, path, val, overwrite) {
  18370. var pathArr = path.split(',');
  18371. var obj = opt;
  18372. var key;
  18373. var i = 0;
  18374. for (; i < pathArr.length - 1; i++) {
  18375. key = pathArr[i];
  18376. if (obj[key] == null) {
  18377. obj[key] = {};
  18378. }
  18379. obj = obj[key];
  18380. }
  18381. if (overwrite || obj[pathArr[i]] == null) {
  18382. obj[pathArr[i]] = val;
  18383. }
  18384. }
  18385. function compatLayoutProperties(option) {
  18386. option && each(LAYOUT_PROPERTIES, function (prop) {
  18387. if (prop[0] in option && !(prop[1] in option)) {
  18388. option[prop[1]] = option[prop[0]];
  18389. }
  18390. });
  18391. }
  18392. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18393. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18394. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  18395. function compatBarItemStyle(option) {
  18396. var itemStyle = option && option.itemStyle;
  18397. if (itemStyle) {
  18398. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  18399. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  18400. var newName = BAR_ITEM_STYLE_MAP[i][0];
  18401. if (itemStyle[oldName] != null) {
  18402. itemStyle[newName] = itemStyle[oldName];
  18403. if ("development" !== 'production') {
  18404. deprecateReplaceLog(oldName, newName);
  18405. }
  18406. }
  18407. }
  18408. }
  18409. }
  18410. function compatPieLabel(option) {
  18411. if (!option) {
  18412. return;
  18413. }
  18414. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18415. if ("development" !== 'production') {
  18416. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18417. }
  18418. option.edgeDistance = option.margin;
  18419. }
  18420. }
  18421. function compatSunburstState(option) {
  18422. if (!option) {
  18423. return;
  18424. }
  18425. if (option.downplay && !option.blur) {
  18426. option.blur = option.downplay;
  18427. if ("development" !== 'production') {
  18428. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18429. }
  18430. }
  18431. }
  18432. function compatGraphFocus(option) {
  18433. if (!option) {
  18434. return;
  18435. }
  18436. if (option.focusNodeAdjacency != null) {
  18437. option.emphasis = option.emphasis || {};
  18438. if (option.emphasis.focus == null) {
  18439. if ("development" !== 'production') {
  18440. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18441. }
  18442. option.emphasis.focus = 'adjacency';
  18443. }
  18444. }
  18445. }
  18446. function traverseTree(data, cb) {
  18447. if (data) {
  18448. for (var i = 0; i < data.length; i++) {
  18449. cb(data[i]);
  18450. data[i] && traverseTree(data[i].children, cb);
  18451. }
  18452. }
  18453. }
  18454. function globalBackwardCompat(option, isTheme) {
  18455. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  18456. option.series = normalizeToArray(option.series);
  18457. each(option.series, function (seriesOpt) {
  18458. if (!isObject(seriesOpt)) {
  18459. return;
  18460. }
  18461. var seriesType = seriesOpt.type;
  18462. if (seriesType === 'line') {
  18463. if (seriesOpt.clipOverflow != null) {
  18464. seriesOpt.clip = seriesOpt.clipOverflow;
  18465. if ("development" !== 'production') {
  18466. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18467. }
  18468. }
  18469. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18470. if (seriesOpt.clockWise != null) {
  18471. seriesOpt.clockwise = seriesOpt.clockWise;
  18472. if ("development" !== 'production') {
  18473. deprecateReplaceLog('clockWise', 'clockwise');
  18474. }
  18475. }
  18476. compatPieLabel(seriesOpt.label);
  18477. var data = seriesOpt.data;
  18478. if (data && !isTypedArray(data)) {
  18479. for (var i = 0; i < data.length; i++) {
  18480. compatPieLabel(data[i]);
  18481. }
  18482. }
  18483. if (seriesOpt.hoverOffset != null) {
  18484. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18485. if (seriesOpt.emphasis.scaleSize = null) {
  18486. if ("development" !== 'production') {
  18487. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18488. }
  18489. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18490. }
  18491. }
  18492. } else if (seriesType === 'gauge') {
  18493. var pointerColor = get(seriesOpt, 'pointer.color');
  18494. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18495. } else if (seriesType === 'bar') {
  18496. compatBarItemStyle(seriesOpt);
  18497. compatBarItemStyle(seriesOpt.backgroundStyle);
  18498. compatBarItemStyle(seriesOpt.emphasis);
  18499. var data = seriesOpt.data;
  18500. if (data && !isTypedArray(data)) {
  18501. for (var i = 0; i < data.length; i++) {
  18502. if (typeof data[i] === 'object') {
  18503. compatBarItemStyle(data[i]);
  18504. compatBarItemStyle(data[i] && data[i].emphasis);
  18505. }
  18506. }
  18507. }
  18508. } else if (seriesType === 'sunburst') {
  18509. var highlightPolicy = seriesOpt.highlightPolicy;
  18510. if (highlightPolicy) {
  18511. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18512. if (!seriesOpt.emphasis.focus) {
  18513. seriesOpt.emphasis.focus = highlightPolicy;
  18514. if ("development" !== 'production') {
  18515. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18516. }
  18517. }
  18518. }
  18519. compatSunburstState(seriesOpt);
  18520. traverseTree(seriesOpt.data, compatSunburstState);
  18521. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18522. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  18523. } else if (seriesType === 'map') {
  18524. if (seriesOpt.mapType && !seriesOpt.map) {
  18525. if ("development" !== 'production') {
  18526. deprecateReplaceLog('mapType', 'map', 'map');
  18527. }
  18528. seriesOpt.map = seriesOpt.mapType;
  18529. }
  18530. if (seriesOpt.mapLocation) {
  18531. if ("development" !== 'production') {
  18532. deprecateLog('`mapLocation` is not used anymore.');
  18533. }
  18534. defaults(seriesOpt, seriesOpt.mapLocation);
  18535. }
  18536. }
  18537. if (seriesOpt.hoverAnimation != null) {
  18538. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18539. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18540. if ("development" !== 'production') {
  18541. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18542. }
  18543. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18544. }
  18545. }
  18546. compatLayoutProperties(seriesOpt);
  18547. }); // dataRange has changed to visualMap
  18548. if (option.dataRange) {
  18549. option.visualMap = option.dataRange;
  18550. }
  18551. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18552. var options = option[componentName];
  18553. if (options) {
  18554. if (!isArray(options)) {
  18555. options = [options];
  18556. }
  18557. each(options, function (option) {
  18558. compatLayoutProperties(option);
  18559. });
  18560. }
  18561. });
  18562. }
  18563. // data processing stage is blocked in stream.
  18564. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18565. // (2) Only register once when import repeatly.
  18566. // Should be executed after series filtered and before stack calculation.
  18567. function dataStack(ecModel) {
  18568. var stackInfoMap = createHashMap();
  18569. ecModel.eachSeries(function (seriesModel) {
  18570. var stack = seriesModel.get('stack'); // Compatibal: when `stack` is set as '', do not stack.
  18571. if (stack) {
  18572. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18573. var data = seriesModel.getData();
  18574. var stackInfo = {
  18575. // Used for calculate axis extent automatically.
  18576. // TODO: Type getCalculationInfo return more specific type?
  18577. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18578. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18579. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18580. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18581. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18582. data: data,
  18583. seriesModel: seriesModel
  18584. }; // If stacked on axis that do not support data stack.
  18585. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18586. return;
  18587. }
  18588. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18589. stackInfoList.push(stackInfo);
  18590. }
  18591. });
  18592. stackInfoMap.each(calculateStack);
  18593. }
  18594. function calculateStack(stackInfoList) {
  18595. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18596. var resultVal = [];
  18597. var resultNaN = [NaN, NaN];
  18598. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18599. var targetData = targetStackInfo.data;
  18600. var isStackedByIndex = targetStackInfo.isStackedByIndex; // Should not write on raw data, because stack series model list changes
  18601. // depending on legend selection.
  18602. targetData.modify(dims, function (v0, v1, dataIndex) {
  18603. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18604. // should also be NaN, to draw a appropriate belt area.
  18605. if (isNaN(sum)) {
  18606. return resultNaN;
  18607. }
  18608. var byValue;
  18609. var stackedDataRawIndex;
  18610. if (isStackedByIndex) {
  18611. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18612. } else {
  18613. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18614. } // If stackOver is NaN, chart view will render point on value start.
  18615. var stackedOver = NaN;
  18616. for (var j = idxInStack - 1; j >= 0; j--) {
  18617. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18618. if (!isStackedByIndex) {
  18619. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18620. }
  18621. if (stackedDataRawIndex >= 0) {
  18622. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18623. if (sum >= 0 && val > 0 || // Positive stack
  18624. sum <= 0 && val < 0 // Negative stack
  18625. ) {
  18626. // The sum should be as less as possible to be effected
  18627. // by floating arithmetic problem. A wrong result probably
  18628. // filtered incorrectly by axis min/max.
  18629. sum = addSafe(sum, val);
  18630. stackedOver = val;
  18631. break;
  18632. }
  18633. }
  18634. }
  18635. resultVal[0] = sum;
  18636. resultVal[1] = stackedOver;
  18637. return resultVal;
  18638. });
  18639. });
  18640. }
  18641. var SourceImpl =
  18642. /** @class */
  18643. function () {
  18644. function SourceImpl(fields) {
  18645. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18646. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  18647. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18648. this.startIndex = fields.startIndex || 0;
  18649. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18650. this.metaRawOption = fields.metaRawOption;
  18651. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  18652. if (dimensionsDefine) {
  18653. for (var i = 0; i < dimensionsDefine.length; i++) {
  18654. var dim = dimensionsDefine[i];
  18655. if (dim.type == null) {
  18656. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  18657. dim.type = 'ordinal';
  18658. }
  18659. }
  18660. }
  18661. }
  18662. }
  18663. return SourceImpl;
  18664. }();
  18665. function isSourceInstance(val) {
  18666. return val instanceof SourceImpl;
  18667. }
  18668. /**
  18669. * Create a source from option.
  18670. * NOTE: Created source is immutable. Don't change any properties in it.
  18671. */
  18672. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  18673. sourceFormat) {
  18674. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18675. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18676. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18677. var source = new SourceImpl({
  18678. data: sourceData,
  18679. sourceFormat: sourceFormat,
  18680. seriesLayoutBy: seriesLayoutBy,
  18681. dimensionsDefine: determined.dimensionsDefine,
  18682. startIndex: determined.startIndex,
  18683. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18684. metaRawOption: clone(thisMetaRawOption)
  18685. });
  18686. return source;
  18687. }
  18688. /**
  18689. * Wrap original series data for some compatibility cases.
  18690. */
  18691. function createSourceFromSeriesDataOption(data) {
  18692. return new SourceImpl({
  18693. data: data,
  18694. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18695. });
  18696. }
  18697. /**
  18698. * Clone source but excludes source data.
  18699. */
  18700. function cloneSourceShallow(source) {
  18701. return new SourceImpl({
  18702. data: source.data,
  18703. sourceFormat: source.sourceFormat,
  18704. seriesLayoutBy: source.seriesLayoutBy,
  18705. dimensionsDefine: clone(source.dimensionsDefine),
  18706. startIndex: source.startIndex,
  18707. dimensionsDetectedCount: source.dimensionsDetectedCount
  18708. });
  18709. }
  18710. /**
  18711. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18712. */
  18713. function detectSourceFormat(data) {
  18714. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18715. if (isTypedArray(data)) {
  18716. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18717. } else if (isArray(data)) {
  18718. // FIXME Whether tolerate null in top level array?
  18719. if (data.length === 0) {
  18720. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18721. }
  18722. for (var i = 0, len = data.length; i < len; i++) {
  18723. var item = data[i];
  18724. if (item == null) {
  18725. continue;
  18726. } else if (isArray(item)) {
  18727. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18728. break;
  18729. } else if (isObject(item)) {
  18730. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18731. break;
  18732. }
  18733. }
  18734. } else if (isObject(data)) {
  18735. for (var key in data) {
  18736. if (hasOwn(data, key) && isArrayLike(data[key])) {
  18737. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18738. break;
  18739. }
  18740. }
  18741. }
  18742. return sourceFormat;
  18743. }
  18744. /**
  18745. * Determine the source definitions from data standalone dimensions definitions
  18746. * are not specified.
  18747. */
  18748. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  18749. // {
  18750. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  18751. // }
  18752. // in `dataset` or `series`
  18753. dimensionsDefine) {
  18754. var dimensionsDetectedCount;
  18755. var startIndex; // PEDING: could data be null/undefined here?
  18756. // currently, if `dataset.source` not specified, error thrown.
  18757. // if `series.data` not specified, nothing rendered without error thrown.
  18758. // Should test these cases.
  18759. if (!data) {
  18760. return {
  18761. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18762. startIndex: startIndex,
  18763. dimensionsDetectedCount: dimensionsDetectedCount
  18764. };
  18765. }
  18766. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18767. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  18768. // Caution: consider a line with 5 string and 1 number,
  18769. // it still can not be sure it is a head, because the
  18770. // 5 string may be 5 values of category columns.
  18771. if (sourceHeader === 'auto' || sourceHeader == null) {
  18772. arrayRowsTravelFirst(function (val) {
  18773. // '-' is regarded as null/undefined.
  18774. if (val != null && val !== '-') {
  18775. if (isString(val)) {
  18776. startIndex == null && (startIndex = 1);
  18777. } else {
  18778. startIndex = 0;
  18779. }
  18780. } // 10 is an experience number, avoid long loop.
  18781. }, seriesLayoutBy, dataArrayRows, 10);
  18782. } else {
  18783. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  18784. }
  18785. if (!dimensionsDefine && startIndex === 1) {
  18786. dimensionsDefine = [];
  18787. arrayRowsTravelFirst(function (val, index) {
  18788. dimensionsDefine[index] = val != null ? val + '' : '';
  18789. }, seriesLayoutBy, dataArrayRows, Infinity);
  18790. }
  18791. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  18792. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18793. if (!dimensionsDefine) {
  18794. dimensionsDefine = objectRowsCollectDimensions(data);
  18795. }
  18796. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18797. if (!dimensionsDefine) {
  18798. dimensionsDefine = [];
  18799. each(data, function (colArr, key) {
  18800. dimensionsDefine.push(key);
  18801. });
  18802. }
  18803. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18804. var value0 = getDataItemValue(data[0]);
  18805. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  18806. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18807. if ("development" !== 'production') {
  18808. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18809. }
  18810. }
  18811. return {
  18812. startIndex: startIndex,
  18813. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18814. dimensionsDetectedCount: dimensionsDetectedCount
  18815. };
  18816. }
  18817. function objectRowsCollectDimensions(data) {
  18818. var firstIndex = 0;
  18819. var obj;
  18820. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18821. if (obj) {
  18822. var dimensions_1 = [];
  18823. each(obj, function (value, key) {
  18824. dimensions_1.push(key);
  18825. });
  18826. return dimensions_1;
  18827. }
  18828. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18829. // which is reasonable. But dimension name is duplicated.
  18830. // Returns undefined or an array contains only object without null/undefiend or string.
  18831. function normalizeDimensionsOption(dimensionsDefine) {
  18832. if (!dimensionsDefine) {
  18833. // The meaning of null/undefined is different from empty array.
  18834. return;
  18835. }
  18836. var nameMap = createHashMap();
  18837. return map(dimensionsDefine, function (rawItem, index) {
  18838. rawItem = isObject(rawItem) ? rawItem : {
  18839. name: rawItem
  18840. }; // Other fields will be discarded.
  18841. var item = {
  18842. name: rawItem.name,
  18843. displayName: rawItem.displayName,
  18844. type: rawItem.type
  18845. }; // User can set null in dimensions.
  18846. // We dont auto specify name, othewise a given name may
  18847. // cause it be refered unexpectedly.
  18848. if (item.name == null) {
  18849. return item;
  18850. } // Also consider number form like 2012.
  18851. item.name += ''; // User may also specify displayName.
  18852. // displayName will always exists except user not
  18853. // specified or dim name is not specified or detected.
  18854. // (A auto generated dim name will not be used as
  18855. // displayName).
  18856. if (item.displayName == null) {
  18857. item.displayName = item.name;
  18858. }
  18859. var exist = nameMap.get(item.name);
  18860. if (!exist) {
  18861. nameMap.set(item.name, {
  18862. count: 1
  18863. });
  18864. } else {
  18865. item.name += '-' + exist.count++;
  18866. }
  18867. return item;
  18868. });
  18869. }
  18870. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18871. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18872. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18873. cb(data[i] ? data[i][0] : null, i);
  18874. }
  18875. } else {
  18876. var value0 = data[0] || [];
  18877. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18878. cb(value0[i], i);
  18879. }
  18880. }
  18881. }
  18882. function shouldRetrieveDataByName(source) {
  18883. var sourceFormat = source.sourceFormat;
  18884. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  18885. }
  18886. /*
  18887. * Licensed to the Apache Software Foundation (ASF) under one
  18888. * or more contributor license agreements. See the NOTICE file
  18889. * distributed with this work for additional information
  18890. * regarding copyright ownership. The ASF licenses this file
  18891. * to you under the Apache License, Version 2.0 (the
  18892. * "License"); you may not use this file except in compliance
  18893. * with the License. You may obtain a copy of the License at
  18894. *
  18895. * http://www.apache.org/licenses/LICENSE-2.0
  18896. *
  18897. * Unless required by applicable law or agreed to in writing,
  18898. * software distributed under the License is distributed on an
  18899. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18900. * KIND, either express or implied. See the License for the
  18901. * specific language governing permissions and limitations
  18902. * under the License.
  18903. */
  18904. /**
  18905. * AUTO-GENERATED FILE. DO NOT MODIFY.
  18906. */
  18907. /*
  18908. * Licensed to the Apache Software Foundation (ASF) under one
  18909. * or more contributor license agreements. See the NOTICE file
  18910. * distributed with this work for additional information
  18911. * regarding copyright ownership. The ASF licenses this file
  18912. * to you under the Apache License, Version 2.0 (the
  18913. * "License"); you may not use this file except in compliance
  18914. * with the License. You may obtain a copy of the License at
  18915. *
  18916. * http://www.apache.org/licenses/LICENSE-2.0
  18917. *
  18918. * Unless required by applicable law or agreed to in writing,
  18919. * software distributed under the License is distributed on an
  18920. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18921. * KIND, either express or implied. See the License for the
  18922. * specific language governing permissions and limitations
  18923. * under the License.
  18924. */
  18925. var _a, _b, _c; // TODO
  18926. var providerMethods;
  18927. var mountMethods;
  18928. /**
  18929. * If normal array used, mutable chunk size is supported.
  18930. * If typed array used, chunk size must be fixed.
  18931. */
  18932. var DefaultDataProvider =
  18933. /** @class */
  18934. function () {
  18935. function DefaultDataProvider(sourceParam, dimSize) {
  18936. // let source: Source;
  18937. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  18938. this._source = source;
  18939. var data = this._data = source.data; // Typed array. TODO IE10+?
  18940. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18941. if ("development" !== 'production') {
  18942. if (dimSize == null) {
  18943. throw new Error('Typed array data must specify dimension size');
  18944. }
  18945. }
  18946. this._offset = 0;
  18947. this._dimSize = dimSize;
  18948. this._data = data;
  18949. }
  18950. mountMethods(this, data, source);
  18951. }
  18952. DefaultDataProvider.prototype.getSource = function () {
  18953. return this._source;
  18954. };
  18955. DefaultDataProvider.prototype.count = function () {
  18956. return 0;
  18957. };
  18958. DefaultDataProvider.prototype.getItem = function (idx, out) {
  18959. return;
  18960. };
  18961. DefaultDataProvider.prototype.appendData = function (newData) {};
  18962. DefaultDataProvider.prototype.clean = function () {};
  18963. DefaultDataProvider.protoInitialize = function () {
  18964. // PENDING: To avoid potential incompat (e.g., prototype
  18965. // is visited somewhere), still init them on prototype.
  18966. var proto = DefaultDataProvider.prototype;
  18967. proto.pure = false;
  18968. proto.persistent = true;
  18969. }();
  18970. DefaultDataProvider.internalField = function () {
  18971. var _a;
  18972. mountMethods = function (provider, data, source) {
  18973. var sourceFormat = source.sourceFormat;
  18974. var seriesLayoutBy = source.seriesLayoutBy;
  18975. var startIndex = source.startIndex;
  18976. var dimsDef = source.dimensionsDefine;
  18977. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18978. if ("development" !== 'production') {
  18979. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18980. }
  18981. extend(provider, methods);
  18982. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18983. provider.getItem = getItemForTypedArray;
  18984. provider.count = countForTypedArray;
  18985. provider.fillStorage = fillStorageForTypedArray;
  18986. } else {
  18987. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  18988. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  18989. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  18990. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  18991. }
  18992. };
  18993. var getItemForTypedArray = function (idx, out) {
  18994. idx = idx - this._offset;
  18995. out = out || [];
  18996. var data = this._data;
  18997. var dimSize = this._dimSize;
  18998. var offset = dimSize * idx;
  18999. for (var i = 0; i < dimSize; i++) {
  19000. out[i] = data[offset + i];
  19001. }
  19002. return out;
  19003. };
  19004. var fillStorageForTypedArray = function (start, end, storage, extent) {
  19005. var data = this._data;
  19006. var dimSize = this._dimSize;
  19007. for (var dim = 0; dim < dimSize; dim++) {
  19008. var dimExtent = extent[dim];
  19009. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  19010. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  19011. var count = end - start;
  19012. var arr = storage[dim];
  19013. for (var i = 0; i < count; i++) {
  19014. // appendData with TypedArray will always do replace in provider.
  19015. var val = data[i * dimSize + dim];
  19016. arr[start + i] = val;
  19017. val < min && (min = val);
  19018. val > max && (max = val);
  19019. }
  19020. dimExtent[0] = min;
  19021. dimExtent[1] = max;
  19022. }
  19023. };
  19024. var countForTypedArray = function () {
  19025. return this._data ? this._data.length / this._dimSize : 0;
  19026. };
  19027. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  19028. pure: true,
  19029. appendData: appendDataSimply
  19030. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  19031. pure: true,
  19032. appendData: function () {
  19033. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19034. }
  19035. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  19036. pure: true,
  19037. appendData: appendDataSimply
  19038. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  19039. pure: true,
  19040. appendData: function (newData) {
  19041. var data = this._data;
  19042. each(newData, function (newCol, key) {
  19043. var oldCol = data[key] || (data[key] = []);
  19044. for (var i = 0; i < (newCol || []).length; i++) {
  19045. oldCol.push(newCol[i]);
  19046. }
  19047. });
  19048. }
  19049. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  19050. appendData: appendDataSimply
  19051. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  19052. persistent: false,
  19053. pure: true,
  19054. appendData: function (newData) {
  19055. if ("development" !== 'production') {
  19056. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  19057. }
  19058. this._data = newData;
  19059. },
  19060. // Clean self if data is already used.
  19061. clean: function () {
  19062. // PENDING
  19063. this._offset += this.count();
  19064. this._data = null;
  19065. }
  19066. }, _a);
  19067. function appendDataSimply(newData) {
  19068. for (var i = 0; i < newData.length; i++) {
  19069. this._data.push(newData[i]);
  19070. }
  19071. }
  19072. }();
  19073. return DefaultDataProvider;
  19074. }();
  19075. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  19076. return rawData[idx];
  19077. };
  19078. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  19079. return rawData[idx + startIndex];
  19080. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  19081. idx += startIndex;
  19082. var item = out || [];
  19083. var data = rawData;
  19084. for (var i = 0; i < data.length; i++) {
  19085. var row = data[i];
  19086. item[i] = row ? row[idx] : null;
  19087. }
  19088. return item;
  19089. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  19090. var item = out || [];
  19091. for (var i = 0; i < dimsDef.length; i++) {
  19092. var dimName = dimsDef[i].name;
  19093. if ("development" !== 'production') {
  19094. if (dimName == null) {
  19095. throw new Error();
  19096. }
  19097. }
  19098. var col = rawData[dimName];
  19099. item[i] = col ? col[idx] : null;
  19100. }
  19101. return item;
  19102. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  19103. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  19104. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19105. if ("development" !== 'production') {
  19106. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19107. }
  19108. return method;
  19109. }
  19110. var countSimply = function (rawData, startIndex, dimsDef) {
  19111. return rawData.length;
  19112. };
  19113. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  19114. return Math.max(0, rawData.length - startIndex);
  19115. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  19116. var row = rawData[0];
  19117. return row ? Math.max(0, row.length - startIndex) : 0;
  19118. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  19119. var dimName = dimsDef[0].name;
  19120. if ("development" !== 'production') {
  19121. if (dimName == null) {
  19122. throw new Error();
  19123. }
  19124. }
  19125. var col = rawData[dimName];
  19126. return col ? col.length : 0;
  19127. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  19128. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  19129. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19130. if ("development" !== 'production') {
  19131. assert(method, 'Do not suppport count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19132. }
  19133. return method;
  19134. }
  19135. var getRawValueSimply = function (dataItem, dimIndex, property) {
  19136. return dataItem[dimIndex];
  19137. };
  19138. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  19139. return dataItem[property];
  19140. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  19141. // FIXME: In some case (markpoint in geo (geo-map.html)),
  19142. // dataItem is {coord: [...]}
  19143. var value = getDataItemValue(dataItem);
  19144. return !(value instanceof Array) ? value : value[dimIndex];
  19145. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  19146. function getRawSourceValueGetter(sourceFormat) {
  19147. var method = rawSourceValueGetterMap[sourceFormat];
  19148. if ("development" !== 'production') {
  19149. assert(method, 'Do not suppport get value on "' + sourceFormat + '".');
  19150. }
  19151. return method;
  19152. }
  19153. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  19154. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  19155. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19156. // Consider persistent.
  19157. // Caution: why use raw value to display on label or tooltip?
  19158. // A reason is to avoid format. For example time value we do not know
  19159. // how to format is expected. More over, if stack is used, calculated
  19160. // value may be 0.91000000001, which have brings trouble to display.
  19161. // TODO: consider how to treat null/undefined/NaN when display?
  19162. function retrieveRawValue(data, dataIndex, // If dimIndex is null/undefined, return OptionDataItem.
  19163. // Otherwise, return OptionDataValue.
  19164. dim) {
  19165. if (!data) {
  19166. return;
  19167. } // Consider data may be not persistent.
  19168. var dataItem = data.getRawDataItem(dataIndex);
  19169. if (dataItem == null) {
  19170. return;
  19171. }
  19172. var store = data.getStore();
  19173. var sourceFormat = store.getSource().sourceFormat;
  19174. if (dim != null) {
  19175. var dimIndex = data.getDimensionIndex(dim);
  19176. var property = store.getDimensionProperty(dimIndex);
  19177. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  19178. } else {
  19179. var result = dataItem;
  19180. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19181. result = getDataItemValue(dataItem);
  19182. }
  19183. return result;
  19184. }
  19185. }
  19186. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19187. var DataFormatMixin =
  19188. /** @class */
  19189. function () {
  19190. function DataFormatMixin() {}
  19191. /**
  19192. * Get params for formatter
  19193. */
  19194. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  19195. var data = this.getData(dataType);
  19196. var rawValue = this.getRawValue(dataIndex, dataType);
  19197. var rawDataIndex = data.getRawIndex(dataIndex);
  19198. var name = data.getName(dataIndex);
  19199. var itemOpt = data.getRawDataItem(dataIndex);
  19200. var style = data.getItemVisual(dataIndex, 'style');
  19201. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  19202. var borderColor = style && style.stroke;
  19203. var mainType = this.mainType;
  19204. var isSeries = mainType === 'series';
  19205. var userOutput = data.userOutput && data.userOutput.get();
  19206. return {
  19207. componentType: mainType,
  19208. componentSubType: this.subType,
  19209. componentIndex: this.componentIndex,
  19210. seriesType: isSeries ? this.subType : null,
  19211. seriesIndex: this.seriesIndex,
  19212. seriesId: isSeries ? this.id : null,
  19213. seriesName: isSeries ? this.name : null,
  19214. name: name,
  19215. dataIndex: rawDataIndex,
  19216. data: itemOpt,
  19217. dataType: dataType,
  19218. value: rawValue,
  19219. color: color,
  19220. borderColor: borderColor,
  19221. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  19222. encode: userOutput ? userOutput.encode : null,
  19223. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19224. $vars: ['seriesName', 'name', 'value']
  19225. };
  19226. };
  19227. /**
  19228. * Format label
  19229. * @param dataIndex
  19230. * @param status 'normal' by default
  19231. * @param dataType
  19232. * @param labelDimIndex Only used in some chart that
  19233. * use formatter in different dimensions, like radar.
  19234. * @param formatter Formatter given outside.
  19235. * @return return null/undefined if no formatter
  19236. */
  19237. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  19238. status = status || 'normal';
  19239. var data = this.getData(dataType);
  19240. var params = this.getDataParams(dataIndex, dataType);
  19241. if (extendParams) {
  19242. params.value = extendParams.interpolatedValue;
  19243. }
  19244. if (labelDimIndex != null && isArray(params.value)) {
  19245. params.value = params.value[labelDimIndex];
  19246. }
  19247. if (!formatter) {
  19248. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  19249. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  19250. }
  19251. if (typeof formatter === 'function') {
  19252. params.status = status;
  19253. params.dimensionIndex = labelDimIndex;
  19254. return formatter(params);
  19255. } else if (typeof formatter === 'string') {
  19256. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  19257. // Do not support '}' in dim name util have to.
  19258. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  19259. var len = dimStr.length;
  19260. var dimLoose = dimStr;
  19261. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  19262. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  19263. if ("development" !== 'production') {
  19264. if (isNaN(dimLoose)) {
  19265. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  19266. }
  19267. }
  19268. }
  19269. var val = retrieveRawValue(data, dataIndex, dimLoose);
  19270. if (extendParams && isArray(extendParams.interpolatedValue)) {
  19271. var dimIndex = data.getDimensionIndex(dimLoose);
  19272. if (dimIndex >= 0) {
  19273. val = extendParams.interpolatedValue[dimIndex];
  19274. }
  19275. }
  19276. return val != null ? val + '' : '';
  19277. });
  19278. }
  19279. };
  19280. /**
  19281. * Get raw value in option
  19282. */
  19283. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  19284. return retrieveRawValue(this.getData(dataType), idx);
  19285. };
  19286. /**
  19287. * Should be implemented.
  19288. * @param {number} dataIndex
  19289. * @param {boolean} [multipleSeries=false]
  19290. * @param {string} [dataType]
  19291. */
  19292. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19293. // Empty function
  19294. return;
  19295. };
  19296. return DataFormatMixin;
  19297. }();
  19298. // but guess little chance has been used outside. Do we need to backward
  19299. // compat it?
  19300. // type TooltipFormatResultLegacyObject = {
  19301. // // `html` means the markup language text, either in 'html' or 'richText'.
  19302. // // The name `html` is not appropriate becuase in 'richText' it is not a HTML
  19303. // // string. But still support it for backward compat.
  19304. // html: string;
  19305. // markers: Dictionary<ColorString>;
  19306. // };
  19307. /**
  19308. * For backward compat, normalize the return from `formatTooltip`.
  19309. */
  19310. function normalizeTooltipFormatResult(result // markersExisting: Dictionary<ColorString>
  19311. ) {
  19312. var markupText; // let markers: Dictionary<ColorString>;
  19313. var markupFragment;
  19314. if (isObject(result)) {
  19315. if (result.type) {
  19316. markupFragment = result;
  19317. } else {
  19318. if ("development" !== 'production') {
  19319. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  19320. }
  19321. } // else {
  19322. // markupText = (result as TooltipFormatResultLegacyObject).html;
  19323. // markers = (result as TooltipFormatResultLegacyObject).markers;
  19324. // if (markersExisting) {
  19325. // markers = zrUtil.merge(markersExisting, markers);
  19326. // }
  19327. // }
  19328. } else {
  19329. markupText = result;
  19330. }
  19331. return {
  19332. markupText: markupText,
  19333. // markers: markers || markersExisting,
  19334. markupFragment: markupFragment
  19335. };
  19336. }
  19337. /**
  19338. * @param {Object} define
  19339. * @return See the return of `createTask`.
  19340. */
  19341. function createTask(define) {
  19342. return new Task(define);
  19343. }
  19344. var Task =
  19345. /** @class */
  19346. function () {
  19347. function Task(define) {
  19348. define = define || {};
  19349. this._reset = define.reset;
  19350. this._plan = define.plan;
  19351. this._count = define.count;
  19352. this._onDirty = define.onDirty;
  19353. this._dirty = true;
  19354. }
  19355. /**
  19356. * @param step Specified step.
  19357. * @param skip Skip customer perform call.
  19358. * @param modBy Sampling window size.
  19359. * @param modDataCount Sampling count.
  19360. * @return whether unfinished.
  19361. */
  19362. Task.prototype.perform = function (performArgs) {
  19363. var upTask = this._upstream;
  19364. var skip = performArgs && performArgs.skip; // TODO some refactor.
  19365. // Pull data. Must pull data each time, because context.data
  19366. // may be updated by Series.setData.
  19367. if (this._dirty && upTask) {
  19368. var context = this.context;
  19369. context.data = context.outputData = upTask.context.outputData;
  19370. }
  19371. if (this.__pipeline) {
  19372. this.__pipeline.currentTask = this;
  19373. }
  19374. var planResult;
  19375. if (this._plan && !skip) {
  19376. planResult = this._plan(this.context);
  19377. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19378. // elements uniformed distributed when progress, especially when moving or zooming.
  19379. var lastModBy = normalizeModBy(this._modBy);
  19380. var lastModDataCount = this._modDataCount || 0;
  19381. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19382. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19383. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19384. planResult = 'reset';
  19385. }
  19386. function normalizeModBy(val) {
  19387. !(val >= 1) && (val = 1); // jshint ignore:line
  19388. return val;
  19389. }
  19390. var forceFirstProgress;
  19391. if (this._dirty || planResult === 'reset') {
  19392. this._dirty = false;
  19393. forceFirstProgress = this._doReset(skip);
  19394. }
  19395. this._modBy = modBy;
  19396. this._modDataCount = modDataCount;
  19397. var step = performArgs && performArgs.step;
  19398. if (upTask) {
  19399. if ("development" !== 'production') {
  19400. assert(upTask._outputDueEnd != null);
  19401. }
  19402. this._dueEnd = upTask._outputDueEnd;
  19403. } // DataTask or overallTask
  19404. else {
  19405. if ("development" !== 'production') {
  19406. assert(!this._progress || this._count);
  19407. }
  19408. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19409. } // Note: Stubs, that its host overall task let it has progress, has progress.
  19410. // If no progress, pass index from upstream to downstream each time plan called.
  19411. if (this._progress) {
  19412. var start = this._dueIndex;
  19413. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19414. if (!skip && (forceFirstProgress || start < end)) {
  19415. var progress = this._progress;
  19416. if (isArray(progress)) {
  19417. for (var i = 0; i < progress.length; i++) {
  19418. this._doProgress(progress[i], start, end, modBy, modDataCount);
  19419. }
  19420. } else {
  19421. this._doProgress(progress, start, end, modBy, modDataCount);
  19422. }
  19423. }
  19424. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  19425. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19426. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19427. if ("development" !== 'production') {
  19428. // ??? Can not rollback.
  19429. assert(outputDueEnd >= this._outputDueEnd);
  19430. }
  19431. this._outputDueEnd = outputDueEnd;
  19432. } else {
  19433. // (1) Some overall task has no progress.
  19434. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19435. // This should always be performed so it can be passed to downstream.
  19436. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19437. }
  19438. return this.unfinished();
  19439. };
  19440. Task.prototype.dirty = function () {
  19441. this._dirty = true;
  19442. this._onDirty && this._onDirty(this.context);
  19443. };
  19444. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19445. iterator.reset(start, end, modBy, modDataCount);
  19446. this._callingProgress = progress;
  19447. this._callingProgress({
  19448. start: start,
  19449. end: end,
  19450. count: end - start,
  19451. next: iterator.next
  19452. }, this.context);
  19453. };
  19454. Task.prototype._doReset = function (skip) {
  19455. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19456. this._settedOutputEnd = null;
  19457. var progress;
  19458. var forceFirstProgress;
  19459. if (!skip && this._reset) {
  19460. progress = this._reset(this.context);
  19461. if (progress && progress.progress) {
  19462. forceFirstProgress = progress.forceFirstProgress;
  19463. progress = progress.progress;
  19464. } // To simplify no progress checking, array must has item.
  19465. if (isArray(progress) && !progress.length) {
  19466. progress = null;
  19467. }
  19468. }
  19469. this._progress = progress;
  19470. this._modBy = this._modDataCount = null;
  19471. var downstream = this._downstream;
  19472. downstream && downstream.dirty();
  19473. return forceFirstProgress;
  19474. };
  19475. Task.prototype.unfinished = function () {
  19476. return this._progress && this._dueIndex < this._dueEnd;
  19477. };
  19478. /**
  19479. * @param downTask The downstream task.
  19480. * @return The downstream task.
  19481. */
  19482. Task.prototype.pipe = function (downTask) {
  19483. if ("development" !== 'production') {
  19484. assert(downTask && !downTask._disposed && downTask !== this);
  19485. } // If already downstream, do not dirty downTask.
  19486. if (this._downstream !== downTask || this._dirty) {
  19487. this._downstream = downTask;
  19488. downTask._upstream = this;
  19489. downTask.dirty();
  19490. }
  19491. };
  19492. Task.prototype.dispose = function () {
  19493. if (this._disposed) {
  19494. return;
  19495. }
  19496. this._upstream && (this._upstream._downstream = null);
  19497. this._downstream && (this._downstream._upstream = null);
  19498. this._dirty = false;
  19499. this._disposed = true;
  19500. };
  19501. Task.prototype.getUpstream = function () {
  19502. return this._upstream;
  19503. };
  19504. Task.prototype.getDownstream = function () {
  19505. return this._downstream;
  19506. };
  19507. Task.prototype.setOutputEnd = function (end) {
  19508. // This only happend in dataTask, dataZoom, map, currently.
  19509. // where dataZoom do not set end each time, but only set
  19510. // when reset. So we should record the setted end, in case
  19511. // that the stub of dataZoom perform again and earse the
  19512. // setted end by upstream.
  19513. this._outputDueEnd = this._settedOutputEnd = end;
  19514. };
  19515. return Task;
  19516. }();
  19517. var iterator = function () {
  19518. var end;
  19519. var current;
  19520. var modBy;
  19521. var modDataCount;
  19522. var winCount;
  19523. var it = {
  19524. reset: function (s, e, sStep, sCount) {
  19525. current = s;
  19526. end = e;
  19527. modBy = sStep;
  19528. modDataCount = sCount;
  19529. winCount = Math.ceil(modDataCount / modBy);
  19530. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19531. }
  19532. };
  19533. return it;
  19534. function sequentialNext() {
  19535. return current < end ? current++ : null;
  19536. }
  19537. function modNext() {
  19538. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19539. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19540. // Use normal linear rendering mode.
  19541. : current;
  19542. current++;
  19543. return result;
  19544. }
  19545. }(); ///////////////////////////////////////////////////////////
  19546. // For stream debug (Should be commented out after used!)
  19547. // @usage: printTask(this, 'begin');
  19548. // @usage: printTask(this, null, {someExtraProp});
  19549. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19550. //
  19551. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19552. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19553. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19554. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19555. // let props = [];
  19556. // if (task.__pipeline) {
  19557. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19558. // props.push({text: '__idxInPipeline/total', value: val});
  19559. // } else {
  19560. // let stubCount = 0;
  19561. // task.agentStubMap.each(() => stubCount++);
  19562. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19563. // }
  19564. // props.push({text: 'uid', value: task.uidDebug});
  19565. // if (task.__pipeline) {
  19566. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19567. // task.agent && props.push(
  19568. // {text: 'stubFor', value: task.agent.uidDebug}
  19569. // );
  19570. // }
  19571. // props.push(
  19572. // {text: 'dirty', value: task._dirty},
  19573. // {text: 'dueIndex', value: task._dueIndex},
  19574. // {text: 'dueEnd', value: task._dueEnd},
  19575. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19576. // );
  19577. // if (extra) {
  19578. // Object.keys(extra).forEach(key => {
  19579. // props.push({text: key, value: extra[key]});
  19580. // });
  19581. // }
  19582. // let args = ['color: blue'];
  19583. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19584. // args.push('color: green', 'color: red'),
  19585. // `${item.text}: %c${item.value}`
  19586. // )).join('%c, ');
  19587. // console.log.apply(console, [msg].concat(args));
  19588. // // console.log(this);
  19589. // };
  19590. // window.printPipeline = function (task: any, prefix: string) {
  19591. // const pipeline = task.__pipeline;
  19592. // let currTask = pipeline.head;
  19593. // while (currTask) {
  19594. // window.printTask(currTask, prefix);
  19595. // currTask = currTask._downstream;
  19596. // }
  19597. // };
  19598. // window.showChain = function (chainHeadTask) {
  19599. // var chain = [];
  19600. // var task = chainHeadTask;
  19601. // while (task) {
  19602. // chain.push({
  19603. // task: task,
  19604. // up: task._upstream,
  19605. // down: task._downstream,
  19606. // idxInPipeline: task.__idxInPipeline
  19607. // });
  19608. // task = task._downstream;
  19609. // }
  19610. // return chain;
  19611. // };
  19612. // window.findTaskInChain = function (task, chainHeadTask) {
  19613. // let chain = window.showChain(chainHeadTask);
  19614. // let result = [];
  19615. // for (let i = 0; i < chain.length; i++) {
  19616. // let chainItem = chain[i];
  19617. // if (chainItem.task === task) {
  19618. // result.push(i);
  19619. // }
  19620. // }
  19621. // return result;
  19622. // };
  19623. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19624. // let chainA = window.showChain(chainHeadTaskA);
  19625. // for (let i = 0; i < chainA.length; i++) {
  19626. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19627. // }
  19628. // };
  19629. /**
  19630. * Convert raw the value in to inner value in List.
  19631. *
  19632. * [Performance sensitive]
  19633. *
  19634. * [Caution]: this is the key logic of user value parser.
  19635. * For backward compatibiliy, do not modify it until have to!
  19636. */
  19637. function parseDataValue(value, // For high performance, do not omit the second param.
  19638. opt) {
  19639. // Performance sensitive.
  19640. var dimType = opt && opt.type;
  19641. if (dimType === 'ordinal') {
  19642. // If given value is a category string
  19643. return value;
  19644. }
  19645. if (dimType === 'time' // spead up when using timestamp
  19646. && typeof value !== 'number' && value != null && value !== '-') {
  19647. value = +parseDate(value);
  19648. } // dimType defaults 'number'.
  19649. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19650. // parse to NaN.
  19651. // number-like string (like ' 123 ') can be converted to a number.
  19652. // where null/undefined or other string will be converted to NaN.
  19653. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19654. // If object, also parse to NaN
  19655. : +value;
  19656. }
  19657. var valueParserMap = createHashMap({
  19658. 'number': function (val) {
  19659. // Do not use `numericToNumber` here. We have by defualt `numericToNumber`.
  19660. // Here the number parser can have loose rule:
  19661. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19662. return parseFloat(val);
  19663. },
  19664. 'time': function (val) {
  19665. // return timestamp.
  19666. return +parseDate(val);
  19667. },
  19668. 'trim': function (val) {
  19669. return typeof val === 'string' ? trim(val) : val;
  19670. }
  19671. });
  19672. function getRawValueParser(type) {
  19673. return valueParserMap.get(type);
  19674. }
  19675. var ORDER_COMPARISON_OP_MAP = {
  19676. lt: function (lval, rval) {
  19677. return lval < rval;
  19678. },
  19679. lte: function (lval, rval) {
  19680. return lval <= rval;
  19681. },
  19682. gt: function (lval, rval) {
  19683. return lval > rval;
  19684. },
  19685. gte: function (lval, rval) {
  19686. return lval >= rval;
  19687. }
  19688. };
  19689. var FilterOrderComparator =
  19690. /** @class */
  19691. function () {
  19692. function FilterOrderComparator(op, rval) {
  19693. if (typeof rval !== 'number') {
  19694. var errMsg = '';
  19695. if ("development" !== 'production') {
  19696. errMsg = 'rvalue of "<", ">", "<=", ">=" can only be number in filter.';
  19697. }
  19698. throwError(errMsg);
  19699. }
  19700. this._opFn = ORDER_COMPARISON_OP_MAP[op];
  19701. this._rvalFloat = numericToNumber(rval);
  19702. } // Performance sensitive.
  19703. FilterOrderComparator.prototype.evaluate = function (lval) {
  19704. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19705. return typeof lval === 'number' ? this._opFn(lval, this._rvalFloat) : this._opFn(numericToNumber(lval), this._rvalFloat);
  19706. };
  19707. return FilterOrderComparator;
  19708. }();
  19709. var SortOrderComparator =
  19710. /** @class */
  19711. function () {
  19712. /**
  19713. * @param order by defualt: 'asc'
  19714. * @param incomparable by defualt: Always on the tail.
  19715. * That is, if 'asc' => 'max', if 'desc' => 'min'
  19716. * See the definition of "incomparable" in [SORT_COMPARISON_RULE]
  19717. */
  19718. function SortOrderComparator(order, incomparable) {
  19719. var isDesc = order === 'desc';
  19720. this._resultLT = isDesc ? 1 : -1;
  19721. if (incomparable == null) {
  19722. incomparable = isDesc ? 'min' : 'max';
  19723. }
  19724. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  19725. } // See [SORT_COMPARISON_RULE].
  19726. // Performance sensitive.
  19727. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  19728. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19729. var lvalTypeof = typeof lval;
  19730. var rvalTypeof = typeof rval;
  19731. var lvalFloat = lvalTypeof === 'number' ? lval : numericToNumber(lval);
  19732. var rvalFloat = rvalTypeof === 'number' ? rval : numericToNumber(rval);
  19733. var lvalNotNumeric = isNaN(lvalFloat);
  19734. var rvalNotNumeric = isNaN(rvalFloat);
  19735. if (lvalNotNumeric) {
  19736. lvalFloat = this._incomparable;
  19737. }
  19738. if (rvalNotNumeric) {
  19739. rvalFloat = this._incomparable;
  19740. }
  19741. if (lvalNotNumeric && rvalNotNumeric) {
  19742. var lvalIsStr = lvalTypeof === 'string';
  19743. var rvalIsStr = rvalTypeof === 'string';
  19744. if (lvalIsStr) {
  19745. lvalFloat = rvalIsStr ? lval : 0;
  19746. }
  19747. if (rvalIsStr) {
  19748. rvalFloat = lvalIsStr ? rval : 0;
  19749. }
  19750. }
  19751. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  19752. };
  19753. return SortOrderComparator;
  19754. }();
  19755. var FilterEqualityComparator =
  19756. /** @class */
  19757. function () {
  19758. function FilterEqualityComparator(isEq, rval) {
  19759. this._rval = rval;
  19760. this._isEQ = isEq;
  19761. this._rvalTypeof = typeof rval;
  19762. this._rvalFloat = numericToNumber(rval);
  19763. } // Performance sensitive.
  19764. FilterEqualityComparator.prototype.evaluate = function (lval) {
  19765. var eqResult = lval === this._rval;
  19766. if (!eqResult) {
  19767. var lvalTypeof = typeof lval;
  19768. if (lvalTypeof !== this._rvalTypeof && (lvalTypeof === 'number' || this._rvalTypeof === 'number')) {
  19769. eqResult = numericToNumber(lval) === this._rvalFloat;
  19770. }
  19771. }
  19772. return this._isEQ ? eqResult : !eqResult;
  19773. };
  19774. return FilterEqualityComparator;
  19775. }();
  19776. /**
  19777. * [FILTER_COMPARISON_RULE]
  19778. * `lt`|`lte`|`gt`|`gte`:
  19779. * + rval must be a number. And lval will be converted to number (`numericToNumber`) to compare.
  19780. * `eq`:
  19781. * + If same type, compare with `===`.
  19782. * + If there is one number, convert to number (`numericToNumber`) to compare.
  19783. * + Else return `false`.
  19784. * `ne`:
  19785. * + Not `eq`.
  19786. *
  19787. *
  19788. * [SORT_COMPARISON_RULE]
  19789. * All the values are grouped into three categories:
  19790. * + "numeric" (number and numeric string)
  19791. * + "non-numeric-string" (string that excluding numeric string)
  19792. * + "others"
  19793. * "numeric" vs "numeric": values are ordered by number order.
  19794. * "non-numeric-string" vs "non-numeric-string": values are ordered by ES spec (#sec-abstract-relational-comparison).
  19795. * "others" vs "others": do not change order (always return 0).
  19796. * "numeric" vs "non-numeric-string": "non-numeric-string" is treated as "incomparable".
  19797. * "number" vs "others": "others" is treated as "incomparable".
  19798. * "non-numeric-string" vs "others": "others" is treated as "incomparable".
  19799. * "incomparable" will be seen as -Infinity or Infinity (depends on the settings).
  19800. * MEMO:
  19801. * non-numeric string sort make sence when need to put the items with the same tag together.
  19802. * But if we support string sort, we still need to avoid the misleading like `'2' > '12'`,
  19803. * So we treat "numeric-string" sorted by number order rather than string comparison.
  19804. *
  19805. *
  19806. * [CHECK_LIST_OF_THE_RULE_DESIGN]
  19807. * + Do not support string comparison until required. And also need to
  19808. * void the misleading of "2" > "12".
  19809. * + Should avoid the misleading case:
  19810. * `" 22 " gte "22"` is `true` but `" 22 " eq "22"` is `false`.
  19811. * + JS bad case should be avoided: null <= 0, [] <= 0, ' ' <= 0, ...
  19812. * + Only "numeric" can be converted to comparable number, otherwise converted to NaN.
  19813. * See `util/number.ts#numericToNumber`.
  19814. *
  19815. * @return If `op` is not `RelationalOperator`, return null;
  19816. */
  19817. function createFilterComparator(op, rval) {
  19818. return op === 'eq' || op === 'ne' ? new FilterEqualityComparator(op === 'eq', rval) : hasOwn(ORDER_COMPARISON_OP_MAP, op) ? new FilterOrderComparator(op, rval) : null;
  19819. }
  19820. /**
  19821. * TODO: disable writable.
  19822. * This structure will be exposed to users.
  19823. */
  19824. var ExternalSource =
  19825. /** @class */
  19826. function () {
  19827. function ExternalSource() {}
  19828. ExternalSource.prototype.getRawData = function () {
  19829. // Only built-in transform available.
  19830. throw new Error('not supported');
  19831. };
  19832. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  19833. // Only built-in transform available.
  19834. throw new Error('not supported');
  19835. };
  19836. ExternalSource.prototype.cloneRawData = function () {
  19837. return;
  19838. };
  19839. /**
  19840. * @return If dimension not found, return null/undefined.
  19841. */
  19842. ExternalSource.prototype.getDimensionInfo = function (dim) {
  19843. return;
  19844. };
  19845. /**
  19846. * dimensions defined if and only if either:
  19847. * (a) dataset.dimensions are declared.
  19848. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  19849. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  19850. * the defined dimensions.
  19851. * Otherwise, `dimensionInfoAll` is determined by data columns.
  19852. * @return Always return an array (even empty array).
  19853. */
  19854. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  19855. return;
  19856. };
  19857. ExternalSource.prototype.count = function () {
  19858. return;
  19859. };
  19860. /**
  19861. * Only support by dimension index.
  19862. * No need to support by dimension name in transform function,
  19863. * becuase transform function is not case-specific, no need to use name literally.
  19864. */
  19865. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  19866. return;
  19867. };
  19868. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  19869. return;
  19870. };
  19871. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  19872. return parseDataValue(rawVal, dimInfo);
  19873. };
  19874. return ExternalSource;
  19875. }();
  19876. function createExternalSource(internalSource, externalTransform) {
  19877. var extSource = new ExternalSource();
  19878. var data = internalSource.data;
  19879. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  19880. var sourceHeaderCount = internalSource.startIndex;
  19881. var errMsg = '';
  19882. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  19883. // For the logic simplicity in transformer, only 'culumn' is
  19884. // supported in data transform. Otherwise, the `dimensionsDefine`
  19885. // might be detected by 'row', which probably confuses users.
  19886. if ("development" !== 'production') {
  19887. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  19888. }
  19889. throwError(errMsg);
  19890. } // [MEMO]
  19891. // Create a new dimensions structure for exposing.
  19892. // Do not expose all dimension info to users directly.
  19893. // Becuase the dimension is probably auto detected from data and not might reliable.
  19894. // Should not lead the transformers to think that is relialbe and return it.
  19895. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19896. var dimensions = [];
  19897. var dimsByName = {};
  19898. var dimsDef = internalSource.dimensionsDefine;
  19899. if (dimsDef) {
  19900. each(dimsDef, function (dimDef, idx) {
  19901. var name = dimDef.name;
  19902. var dimDefExt = {
  19903. index: idx,
  19904. name: name,
  19905. displayName: dimDef.displayName
  19906. };
  19907. dimensions.push(dimDefExt); // Users probably not sepcify dimension name. For simplicity, data transform
  19908. // do not generate dimension name.
  19909. if (name != null) {
  19910. // Dimension name should not be duplicated.
  19911. // For simplicity, data transform forbid name duplication, do not generate
  19912. // new name like module `completeDimensions.ts` did, but just tell users.
  19913. var errMsg_1 = '';
  19914. if (hasOwn(dimsByName, name)) {
  19915. if ("development" !== 'production') {
  19916. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  19917. }
  19918. throwError(errMsg_1);
  19919. }
  19920. dimsByName[name] = dimDefExt;
  19921. }
  19922. });
  19923. } // If dimension definitions are not defined and can not be detected.
  19924. // e.g., pure data `[[11, 22], ...]`.
  19925. else {
  19926. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  19927. // Do not generete name or anything others. The consequence process in
  19928. // `transform` or `series` probably have there own name generation strategry.
  19929. dimensions.push({
  19930. index: i
  19931. });
  19932. }
  19933. } // Implement public methods:
  19934. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19935. if (externalTransform.__isBuiltIn) {
  19936. extSource.getRawDataItem = function (dataIndex) {
  19937. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19938. };
  19939. extSource.getRawData = bind(getRawData, null, internalSource);
  19940. }
  19941. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  19942. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19943. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  19944. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  19945. extSource.retrieveValue = function (dataIndex, dimIndex) {
  19946. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19947. return retrieveValueFromItem(rawItem, dimIndex);
  19948. };
  19949. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  19950. if (dataItem == null) {
  19951. return;
  19952. }
  19953. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  19954. if (dimDef) {
  19955. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  19956. }
  19957. };
  19958. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  19959. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  19960. return extSource;
  19961. }
  19962. function getRawData(upstream) {
  19963. var sourceFormat = upstream.sourceFormat;
  19964. if (!isSupportedSourceFormat(sourceFormat)) {
  19965. var errMsg = '';
  19966. if ("development" !== 'production') {
  19967. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  19968. }
  19969. throwError(errMsg);
  19970. }
  19971. return upstream.data;
  19972. }
  19973. function cloneRawData(upstream) {
  19974. var sourceFormat = upstream.sourceFormat;
  19975. var data = upstream.data;
  19976. if (!isSupportedSourceFormat(sourceFormat)) {
  19977. var errMsg = '';
  19978. if ("development" !== 'production') {
  19979. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  19980. }
  19981. throwError(errMsg);
  19982. }
  19983. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19984. var result = [];
  19985. for (var i = 0, len = data.length; i < len; i++) {
  19986. // Not strictly clone for performance
  19987. result.push(data[i].slice());
  19988. }
  19989. return result;
  19990. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19991. var result = [];
  19992. for (var i = 0, len = data.length; i < len; i++) {
  19993. // Not strictly clone for performance
  19994. result.push(extend({}, data[i]));
  19995. }
  19996. return result;
  19997. }
  19998. }
  19999. function getDimensionInfo(dimensions, dimsByName, dim) {
  20000. if (dim == null) {
  20001. return;
  20002. } // Keep the same logic as `List::getDimension` did.
  20003. if (typeof dim === 'number' // If being a number-like string but not being defined a dimension name.
  20004. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  20005. return dimensions[dim];
  20006. } else if (hasOwn(dimsByName, dim)) {
  20007. return dimsByName[dim];
  20008. }
  20009. }
  20010. function cloneAllDimensionInfo(dimensions) {
  20011. return clone(dimensions);
  20012. }
  20013. var externalTransformMap = createHashMap();
  20014. function registerExternalTransform(externalTransform) {
  20015. externalTransform = clone(externalTransform);
  20016. var type = externalTransform.type;
  20017. var errMsg = '';
  20018. if (!type) {
  20019. if ("development" !== 'production') {
  20020. errMsg = 'Must have a `type` when `registerTransform`.';
  20021. }
  20022. throwError(errMsg);
  20023. }
  20024. var typeParsed = type.split(':');
  20025. if (typeParsed.length !== 2) {
  20026. if ("development" !== 'production') {
  20027. errMsg = 'Name must include namespace like "ns:regression".';
  20028. }
  20029. throwError(errMsg);
  20030. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  20031. // be called directly via 'xxx' rather than 'echarts:xxx'.
  20032. var isBuiltIn = false;
  20033. if (typeParsed[0] === 'echarts') {
  20034. type = typeParsed[1];
  20035. isBuiltIn = true;
  20036. }
  20037. externalTransform.__isBuiltIn = isBuiltIn;
  20038. externalTransformMap.set(type, externalTransform);
  20039. }
  20040. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  20041. var pipedTransOption = normalizeToArray(rawTransOption);
  20042. var pipeLen = pipedTransOption.length;
  20043. var errMsg = '';
  20044. if (!pipeLen) {
  20045. if ("development" !== 'production') {
  20046. errMsg = 'If `transform` declared, it should at least contain one transform.';
  20047. }
  20048. throwError(errMsg);
  20049. }
  20050. for (var i = 0, len = pipeLen; i < len; i++) {
  20051. var transOption = pipedTransOption[i];
  20052. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  20053. // piped transform only support single output, except the last one.
  20054. if (i !== len - 1) {
  20055. sourceList.length = Math.max(sourceList.length, 1);
  20056. }
  20057. }
  20058. return sourceList;
  20059. }
  20060. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  20061. pipeIndex) {
  20062. var errMsg = '';
  20063. if (!upSourceList.length) {
  20064. if ("development" !== 'production') {
  20065. errMsg = 'Must have at least one upstream dataset.';
  20066. }
  20067. throwError(errMsg);
  20068. }
  20069. if (!isObject(transOption)) {
  20070. if ("development" !== 'production') {
  20071. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  20072. }
  20073. throwError(errMsg);
  20074. }
  20075. var transType = transOption.type;
  20076. var externalTransform = externalTransformMap.get(transType);
  20077. if (!externalTransform) {
  20078. if ("development" !== 'production') {
  20079. errMsg = 'Can not find transform on type "' + transType + '".';
  20080. }
  20081. throwError(errMsg);
  20082. } // Prepare source
  20083. var extUpSourceList = map(upSourceList, function (upSource) {
  20084. return createExternalSource(upSource, externalTransform);
  20085. });
  20086. var resultList = normalizeToArray(externalTransform.transform({
  20087. upstream: extUpSourceList[0],
  20088. upstreamList: extUpSourceList,
  20089. config: clone(transOption.config)
  20090. }));
  20091. if ("development" !== 'production') {
  20092. if (transOption.print) {
  20093. var printStrArr = map(resultList, function (extSource) {
  20094. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  20095. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  20096. }).join('\n');
  20097. consoleLog(printStrArr);
  20098. }
  20099. }
  20100. return map(resultList, function (result, resultIndex) {
  20101. var errMsg = '';
  20102. if (!isObject(result)) {
  20103. if ("development" !== 'production') {
  20104. errMsg = 'A transform should not return some empty results.';
  20105. }
  20106. throwError(errMsg);
  20107. }
  20108. if (!result.data) {
  20109. if ("development" !== 'production') {
  20110. errMsg = 'Transform result data should be not be null or undefined';
  20111. }
  20112. throwError(errMsg);
  20113. }
  20114. var sourceFormat = detectSourceFormat(result.data);
  20115. if (!isSupportedSourceFormat(sourceFormat)) {
  20116. if ("development" !== 'production') {
  20117. errMsg = 'Transform result data should be array rows or object rows.';
  20118. }
  20119. throwError(errMsg);
  20120. }
  20121. var resultMetaRawOption;
  20122. var firstUpSource = upSourceList[0];
  20123. /**
  20124. * Intuitively, the end users known the content of the original `dataset.source`,
  20125. * calucating the transform result in mind.
  20126. * Suppose the original `dataset.source` is:
  20127. * ```js
  20128. * [
  20129. * ['product', '2012', '2013', '2014', '2015'],
  20130. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  20131. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  20132. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  20133. * ]
  20134. * ```
  20135. * The dimension info have to be detected from the source data.
  20136. * Some of the transformers (like filter, sort) will follow the dimension info
  20137. * of upstream, while others use new dimensions (like aggregate).
  20138. * Transformer can output a field `dimensions` to define the its own output dimensions.
  20139. * We also allow transformers to ignore the output `dimensions` field, and
  20140. * inherit the upstream dimensions definition. It can reduce the burden of handling
  20141. * dimensions in transformers.
  20142. *
  20143. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20144. */
  20145. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  20146. // dimensions definitions. We do not inherit anything from upstream.
  20147. && !result.dimensions) {
  20148. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result becuase:
  20149. // (1) The returned data always does not contain header line and can not be used
  20150. // as dimension-detection. In this case we can not use "detected dimensions" of
  20151. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  20152. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  20153. // So the original detected header should be add to the result, otherwise they can not be read.
  20154. if (startIndex) {
  20155. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  20156. }
  20157. resultMetaRawOption = {
  20158. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20159. sourceHeader: startIndex,
  20160. dimensions: firstUpSource.metaRawOption.dimensions
  20161. };
  20162. } else {
  20163. resultMetaRawOption = {
  20164. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20165. sourceHeader: 0,
  20166. dimensions: result.dimensions
  20167. };
  20168. }
  20169. return createSource(result.data, resultMetaRawOption, null);
  20170. });
  20171. }
  20172. function isSupportedSourceFormat(sourceFormat) {
  20173. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  20174. }
  20175. var UNDEFINED = 'undefined';
  20176. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  20177. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  20178. // different from the Ctor of typed array.
  20179. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  20180. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  20181. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  20182. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  20183. /**
  20184. * Multi dimensional data store
  20185. */
  20186. var dataCtors = {
  20187. 'float': CtorFloat64Array,
  20188. 'int': CtorInt32Array,
  20189. // Ordinal data type can be string or int
  20190. 'ordinal': Array,
  20191. 'number': Array,
  20192. 'time': CtorFloat64Array
  20193. };
  20194. var defaultDimValueGetters;
  20195. function getIndicesCtor(rawCount) {
  20196. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  20197. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  20198. }
  20199. function getInitialExtent() {
  20200. return [Infinity, -Infinity];
  20201. }
  20202. function cloneChunk(originalChunk) {
  20203. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  20204. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  20205. }
  20206. function prepareStore(store, dimIdx, dimType, end, append) {
  20207. var DataCtor = dataCtors[dimType || 'float'];
  20208. if (append) {
  20209. var oldStore = store[dimIdx];
  20210. var oldLen = oldStore && oldStore.length;
  20211. if (!(oldLen === end)) {
  20212. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  20213. // within the initial chunkSize.
  20214. for (var j = 0; j < oldLen; j++) {
  20215. newStore[j] = oldStore[j];
  20216. }
  20217. store[dimIdx] = newStore;
  20218. }
  20219. } else {
  20220. store[dimIdx] = new DataCtor(end);
  20221. }
  20222. }
  20223. /**
  20224. * Basically, DataStore API keep immutable.
  20225. */
  20226. var DataStore =
  20227. /** @class */
  20228. function () {
  20229. function DataStore() {
  20230. this._chunks = []; // It will not be calculated util needed.
  20231. this._rawExtent = [];
  20232. this._extent = [];
  20233. this._count = 0;
  20234. this._rawCount = 0;
  20235. this._calcDimNameToIdx = createHashMap();
  20236. }
  20237. /**
  20238. * Initialize from data
  20239. */
  20240. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  20241. if ("development" !== 'production') {
  20242. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Inavlid data provider.');
  20243. }
  20244. this._provider = provider; // Clear
  20245. this._chunks = [];
  20246. this._indices = null;
  20247. this.getRawIndex = this._getRawIdxIdentity;
  20248. var source = provider.getSource();
  20249. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat]; // Default dim value getter
  20250. this._dimValueGetter = dimValueGetter || defaultGetter; // Reset raw extent.
  20251. this._rawExtent = [];
  20252. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  20253. this._dimensions = map(inputDimensions, function (dim) {
  20254. if ("development" !== 'production') {
  20255. if (willRetrieveDataByName) {
  20256. assert(dim.property != null);
  20257. }
  20258. }
  20259. return {
  20260. // Only pick these two props. Not leak other properties like orderMeta.
  20261. type: dim.type,
  20262. property: dim.property
  20263. };
  20264. });
  20265. this._initDataFromProvider(0, provider.count());
  20266. };
  20267. DataStore.prototype.getProvider = function () {
  20268. return this._provider;
  20269. };
  20270. /**
  20271. * Caution: even when a `source` instance owned by a series, the created data store
  20272. * may still be shared by different sereis (the source hash does not use all `source`
  20273. * props, see `sourceManager`). In this case, the `source` props that are not used in
  20274. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  20275. * thus should not be fetch here.
  20276. */
  20277. DataStore.prototype.getSource = function () {
  20278. return this._provider.getSource();
  20279. };
  20280. /**
  20281. * @caution Only used in dataStack.
  20282. */
  20283. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  20284. var calcDimNameToIdx = this._calcDimNameToIdx;
  20285. var dimensions = this._dimensions;
  20286. var calcDimIdx = calcDimNameToIdx.get(dimName);
  20287. if (calcDimIdx != null) {
  20288. if (dimensions[calcDimIdx].type === type) {
  20289. return calcDimIdx;
  20290. }
  20291. } else {
  20292. calcDimIdx = dimensions.length;
  20293. }
  20294. dimensions[calcDimIdx] = {
  20295. type: type
  20296. };
  20297. calcDimNameToIdx.set(dimName, calcDimIdx);
  20298. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  20299. this._rawExtent[calcDimIdx] = getInitialExtent();
  20300. return calcDimIdx;
  20301. };
  20302. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  20303. var chunk = this._chunks[dimIdx];
  20304. var dim = this._dimensions[dimIdx];
  20305. var rawExtents = this._rawExtent;
  20306. var offset = dim.ordinalOffset || 0;
  20307. var len = chunk.length;
  20308. if (offset === 0) {
  20309. // We need to reset the rawExtent if collect is from start.
  20310. // Because this dimension may be guessed as number and calcuating a wrong extent.
  20311. rawExtents[dimIdx] = getInitialExtent();
  20312. }
  20313. var dimRawExtent = rawExtents[dimIdx]; // Parse from previous data offset. len may be changed after appendData
  20314. for (var i = offset; i < len; i++) {
  20315. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  20316. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  20317. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  20318. }
  20319. dim.ordinalMeta = ordinalMeta;
  20320. dim.ordinalOffset = len;
  20321. dim.type = 'ordinal'; // Force to be ordinal
  20322. };
  20323. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  20324. var dimInfo = this._dimensions[dimIdx];
  20325. var ordinalMeta = dimInfo.ordinalMeta;
  20326. return ordinalMeta;
  20327. };
  20328. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  20329. var item = this._dimensions[dimIndex];
  20330. return item && item.property;
  20331. };
  20332. /**
  20333. * Caution: Can be only called on raw data (before `this._indices` created).
  20334. */
  20335. DataStore.prototype.appendData = function (data) {
  20336. if ("development" !== 'production') {
  20337. assert(!this._indices, 'appendData can only be called on raw data.');
  20338. }
  20339. var provider = this._provider;
  20340. var start = this.count();
  20341. provider.appendData(data);
  20342. var end = provider.count();
  20343. if (!provider.persistent) {
  20344. end += start;
  20345. }
  20346. if (start < end) {
  20347. this._initDataFromProvider(start, end, true);
  20348. }
  20349. return [start, end];
  20350. };
  20351. DataStore.prototype.appendValues = function (values, minFillLen) {
  20352. var chunks = this._chunks;
  20353. var dimensions = this._dimensions;
  20354. var dimLen = dimensions.length;
  20355. var rawExtent = this._rawExtent;
  20356. var start = this.count();
  20357. var end = start + Math.max(values.length, minFillLen || 0);
  20358. for (var i = 0; i < dimLen; i++) {
  20359. var dim = dimensions[i];
  20360. prepareStore(chunks, i, dim.type, end, true);
  20361. }
  20362. var emptyDataItem = [];
  20363. for (var idx = start; idx < end; idx++) {
  20364. var sourceIdx = idx - start; // Store the data by dimensions
  20365. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20366. var dim = dimensions[dimIdx];
  20367. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  20368. chunks[dimIdx][idx] = val;
  20369. var dimRawExtent = rawExtent[dimIdx];
  20370. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20371. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20372. }
  20373. }
  20374. this._rawCount = this._count = end;
  20375. return {
  20376. start: start,
  20377. end: end
  20378. };
  20379. };
  20380. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  20381. var provider = this._provider;
  20382. var chunks = this._chunks;
  20383. var dimensions = this._dimensions;
  20384. var dimLen = dimensions.length;
  20385. var rawExtent = this._rawExtent;
  20386. var dimNames = map(dimensions, function (dim) {
  20387. return dim.property;
  20388. });
  20389. for (var i = 0; i < dimLen; i++) {
  20390. var dim = dimensions[i];
  20391. if (!rawExtent[i]) {
  20392. rawExtent[i] = getInitialExtent();
  20393. }
  20394. prepareStore(chunks, i, dim.type, end, append);
  20395. }
  20396. if (provider.fillStorage) {
  20397. provider.fillStorage(start, end, chunks, rawExtent);
  20398. } else {
  20399. var dataItem = [];
  20400. for (var idx = start; idx < end; idx++) {
  20401. // NOTICE: Try not to write things into dataItem
  20402. dataItem = provider.getItem(idx, dataItem); // Each data item is value
  20403. // [1, 2]
  20404. // 2
  20405. // Bar chart, line chart which uses category axis
  20406. // only gives the 'y' value. 'x' value is the indices of category
  20407. // Use a tempValue to normalize the value to be a (x, y) value
  20408. // Store the data by dimensions
  20409. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20410. var dimStorage = chunks[dimIdx]; // PENDING NULL is empty or zero
  20411. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  20412. dimStorage[idx] = val;
  20413. var dimRawExtent = rawExtent[dimIdx];
  20414. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20415. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20416. }
  20417. }
  20418. }
  20419. if (!provider.persistent && provider.clean) {
  20420. // Clean unused data if data source is typed array.
  20421. provider.clean();
  20422. }
  20423. this._rawCount = this._count = end; // Reset data extent
  20424. this._extent = [];
  20425. };
  20426. DataStore.prototype.count = function () {
  20427. return this._count;
  20428. };
  20429. /**
  20430. * Get value. Return NaN if idx is out of range.
  20431. */
  20432. DataStore.prototype.get = function (dim, idx) {
  20433. if (!(idx >= 0 && idx < this._count)) {
  20434. return NaN;
  20435. }
  20436. var dimStore = this._chunks[dim];
  20437. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  20438. };
  20439. DataStore.prototype.getValues = function (dimensions, idx) {
  20440. var values = [];
  20441. var dimArr = [];
  20442. if (idx == null) {
  20443. idx = dimensions; // TODO get all from store?
  20444. dimensions = []; // All dimensions
  20445. for (var i = 0; i < this._dimensions.length; i++) {
  20446. dimArr.push(i);
  20447. }
  20448. } else {
  20449. dimArr = dimensions;
  20450. }
  20451. for (var i = 0, len = dimArr.length; i < len; i++) {
  20452. values.push(this.get(dimArr[i], idx));
  20453. }
  20454. return values;
  20455. };
  20456. /**
  20457. * @param dim concrete dim
  20458. */
  20459. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  20460. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  20461. return NaN;
  20462. }
  20463. var dimStore = this._chunks[dim];
  20464. return dimStore ? dimStore[rawIdx] : NaN;
  20465. };
  20466. /**
  20467. * Get sum of data in one dimension
  20468. */
  20469. DataStore.prototype.getSum = function (dim) {
  20470. var dimData = this._chunks[dim];
  20471. var sum = 0;
  20472. if (dimData) {
  20473. for (var i = 0, len = this.count(); i < len; i++) {
  20474. var value = this.get(dim, i);
  20475. if (!isNaN(value)) {
  20476. sum += value;
  20477. }
  20478. }
  20479. }
  20480. return sum;
  20481. };
  20482. /**
  20483. * Get median of data in one dimension
  20484. */
  20485. DataStore.prototype.getMedian = function (dim) {
  20486. var dimDataArray = []; // map all data of one dimension
  20487. this.each([dim], function (val) {
  20488. if (!isNaN(val)) {
  20489. dimDataArray.push(val);
  20490. }
  20491. }); // TODO
  20492. // Use quick select?
  20493. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  20494. return a - b;
  20495. });
  20496. var len = this.count(); // calculate median
  20497. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  20498. };
  20499. /**
  20500. * Retreive the index with given raw data index
  20501. */
  20502. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  20503. if (rawIndex >= this._rawCount || rawIndex < 0) {
  20504. return -1;
  20505. }
  20506. if (!this._indices) {
  20507. return rawIndex;
  20508. } // Indices are ascending
  20509. var indices = this._indices; // If rawIndex === dataIndex
  20510. var rawDataIndex = indices[rawIndex];
  20511. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  20512. return rawIndex;
  20513. }
  20514. var left = 0;
  20515. var right = this._count - 1;
  20516. while (left <= right) {
  20517. var mid = (left + right) / 2 | 0;
  20518. if (indices[mid] < rawIndex) {
  20519. left = mid + 1;
  20520. } else if (indices[mid] > rawIndex) {
  20521. right = mid - 1;
  20522. } else {
  20523. return mid;
  20524. }
  20525. }
  20526. return -1;
  20527. };
  20528. /**
  20529. * Retreive the index of nearest value
  20530. * @param dim
  20531. * @param value
  20532. * @param [maxDistance=Infinity]
  20533. * @return If and only if multiple indices has
  20534. * the same value, they are put to the result.
  20535. */
  20536. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  20537. var chunks = this._chunks;
  20538. var dimData = chunks[dim];
  20539. var nearestIndices = [];
  20540. if (!dimData) {
  20541. return nearestIndices;
  20542. }
  20543. if (maxDistance == null) {
  20544. maxDistance = Infinity;
  20545. }
  20546. var minDist = Infinity;
  20547. var minDiff = -1;
  20548. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/SeriesData.js`.
  20549. for (var i = 0, len = this.count(); i < len; i++) {
  20550. var dataIndex = this.getRawIndex(i);
  20551. var diff = value - dimData[dataIndex];
  20552. var dist = Math.abs(diff);
  20553. if (dist <= maxDistance) {
  20554. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  20555. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  20556. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  20557. // So we chose the one that `diff >= 0` in this csae.
  20558. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  20559. // should be push to `nearestIndices`.
  20560. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  20561. minDist = dist;
  20562. minDiff = diff;
  20563. nearestIndicesLen = 0;
  20564. }
  20565. if (diff === minDiff) {
  20566. nearestIndices[nearestIndicesLen++] = i;
  20567. }
  20568. }
  20569. }
  20570. nearestIndices.length = nearestIndicesLen;
  20571. return nearestIndices;
  20572. };
  20573. DataStore.prototype.getIndices = function () {
  20574. var newIndices;
  20575. var indices = this._indices;
  20576. if (indices) {
  20577. var Ctor = indices.constructor;
  20578. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  20579. if (Ctor === Array) {
  20580. newIndices = new Ctor(thisCount);
  20581. for (var i = 0; i < thisCount; i++) {
  20582. newIndices[i] = indices[i];
  20583. }
  20584. } else {
  20585. newIndices = new Ctor(indices.buffer, 0, thisCount);
  20586. }
  20587. } else {
  20588. var Ctor = getIndicesCtor(this._rawCount);
  20589. newIndices = new Ctor(this.count());
  20590. for (var i = 0; i < newIndices.length; i++) {
  20591. newIndices[i] = i;
  20592. }
  20593. }
  20594. return newIndices;
  20595. };
  20596. /**
  20597. * Data filter.
  20598. */
  20599. DataStore.prototype.filter = function (dims, cb) {
  20600. if (!this._count) {
  20601. return this;
  20602. }
  20603. var newStore = this.clone();
  20604. var count = newStore.count();
  20605. var Ctor = getIndicesCtor(newStore._rawCount);
  20606. var newIndices = new Ctor(count);
  20607. var value = [];
  20608. var dimSize = dims.length;
  20609. var offset = 0;
  20610. var dim0 = dims[0];
  20611. var chunks = newStore._chunks;
  20612. for (var i = 0; i < count; i++) {
  20613. var keep = void 0;
  20614. var rawIdx = newStore.getRawIndex(i); // Simple optimization
  20615. if (dimSize === 0) {
  20616. keep = cb(i);
  20617. } else if (dimSize === 1) {
  20618. var val = chunks[dim0][rawIdx];
  20619. keep = cb(val, i);
  20620. } else {
  20621. var k = 0;
  20622. for (; k < dimSize; k++) {
  20623. value[k] = chunks[dims[k]][rawIdx];
  20624. }
  20625. value[k] = i;
  20626. keep = cb.apply(null, value);
  20627. }
  20628. if (keep) {
  20629. newIndices[offset++] = rawIdx;
  20630. }
  20631. } // Set indices after filtered.
  20632. if (offset < count) {
  20633. newStore._indices = newIndices;
  20634. }
  20635. newStore._count = offset; // Reset data extent
  20636. newStore._extent = [];
  20637. newStore._updateGetRawIdx();
  20638. return newStore;
  20639. };
  20640. /**
  20641. * Select data in range. (For optimization of filter)
  20642. * (Manually inline code, support 5 million data filtering in data zoom.)
  20643. */
  20644. DataStore.prototype.selectRange = function (range) {
  20645. var newStore = this.clone();
  20646. var len = newStore._count;
  20647. if (!len) {
  20648. return this;
  20649. }
  20650. var dims = keys(range);
  20651. var dimSize = dims.length;
  20652. if (!dimSize) {
  20653. return this;
  20654. }
  20655. var originalCount = newStore.count();
  20656. var Ctor = getIndicesCtor(newStore._rawCount);
  20657. var newIndices = new Ctor(originalCount);
  20658. var offset = 0;
  20659. var dim0 = dims[0];
  20660. var min = range[dim0][0];
  20661. var max = range[dim0][1];
  20662. var storeArr = newStore._chunks;
  20663. var quickFinished = false;
  20664. if (!newStore._indices) {
  20665. // Extreme optimization for common case. About 2x faster in chrome.
  20666. var idx = 0;
  20667. if (dimSize === 1) {
  20668. var dimStorage = storeArr[dims[0]];
  20669. for (var i = 0; i < len; i++) {
  20670. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  20671. // value indicates the line should be broken. But for the case like
  20672. // scatter plot, a data item with empty value will not be rendered,
  20673. // but the axis extent may be effected if some other dim of the data
  20674. // item has value. Fortunately it is not a significant negative effect.
  20675. if (val >= min && val <= max || isNaN(val)) {
  20676. newIndices[offset++] = idx;
  20677. }
  20678. idx++;
  20679. }
  20680. quickFinished = true;
  20681. } else if (dimSize === 2) {
  20682. var dimStorage = storeArr[dims[0]];
  20683. var dimStorage2 = storeArr[dims[1]];
  20684. var min2 = range[dims[1]][0];
  20685. var max2 = range[dims[1]][1];
  20686. for (var i = 0; i < len; i++) {
  20687. var val = dimStorage[i];
  20688. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  20689. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  20690. newIndices[offset++] = idx;
  20691. }
  20692. idx++;
  20693. }
  20694. quickFinished = true;
  20695. }
  20696. }
  20697. if (!quickFinished) {
  20698. if (dimSize === 1) {
  20699. for (var i = 0; i < originalCount; i++) {
  20700. var rawIndex = newStore.getRawIndex(i);
  20701. var val = storeArr[dims[0]][rawIndex]; // Do not filter NaN, see comment above.
  20702. if (val >= min && val <= max || isNaN(val)) {
  20703. newIndices[offset++] = rawIndex;
  20704. }
  20705. }
  20706. } else {
  20707. for (var i = 0; i < originalCount; i++) {
  20708. var keep = true;
  20709. var rawIndex = newStore.getRawIndex(i);
  20710. for (var k = 0; k < dimSize; k++) {
  20711. var dimk = dims[k];
  20712. var val = storeArr[dimk][rawIndex]; // Do not filter NaN, see comment above.
  20713. if (val < range[dimk][0] || val > range[dimk][1]) {
  20714. keep = false;
  20715. }
  20716. }
  20717. if (keep) {
  20718. newIndices[offset++] = newStore.getRawIndex(i);
  20719. }
  20720. }
  20721. }
  20722. } // Set indices after filtered.
  20723. if (offset < originalCount) {
  20724. newStore._indices = newIndices;
  20725. }
  20726. newStore._count = offset; // Reset data extent
  20727. newStore._extent = [];
  20728. newStore._updateGetRawIdx();
  20729. return newStore;
  20730. }; // /**
  20731. // * Data mapping to a plain array
  20732. // */
  20733. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  20734. // const result: any[] = [];
  20735. // this.each(dims, function () {
  20736. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  20737. // });
  20738. // return result;
  20739. // }
  20740. /**
  20741. * Data mapping to a new List with given dimensions
  20742. */
  20743. DataStore.prototype.map = function (dims, cb) {
  20744. // TODO only clone picked chunks.
  20745. var target = this.clone(dims);
  20746. this._updateDims(target, dims, cb);
  20747. return target;
  20748. };
  20749. /**
  20750. * @caution Danger!! Only used in dataStack.
  20751. */
  20752. DataStore.prototype.modify = function (dims, cb) {
  20753. this._updateDims(this, dims, cb);
  20754. };
  20755. DataStore.prototype._updateDims = function (target, dims, cb) {
  20756. var targetChunks = target._chunks;
  20757. var tmpRetValue = [];
  20758. var dimSize = dims.length;
  20759. var dataCount = target.count();
  20760. var values = [];
  20761. var rawExtent = target._rawExtent;
  20762. for (var i = 0; i < dims.length; i++) {
  20763. rawExtent[dims[i]] = getInitialExtent();
  20764. }
  20765. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  20766. var rawIndex = target.getRawIndex(dataIndex);
  20767. for (var k = 0; k < dimSize; k++) {
  20768. values[k] = targetChunks[dims[k]][rawIndex];
  20769. }
  20770. values[dimSize] = dataIndex;
  20771. var retValue = cb && cb.apply(null, values);
  20772. if (retValue != null) {
  20773. // a number or string (in oridinal dimension)?
  20774. if (typeof retValue !== 'object') {
  20775. tmpRetValue[0] = retValue;
  20776. retValue = tmpRetValue;
  20777. }
  20778. for (var i = 0; i < retValue.length; i++) {
  20779. var dim = dims[i];
  20780. var val = retValue[i];
  20781. var rawExtentOnDim = rawExtent[dim];
  20782. var dimStore = targetChunks[dim];
  20783. if (dimStore) {
  20784. dimStore[rawIndex] = val;
  20785. }
  20786. if (val < rawExtentOnDim[0]) {
  20787. rawExtentOnDim[0] = val;
  20788. }
  20789. if (val > rawExtentOnDim[1]) {
  20790. rawExtentOnDim[1] = val;
  20791. }
  20792. }
  20793. }
  20794. }
  20795. };
  20796. /**
  20797. * Large data down sampling using largest-triangle-three-buckets
  20798. * @param {string} valueDimension
  20799. * @param {number} targetCount
  20800. */
  20801. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  20802. var target = this.clone([valueDimension], true);
  20803. var targetStorage = target._chunks;
  20804. var dimStore = targetStorage[valueDimension];
  20805. var len = this.count();
  20806. var sampledIndex = 0;
  20807. var frameSize = Math.floor(1 / rate);
  20808. var currentRawIndex = this.getRawIndex(0);
  20809. var maxArea;
  20810. var area;
  20811. var nextRawIndex;
  20812. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize) + 2); // First frame use the first data.
  20813. newIndices[sampledIndex++] = currentRawIndex;
  20814. for (var i = 1; i < len - 1; i += frameSize) {
  20815. var nextFrameStart = Math.min(i + frameSize, len - 1);
  20816. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  20817. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  20818. var avgY = 0;
  20819. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  20820. var rawIndex = this.getRawIndex(idx);
  20821. var y = dimStore[rawIndex];
  20822. if (isNaN(y)) {
  20823. continue;
  20824. }
  20825. avgY += y;
  20826. }
  20827. avgY /= nextFrameEnd - nextFrameStart;
  20828. var frameStart = i;
  20829. var frameEnd = Math.min(i + frameSize, len);
  20830. var pointAX = i - 1;
  20831. var pointAY = dimStore[currentRawIndex];
  20832. maxArea = -1;
  20833. nextRawIndex = frameStart; // Find a point from current frame that construct a triangel with largest area with previous selected point
  20834. // And the average of next frame.
  20835. for (var idx = frameStart; idx < frameEnd; idx++) {
  20836. var rawIndex = this.getRawIndex(idx);
  20837. var y = dimStore[rawIndex];
  20838. if (isNaN(y)) {
  20839. continue;
  20840. } // Calculate triangle area over three buckets
  20841. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  20842. if (area > maxArea) {
  20843. maxArea = area;
  20844. nextRawIndex = rawIndex; // Next a is this b
  20845. }
  20846. }
  20847. newIndices[sampledIndex++] = nextRawIndex;
  20848. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  20849. } // First frame use the last data.
  20850. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  20851. target._count = sampledIndex;
  20852. target._indices = newIndices;
  20853. target.getRawIndex = this._getRawIdx;
  20854. return target;
  20855. };
  20856. /**
  20857. * Large data down sampling on given dimension
  20858. * @param sampleIndex Sample index for name and id
  20859. */
  20860. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  20861. var target = this.clone([dimension], true);
  20862. var targetStorage = target._chunks;
  20863. var frameValues = [];
  20864. var frameSize = Math.floor(1 / rate);
  20865. var dimStore = targetStorage[dimension];
  20866. var len = this.count();
  20867. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  20868. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  20869. var offset = 0;
  20870. for (var i = 0; i < len; i += frameSize) {
  20871. // Last frame
  20872. if (frameSize > len - i) {
  20873. frameSize = len - i;
  20874. frameValues.length = frameSize;
  20875. }
  20876. for (var k = 0; k < frameSize; k++) {
  20877. var dataIdx = this.getRawIndex(i + k);
  20878. frameValues[k] = dimStore[dataIdx];
  20879. }
  20880. var value = sampleValue(frameValues);
  20881. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  20882. dimStore[sampleFrameIdx] = value;
  20883. if (value < rawExtentOnDim[0]) {
  20884. rawExtentOnDim[0] = value;
  20885. }
  20886. if (value > rawExtentOnDim[1]) {
  20887. rawExtentOnDim[1] = value;
  20888. }
  20889. newIndices[offset++] = sampleFrameIdx;
  20890. }
  20891. target._count = offset;
  20892. target._indices = newIndices;
  20893. target._updateGetRawIdx();
  20894. return target;
  20895. };
  20896. /**
  20897. * Data iteration
  20898. * @param ctx default this
  20899. * @example
  20900. * list.each('x', function (x, idx) {});
  20901. * list.each(['x', 'y'], function (x, y, idx) {});
  20902. * list.each(function (idx) {})
  20903. */
  20904. DataStore.prototype.each = function (dims, cb) {
  20905. if (!this._count) {
  20906. return;
  20907. }
  20908. var dimSize = dims.length;
  20909. var chunks = this._chunks;
  20910. for (var i = 0, len = this.count(); i < len; i++) {
  20911. var rawIdx = this.getRawIndex(i); // Simple optimization
  20912. switch (dimSize) {
  20913. case 0:
  20914. cb(i);
  20915. break;
  20916. case 1:
  20917. cb(chunks[dims[0]][rawIdx], i);
  20918. break;
  20919. case 2:
  20920. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  20921. break;
  20922. default:
  20923. var k = 0;
  20924. var value = [];
  20925. for (; k < dimSize; k++) {
  20926. value[k] = chunks[dims[k]][rawIdx];
  20927. } // Index
  20928. value[k] = i;
  20929. cb.apply(null, value);
  20930. }
  20931. }
  20932. };
  20933. /**
  20934. * Get extent of data in one dimension
  20935. */
  20936. DataStore.prototype.getDataExtent = function (dim) {
  20937. // Make sure use concrete dim as cache name.
  20938. var dimData = this._chunks[dim];
  20939. var initialExtent = getInitialExtent();
  20940. if (!dimData) {
  20941. return initialExtent;
  20942. } // Make more strict checkings to ensure hitting cache.
  20943. var currEnd = this.count(); // Consider the most cases when using data zoom, `getDataExtent`
  20944. // happened before filtering. We cache raw extent, which is not
  20945. // necessary to be cleared and recalculated when restore data.
  20946. var useRaw = !this._indices;
  20947. var dimExtent;
  20948. if (useRaw) {
  20949. return this._rawExtent[dim].slice();
  20950. }
  20951. dimExtent = this._extent[dim];
  20952. if (dimExtent) {
  20953. return dimExtent.slice();
  20954. }
  20955. dimExtent = initialExtent;
  20956. var min = dimExtent[0];
  20957. var max = dimExtent[1];
  20958. for (var i = 0; i < currEnd; i++) {
  20959. var rawIdx = this.getRawIndex(i);
  20960. var value = dimData[rawIdx];
  20961. value < min && (min = value);
  20962. value > max && (max = value);
  20963. }
  20964. dimExtent = [min, max];
  20965. this._extent[dim] = dimExtent;
  20966. return dimExtent;
  20967. };
  20968. /**
  20969. * Get raw data item
  20970. */
  20971. DataStore.prototype.getRawDataItem = function (idx) {
  20972. var rawIdx = this.getRawIndex(idx);
  20973. if (!this._provider.persistent) {
  20974. var val = [];
  20975. var chunks = this._chunks;
  20976. for (var i = 0; i < chunks.length; i++) {
  20977. val.push(chunks[i][rawIdx]);
  20978. }
  20979. return val;
  20980. } else {
  20981. return this._provider.getItem(rawIdx);
  20982. }
  20983. };
  20984. /**
  20985. * Clone shallow.
  20986. *
  20987. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  20988. */
  20989. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  20990. var target = new DataStore();
  20991. var chunks = this._chunks;
  20992. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  20993. obj[dimIdx] = true;
  20994. return obj;
  20995. }, {});
  20996. if (clonedDimsMap) {
  20997. for (var i = 0; i < chunks.length; i++) {
  20998. // Not clone if dim is not picked.
  20999. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  21000. }
  21001. } else {
  21002. target._chunks = chunks;
  21003. }
  21004. this._copyCommonProps(target);
  21005. if (!ignoreIndices) {
  21006. target._indices = this._cloneIndices();
  21007. }
  21008. target._updateGetRawIdx();
  21009. return target;
  21010. };
  21011. DataStore.prototype._copyCommonProps = function (target) {
  21012. target._count = this._count;
  21013. target._rawCount = this._rawCount;
  21014. target._provider = this._provider;
  21015. target._dimensions = this._dimensions;
  21016. target._extent = clone(this._extent);
  21017. target._rawExtent = clone(this._rawExtent);
  21018. };
  21019. DataStore.prototype._cloneIndices = function () {
  21020. if (this._indices) {
  21021. var Ctor = this._indices.constructor;
  21022. var indices = void 0;
  21023. if (Ctor === Array) {
  21024. var thisCount = this._indices.length;
  21025. indices = new Ctor(thisCount);
  21026. for (var i = 0; i < thisCount; i++) {
  21027. indices[i] = this._indices[i];
  21028. }
  21029. } else {
  21030. indices = new Ctor(this._indices);
  21031. }
  21032. return indices;
  21033. }
  21034. return null;
  21035. };
  21036. DataStore.prototype._getRawIdxIdentity = function (idx) {
  21037. return idx;
  21038. };
  21039. DataStore.prototype._getRawIdx = function (idx) {
  21040. if (idx < this._count && idx >= 0) {
  21041. return this._indices[idx];
  21042. }
  21043. return -1;
  21044. };
  21045. DataStore.prototype._updateGetRawIdx = function () {
  21046. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  21047. };
  21048. DataStore.internalField = function () {
  21049. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  21050. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  21051. }
  21052. defaultDimValueGetters = {
  21053. arrayRows: getDimValueSimply,
  21054. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  21055. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  21056. },
  21057. keyedColumns: getDimValueSimply,
  21058. original: function (dataItem, property, dataIndex, dimIndex) {
  21059. // Performance sensitive, do not use modelUtil.getDataItemValue.
  21060. // If dataItem is an plain object with no value field, the let `value`
  21061. // will be assigned with the object, but it will be tread correctly
  21062. // in the `convertValue`.
  21063. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  21064. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  21065. : value, this._dimensions[dimIndex]);
  21066. },
  21067. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  21068. return dataItem[dimIndex];
  21069. }
  21070. };
  21071. }();
  21072. return DataStore;
  21073. }();
  21074. /**
  21075. * [REQUIREMENT_MEMO]:
  21076. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  21077. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  21078. * `root-dataset`. Them on `series` has higher priority.
  21079. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  21080. * confuse users: whether those props indicate how to visit the upstream source or visit
  21081. * the transform result source, and some transforms has nothing to do with these props,
  21082. * and some transforms might have multiple upstream.
  21083. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  21084. * declared in `root-dataset`.
  21085. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  21086. * That is for reducing complexity in transfroms.
  21087. * PENDING: Whether to provide transposition transform?
  21088. *
  21089. * [IMPLEMENTAION_MEMO]:
  21090. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  21091. * They will not be calculated until `source` is about to be visited (to prevent from
  21092. * duplicate calcuation). `source` is visited only in series and input to transforms.
  21093. *
  21094. * [DIMENSION_INHERIT_RULE]:
  21095. * By default the dimensions are inherited from ancestors, unless a transform return
  21096. * a new dimensions definition.
  21097. * Consider the case:
  21098. * ```js
  21099. * dataset: [{
  21100. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  21101. * }, {
  21102. * transform: { type: 'filter', ... }
  21103. * }]
  21104. * dataset: [{
  21105. * dimension: ['Product', 'Sales', 'Prise'],
  21106. * source: [ ['Cookies', 321, 44.21], ...]
  21107. * }, {
  21108. * transform: { type: 'filter', ... }
  21109. * }]
  21110. * ```
  21111. * The two types of option should have the same behavior after transform.
  21112. *
  21113. *
  21114. * [SCENARIO]:
  21115. * (1) Provide source data directly:
  21116. * ```js
  21117. * series: {
  21118. * encode: {...},
  21119. * dimensions: [...]
  21120. * seriesLayoutBy: 'row',
  21121. * data: [[...]]
  21122. * }
  21123. * ```
  21124. * (2) Series refer to dataset.
  21125. * ```js
  21126. * series: [{
  21127. * encode: {...}
  21128. * // Ignore datasetIndex means `datasetIndex: 0`
  21129. * // and the dimensions defination in dataset is used
  21130. * }, {
  21131. * encode: {...},
  21132. * seriesLayoutBy: 'column',
  21133. * datasetIndex: 1
  21134. * }]
  21135. * ```
  21136. * (3) dataset transform
  21137. * ```js
  21138. * dataset: [{
  21139. * source: [...]
  21140. * }, {
  21141. * source: [...]
  21142. * }, {
  21143. * // By default from 0.
  21144. * transform: { type: 'filter', config: {...} }
  21145. * }, {
  21146. * // Piped.
  21147. * transform: [
  21148. * { type: 'filter', config: {...} },
  21149. * { type: 'sort', config: {...} }
  21150. * ]
  21151. * }, {
  21152. * id: 'regressionData',
  21153. * fromDatasetIndex: 1,
  21154. * // Third-party transform
  21155. * transform: { type: 'ecStat:regression', config: {...} }
  21156. * }, {
  21157. * // retrieve the extra result.
  21158. * id: 'regressionFormula',
  21159. * fromDatasetId: 'regressionData',
  21160. * fromTransformResult: 1
  21161. * }]
  21162. * ```
  21163. */
  21164. var SourceManager =
  21165. /** @class */
  21166. function () {
  21167. function SourceManager(sourceHost) {
  21168. // Cached source. Do not repeat calculating if not dirty.
  21169. this._sourceList = [];
  21170. this._storeList = []; // version sign of each upstream source manager.
  21171. this._upstreamSignList = [];
  21172. this._versionSignBase = 0;
  21173. this._dirty = true;
  21174. this._sourceHost = sourceHost;
  21175. }
  21176. /**
  21177. * Mark dirty.
  21178. */
  21179. SourceManager.prototype.dirty = function () {
  21180. this._setLocalSource([], []);
  21181. this._storeList = [];
  21182. this._dirty = true;
  21183. };
  21184. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  21185. this._sourceList = sourceList;
  21186. this._upstreamSignList = upstreamSignList;
  21187. this._versionSignBase++;
  21188. if (this._versionSignBase > 9e10) {
  21189. this._versionSignBase = 0;
  21190. }
  21191. };
  21192. /**
  21193. * For detecting whether the upstream source is dirty, so that
  21194. * the local cached source (in `_sourceList`) should be discarded.
  21195. */
  21196. SourceManager.prototype._getVersionSign = function () {
  21197. return this._sourceHost.uid + '_' + this._versionSignBase;
  21198. };
  21199. /**
  21200. * Always return a source instance. Otherwise throw error.
  21201. */
  21202. SourceManager.prototype.prepareSource = function () {
  21203. // For the case that call `setOption` multiple time but no data changed,
  21204. // cache the result source to prevent from repeating transform.
  21205. if (this._isDirty()) {
  21206. this._createSource();
  21207. this._dirty = false;
  21208. }
  21209. };
  21210. SourceManager.prototype._createSource = function () {
  21211. this._setLocalSource([], []);
  21212. var sourceHost = this._sourceHost;
  21213. var upSourceMgrList = this._getUpstreamSourceManagers();
  21214. var hasUpstream = !!upSourceMgrList.length;
  21215. var resultSourceList;
  21216. var upstreamSignList;
  21217. if (isSeries(sourceHost)) {
  21218. var seriesModel = sourceHost;
  21219. var data = void 0;
  21220. var sourceFormat = void 0;
  21221. var upSource = void 0; // Has upstream dataset
  21222. if (hasUpstream) {
  21223. var upSourceMgr = upSourceMgrList[0];
  21224. upSourceMgr.prepareSource();
  21225. upSource = upSourceMgr.getSource();
  21226. data = upSource.data;
  21227. sourceFormat = upSource.sourceFormat;
  21228. upstreamSignList = [upSourceMgr._getVersionSign()];
  21229. } // Series data is from own.
  21230. else {
  21231. data = seriesModel.get('data', true);
  21232. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  21233. upstreamSignList = [];
  21234. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  21235. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  21236. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  21237. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  21238. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader) || null; // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  21239. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  21240. // but series need `seriesLayoutBy: 'row'`.
  21241. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions); // We share source with dataset as much as possible
  21242. // to avoid extra memroy cost of high dimensional data.
  21243. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  21244. resultSourceList = needsCreateSource ? [createSource(data, {
  21245. seriesLayoutBy: seriesLayoutBy,
  21246. sourceHeader: sourceHeader,
  21247. dimensions: dimensions
  21248. }, sourceFormat)] : [];
  21249. } else {
  21250. var datasetModel = sourceHost; // Has upstream dataset.
  21251. if (hasUpstream) {
  21252. var result = this._applyTransform(upSourceMgrList);
  21253. resultSourceList = result.sourceList;
  21254. upstreamSignList = result.upstreamSignList;
  21255. } // Is root dataset.
  21256. else {
  21257. var sourceData = datasetModel.get('source', true);
  21258. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  21259. upstreamSignList = [];
  21260. }
  21261. }
  21262. if ("development" !== 'production') {
  21263. assert(resultSourceList && upstreamSignList);
  21264. }
  21265. this._setLocalSource(resultSourceList, upstreamSignList);
  21266. };
  21267. SourceManager.prototype._applyTransform = function (upMgrList) {
  21268. var datasetModel = this._sourceHost;
  21269. var transformOption = datasetModel.get('transform', true);
  21270. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  21271. if ("development" !== 'production') {
  21272. assert(fromTransformResult != null || transformOption != null);
  21273. }
  21274. if (fromTransformResult != null) {
  21275. var errMsg = '';
  21276. if (upMgrList.length !== 1) {
  21277. if ("development" !== 'production') {
  21278. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  21279. }
  21280. doThrow(errMsg);
  21281. }
  21282. }
  21283. var sourceList;
  21284. var upSourceList = [];
  21285. var upstreamSignList = [];
  21286. each(upMgrList, function (upMgr) {
  21287. upMgr.prepareSource();
  21288. var upSource = upMgr.getSource(fromTransformResult || 0);
  21289. var errMsg = '';
  21290. if (fromTransformResult != null && !upSource) {
  21291. if ("development" !== 'production') {
  21292. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  21293. }
  21294. doThrow(errMsg);
  21295. }
  21296. upSourceList.push(upSource);
  21297. upstreamSignList.push(upMgr._getVersionSign());
  21298. });
  21299. if (transformOption) {
  21300. sourceList = applyDataTransform(transformOption, upSourceList, {
  21301. datasetIndex: datasetModel.componentIndex
  21302. });
  21303. } else if (fromTransformResult != null) {
  21304. sourceList = [cloneSourceShallow(upSourceList[0])];
  21305. }
  21306. return {
  21307. sourceList: sourceList,
  21308. upstreamSignList: upstreamSignList
  21309. };
  21310. };
  21311. SourceManager.prototype._isDirty = function () {
  21312. if (this._dirty) {
  21313. return true;
  21314. } // All sourceList is from the some upsteam.
  21315. var upSourceMgrList = this._getUpstreamSourceManagers();
  21316. for (var i = 0; i < upSourceMgrList.length; i++) {
  21317. var upSrcMgr = upSourceMgrList[i];
  21318. if ( // Consider the case that there is ancestor diry, call it recursively.
  21319. // The performance is probably not an issue because usually the chain is not long.
  21320. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  21321. return true;
  21322. }
  21323. }
  21324. };
  21325. /**
  21326. * @param sourceIndex By defualt 0, means "main source".
  21327. * Most cases there is only one source.
  21328. */
  21329. SourceManager.prototype.getSource = function (sourceIndex) {
  21330. sourceIndex = sourceIndex || 0;
  21331. var source = this._sourceList[sourceIndex];
  21332. if (!source) {
  21333. // Series may share source instance with dataset.
  21334. var upSourceMgrList = this._getUpstreamSourceManagers();
  21335. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  21336. }
  21337. return source;
  21338. };
  21339. /**
  21340. *
  21341. * Get a data store which can be shared across series.
  21342. * Only available for series.
  21343. *
  21344. * @param seriesDimRequest Dimensions that are generated in series.
  21345. * Should have been sorted by `storeDimIndex` asc.
  21346. */
  21347. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  21348. if ("development" !== 'production') {
  21349. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  21350. }
  21351. var schema = seriesDimRequest.makeStoreSchema();
  21352. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  21353. };
  21354. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  21355. // TODO Can use other sourceIndex?
  21356. var sourceIndex = 0;
  21357. var storeList = this._storeList;
  21358. var cachedStoreMap = storeList[sourceIndex];
  21359. if (!cachedStoreMap) {
  21360. cachedStoreMap = storeList[sourceIndex] = {};
  21361. }
  21362. var cachedStore = cachedStoreMap[sourceReadKey];
  21363. if (!cachedStore) {
  21364. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  21365. if (isSeries(this._sourceHost) && upSourceMgr) {
  21366. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  21367. } else {
  21368. cachedStore = new DataStore(); // Always create store from source of series.
  21369. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  21370. }
  21371. cachedStoreMap[sourceReadKey] = cachedStore;
  21372. }
  21373. return cachedStore;
  21374. };
  21375. /**
  21376. * PEDING: Is it fast enough?
  21377. * If no upstream, return empty array.
  21378. */
  21379. SourceManager.prototype._getUpstreamSourceManagers = function () {
  21380. // Always get the relationship from the raw option.
  21381. // Do not cache the link of the dependency graph, so that
  21382. // no need to update them when change happen.
  21383. var sourceHost = this._sourceHost;
  21384. if (isSeries(sourceHost)) {
  21385. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  21386. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  21387. } else {
  21388. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  21389. return datasetModel.getSourceManager();
  21390. });
  21391. }
  21392. };
  21393. SourceManager.prototype._getSourceMetaRawOption = function () {
  21394. var sourceHost = this._sourceHost;
  21395. var seriesLayoutBy;
  21396. var sourceHeader;
  21397. var dimensions;
  21398. if (isSeries(sourceHost)) {
  21399. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  21400. sourceHeader = sourceHost.get('sourceHeader', true);
  21401. dimensions = sourceHost.get('dimensions', true);
  21402. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  21403. else if (!this._getUpstreamSourceManagers().length) {
  21404. var model = sourceHost;
  21405. seriesLayoutBy = model.get('seriesLayoutBy', true);
  21406. sourceHeader = model.get('sourceHeader', true);
  21407. dimensions = model.get('dimensions', true);
  21408. }
  21409. return {
  21410. seriesLayoutBy: seriesLayoutBy,
  21411. sourceHeader: sourceHeader,
  21412. dimensions: dimensions
  21413. };
  21414. };
  21415. return SourceManager;
  21416. }();
  21417. // disable the transform merge, but do not disable transfrom clone from rawOption.
  21418. function disableTransformOptionMerge(datasetModel) {
  21419. var transformOption = datasetModel.option.transform;
  21420. transformOption && setAsPrimitive(datasetModel.option.transform);
  21421. }
  21422. function isSeries(sourceHost) {
  21423. // Avoid circular dependency with Series.ts
  21424. return sourceHost.mainType === 'series';
  21425. }
  21426. function doThrow(errMsg) {
  21427. throw new Error(errMsg);
  21428. }
  21429. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1'; // TODO: more textStyle option
  21430. function getTooltipTextStyle(textStyle, renderMode) {
  21431. var nameFontColor = textStyle.color || '#6e7079';
  21432. var nameFontSize = textStyle.fontSize || 12;
  21433. var nameFontWeight = textStyle.fontWeight || '400';
  21434. var valueFontColor = textStyle.color || '#464646';
  21435. var valueFontSize = textStyle.fontSize || 14;
  21436. var valueFontWeight = textStyle.fontWeight || '900';
  21437. if (renderMode === 'html') {
  21438. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  21439. return {
  21440. // eslint-disable-next-line max-len
  21441. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  21442. // eslint-disable-next-line max-len
  21443. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  21444. };
  21445. } else {
  21446. return {
  21447. nameStyle: {
  21448. fontSize: nameFontSize,
  21449. fill: nameFontColor,
  21450. fontWeight: nameFontWeight
  21451. },
  21452. valueStyle: {
  21453. fontSize: valueFontSize,
  21454. fill: valueFontColor,
  21455. fontWeight: valueFontWeight
  21456. }
  21457. };
  21458. }
  21459. } // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  21460. // (value from UI design)
  21461. var HTML_GAPS = [0, 10, 20, 30];
  21462. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n']; // eslint-disable-next-line max-len
  21463. function createTooltipMarkup(type, option) {
  21464. option.type = type;
  21465. return option;
  21466. }
  21467. function getBuilder(fragment) {
  21468. return hasOwn(builderMap, fragment.type) && builderMap[fragment.type];
  21469. }
  21470. var builderMap = {
  21471. /**
  21472. * A `section` block is like:
  21473. * ```
  21474. * header
  21475. * subBlock
  21476. * subBlock
  21477. * ...
  21478. * ```
  21479. */
  21480. section: {
  21481. planLayout: function (fragment) {
  21482. var subBlockLen = fragment.blocks.length;
  21483. var thisBlockHasInnerGap = subBlockLen > 1 || subBlockLen > 0 && !fragment.noHeader;
  21484. var thisGapLevelBetweenSubBlocks = 0;
  21485. each(fragment.blocks, function (subBlock) {
  21486. getBuilder(subBlock).planLayout(subBlock);
  21487. var subGapLevel = subBlock.__gapLevelBetweenSubBlocks; // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  21488. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  21489. if (subGapLevel >= thisGapLevelBetweenSubBlocks) {
  21490. thisGapLevelBetweenSubBlocks = subGapLevel + (thisBlockHasInnerGap && ( // 0 always can not be readable gap level.
  21491. !subGapLevel // If no header, always keep the sub gap level. Otherwise
  21492. // look weird in case `multipleSeries`.
  21493. || subBlock.type === 'section' && !subBlock.noHeader) ? 1 : 0);
  21494. }
  21495. });
  21496. fragment.__gapLevelBetweenSubBlocks = thisGapLevelBetweenSubBlocks;
  21497. },
  21498. build: function (ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21499. var noHeader = fragment.noHeader;
  21500. var gaps = getGap(fragment);
  21501. var subMarkupText = buildSubBlocks(ctx, fragment, noHeader ? topMarginForOuterGap : gaps.html, toolTipTextStyle);
  21502. if (noHeader) {
  21503. return subMarkupText;
  21504. }
  21505. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  21506. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  21507. if (ctx.renderMode === 'richText') {
  21508. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  21509. } else {
  21510. return wrapBlockHTML("<div style=\"" + nameStyle + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  21511. }
  21512. }
  21513. },
  21514. /**
  21515. * A `nameValue` block is like:
  21516. * ```
  21517. * marker name value
  21518. * ```
  21519. */
  21520. nameValue: {
  21521. planLayout: function (fragment) {
  21522. fragment.__gapLevelBetweenSubBlocks = 0;
  21523. },
  21524. build: function (ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21525. var renderMode = ctx.renderMode;
  21526. var noName = fragment.noName;
  21527. var noValue = fragment.noValue;
  21528. var noMarker = !fragment.markerType;
  21529. var name = fragment.name;
  21530. var value = fragment.value;
  21531. var useUTC = ctx.useUTC;
  21532. if (noName && noValue) {
  21533. return;
  21534. }
  21535. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  21536. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  21537. var valueTypeOption = fragment.valueType;
  21538. var readableValueList = noValue ? [] : isArray(value) ? map(value, function (val, idx) {
  21539. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  21540. }) : [makeValueReadable(value, isArray(valueTypeOption) ? valueTypeOption[0] : valueTypeOption, useUTC)];
  21541. var valueAlignRight = !noMarker || !noName; // It little weird if only value next to marker but far from marker.
  21542. var valueCloseToMarker = !noMarker && noName;
  21543. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  21544. nameStyle = _a.nameStyle,
  21545. valueStyle = _a.valueStyle;
  21546. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle)) // Value has commas inside, so use ' ' as delimiter for multiple values.
  21547. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  21548. }
  21549. }
  21550. };
  21551. function buildSubBlocks(ctx, fragment, topMarginForOuterGap, tooltipTextStyle) {
  21552. var subMarkupTextList = [];
  21553. var subBlocks = fragment.blocks || [];
  21554. assert(!subBlocks || isArray(subBlocks));
  21555. subBlocks = subBlocks || [];
  21556. var orderMode = ctx.orderMode;
  21557. if (fragment.sortBlocks && orderMode) {
  21558. subBlocks = subBlocks.slice();
  21559. var orderMap = {
  21560. valueAsc: 'asc',
  21561. valueDesc: 'desc'
  21562. };
  21563. if (hasOwn(orderMap, orderMode)) {
  21564. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  21565. subBlocks.sort(function (a, b) {
  21566. return comparator_1.evaluate(a.sortParam, b.sortParam);
  21567. });
  21568. } // FIXME 'seriesDesc' necessary?
  21569. else if (orderMode === 'seriesDesc') {
  21570. subBlocks.reverse();
  21571. }
  21572. }
  21573. var gaps = getGap(fragment);
  21574. each(subBlocks, function (subBlock, idx) {
  21575. var subMarkupText = getBuilder(subBlock).build(ctx, subBlock, idx > 0 ? gaps.html : 0, tooltipTextStyle);
  21576. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  21577. });
  21578. if (!subMarkupTextList.length) {
  21579. return;
  21580. }
  21581. return ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), topMarginForOuterGap);
  21582. }
  21583. /**
  21584. * @return markupText. null/undefined means no content.
  21585. */
  21586. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  21587. if (!fragment) {
  21588. return;
  21589. }
  21590. var builder = getBuilder(fragment);
  21591. builder.planLayout(fragment);
  21592. var ctx = {
  21593. useUTC: useUTC,
  21594. renderMode: renderMode,
  21595. orderMode: orderMode,
  21596. markupStyleCreator: markupStyleCreator
  21597. };
  21598. return builder.build(ctx, fragment, 0, toolTipTextStyle);
  21599. }
  21600. function getGap(fragment) {
  21601. var gapLevelBetweenSubBlocks = fragment.__gapLevelBetweenSubBlocks;
  21602. return {
  21603. html: HTML_GAPS[gapLevelBetweenSubBlocks],
  21604. richText: RICH_TEXT_GAPS[gapLevelBetweenSubBlocks]
  21605. };
  21606. }
  21607. function wrapBlockHTML(encodedContent, topGap) {
  21608. var clearfix = '<div style="clear:both"></div>';
  21609. var marginCSS = "margin: " + topGap + "px 0 0";
  21610. return "<div style=\"" + marginCSS + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodedContent + clearfix + '</div>';
  21611. }
  21612. function wrapInlineNameHTML(name, leftHasMarker, style) {
  21613. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  21614. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  21615. }
  21616. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  21617. // Do not too close to marker, considering there are multiple values separated by spaces.
  21618. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  21619. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  21620. return "<span style=\"" + alignCSS + ";" + style + "\">" // Value has commas inside, so use ' ' as delimiter for multiple values.
  21621. + map(valueList, function (value) {
  21622. return encodeHTML(value);
  21623. }).join('&nbsp;&nbsp;') + '</span>';
  21624. }
  21625. function wrapInlineNameRichText(ctx, name, style) {
  21626. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  21627. }
  21628. function wrapInlineValueRichText(ctx, valueList, alignRight, valueCloseToMarker, style) {
  21629. var styles = [style];
  21630. var paddingLeft = valueCloseToMarker ? 10 : 20;
  21631. alignRight && styles.push({
  21632. padding: [0, 0, 0, paddingLeft],
  21633. align: 'right'
  21634. }); // Value has commas inside, so use ' ' as delimiter for multiple values.
  21635. return ctx.markupStyleCreator.wrapRichTextStyle(valueList.join(' '), styles);
  21636. }
  21637. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  21638. var style = series.getData().getItemVisual(dataIndex, 'style');
  21639. var color = style[series.visualDrawType];
  21640. return convertToColorString(color);
  21641. }
  21642. function getPaddingFromTooltipModel(model, renderMode) {
  21643. var padding = model.get('padding');
  21644. return padding != null ? padding // We give slightly different to look pretty.
  21645. : renderMode === 'richText' ? [8, 10] : 10;
  21646. }
  21647. /**
  21648. * The major feature is generate styles for `renderMode: 'richText'`.
  21649. * But it also serves `renderMode: 'html'` to provide
  21650. * "renderMode-independent" API.
  21651. */
  21652. var TooltipMarkupStyleCreator =
  21653. /** @class */
  21654. function () {
  21655. function TooltipMarkupStyleCreator() {
  21656. this.richTextStyles = {}; // Notice that "generate a style name" usuall happens repeatly when mouse moving and
  21657. // displaying a tooltip. So we put the `_nextStyleNameId` as a member of each creator
  21658. // rather than static shared by all creators (which will cause it increase to fast).
  21659. this._nextStyleNameId = getRandomIdBase();
  21660. }
  21661. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  21662. return '__EC_aUTo_' + this._nextStyleNameId++;
  21663. };
  21664. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  21665. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  21666. var marker = getTooltipMarker({
  21667. color: colorStr,
  21668. type: markerType,
  21669. renderMode: renderMode,
  21670. markerId: markerId
  21671. });
  21672. if (isString(marker)) {
  21673. return marker;
  21674. } else {
  21675. if ("development" !== 'production') {
  21676. assert(markerId);
  21677. }
  21678. this.richTextStyles[markerId] = marker.style;
  21679. return marker.content;
  21680. }
  21681. };
  21682. /**
  21683. * @usage
  21684. * ```ts
  21685. * const styledText = markupStyleCreator.wrapRichTextStyle([
  21686. * // The styles will be auto merged.
  21687. * {
  21688. * fontSize: 12,
  21689. * color: 'blue'
  21690. * },
  21691. * {
  21692. * padding: 20
  21693. * }
  21694. * ]);
  21695. * ```
  21696. */
  21697. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  21698. var finalStl = {};
  21699. if (isArray(styles)) {
  21700. each(styles, function (stl) {
  21701. return extend(finalStl, stl);
  21702. });
  21703. } else {
  21704. extend(finalStl, styles);
  21705. }
  21706. var styleName = this._generateStyleName();
  21707. this.richTextStyles[styleName] = finalStl;
  21708. return "{" + styleName + "|" + text + "}";
  21709. };
  21710. return TooltipMarkupStyleCreator;
  21711. }();
  21712. function defaultSeriesFormatTooltip(opt) {
  21713. var series = opt.series;
  21714. var dataIndex = opt.dataIndex;
  21715. var multipleSeries = opt.multipleSeries;
  21716. var data = series.getData();
  21717. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  21718. var tooltipDimLen = tooltipDims.length;
  21719. var value = series.getRawValue(dataIndex);
  21720. var isValueArr = isArray(value);
  21721. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  21722. var inlineValue;
  21723. var inlineValueType;
  21724. var subBlocks;
  21725. var sortParam;
  21726. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  21727. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  21728. inlineValue = formatArrResult.inlineValues;
  21729. inlineValueType = formatArrResult.inlineValueTypes;
  21730. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  21731. sortParam = formatArrResult.inlineValues[0];
  21732. } else if (tooltipDimLen) {
  21733. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  21734. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  21735. inlineValueType = dimInfo.type;
  21736. } else {
  21737. sortParam = inlineValue = isValueArr ? value[0] : value;
  21738. } // Do not show generated series name. It might not be readable.
  21739. var seriesNameSpecified = isNameSpecified(series);
  21740. var seriesName = seriesNameSpecified && series.name || '';
  21741. var itemName = data.getName(dataIndex);
  21742. var inlineName = multipleSeries ? seriesName : itemName;
  21743. return createTooltipMarkup('section', {
  21744. header: seriesName,
  21745. // When series name not specified, do not show a header line with only '-'.
  21746. // This case alway happen in tooltip.trigger: 'item'.
  21747. noHeader: multipleSeries || !seriesNameSpecified,
  21748. sortParam: sortParam,
  21749. blocks: [createTooltipMarkup('nameValue', {
  21750. markerType: 'item',
  21751. markerColor: markerColor,
  21752. // Do not mix display seriesName and itemName in one tooltip,
  21753. // which might confuses users.
  21754. name: inlineName,
  21755. // name dimension might be auto assigned, where the name might
  21756. // be not readable. So we check trim here.
  21757. noName: !trim(inlineName),
  21758. value: inlineValue,
  21759. valueType: inlineValueType
  21760. })].concat(subBlocks || [])
  21761. });
  21762. }
  21763. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  21764. // check: category-no-encode-has-axis-data in dataset.html
  21765. var data = series.getData();
  21766. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  21767. var dimItem = data.getDimensionInfo(idx);
  21768. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21769. }, false);
  21770. var inlineValues = [];
  21771. var inlineValueTypes = [];
  21772. var blocks = [];
  21773. tooltipDims.length ? each(tooltipDims, function (dim) {
  21774. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21775. }) // By default, all dims is used on tooltip.
  21776. : each(value, setEachItem);
  21777. function setEachItem(val, dim) {
  21778. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  21779. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21780. return;
  21781. }
  21782. if (isValueMultipleLine) {
  21783. blocks.push(createTooltipMarkup('nameValue', {
  21784. markerType: 'subItem',
  21785. markerColor: colorStr,
  21786. name: dimInfo.displayName,
  21787. value: val,
  21788. valueType: dimInfo.type
  21789. }));
  21790. } else {
  21791. inlineValues.push(val);
  21792. inlineValueTypes.push(dimInfo.type);
  21793. }
  21794. }
  21795. return {
  21796. inlineValues: inlineValues,
  21797. inlineValueTypes: inlineValueTypes,
  21798. blocks: blocks
  21799. };
  21800. }
  21801. var inner$1 = makeInner();
  21802. function getSelectionKey(data, dataIndex) {
  21803. return data.getName(dataIndex) || data.getId(dataIndex);
  21804. }
  21805. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  21806. var SeriesModel =
  21807. /** @class */
  21808. function (_super) {
  21809. __extends(SeriesModel, _super);
  21810. function SeriesModel() {
  21811. // [Caution]: Becuase this class or desecendants can be used as `XXX.extend(subProto)`,
  21812. // the class members must not be initialized in constructor or declaration place.
  21813. // Otherwise there is bad case:
  21814. // class A {xxx = 1;}
  21815. // enableClassExtend(A);
  21816. // class B extends A {}
  21817. // var C = B.extend({xxx: 5});
  21818. // var c = new C();
  21819. // console.log(c.xxx); // expect 5 but always 1.
  21820. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  21821. // Props about data selection
  21822. // ---------------------------------------
  21823. _this._selectedDataIndicesMap = {};
  21824. return _this;
  21825. }
  21826. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  21827. this.seriesIndex = this.componentIndex;
  21828. this.dataTask = createTask({
  21829. count: dataTaskCount,
  21830. reset: dataTaskReset
  21831. });
  21832. this.dataTask.context = {
  21833. model: this
  21834. };
  21835. this.mergeDefaultAndTheme(option, ecModel);
  21836. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  21837. sourceManager.prepareSource();
  21838. var data = this.getInitialData(option, ecModel);
  21839. wrapData(data, this);
  21840. this.dataTask.context.data = data;
  21841. if ("development" !== 'production') {
  21842. assert(data, 'getInitialData returned invalid data.');
  21843. }
  21844. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  21845. // dataBeforeProcessed by cloneShallow), cloneShallow will
  21846. // cause data.graph.data !== data when using
  21847. // module:echarts/data/Graph or module:echarts/data/Tree.
  21848. // See module:echarts/data/helper/linkSeriesData
  21849. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  21850. // init or merge stage, because the data can be restored. So we do not `restoreData`
  21851. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  21852. // Call `seriesModel.getRawData()` instead.
  21853. // this.restoreData();
  21854. autoSeriesName(this);
  21855. this._initSelectedMapFromData(data);
  21856. };
  21857. /**
  21858. * Util for merge default and theme to option
  21859. */
  21860. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  21861. var layoutMode = fetchLayoutMode(this);
  21862. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  21863. // But if name duplicate between series subType
  21864. // (for example: parallel) add component mainType,
  21865. // add suffix 'Series'.
  21866. var themeSubType = this.subType;
  21867. if (ComponentModel.hasClass(themeSubType)) {
  21868. themeSubType += 'Series';
  21869. }
  21870. merge(option, ecModel.getTheme().get(this.subType));
  21871. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  21872. defaultEmphasis(option, 'label', ['show']);
  21873. this.fillDataTextStyle(option.data);
  21874. if (layoutMode) {
  21875. mergeLayoutParam(option, inputPositionParams, layoutMode);
  21876. }
  21877. };
  21878. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  21879. // this.settingTask.dirty();
  21880. newSeriesOption = merge(this.option, newSeriesOption, true);
  21881. this.fillDataTextStyle(newSeriesOption.data);
  21882. var layoutMode = fetchLayoutMode(this);
  21883. if (layoutMode) {
  21884. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  21885. }
  21886. var sourceManager = inner$1(this).sourceManager;
  21887. sourceManager.dirty();
  21888. sourceManager.prepareSource();
  21889. var data = this.getInitialData(newSeriesOption, ecModel);
  21890. wrapData(data, this);
  21891. this.dataTask.dirty();
  21892. this.dataTask.context.data = data;
  21893. inner$1(this).dataBeforeProcessed = data;
  21894. autoSeriesName(this);
  21895. this._initSelectedMapFromData(data);
  21896. };
  21897. SeriesModel.prototype.fillDataTextStyle = function (data) {
  21898. // Default data label emphasis `show`
  21899. // FIXME Tree structure data ?
  21900. // FIXME Performance ?
  21901. if (data && !isTypedArray(data)) {
  21902. var props = ['show'];
  21903. for (var i = 0; i < data.length; i++) {
  21904. if (data[i] && data[i].label) {
  21905. defaultEmphasis(data[i], 'label', props);
  21906. }
  21907. }
  21908. }
  21909. };
  21910. /**
  21911. * Init a data structure from data related option in series
  21912. * Must be overriden.
  21913. */
  21914. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  21915. return;
  21916. };
  21917. /**
  21918. * Append data to list
  21919. */
  21920. SeriesModel.prototype.appendData = function (params) {
  21921. // FIXME ???
  21922. // (1) If data from dataset, forbidden append.
  21923. // (2) support append data of dataset.
  21924. var data = this.getRawData();
  21925. data.appendData(params.data);
  21926. };
  21927. /**
  21928. * Consider some method like `filter`, `map` need make new data,
  21929. * We should make sure that `seriesModel.getData()` get correct
  21930. * data in the stream procedure. So we fetch data from upstream
  21931. * each time `task.perform` called.
  21932. */
  21933. SeriesModel.prototype.getData = function (dataType) {
  21934. var task = getCurrentTask(this);
  21935. if (task) {
  21936. var data = task.context.data;
  21937. return dataType == null ? data : data.getLinkedData(dataType);
  21938. } else {
  21939. // When series is not alive (that may happen when click toolbox
  21940. // restore or setOption with not merge mode), series data may
  21941. // be still need to judge animation or something when graphic
  21942. // elements want to know whether fade out.
  21943. return inner$1(this).data;
  21944. }
  21945. };
  21946. SeriesModel.prototype.getAllData = function () {
  21947. var mainData = this.getData();
  21948. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  21949. data: mainData
  21950. }];
  21951. };
  21952. SeriesModel.prototype.setData = function (data) {
  21953. var task = getCurrentTask(this);
  21954. if (task) {
  21955. var context = task.context; // Consider case: filter, data sample.
  21956. // FIXME:TS never used, so comment it
  21957. // if (context.data !== data && task.modifyOutputEnd) {
  21958. // task.setOutputEnd(data.count());
  21959. // }
  21960. context.outputData = data; // Caution: setData should update context.data,
  21961. // Because getData may be called multiply in a
  21962. // single stage and expect to get the data just
  21963. // set. (For example, AxisProxy, x y both call
  21964. // getData and setDate sequentially).
  21965. // So the context.data should be fetched from
  21966. // upstream each time when a stage starts to be
  21967. // performed.
  21968. if (task !== this.dataTask) {
  21969. context.data = data;
  21970. }
  21971. }
  21972. inner$1(this).data = data;
  21973. };
  21974. SeriesModel.prototype.getEncode = function () {
  21975. var encode = this.get('encode', true);
  21976. if (encode) {
  21977. return createHashMap(encode);
  21978. }
  21979. };
  21980. SeriesModel.prototype.getSourceManager = function () {
  21981. return inner$1(this).sourceManager;
  21982. };
  21983. SeriesModel.prototype.getSource = function () {
  21984. return this.getSourceManager().getSource();
  21985. };
  21986. /**
  21987. * Get data before processed
  21988. */
  21989. SeriesModel.prototype.getRawData = function () {
  21990. return inner$1(this).dataBeforeProcessed;
  21991. };
  21992. SeriesModel.prototype.getColorBy = function () {
  21993. var colorBy = this.get('colorBy');
  21994. return colorBy || 'series';
  21995. };
  21996. SeriesModel.prototype.isColorBySeries = function () {
  21997. return this.getColorBy() === 'series';
  21998. };
  21999. /**
  22000. * Get base axis if has coordinate system and has axis.
  22001. * By default use coordSys.getBaseAxis();
  22002. * Can be overrided for some chart.
  22003. * @return {type} description
  22004. */
  22005. SeriesModel.prototype.getBaseAxis = function () {
  22006. var coordSys = this.coordinateSystem; // @ts-ignore
  22007. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  22008. };
  22009. /**
  22010. * Default tooltip formatter
  22011. *
  22012. * @param dataIndex
  22013. * @param multipleSeries
  22014. * @param dataType
  22015. * @param renderMode valid values: 'html'(by default) and 'richText'.
  22016. * 'html' is used for rendering tooltip in extra DOM form, and the result
  22017. * string is used as DOM HTML content.
  22018. * 'richText' is used for rendering tooltip in rich text form, for those where
  22019. * DOM operation is not supported.
  22020. * @return formatted tooltip with `html` and `markers`
  22021. * Notice: The override method can also return string
  22022. */
  22023. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  22024. return defaultSeriesFormatTooltip({
  22025. series: this,
  22026. dataIndex: dataIndex,
  22027. multipleSeries: multipleSeries
  22028. });
  22029. };
  22030. SeriesModel.prototype.isAnimationEnabled = function () {
  22031. if (env.node) {
  22032. return false;
  22033. }
  22034. var animationEnabled = this.getShallow('animation');
  22035. if (animationEnabled) {
  22036. if (this.getData().count() > this.getShallow('animationThreshold')) {
  22037. animationEnabled = false;
  22038. }
  22039. }
  22040. return !!animationEnabled;
  22041. };
  22042. SeriesModel.prototype.restoreData = function () {
  22043. this.dataTask.dirty();
  22044. };
  22045. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  22046. var ecModel = this.ecModel; // PENDING
  22047. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  22048. if (!color) {
  22049. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  22050. }
  22051. return color;
  22052. };
  22053. /**
  22054. * Use `data.mapDimensionsAll(coordDim)` instead.
  22055. * @deprecated
  22056. */
  22057. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  22058. return this.getRawData().mapDimensionsAll(coordDim);
  22059. };
  22060. /**
  22061. * Get progressive rendering count each step
  22062. */
  22063. SeriesModel.prototype.getProgressive = function () {
  22064. return this.get('progressive');
  22065. };
  22066. /**
  22067. * Get progressive rendering count each step
  22068. */
  22069. SeriesModel.prototype.getProgressiveThreshold = function () {
  22070. return this.get('progressiveThreshold');
  22071. }; // PENGING If selectedMode is null ?
  22072. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  22073. this._innerSelect(this.getData(dataType), innerDataIndices);
  22074. };
  22075. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  22076. var selectedMap = this.option.selectedMap;
  22077. if (!selectedMap) {
  22078. return;
  22079. }
  22080. var data = this.getData(dataType);
  22081. for (var i = 0; i < innerDataIndices.length; i++) {
  22082. var dataIndex = innerDataIndices[i];
  22083. var nameOrId = getSelectionKey(data, dataIndex);
  22084. selectedMap[nameOrId] = false;
  22085. this._selectedDataIndicesMap[nameOrId] = -1;
  22086. }
  22087. };
  22088. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  22089. var tmpArr = [];
  22090. for (var i = 0; i < innerDataIndices.length; i++) {
  22091. tmpArr[0] = innerDataIndices[i];
  22092. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  22093. }
  22094. };
  22095. SeriesModel.prototype.getSelectedDataIndices = function () {
  22096. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  22097. var nameOrIds = keys(selectedDataIndicesMap);
  22098. var dataIndices = [];
  22099. for (var i = 0; i < nameOrIds.length; i++) {
  22100. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  22101. if (dataIndex >= 0) {
  22102. dataIndices.push(dataIndex);
  22103. }
  22104. }
  22105. return dataIndices;
  22106. };
  22107. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  22108. var selectedMap = this.option.selectedMap;
  22109. if (!selectedMap) {
  22110. return false;
  22111. }
  22112. var data = this.getData(dataType);
  22113. var nameOrId = getSelectionKey(data, dataIndex);
  22114. return selectedMap[nameOrId] || false;
  22115. };
  22116. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  22117. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  22118. return true;
  22119. }
  22120. var universalTransitionOpt = this.option.universalTransition; // Quick reject
  22121. if (!universalTransitionOpt) {
  22122. return false;
  22123. }
  22124. if (universalTransitionOpt === true) {
  22125. return true;
  22126. } // Can be simply 'universalTransition: true'
  22127. return universalTransitionOpt && universalTransitionOpt.enabled;
  22128. };
  22129. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  22130. var _a, _b;
  22131. var selectedMode = this.option.selectedMode;
  22132. var len = innerDataIndices.length;
  22133. if (!selectedMode || !len) {
  22134. return;
  22135. }
  22136. if (selectedMode === 'multiple') {
  22137. var selectedMap = this.option.selectedMap || (this.option.selectedMap = {});
  22138. for (var i = 0; i < len; i++) {
  22139. var dataIndex = innerDataIndices[i]; // TODO diffrent types of data share same object.
  22140. var nameOrId = getSelectionKey(data, dataIndex);
  22141. selectedMap[nameOrId] = true;
  22142. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  22143. }
  22144. } else if (selectedMode === 'single' || selectedMode === true) {
  22145. var lastDataIndex = innerDataIndices[len - 1];
  22146. var nameOrId = getSelectionKey(data, lastDataIndex);
  22147. this.option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  22148. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  22149. }
  22150. };
  22151. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  22152. // Ignore select info in data if selectedMap exists.
  22153. // NOTE It's only for legacy usage. edge data is not supported.
  22154. if (this.option.selectedMap) {
  22155. return;
  22156. }
  22157. var dataIndices = [];
  22158. if (data.hasItemOption) {
  22159. data.each(function (idx) {
  22160. var rawItem = data.getRawDataItem(idx);
  22161. if (rawItem && rawItem.selected) {
  22162. dataIndices.push(idx);
  22163. }
  22164. });
  22165. }
  22166. if (dataIndices.length > 0) {
  22167. this._innerSelect(data, dataIndices);
  22168. }
  22169. }; // /**
  22170. // * @see {module:echarts/stream/Scheduler}
  22171. // */
  22172. // abstract pipeTask: null
  22173. SeriesModel.registerClass = function (clz) {
  22174. return ComponentModel.registerClass(clz);
  22175. };
  22176. SeriesModel.protoInitialize = function () {
  22177. var proto = SeriesModel.prototype;
  22178. proto.type = 'series.__base__';
  22179. proto.seriesIndex = 0;
  22180. proto.ignoreStyleOnData = false;
  22181. proto.hasSymbolVisual = false;
  22182. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  22183. proto.visualStyleAccessPath = 'itemStyle';
  22184. proto.visualDrawType = 'fill';
  22185. }();
  22186. return SeriesModel;
  22187. }(ComponentModel);
  22188. mixin(SeriesModel, DataFormatMixin);
  22189. mixin(SeriesModel, PaletteMixin);
  22190. mountExtend(SeriesModel, ComponentModel);
  22191. /**
  22192. * MUST be called after `prepareSource` called
  22193. * Here we need to make auto series, especially for auto legend. But we
  22194. * do not modify series.name in option to avoid side effects.
  22195. */
  22196. function autoSeriesName(seriesModel) {
  22197. // User specified name has higher priority, otherwise it may cause
  22198. // series can not be queried unexpectedly.
  22199. var name = seriesModel.name;
  22200. if (!isNameSpecified(seriesModel)) {
  22201. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  22202. }
  22203. }
  22204. function getSeriesAutoName(seriesModel) {
  22205. var data = seriesModel.getRawData();
  22206. var dataDims = data.mapDimensionsAll('seriesName');
  22207. var nameArr = [];
  22208. each(dataDims, function (dataDim) {
  22209. var dimInfo = data.getDimensionInfo(dataDim);
  22210. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  22211. });
  22212. return nameArr.join(' ');
  22213. }
  22214. function dataTaskCount(context) {
  22215. return context.model.getRawData().count();
  22216. }
  22217. function dataTaskReset(context) {
  22218. var seriesModel = context.model;
  22219. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  22220. return dataTaskProgress;
  22221. }
  22222. function dataTaskProgress(param, context) {
  22223. // Avoid repead cloneShallow when data just created in reset.
  22224. if (context.outputData && param.end > context.outputData.count()) {
  22225. context.model.getRawData().cloneShallow(context.outputData);
  22226. }
  22227. } // TODO refactor
  22228. function wrapData(data, seriesModel) {
  22229. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  22230. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  22231. });
  22232. }
  22233. function onDataChange(seriesModel, newList) {
  22234. var task = getCurrentTask(seriesModel);
  22235. if (task) {
  22236. // Consider case: filter, selectRange
  22237. task.setOutputEnd((newList || this).count());
  22238. }
  22239. return newList;
  22240. }
  22241. function getCurrentTask(seriesModel) {
  22242. var scheduler = (seriesModel.ecModel || {}).scheduler;
  22243. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  22244. if (pipeline) {
  22245. // When pipline finished, the currrentTask keep the last
  22246. // task (renderTask).
  22247. var task = pipeline.currentTask;
  22248. if (task) {
  22249. var agentStubMap = task.agentStubMap;
  22250. if (agentStubMap) {
  22251. task = agentStubMap.get(seriesModel.uid);
  22252. }
  22253. }
  22254. return task;
  22255. }
  22256. }
  22257. var ComponentView =
  22258. /** @class */
  22259. function () {
  22260. function ComponentView() {
  22261. this.group = new Group();
  22262. this.uid = getUID('viewComponent');
  22263. }
  22264. ComponentView.prototype.init = function (ecModel, api) {};
  22265. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  22266. ComponentView.prototype.dispose = function (ecModel, api) {};
  22267. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  22268. };
  22269. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  22270. };
  22271. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  22272. };
  22273. /**
  22274. * Hook for blur target series.
  22275. * Can be used in marker for blur the markers
  22276. */
  22277. ComponentView.prototype.blurSeries = function (seriesModels, ecModel) {// Do nothing;
  22278. };
  22279. return ComponentView;
  22280. }();
  22281. enableClassExtend(ComponentView);
  22282. enableClassManagement(ComponentView);
  22283. /**
  22284. * @return {string} If large mode changed, return string 'reset';
  22285. */
  22286. function createRenderPlanner() {
  22287. var inner = makeInner();
  22288. return function (seriesModel) {
  22289. var fields = inner(seriesModel);
  22290. var pipelineContext = seriesModel.pipelineContext;
  22291. var originalLarge = !!fields.large;
  22292. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  22293. // exists. See #11611 . Probably we need to modify this structure, see the comment
  22294. // on `performRawSeries` in `Schedular.js`.
  22295. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  22296. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  22297. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  22298. };
  22299. }
  22300. var inner$2 = makeInner();
  22301. var renderPlanner = createRenderPlanner();
  22302. var ChartView =
  22303. /** @class */
  22304. function () {
  22305. function ChartView() {
  22306. this.group = new Group();
  22307. this.uid = getUID('viewChart');
  22308. this.renderTask = createTask({
  22309. plan: renderTaskPlan,
  22310. reset: renderTaskReset
  22311. });
  22312. this.renderTask.context = {
  22313. view: this
  22314. };
  22315. }
  22316. ChartView.prototype.init = function (ecModel, api) {};
  22317. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {};
  22318. /**
  22319. * Highlight series or specified data item.
  22320. */
  22321. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  22322. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  22323. };
  22324. /**
  22325. * Downplay series or specified data item.
  22326. */
  22327. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  22328. toggleHighlight(seriesModel.getData(), payload, 'normal');
  22329. };
  22330. /**
  22331. * Remove self.
  22332. */
  22333. ChartView.prototype.remove = function (ecModel, api) {
  22334. this.group.removeAll();
  22335. };
  22336. /**
  22337. * Dispose self.
  22338. */
  22339. ChartView.prototype.dispose = function (ecModel, api) {};
  22340. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  22341. this.render(seriesModel, ecModel, api, payload);
  22342. }; // FIXME never used?
  22343. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  22344. this.render(seriesModel, ecModel, api, payload);
  22345. }; // FIXME never used?
  22346. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  22347. this.render(seriesModel, ecModel, api, payload);
  22348. };
  22349. ChartView.markUpdateMethod = function (payload, methodName) {
  22350. inner$2(payload).updateMethod = methodName;
  22351. };
  22352. ChartView.protoInitialize = function () {
  22353. var proto = ChartView.prototype;
  22354. proto.type = 'chart';
  22355. }();
  22356. return ChartView;
  22357. }();
  22358. /**
  22359. * Set state of single element
  22360. */
  22361. function elSetState(el, state, highlightDigit) {
  22362. if (el) {
  22363. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  22364. }
  22365. }
  22366. function toggleHighlight(data, payload, state) {
  22367. var dataIndex = queryDataIndex(data, payload);
  22368. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  22369. if (dataIndex != null) {
  22370. each(normalizeToArray(dataIndex), function (dataIdx) {
  22371. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22372. });
  22373. } else {
  22374. data.eachItemGraphicEl(function (el) {
  22375. elSetState(el, state, highlightDigit);
  22376. });
  22377. }
  22378. }
  22379. enableClassExtend(ChartView, ['dispose']);
  22380. enableClassManagement(ChartView);
  22381. function renderTaskPlan(context) {
  22382. return renderPlanner(context.model);
  22383. }
  22384. function renderTaskReset(context) {
  22385. var seriesModel = context.model;
  22386. var ecModel = context.ecModel;
  22387. var api = context.api;
  22388. var payload = context.payload; // FIXME: remove updateView updateVisual
  22389. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22390. var view = context.view;
  22391. var updateMethod = payload && inner$2(payload).updateMethod;
  22392. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  22393. // is less than progressive threshold.
  22394. : 'render';
  22395. if (methodName !== 'render') {
  22396. view[methodName](seriesModel, ecModel, api, payload);
  22397. }
  22398. return progressMethodMap[methodName];
  22399. }
  22400. var progressMethodMap = {
  22401. incrementalPrepareRender: {
  22402. progress: function (params, context) {
  22403. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  22404. }
  22405. },
  22406. render: {
  22407. // Put view.render in `progress` to support appendData. But in this case
  22408. // view.render should not be called in reset, otherwise it will be called
  22409. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22410. // in any cases.
  22411. forceFirstProgress: true,
  22412. progress: function (params, context) {
  22413. context.view.render(context.model, context.ecModel, context.api, context.payload);
  22414. }
  22415. }
  22416. };
  22417. /*
  22418. * Licensed to the Apache Software Foundation (ASF) under one
  22419. * or more contributor license agreements. See the NOTICE file
  22420. * distributed with this work for additional information
  22421. * regarding copyright ownership. The ASF licenses this file
  22422. * to you under the Apache License, Version 2.0 (the
  22423. * "License"); you may not use this file except in compliance
  22424. * with the License. You may obtain a copy of the License at
  22425. *
  22426. * http://www.apache.org/licenses/LICENSE-2.0
  22427. *
  22428. * Unless required by applicable law or agreed to in writing,
  22429. * software distributed under the License is distributed on an
  22430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22431. * KIND, either express or implied. See the License for the
  22432. * specific language governing permissions and limitations
  22433. * under the License.
  22434. */
  22435. /**
  22436. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22437. */
  22438. /*
  22439. * Licensed to the Apache Software Foundation (ASF) under one
  22440. * or more contributor license agreements. See the NOTICE file
  22441. * distributed with this work for additional information
  22442. * regarding copyright ownership. The ASF licenses this file
  22443. * to you under the Apache License, Version 2.0 (the
  22444. * "License"); you may not use this file except in compliance
  22445. * with the License. You may obtain a copy of the License at
  22446. *
  22447. * http://www.apache.org/licenses/LICENSE-2.0
  22448. *
  22449. * Unless required by applicable law or agreed to in writing,
  22450. * software distributed under the License is distributed on an
  22451. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22452. * KIND, either express or implied. See the License for the
  22453. * specific language governing permissions and limitations
  22454. * under the License.
  22455. */
  22456. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22457. var RATE = '\0__throttleRate';
  22458. var THROTTLE_TYPE = '\0__throttleType';
  22459. /**
  22460. * @public
  22461. * @param {(Function)} fn
  22462. * @param {number} [delay=0] Unit: ms.
  22463. * @param {boolean} [debounce=false]
  22464. * true: If call interval less than `delay`, only the last call works.
  22465. * false: If call interval less than `delay, call works on fixed rate.
  22466. * @return {(Function)} throttled fn.
  22467. */
  22468. function throttle(fn, delay, debounce) {
  22469. var currCall;
  22470. var lastCall = 0;
  22471. var lastExec = 0;
  22472. var timer = null;
  22473. var diff;
  22474. var scope;
  22475. var args;
  22476. var debounceNextCall;
  22477. delay = delay || 0;
  22478. function exec() {
  22479. lastExec = new Date().getTime();
  22480. timer = null;
  22481. fn.apply(scope, args || []);
  22482. }
  22483. var cb = function () {
  22484. var cbArgs = [];
  22485. for (var _i = 0; _i < arguments.length; _i++) {
  22486. cbArgs[_i] = arguments[_i];
  22487. }
  22488. currCall = new Date().getTime();
  22489. scope = this;
  22490. args = cbArgs;
  22491. var thisDelay = debounceNextCall || delay;
  22492. var thisDebounce = debounceNextCall || debounce;
  22493. debounceNextCall = null;
  22494. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22495. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  22496. // than a new call of `cb`, that is, preserving the command order. Consider
  22497. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22498. // happens, either the `exec` is called dierectly, or the call is delayed.
  22499. // But the delayed call should never be later than next call of `cb`. Under
  22500. // this assurance, we can simply update view state each time `dispatchAction`
  22501. // triggered by user roaming, but not need to add extra code to avoid the
  22502. // state being "rolled-back".
  22503. if (thisDebounce) {
  22504. timer = setTimeout(exec, thisDelay);
  22505. } else {
  22506. if (diff >= 0) {
  22507. exec();
  22508. } else {
  22509. timer = setTimeout(exec, -diff);
  22510. }
  22511. }
  22512. lastCall = currCall;
  22513. };
  22514. /**
  22515. * Clear throttle.
  22516. * @public
  22517. */
  22518. cb.clear = function () {
  22519. if (timer) {
  22520. clearTimeout(timer);
  22521. timer = null;
  22522. }
  22523. };
  22524. /**
  22525. * Enable debounce once.
  22526. */
  22527. cb.debounceNextCall = function (debounceDelay) {
  22528. debounceNextCall = debounceDelay;
  22529. };
  22530. return cb;
  22531. }
  22532. /**
  22533. * Create throttle method or update throttle rate.
  22534. *
  22535. * @example
  22536. * ComponentView.prototype.render = function () {
  22537. * ...
  22538. * throttle.createOrUpdate(
  22539. * this,
  22540. * '_dispatchAction',
  22541. * this.model.get('throttle'),
  22542. * 'fixRate'
  22543. * );
  22544. * };
  22545. * ComponentView.prototype.remove = function () {
  22546. * throttle.clear(this, '_dispatchAction');
  22547. * };
  22548. * ComponentView.prototype.dispose = function () {
  22549. * throttle.clear(this, '_dispatchAction');
  22550. * };
  22551. *
  22552. */
  22553. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22554. var fn = obj[fnAttr];
  22555. if (!fn) {
  22556. return;
  22557. }
  22558. var originFn = fn[ORIGIN_METHOD] || fn;
  22559. var lastThrottleType = fn[THROTTLE_TYPE];
  22560. var lastRate = fn[RATE];
  22561. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22562. if (rate == null || !throttleType) {
  22563. return obj[fnAttr] = originFn;
  22564. }
  22565. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  22566. fn[ORIGIN_METHOD] = originFn;
  22567. fn[THROTTLE_TYPE] = throttleType;
  22568. fn[RATE] = rate;
  22569. }
  22570. return fn;
  22571. }
  22572. /**
  22573. * Clear throttle. Example see throttle.createOrUpdate.
  22574. */
  22575. function clear(obj, fnAttr) {
  22576. var fn = obj[fnAttr];
  22577. if (fn && fn[ORIGIN_METHOD]) {
  22578. obj[fnAttr] = fn[ORIGIN_METHOD];
  22579. }
  22580. }
  22581. var inner$3 = makeInner();
  22582. var defaultStyleMappers = {
  22583. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  22584. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  22585. };
  22586. var defaultColorKey = {
  22587. lineStyle: 'stroke',
  22588. itemStyle: 'fill'
  22589. };
  22590. function getStyleMapper(seriesModel, stylePath) {
  22591. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  22592. if (!styleMapper) {
  22593. console.warn("Unkown style type '" + stylePath + "'.");
  22594. return defaultStyleMappers.itemStyle;
  22595. }
  22596. return styleMapper;
  22597. }
  22598. function getDefaultColorKey(seriesModel, stylePath) {
  22599. // return defaultColorKey[stylePath] ||
  22600. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  22601. if (!colorKey) {
  22602. console.warn("Unkown style type '" + stylePath + "'.");
  22603. return 'fill';
  22604. }
  22605. return colorKey;
  22606. }
  22607. var seriesStyleTask = {
  22608. createOnAllSeries: true,
  22609. performRawSeries: true,
  22610. reset: function (seriesModel, ecModel) {
  22611. var data = seriesModel.getData();
  22612. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22613. var styleModel = seriesModel.getModel(stylePath);
  22614. var getStyle = getStyleMapper(seriesModel, stylePath);
  22615. var globalStyle = getStyle(styleModel);
  22616. var decalOption = styleModel.getShallow('decal');
  22617. if (decalOption) {
  22618. data.setVisual('decal', decalOption);
  22619. decalOption.dirty = true;
  22620. } // TODO
  22621. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22622. var color = globalStyle[colorKey]; // TODO style callback
  22623. var colorCallback = isFunction(color) ? color : null;
  22624. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto'; // Get from color palette by default.
  22625. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  22626. // Note: if some series has color specified (e.g., by itemStyle.color), we DO NOT
  22627. // make it effect palette. Bacause some scenarios users need to make some series
  22628. // transparent or as background, which should better not effect the palette.
  22629. var colorPalette = seriesModel.getColorFromPalette( // TODO series count changed.
  22630. seriesModel.name, null, ecModel.getSeriesCount());
  22631. if (!globalStyle[colorKey]) {
  22632. globalStyle[colorKey] = colorPalette;
  22633. data.setVisual('colorFromPalette', true);
  22634. }
  22635. globalStyle.fill = globalStyle.fill === 'auto' || typeof globalStyle.fill === 'function' ? colorPalette : globalStyle.fill;
  22636. globalStyle.stroke = globalStyle.stroke === 'auto' || typeof globalStyle.stroke === 'function' ? colorPalette : globalStyle.stroke;
  22637. }
  22638. data.setVisual('style', globalStyle);
  22639. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  22640. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  22641. data.setVisual('colorFromPalette', false);
  22642. return {
  22643. dataEach: function (data, idx) {
  22644. var dataParams = seriesModel.getDataParams(idx);
  22645. var itemStyle = extend({}, globalStyle);
  22646. itemStyle[colorKey] = colorCallback(dataParams);
  22647. data.setItemVisual(idx, 'style', itemStyle);
  22648. }
  22649. };
  22650. }
  22651. }
  22652. };
  22653. var sharedModel = new Model();
  22654. var dataStyleTask = {
  22655. createOnAllSeries: true,
  22656. performRawSeries: true,
  22657. reset: function (seriesModel, ecModel) {
  22658. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  22659. return;
  22660. }
  22661. var data = seriesModel.getData();
  22662. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22663. var getStyle = getStyleMapper(seriesModel, stylePath);
  22664. var colorKey = data.getVisual('drawType');
  22665. return {
  22666. dataEach: data.hasItemOption ? function (data, idx) {
  22667. // Not use getItemModel for performance considuration
  22668. var rawItem = data.getRawDataItem(idx);
  22669. if (rawItem && rawItem[stylePath]) {
  22670. sharedModel.option = rawItem[stylePath];
  22671. var style = getStyle(sharedModel);
  22672. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  22673. extend(existsStyle, style);
  22674. if (sharedModel.option.decal) {
  22675. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  22676. sharedModel.option.decal.dirty = true;
  22677. }
  22678. if (colorKey in style) {
  22679. data.setItemVisual(idx, 'colorFromPalette', false);
  22680. }
  22681. }
  22682. } : null
  22683. };
  22684. }
  22685. }; // Pick color from palette for the data which has not been set with color yet.
  22686. // Note: do not support stream rendering. No such cases yet.
  22687. var dataColorPaletteTask = {
  22688. performRawSeries: true,
  22689. overallReset: function (ecModel) {
  22690. // Each type of series use one scope.
  22691. // Pie and funnel are using diferrent scopes
  22692. var paletteScopeGroupByType = createHashMap();
  22693. ecModel.eachSeries(function (seriesModel) {
  22694. var colorBy = seriesModel.getColorBy();
  22695. if (seriesModel.isColorBySeries()) {
  22696. return;
  22697. }
  22698. var key = seriesModel.type + '-' + colorBy;
  22699. var colorScope = paletteScopeGroupByType.get(key);
  22700. if (!colorScope) {
  22701. colorScope = {};
  22702. paletteScopeGroupByType.set(key, colorScope);
  22703. }
  22704. inner$3(seriesModel).scope = colorScope;
  22705. });
  22706. ecModel.eachSeries(function (seriesModel) {
  22707. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  22708. return;
  22709. }
  22710. var dataAll = seriesModel.getRawData();
  22711. var idxMap = {};
  22712. var data = seriesModel.getData();
  22713. var colorScope = inner$3(seriesModel).scope;
  22714. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  22715. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22716. data.each(function (idx) {
  22717. var rawIdx = data.getRawIndex(idx);
  22718. idxMap[rawIdx] = idx;
  22719. }); // Iterate on data before filtered. To make sure color from palette can be
  22720. // Consistent when toggling legend.
  22721. dataAll.each(function (rawIdx) {
  22722. var idx = idxMap[rawIdx];
  22723. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  22724. // also picked from color palette. So following situation is not in the case:
  22725. // 1. series.itemStyle.color is set
  22726. // 2. color is encoded by visualMap
  22727. if (fromPalette) {
  22728. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  22729. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  22730. var dataCount = dataAll.count();
  22731. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  22732. }
  22733. });
  22734. });
  22735. }
  22736. };
  22737. var PI$3 = Math.PI;
  22738. /**
  22739. * @param {module:echarts/ExtensionAPI} api
  22740. * @param {Object} [opts]
  22741. * @param {string} [opts.text]
  22742. * @param {string} [opts.color]
  22743. * @param {string} [opts.textColor]
  22744. * @return {module:zrender/Element}
  22745. */
  22746. function defaultLoading(api, opts) {
  22747. opts = opts || {};
  22748. defaults(opts, {
  22749. text: 'loading',
  22750. textColor: '#000',
  22751. fontSize: 12,
  22752. fontWeight: 'normal',
  22753. fontStyle: 'normal',
  22754. fontFamily: 'sans-serif',
  22755. maskColor: 'rgba(255, 255, 255, 0.8)',
  22756. showSpinner: true,
  22757. color: '#5470c6',
  22758. spinnerRadius: 10,
  22759. lineWidth: 5,
  22760. zlevel: 0
  22761. });
  22762. var group = new Group();
  22763. var mask = new Rect({
  22764. style: {
  22765. fill: opts.maskColor
  22766. },
  22767. zlevel: opts.zlevel,
  22768. z: 10000
  22769. });
  22770. group.add(mask);
  22771. var textContent = new ZRText({
  22772. style: {
  22773. text: opts.text,
  22774. fill: opts.textColor,
  22775. fontSize: opts.fontSize,
  22776. fontWeight: opts.fontWeight,
  22777. fontStyle: opts.fontStyle,
  22778. fontFamily: opts.fontFamily
  22779. },
  22780. zlevel: opts.zlevel,
  22781. z: 10001
  22782. });
  22783. var labelRect = new Rect({
  22784. style: {
  22785. fill: 'none'
  22786. },
  22787. textContent: textContent,
  22788. textConfig: {
  22789. position: 'right',
  22790. distance: 10
  22791. },
  22792. zlevel: opts.zlevel,
  22793. z: 10001
  22794. });
  22795. group.add(labelRect);
  22796. var arc;
  22797. if (opts.showSpinner) {
  22798. arc = new Arc({
  22799. shape: {
  22800. startAngle: -PI$3 / 2,
  22801. endAngle: -PI$3 / 2 + 0.1,
  22802. r: opts.spinnerRadius
  22803. },
  22804. style: {
  22805. stroke: opts.color,
  22806. lineCap: 'round',
  22807. lineWidth: opts.lineWidth
  22808. },
  22809. zlevel: opts.zlevel,
  22810. z: 10001
  22811. });
  22812. arc.animateShape(true).when(1000, {
  22813. endAngle: PI$3 * 3 / 2
  22814. }).start('circularInOut');
  22815. arc.animateShape(true).when(1000, {
  22816. startAngle: PI$3 * 3 / 2
  22817. }).delay(300).start('circularInOut');
  22818. group.add(arc);
  22819. } // Inject resize
  22820. group.resize = function () {
  22821. var textWidth = textContent.getBoundingRect().width;
  22822. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  22823. // textDistance needs to be calculated when both animation and text exist
  22824. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  22825. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  22826. + (textWidth ? 0 : r);
  22827. var cy = api.getHeight() / 2;
  22828. opts.showSpinner && arc.setShape({
  22829. cx: cx,
  22830. cy: cy
  22831. });
  22832. labelRect.setShape({
  22833. x: cx - r,
  22834. y: cy - r,
  22835. width: r * 2,
  22836. height: r * 2
  22837. });
  22838. mask.setShape({
  22839. x: 0,
  22840. y: 0,
  22841. width: api.getWidth(),
  22842. height: api.getHeight()
  22843. });
  22844. };
  22845. group.resize();
  22846. return group;
  22847. }
  22848. var Scheduler =
  22849. /** @class */
  22850. function () {
  22851. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22852. // key: handlerUID
  22853. this._stageTaskMap = createHashMap();
  22854. this.ecInstance = ecInstance;
  22855. this.api = api; // Fix current processors in case that in some rear cases that
  22856. // processors might be registered after echarts instance created.
  22857. // Register processors incrementally for a echarts instance is
  22858. // not supported by this stream architecture.
  22859. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22860. visualHandlers = this._visualHandlers = visualHandlers.slice();
  22861. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22862. }
  22863. Scheduler.prototype.restoreData = function (ecModel, payload) {
  22864. // TODO: Only restore needed series and components, but not all components.
  22865. // Currently `restoreData` of all of the series and component will be called.
  22866. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22867. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22868. // and some components like coordinate system, axes, dataZoom, visualMap only
  22869. // need their target series refresh.
  22870. // (1) If we are implementing this feature some day, we should consider these cases:
  22871. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22872. // on the settings of `dataZoom`), it should be re-performed if the component
  22873. // is modified by `setOption`.
  22874. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22875. // it should be re-performed when the result array of `getTargetSeries` changed.
  22876. // We use `dependencies` to cover these issues.
  22877. // (3) How to update target series when coordinate system related components modified.
  22878. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22879. // and this case all of the tasks will be set as dirty.
  22880. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  22881. // depends on all of the series.
  22882. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22883. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22884. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22885. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22886. // probably cause state chaos (consider `dataZoomProcessor`).
  22887. this._stageTaskMap.each(function (taskRecord) {
  22888. var overallTask = taskRecord.overallTask;
  22889. overallTask && overallTask.dirty();
  22890. });
  22891. }; // If seriesModel provided, incremental threshold is check by series data.
  22892. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  22893. // For overall task
  22894. if (!task.__pipeline) {
  22895. return;
  22896. }
  22897. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22898. var pCtx = pipeline.context;
  22899. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  22900. var step = incremental ? pipeline.step : null;
  22901. var modDataCount = pCtx && pCtx.modDataCount;
  22902. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22903. return {
  22904. step: step,
  22905. modBy: modBy,
  22906. modDataCount: modDataCount
  22907. };
  22908. };
  22909. Scheduler.prototype.getPipeline = function (pipelineId) {
  22910. return this._pipelineMap.get(pipelineId);
  22911. };
  22912. /**
  22913. * Current, progressive rendering starts from visual and layout.
  22914. * Always detect render mode in the same stage, avoiding that incorrect
  22915. * detection caused by data filtering.
  22916. * Caution:
  22917. * `updateStreamModes` use `seriesModel.getData()`.
  22918. */
  22919. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  22920. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22921. var data = seriesModel.getData();
  22922. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  22923. // animation frame. Note that some types of series do not provide
  22924. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22925. // use the term `incremental` but not `progressive` to describe the
  22926. // case that `chart.appendData`.
  22927. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  22928. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22929. // see `test/candlestick-large3.html`
  22930. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22931. seriesModel.pipelineContext = pipeline.context = {
  22932. progressiveRender: progressiveRender,
  22933. modDataCount: modDataCount,
  22934. large: large
  22935. };
  22936. };
  22937. Scheduler.prototype.restorePipelines = function (ecModel) {
  22938. var scheduler = this;
  22939. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22940. ecModel.eachSeries(function (seriesModel) {
  22941. var progressive = seriesModel.getProgressive();
  22942. var pipelineId = seriesModel.uid;
  22943. pipelineMap.set(pipelineId, {
  22944. id: pipelineId,
  22945. head: null,
  22946. tail: null,
  22947. threshold: seriesModel.getProgressiveThreshold(),
  22948. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22949. blockIndex: -1,
  22950. step: Math.round(progressive || 700),
  22951. count: 0
  22952. });
  22953. scheduler._pipe(seriesModel, seriesModel.dataTask);
  22954. });
  22955. };
  22956. Scheduler.prototype.prepareStageTasks = function () {
  22957. var stageTaskMap = this._stageTaskMap;
  22958. var ecModel = this.api.getModel();
  22959. var api = this.api;
  22960. each(this._allHandlers, function (handler) {
  22961. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  22962. var errMsg = '';
  22963. if ("development" !== 'production') {
  22964. // Currently do not need to support to sepecify them both.
  22965. errMsg = '"reset" and "overallReset" must not be both specified.';
  22966. }
  22967. assert(!(handler.reset && handler.overallReset), errMsg);
  22968. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  22969. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  22970. }, this);
  22971. };
  22972. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  22973. var renderTask = view.renderTask;
  22974. var context = renderTask.context;
  22975. context.model = model;
  22976. context.ecModel = ecModel;
  22977. context.api = api;
  22978. renderTask.__block = !view.incrementalPrepareRender;
  22979. this._pipe(model, renderTask);
  22980. };
  22981. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  22982. // If we do not use `block` here, it should be considered when to update modes.
  22983. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  22984. block: true
  22985. });
  22986. };
  22987. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  22988. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  22989. };
  22990. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  22991. opt = opt || {};
  22992. var unfinished = false;
  22993. var scheduler = this;
  22994. each(stageHandlers, function (stageHandler, idx) {
  22995. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22996. return;
  22997. }
  22998. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22999. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23000. var overallTask = stageHandlerRecord.overallTask;
  23001. if (overallTask) {
  23002. var overallNeedDirty_1;
  23003. var agentStubMap = overallTask.agentStubMap;
  23004. agentStubMap.each(function (stub) {
  23005. if (needSetDirty(opt, stub)) {
  23006. stub.dirty();
  23007. overallNeedDirty_1 = true;
  23008. }
  23009. });
  23010. overallNeedDirty_1 && overallTask.dirty();
  23011. scheduler.updatePayload(overallTask, payload);
  23012. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  23013. // then execute the overall task. And stub will call seriesModel.setData,
  23014. // which ensures that in the overallTask seriesModel.getData() will not
  23015. // return incorrect data.
  23016. agentStubMap.each(function (stub) {
  23017. stub.perform(performArgs_1);
  23018. });
  23019. if (overallTask.perform(performArgs_1)) {
  23020. unfinished = true;
  23021. }
  23022. } else if (seriesTaskMap) {
  23023. seriesTaskMap.each(function (task, pipelineId) {
  23024. if (needSetDirty(opt, task)) {
  23025. task.dirty();
  23026. }
  23027. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  23028. // if intending to decalare `performRawSeries` in handlers, only
  23029. // stream-independent (specifically, data item independent) operations can be
  23030. // performed. Because is a series is filtered, most of the tasks will not
  23031. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23032. // Perhaps we should not provide a separate callback for this case instead
  23033. // of providing the config `performRawSeries`. The stream-dependent operaions
  23034. // and stream-independent operations should better not be mixed.
  23035. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  23036. scheduler.updatePayload(task, payload);
  23037. if (task.perform(performArgs)) {
  23038. unfinished = true;
  23039. }
  23040. });
  23041. }
  23042. });
  23043. function needSetDirty(opt, task) {
  23044. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23045. }
  23046. this.unfinished = unfinished || this.unfinished;
  23047. };
  23048. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  23049. var unfinished;
  23050. ecModel.eachSeries(function (seriesModel) {
  23051. // Progress to the end for dataInit and dataRestore.
  23052. unfinished = seriesModel.dataTask.perform() || unfinished;
  23053. });
  23054. this.unfinished = unfinished || this.unfinished;
  23055. };
  23056. Scheduler.prototype.plan = function () {
  23057. // Travel pipelines, check block.
  23058. this._pipelineMap.each(function (pipeline) {
  23059. var task = pipeline.tail;
  23060. do {
  23061. if (task.__block) {
  23062. pipeline.blockIndex = task.__idxInPipeline;
  23063. break;
  23064. }
  23065. task = task.getUpstream();
  23066. } while (task);
  23067. });
  23068. };
  23069. Scheduler.prototype.updatePayload = function (task, payload) {
  23070. payload !== 'remain' && (task.context.payload = payload);
  23071. };
  23072. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23073. var scheduler = this;
  23074. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  23075. // do not need to reuse the map.
  23076. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  23077. var seriesType = stageHandler.seriesType;
  23078. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23079. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23080. // it works but it may cause other irrelevant charts blocked.
  23081. if (stageHandler.createOnAllSeries) {
  23082. ecModel.eachRawSeries(create);
  23083. } else if (seriesType) {
  23084. ecModel.eachRawSeriesByType(seriesType, create);
  23085. } else if (getTargetSeries) {
  23086. getTargetSeries(ecModel, api).each(create);
  23087. }
  23088. function create(seriesModel) {
  23089. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  23090. // Reuse original task instance.
  23091. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  23092. plan: seriesTaskPlan,
  23093. reset: seriesTaskReset,
  23094. count: seriesTaskCount
  23095. }));
  23096. task.context = {
  23097. model: seriesModel,
  23098. ecModel: ecModel,
  23099. api: api,
  23100. // PENDING: `useClearVisual` not used?
  23101. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23102. plan: stageHandler.plan,
  23103. reset: stageHandler.reset,
  23104. scheduler: scheduler
  23105. };
  23106. scheduler._pipe(seriesModel, task);
  23107. }
  23108. };
  23109. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23110. var scheduler = this;
  23111. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  23112. || createTask({
  23113. reset: overallTaskReset
  23114. });
  23115. overallTask.context = {
  23116. ecModel: ecModel,
  23117. api: api,
  23118. overallReset: stageHandler.overallReset,
  23119. scheduler: scheduler
  23120. };
  23121. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  23122. // do not need to reuse the map.
  23123. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  23124. var seriesType = stageHandler.seriesType;
  23125. var getTargetSeries = stageHandler.getTargetSeries;
  23126. var overallProgress = true;
  23127. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  23128. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  23129. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23130. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23131. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23132. // we set the pipeline block.
  23133. var errMsg = '';
  23134. if ("development" !== 'production') {
  23135. errMsg = '"createOnAllSeries" do not supported for "overallReset", ' + 'becuase it will block all streams.';
  23136. }
  23137. assert(!stageHandler.createOnAllSeries, errMsg);
  23138. if (seriesType) {
  23139. ecModel.eachRawSeriesByType(seriesType, createStub);
  23140. } else if (getTargetSeries) {
  23141. getTargetSeries(ecModel, api).each(createStub);
  23142. } // Otherwise, (usually it is legancy case), the overall task will only be
  23143. // executed when upstream dirty. Otherwise the progressive rendering of all
  23144. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23145. // dirty info from upsteam.
  23146. else {
  23147. overallProgress = false;
  23148. each(ecModel.getSeries(), createStub);
  23149. }
  23150. function createStub(seriesModel) {
  23151. var pipelineId = seriesModel.uid;
  23152. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  23153. // should be set as dirty and re-performed.
  23154. shouldOverallTaskDirty = true, createTask({
  23155. reset: stubReset,
  23156. onDirty: stubOnDirty
  23157. })));
  23158. stub.context = {
  23159. model: seriesModel,
  23160. overallProgress: overallProgress // FIXME:TS never used, so comment it
  23161. // modifyOutputEnd: modifyOutputEnd
  23162. };
  23163. stub.agent = overallTask;
  23164. stub.__block = overallProgress;
  23165. scheduler._pipe(seriesModel, stub);
  23166. }
  23167. if (shouldOverallTaskDirty) {
  23168. overallTask.dirty();
  23169. }
  23170. };
  23171. Scheduler.prototype._pipe = function (seriesModel, task) {
  23172. var pipelineId = seriesModel.uid;
  23173. var pipeline = this._pipelineMap.get(pipelineId);
  23174. !pipeline.head && (pipeline.head = task);
  23175. pipeline.tail && pipeline.tail.pipe(task);
  23176. pipeline.tail = task;
  23177. task.__idxInPipeline = pipeline.count++;
  23178. task.__pipeline = pipeline;
  23179. };
  23180. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23181. if (isFunction(stageHandler)) {
  23182. stageHandler = {
  23183. overallReset: stageHandler,
  23184. seriesType: detectSeriseType(stageHandler)
  23185. };
  23186. }
  23187. stageHandler.uid = getUID('stageHandler');
  23188. visualType && (stageHandler.visualType = visualType);
  23189. return stageHandler;
  23190. };
  23191. return Scheduler;
  23192. }();
  23193. function overallTaskReset(context) {
  23194. context.overallReset(context.ecModel, context.api, context.payload);
  23195. }
  23196. function stubReset(context) {
  23197. return context.overallProgress && stubProgress;
  23198. }
  23199. function stubProgress() {
  23200. this.agent.dirty();
  23201. this.getDownstream().dirty();
  23202. }
  23203. function stubOnDirty() {
  23204. this.agent && this.agent.dirty();
  23205. }
  23206. function seriesTaskPlan(context) {
  23207. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  23208. }
  23209. function seriesTaskReset(context) {
  23210. if (context.useClearVisual) {
  23211. context.data.clearAllVisual();
  23212. }
  23213. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  23214. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  23215. return makeSeriesTaskProgress(idx);
  23216. }) : singleSeriesTaskProgress;
  23217. }
  23218. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23219. function makeSeriesTaskProgress(resetDefineIdx) {
  23220. return function (params, context) {
  23221. var data = context.data;
  23222. var resetDefine = context.resetDefines[resetDefineIdx];
  23223. if (resetDefine && resetDefine.dataEach) {
  23224. for (var i = params.start; i < params.end; i++) {
  23225. resetDefine.dataEach(data, i);
  23226. }
  23227. } else if (resetDefine && resetDefine.progress) {
  23228. resetDefine.progress(params, data);
  23229. }
  23230. };
  23231. }
  23232. function seriesTaskCount(context) {
  23233. return context.data.count();
  23234. }
  23235. /**
  23236. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23237. * To ensure that they can work normally, they should work in block mode, that is,
  23238. * they should not be started util the previous tasks finished. So they cause the
  23239. * progressive rendering disabled. We try to detect the series type, to narrow down
  23240. * the block range to only the series type they concern, but not all series.
  23241. */
  23242. function detectSeriseType(legacyFunc) {
  23243. seriesType = null;
  23244. try {
  23245. // Assume there is no async when calling `eachSeriesByType`.
  23246. legacyFunc(ecModelMock, apiMock);
  23247. } catch (e) {}
  23248. return seriesType;
  23249. }
  23250. var ecModelMock = {};
  23251. var apiMock = {};
  23252. var seriesType;
  23253. mockMethods(ecModelMock, GlobalModel);
  23254. mockMethods(apiMock, ExtensionAPI);
  23255. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23256. seriesType = type;
  23257. };
  23258. ecModelMock.eachComponent = function (cond) {
  23259. if (cond.mainType === 'series' && cond.subType) {
  23260. seriesType = cond.subType;
  23261. }
  23262. };
  23263. function mockMethods(target, Clz) {
  23264. /* eslint-disable */
  23265. for (var name_1 in Clz.prototype) {
  23266. // Do not use hasOwnProperty
  23267. target[name_1] = noop;
  23268. }
  23269. /* eslint-enable */
  23270. }
  23271. /*
  23272. * Licensed to the Apache Software Foundation (ASF) under one
  23273. * or more contributor license agreements. See the NOTICE file
  23274. * distributed with this work for additional information
  23275. * regarding copyright ownership. The ASF licenses this file
  23276. * to you under the Apache License, Version 2.0 (the
  23277. * "License"); you may not use this file except in compliance
  23278. * with the License. You may obtain a copy of the License at
  23279. *
  23280. * http://www.apache.org/licenses/LICENSE-2.0
  23281. *
  23282. * Unless required by applicable law or agreed to in writing,
  23283. * software distributed under the License is distributed on an
  23284. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23285. * KIND, either express or implied. See the License for the
  23286. * specific language governing permissions and limitations
  23287. * under the License.
  23288. */
  23289. /**
  23290. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23291. */
  23292. /*
  23293. * Licensed to the Apache Software Foundation (ASF) under one
  23294. * or more contributor license agreements. See the NOTICE file
  23295. * distributed with this work for additional information
  23296. * regarding copyright ownership. The ASF licenses this file
  23297. * to you under the Apache License, Version 2.0 (the
  23298. * "License"); you may not use this file except in compliance
  23299. * with the License. You may obtain a copy of the License at
  23300. *
  23301. * http://www.apache.org/licenses/LICENSE-2.0
  23302. *
  23303. * Unless required by applicable law or agreed to in writing,
  23304. * software distributed under the License is distributed on an
  23305. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23306. * KIND, either express or implied. See the License for the
  23307. * specific language governing permissions and limitations
  23308. * under the License.
  23309. */
  23310. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  23311. var lightTheme = {
  23312. color: colorAll,
  23313. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  23314. };
  23315. /*
  23316. * Licensed to the Apache Software Foundation (ASF) under one
  23317. * or more contributor license agreements. See the NOTICE file
  23318. * distributed with this work for additional information
  23319. * regarding copyright ownership. The ASF licenses this file
  23320. * to you under the Apache License, Version 2.0 (the
  23321. * "License"); you may not use this file except in compliance
  23322. * with the License. You may obtain a copy of the License at
  23323. *
  23324. * http://www.apache.org/licenses/LICENSE-2.0
  23325. *
  23326. * Unless required by applicable law or agreed to in writing,
  23327. * software distributed under the License is distributed on an
  23328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23329. * KIND, either express or implied. See the License for the
  23330. * specific language governing permissions and limitations
  23331. * under the License.
  23332. */
  23333. /**
  23334. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23335. */
  23336. /*
  23337. * Licensed to the Apache Software Foundation (ASF) under one
  23338. * or more contributor license agreements. See the NOTICE file
  23339. * distributed with this work for additional information
  23340. * regarding copyright ownership. The ASF licenses this file
  23341. * to you under the Apache License, Version 2.0 (the
  23342. * "License"); you may not use this file except in compliance
  23343. * with the License. You may obtain a copy of the License at
  23344. *
  23345. * http://www.apache.org/licenses/LICENSE-2.0
  23346. *
  23347. * Unless required by applicable law or agreed to in writing,
  23348. * software distributed under the License is distributed on an
  23349. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23350. * KIND, either express or implied. See the License for the
  23351. * specific language governing permissions and limitations
  23352. * under the License.
  23353. */
  23354. var contrastColor = '#B9B8CE';
  23355. var backgroundColor = '#100C2A';
  23356. var axisCommon = function () {
  23357. return {
  23358. axisLine: {
  23359. lineStyle: {
  23360. color: contrastColor
  23361. }
  23362. },
  23363. splitLine: {
  23364. lineStyle: {
  23365. color: '#484753'
  23366. }
  23367. },
  23368. splitArea: {
  23369. areaStyle: {
  23370. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  23371. }
  23372. },
  23373. minorSplitLine: {
  23374. lineStyle: {
  23375. color: '#20203B'
  23376. }
  23377. }
  23378. };
  23379. };
  23380. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  23381. var theme = {
  23382. darkMode: true,
  23383. color: colorPalette,
  23384. backgroundColor: backgroundColor,
  23385. axisPointer: {
  23386. lineStyle: {
  23387. color: '#817f91'
  23388. },
  23389. crossStyle: {
  23390. color: '#817f91'
  23391. },
  23392. label: {
  23393. // TODO Contrast of label backgorundColor
  23394. color: '#fff'
  23395. }
  23396. },
  23397. legend: {
  23398. textStyle: {
  23399. color: contrastColor
  23400. }
  23401. },
  23402. textStyle: {
  23403. color: contrastColor
  23404. },
  23405. title: {
  23406. textStyle: {
  23407. color: '#EEF1FA'
  23408. },
  23409. subtextStyle: {
  23410. color: '#B9B8CE'
  23411. }
  23412. },
  23413. toolbox: {
  23414. iconStyle: {
  23415. borderColor: contrastColor
  23416. }
  23417. },
  23418. dataZoom: {
  23419. borderColor: '#71708A',
  23420. textStyle: {
  23421. color: contrastColor
  23422. },
  23423. brushStyle: {
  23424. color: 'rgba(135,163,206,0.3)'
  23425. },
  23426. handleStyle: {
  23427. color: '#353450',
  23428. borderColor: '#C5CBE3'
  23429. },
  23430. moveHandleStyle: {
  23431. color: '#B0B6C3',
  23432. opacity: 0.3
  23433. },
  23434. fillerColor: 'rgba(135,163,206,0.2)',
  23435. emphasis: {
  23436. handleStyle: {
  23437. borderColor: '#91B7F2',
  23438. color: '#4D587D'
  23439. },
  23440. moveHandleStyle: {
  23441. color: '#636D9A',
  23442. opacity: 0.7
  23443. }
  23444. },
  23445. dataBackground: {
  23446. lineStyle: {
  23447. color: '#71708A',
  23448. width: 1
  23449. },
  23450. areaStyle: {
  23451. color: '#71708A'
  23452. }
  23453. },
  23454. selectedDataBackground: {
  23455. lineStyle: {
  23456. color: '#87A3CE'
  23457. },
  23458. areaStyle: {
  23459. color: '#87A3CE'
  23460. }
  23461. }
  23462. },
  23463. visualMap: {
  23464. textStyle: {
  23465. color: contrastColor
  23466. }
  23467. },
  23468. timeline: {
  23469. lineStyle: {
  23470. color: contrastColor
  23471. },
  23472. label: {
  23473. color: contrastColor
  23474. },
  23475. controlStyle: {
  23476. color: contrastColor,
  23477. borderColor: contrastColor
  23478. }
  23479. },
  23480. calendar: {
  23481. itemStyle: {
  23482. color: backgroundColor
  23483. },
  23484. dayLabel: {
  23485. color: contrastColor
  23486. },
  23487. monthLabel: {
  23488. color: contrastColor
  23489. },
  23490. yearLabel: {
  23491. color: contrastColor
  23492. }
  23493. },
  23494. timeAxis: axisCommon(),
  23495. logAxis: axisCommon(),
  23496. valueAxis: axisCommon(),
  23497. categoryAxis: axisCommon(),
  23498. line: {
  23499. symbol: 'circle'
  23500. },
  23501. graph: {
  23502. color: colorPalette
  23503. },
  23504. gauge: {
  23505. title: {
  23506. color: contrastColor
  23507. },
  23508. axisLine: {
  23509. lineStyle: {
  23510. color: [[1, 'rgba(207,212,219,0.2)']]
  23511. }
  23512. },
  23513. axisLabel: {
  23514. color: contrastColor
  23515. },
  23516. detail: {
  23517. color: '#EEF1FA'
  23518. }
  23519. },
  23520. candlestick: {
  23521. itemStyle: {
  23522. color: '#f64e56',
  23523. color0: '#54ea92',
  23524. borderColor: '#f64e56',
  23525. borderColor0: '#54ea92' // borderColor: '#ca2824',
  23526. // borderColor0: '#09a443'
  23527. }
  23528. }
  23529. };
  23530. theme.categoryAxis.splitLine.show = false;
  23531. /**
  23532. * Usage of query:
  23533. * `chart.on('click', query, handler);`
  23534. * The `query` can be:
  23535. * + The component type query string, only `mainType` or `mainType.subType`,
  23536. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  23537. * + The component query object, like:
  23538. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  23539. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  23540. * + The data query object, like:
  23541. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  23542. * + The other query object (cmponent customized query), like:
  23543. * `{element: 'some'}` (only available in custom series).
  23544. *
  23545. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  23546. * same as there is no such prop in the `query` object.
  23547. */
  23548. var ECEventProcessor =
  23549. /** @class */
  23550. function () {
  23551. function ECEventProcessor() {}
  23552. ECEventProcessor.prototype.normalizeQuery = function (query) {
  23553. var cptQuery = {};
  23554. var dataQuery = {};
  23555. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  23556. if (isString(query)) {
  23557. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  23558. cptQuery.mainType = condCptType.main || null;
  23559. cptQuery.subType = condCptType.sub || null;
  23560. } // `query` is an object, convert to {mainType, index, name, id}.
  23561. else {
  23562. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  23563. // can not be used in `compomentModel.filterForExposedEvent`.
  23564. var suffixes_1 = ['Index', 'Name', 'Id'];
  23565. var dataKeys_1 = {
  23566. name: 1,
  23567. dataIndex: 1,
  23568. dataType: 1
  23569. };
  23570. each(query, function (val, key) {
  23571. var reserved = false;
  23572. for (var i = 0; i < suffixes_1.length; i++) {
  23573. var propSuffix = suffixes_1[i];
  23574. var suffixPos = key.lastIndexOf(propSuffix);
  23575. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  23576. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  23577. if (mainType !== 'data') {
  23578. cptQuery.mainType = mainType;
  23579. cptQuery[propSuffix.toLowerCase()] = val;
  23580. reserved = true;
  23581. }
  23582. }
  23583. }
  23584. if (dataKeys_1.hasOwnProperty(key)) {
  23585. dataQuery[key] = val;
  23586. reserved = true;
  23587. }
  23588. if (!reserved) {
  23589. otherQuery[key] = val;
  23590. }
  23591. });
  23592. }
  23593. return {
  23594. cptQuery: cptQuery,
  23595. dataQuery: dataQuery,
  23596. otherQuery: otherQuery
  23597. };
  23598. };
  23599. ECEventProcessor.prototype.filter = function (eventType, query) {
  23600. // They should be assigned before each trigger call.
  23601. var eventInfo = this.eventInfo;
  23602. if (!eventInfo) {
  23603. return true;
  23604. }
  23605. var targetEl = eventInfo.targetEl;
  23606. var packedEvent = eventInfo.packedEvent;
  23607. var model = eventInfo.model;
  23608. var view = eventInfo.view; // For event like 'globalout'.
  23609. if (!model || !view) {
  23610. return true;
  23611. }
  23612. var cptQuery = query.cptQuery;
  23613. var dataQuery = query.dataQuery;
  23614. 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));
  23615. function check(query, host, prop, propOnHost) {
  23616. return query[prop] == null || host[propOnHost || prop] === query[prop];
  23617. }
  23618. };
  23619. ECEventProcessor.prototype.afterTrigger = function () {
  23620. // Make sure the eventInfo wont be used in next trigger.
  23621. this.eventInfo = null;
  23622. };
  23623. return ECEventProcessor;
  23624. }();
  23625. var seriesSymbolTask = {
  23626. createOnAllSeries: true,
  23627. // For legend.
  23628. performRawSeries: true,
  23629. reset: function (seriesModel, ecModel) {
  23630. var data = seriesModel.getData();
  23631. if (seriesModel.legendIcon) {
  23632. data.setVisual('legendIcon', seriesModel.legendIcon);
  23633. }
  23634. if (!seriesModel.hasSymbolVisual) {
  23635. return;
  23636. }
  23637. var symbolType = seriesModel.get('symbol');
  23638. var symbolSize = seriesModel.get('symbolSize');
  23639. var keepAspect = seriesModel.get('symbolKeepAspect');
  23640. var symbolRotate = seriesModel.get('symbolRotate');
  23641. var symbolOffset = seriesModel.get('symbolOffset');
  23642. var hasSymbolTypeCallback = isFunction(symbolType);
  23643. var hasSymbolSizeCallback = isFunction(symbolSize);
  23644. var hasSymbolRotateCallback = isFunction(symbolRotate);
  23645. var hasSymbolOffsetCallback = isFunction(symbolOffset);
  23646. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback || hasSymbolOffsetCallback;
  23647. var seriesSymbol = !hasSymbolTypeCallback && symbolType ? symbolType : seriesModel.defaultSymbol;
  23648. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  23649. var seriesSymbolRotate = !hasSymbolRotateCallback ? symbolRotate : null;
  23650. var seriesSymbolOffset = !hasSymbolOffsetCallback ? symbolOffset : null;
  23651. data.setVisual({
  23652. legendIcon: seriesModel.legendIcon || seriesSymbol,
  23653. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  23654. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  23655. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  23656. // some cases but generally it is not recommanded.
  23657. symbol: seriesSymbol,
  23658. symbolSize: seriesSymbolSize,
  23659. symbolKeepAspect: keepAspect,
  23660. symbolRotate: seriesSymbolRotate,
  23661. symbolOffset: seriesSymbolOffset
  23662. }); // Only visible series has each data be visual encoded
  23663. if (ecModel.isSeriesFiltered(seriesModel)) {
  23664. return;
  23665. }
  23666. function dataEach(data, idx) {
  23667. var rawValue = seriesModel.getRawValue(idx);
  23668. var params = seriesModel.getDataParams(idx);
  23669. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  23670. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  23671. hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params));
  23672. hasSymbolOffsetCallback && data.setItemVisual(idx, 'symbolOffset', symbolOffset(rawValue, params));
  23673. }
  23674. return {
  23675. dataEach: hasCallback ? dataEach : null
  23676. };
  23677. }
  23678. };
  23679. var dataSymbolTask = {
  23680. createOnAllSeries: true,
  23681. // For legend.
  23682. performRawSeries: true,
  23683. reset: function (seriesModel, ecModel) {
  23684. if (!seriesModel.hasSymbolVisual) {
  23685. return;
  23686. } // Only visible series has each data be visual encoded
  23687. if (ecModel.isSeriesFiltered(seriesModel)) {
  23688. return;
  23689. }
  23690. var data = seriesModel.getData();
  23691. function dataEach(data, idx) {
  23692. var itemModel = data.getItemModel(idx);
  23693. var itemSymbolType = itemModel.getShallow('symbol', true);
  23694. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  23695. var itemSymbolRotate = itemModel.getShallow('symbolRotate', true);
  23696. var itemSymbolOffset = itemModel.getShallow('symbolOffset', true);
  23697. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true); // If has item symbol
  23698. if (itemSymbolType != null) {
  23699. data.setItemVisual(idx, 'symbol', itemSymbolType);
  23700. }
  23701. if (itemSymbolSize != null) {
  23702. // PENDING Transform symbolSize ?
  23703. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  23704. }
  23705. if (itemSymbolRotate != null) {
  23706. data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate);
  23707. }
  23708. if (itemSymbolOffset != null) {
  23709. data.setItemVisual(idx, 'symbolOffset', itemSymbolOffset);
  23710. }
  23711. if (itemSymbolKeepAspect != null) {
  23712. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  23713. }
  23714. }
  23715. return {
  23716. dataEach: data.hasItemOption ? dataEach : null
  23717. };
  23718. }
  23719. };
  23720. /*
  23721. * Licensed to the Apache Software Foundation (ASF) under one
  23722. * or more contributor license agreements. See the NOTICE file
  23723. * distributed with this work for additional information
  23724. * regarding copyright ownership. The ASF licenses this file
  23725. * to you under the Apache License, Version 2.0 (the
  23726. * "License"); you may not use this file except in compliance
  23727. * with the License. You may obtain a copy of the License at
  23728. *
  23729. * http://www.apache.org/licenses/LICENSE-2.0
  23730. *
  23731. * Unless required by applicable law or agreed to in writing,
  23732. * software distributed under the License is distributed on an
  23733. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23734. * KIND, either express or implied. See the License for the
  23735. * specific language governing permissions and limitations
  23736. * under the License.
  23737. */
  23738. /**
  23739. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23740. */
  23741. /*
  23742. * Licensed to the Apache Software Foundation (ASF) under one
  23743. * or more contributor license agreements. See the NOTICE file
  23744. * distributed with this work for additional information
  23745. * regarding copyright ownership. The ASF licenses this file
  23746. * to you under the Apache License, Version 2.0 (the
  23747. * "License"); you may not use this file except in compliance
  23748. * with the License. You may obtain a copy of the License at
  23749. *
  23750. * http://www.apache.org/licenses/LICENSE-2.0
  23751. *
  23752. * Unless required by applicable law or agreed to in writing,
  23753. * software distributed under the License is distributed on an
  23754. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23755. * KIND, either express or implied. See the License for the
  23756. * specific language governing permissions and limitations
  23757. * under the License.
  23758. */
  23759. function getItemVisualFromData(data, dataIndex, key) {
  23760. switch (key) {
  23761. case 'color':
  23762. var style = data.getItemVisual(dataIndex, 'style');
  23763. return style[data.getVisual('drawType')];
  23764. case 'opacity':
  23765. return data.getItemVisual(dataIndex, 'style').opacity;
  23766. case 'symbol':
  23767. case 'symbolSize':
  23768. case 'liftZ':
  23769. return data.getItemVisual(dataIndex, key);
  23770. default:
  23771. if ("development" !== 'production') {
  23772. console.warn("Unknown visual type " + key);
  23773. }
  23774. }
  23775. }
  23776. function getVisualFromData(data, key) {
  23777. switch (key) {
  23778. case 'color':
  23779. var style = data.getVisual('style');
  23780. return style[data.getVisual('drawType')];
  23781. case 'opacity':
  23782. return data.getVisual('style').opacity;
  23783. case 'symbol':
  23784. case 'symbolSize':
  23785. case 'liftZ':
  23786. return data.getVisual(key);
  23787. default:
  23788. if ("development" !== 'production') {
  23789. console.warn("Unknown visual type " + key);
  23790. }
  23791. }
  23792. }
  23793. function setItemVisualFromData(data, dataIndex, key, value) {
  23794. switch (key) {
  23795. case 'color':
  23796. // Make sure not sharing style object.
  23797. var style = data.ensureUniqueItemVisual(dataIndex, 'style');
  23798. style[data.getVisual('drawType')] = value; // Mark the color has been changed, not from palette anymore
  23799. data.setItemVisual(dataIndex, 'colorFromPalette', false);
  23800. break;
  23801. case 'opacity':
  23802. data.ensureUniqueItemVisual(dataIndex, 'style').opacity = value;
  23803. break;
  23804. case 'symbol':
  23805. case 'symbolSize':
  23806. case 'liftZ':
  23807. data.setItemVisual(dataIndex, key, value);
  23808. break;
  23809. default:
  23810. if ("development" !== 'production') {
  23811. console.warn("Unknown visual type " + key);
  23812. }
  23813. }
  23814. }
  23815. // Inlucdes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  23816. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  23817. function getSeriesIndices(ecModel, payload) {
  23818. var seriesIndices = [];
  23819. ecModel.eachComponent({
  23820. mainType: 'series',
  23821. subType: seriesType,
  23822. query: payload
  23823. }, function (seriesModel) {
  23824. seriesIndices.push(seriesModel.seriesIndex);
  23825. });
  23826. return seriesIndices;
  23827. }
  23828. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  23829. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  23830. payload = extend({}, payload);
  23831. if ("development" !== 'production') {
  23832. deprecateReplaceLog(payload.type, eventsMap[1]);
  23833. }
  23834. api.dispatchAction(extend(payload, {
  23835. type: eventsMap[1],
  23836. seriesIndex: getSeriesIndices(ecModel, payload)
  23837. }));
  23838. });
  23839. });
  23840. }
  23841. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  23842. var legacyEventName = type + eventPostfix;
  23843. if (!ecIns.isSilent(legacyEventName)) {
  23844. if ("development" !== 'production') {
  23845. deprecateLog("event " + legacyEventName + " is deprecated.");
  23846. }
  23847. ecModel.eachComponent({
  23848. mainType: 'series',
  23849. subType: 'pie'
  23850. }, function (seriesModel) {
  23851. var seriesIndex = seriesModel.seriesIndex;
  23852. var selected = payload.selected;
  23853. for (var i = 0; i < selected.length; i++) {
  23854. if (selected[i].seriesIndex === seriesIndex) {
  23855. var data = seriesModel.getData();
  23856. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  23857. ecIns.trigger(legacyEventName, {
  23858. type: legacyEventName,
  23859. seriesId: seriesModel.id,
  23860. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  23861. selected: extend({}, seriesModel.option.selectedMap)
  23862. });
  23863. }
  23864. }
  23865. });
  23866. }
  23867. }
  23868. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  23869. messageCenter.on('selectchanged', function (params) {
  23870. var ecModel = api.getModel();
  23871. if (params.isFromClick) {
  23872. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  23873. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  23874. } else if (params.fromAction === 'select') {
  23875. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  23876. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  23877. } else if (params.fromAction === 'unselect') {
  23878. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  23879. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  23880. }
  23881. });
  23882. }
  23883. /*
  23884. * Licensed to the Apache Software Foundation (ASF) under one
  23885. * or more contributor license agreements. See the NOTICE file
  23886. * distributed with this work for additional information
  23887. * regarding copyright ownership. The ASF licenses this file
  23888. * to you under the Apache License, Version 2.0 (the
  23889. * "License"); you may not use this file except in compliance
  23890. * with the License. You may obtain a copy of the License at
  23891. *
  23892. * http://www.apache.org/licenses/LICENSE-2.0
  23893. *
  23894. * Unless required by applicable law or agreed to in writing,
  23895. * software distributed under the License is distributed on an
  23896. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23897. * KIND, either express or implied. See the License for the
  23898. * specific language governing permissions and limitations
  23899. * under the License.
  23900. */
  23901. /**
  23902. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23903. */
  23904. /*
  23905. * Licensed to the Apache Software Foundation (ASF) under one
  23906. * or more contributor license agreements. See the NOTICE file
  23907. * distributed with this work for additional information
  23908. * regarding copyright ownership. The ASF licenses this file
  23909. * to you under the Apache License, Version 2.0 (the
  23910. * "License"); you may not use this file except in compliance
  23911. * with the License. You may obtain a copy of the License at
  23912. *
  23913. * http://www.apache.org/licenses/LICENSE-2.0
  23914. *
  23915. * Unless required by applicable law or agreed to in writing,
  23916. * software distributed under the License is distributed on an
  23917. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23918. * KIND, either express or implied. See the License for the
  23919. * specific language governing permissions and limitations
  23920. * under the License.
  23921. */
  23922. function findEventDispatcher(target, det, returnFirstMatch) {
  23923. var found;
  23924. while (target) {
  23925. if (det(target)) {
  23926. found = target;
  23927. if (returnFirstMatch) {
  23928. break;
  23929. }
  23930. }
  23931. target = target.__hostTarget || target.parent;
  23932. }
  23933. return found;
  23934. }
  23935. var wmUniqueIndex = Math.round(Math.random() * 9);
  23936. var supportDefineProperty = typeof Object.defineProperty === 'function';
  23937. var WeakMap = (function () {
  23938. function WeakMap() {
  23939. this._id = '__ec_inner_' + wmUniqueIndex++;
  23940. }
  23941. WeakMap.prototype.get = function (key) {
  23942. return this._guard(key)[this._id];
  23943. };
  23944. WeakMap.prototype.set = function (key, value) {
  23945. var target = this._guard(key);
  23946. if (supportDefineProperty) {
  23947. Object.defineProperty(target, this._id, {
  23948. value: value,
  23949. enumerable: false,
  23950. configurable: true
  23951. });
  23952. }
  23953. else {
  23954. target[this._id] = value;
  23955. }
  23956. return this;
  23957. };
  23958. WeakMap.prototype["delete"] = function (key) {
  23959. if (this.has(key)) {
  23960. delete this._guard(key)[this._id];
  23961. return true;
  23962. }
  23963. return false;
  23964. };
  23965. WeakMap.prototype.has = function (key) {
  23966. return !!this._guard(key)[this._id];
  23967. };
  23968. WeakMap.prototype._guard = function (key) {
  23969. if (key !== Object(key)) {
  23970. throw TypeError('Value of WeakMap is not a non-null object.');
  23971. }
  23972. return key;
  23973. };
  23974. return WeakMap;
  23975. }());
  23976. /**
  23977. * Triangle shape
  23978. * @inner
  23979. */
  23980. var Triangle = Path.extend({
  23981. type: 'triangle',
  23982. shape: {
  23983. cx: 0,
  23984. cy: 0,
  23985. width: 0,
  23986. height: 0
  23987. },
  23988. buildPath: function (path, shape) {
  23989. var cx = shape.cx;
  23990. var cy = shape.cy;
  23991. var width = shape.width / 2;
  23992. var height = shape.height / 2;
  23993. path.moveTo(cx, cy - height);
  23994. path.lineTo(cx + width, cy + height);
  23995. path.lineTo(cx - width, cy + height);
  23996. path.closePath();
  23997. }
  23998. });
  23999. /**
  24000. * Diamond shape
  24001. * @inner
  24002. */
  24003. var Diamond = Path.extend({
  24004. type: 'diamond',
  24005. shape: {
  24006. cx: 0,
  24007. cy: 0,
  24008. width: 0,
  24009. height: 0
  24010. },
  24011. buildPath: function (path, shape) {
  24012. var cx = shape.cx;
  24013. var cy = shape.cy;
  24014. var width = shape.width / 2;
  24015. var height = shape.height / 2;
  24016. path.moveTo(cx, cy - height);
  24017. path.lineTo(cx + width, cy);
  24018. path.lineTo(cx, cy + height);
  24019. path.lineTo(cx - width, cy);
  24020. path.closePath();
  24021. }
  24022. });
  24023. /**
  24024. * Pin shape
  24025. * @inner
  24026. */
  24027. var Pin = Path.extend({
  24028. type: 'pin',
  24029. shape: {
  24030. // x, y on the cusp
  24031. x: 0,
  24032. y: 0,
  24033. width: 0,
  24034. height: 0
  24035. },
  24036. buildPath: function (path, shape) {
  24037. var x = shape.x;
  24038. var y = shape.y;
  24039. var w = shape.width / 5 * 3; // Height must be larger than width
  24040. var h = Math.max(w, shape.height);
  24041. var r = w / 2; // Dist on y with tangent point and circle center
  24042. var dy = r * r / (h - r);
  24043. var cy = y - h + r + dy;
  24044. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  24045. var dx = Math.cos(angle) * r;
  24046. var tanX = Math.sin(angle);
  24047. var tanY = Math.cos(angle);
  24048. var cpLen = r * 0.6;
  24049. var cpLen2 = r * 0.7;
  24050. path.moveTo(x - dx, cy + dy);
  24051. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  24052. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  24053. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  24054. path.closePath();
  24055. }
  24056. });
  24057. /**
  24058. * Arrow shape
  24059. * @inner
  24060. */
  24061. var Arrow = Path.extend({
  24062. type: 'arrow',
  24063. shape: {
  24064. x: 0,
  24065. y: 0,
  24066. width: 0,
  24067. height: 0
  24068. },
  24069. buildPath: function (ctx, shape) {
  24070. var height = shape.height;
  24071. var width = shape.width;
  24072. var x = shape.x;
  24073. var y = shape.y;
  24074. var dx = width / 3 * 2;
  24075. ctx.moveTo(x, y);
  24076. ctx.lineTo(x + dx, y + height);
  24077. ctx.lineTo(x, y + height / 4 * 3);
  24078. ctx.lineTo(x - dx, y + height);
  24079. ctx.lineTo(x, y);
  24080. ctx.closePath();
  24081. }
  24082. });
  24083. /**
  24084. * Map of path contructors
  24085. */
  24086. // TODO Use function to build symbol path.
  24087. var symbolCtors = {
  24088. line: Line,
  24089. rect: Rect,
  24090. roundRect: Rect,
  24091. square: Rect,
  24092. circle: Circle,
  24093. diamond: Diamond,
  24094. pin: Pin,
  24095. arrow: Arrow,
  24096. triangle: Triangle
  24097. };
  24098. var symbolShapeMakers = {
  24099. line: function (x, y, w, h, shape) {
  24100. shape.x1 = x;
  24101. shape.y1 = y + h / 2;
  24102. shape.x2 = x + w;
  24103. shape.y2 = y + h / 2;
  24104. },
  24105. rect: function (x, y, w, h, shape) {
  24106. shape.x = x;
  24107. shape.y = y;
  24108. shape.width = w;
  24109. shape.height = h;
  24110. },
  24111. roundRect: function (x, y, w, h, shape) {
  24112. shape.x = x;
  24113. shape.y = y;
  24114. shape.width = w;
  24115. shape.height = h;
  24116. shape.r = Math.min(w, h) / 4;
  24117. },
  24118. square: function (x, y, w, h, shape) {
  24119. var size = Math.min(w, h);
  24120. shape.x = x;
  24121. shape.y = y;
  24122. shape.width = size;
  24123. shape.height = size;
  24124. },
  24125. circle: function (x, y, w, h, shape) {
  24126. // Put circle in the center of square
  24127. shape.cx = x + w / 2;
  24128. shape.cy = y + h / 2;
  24129. shape.r = Math.min(w, h) / 2;
  24130. },
  24131. diamond: function (x, y, w, h, shape) {
  24132. shape.cx = x + w / 2;
  24133. shape.cy = y + h / 2;
  24134. shape.width = w;
  24135. shape.height = h;
  24136. },
  24137. pin: function (x, y, w, h, shape) {
  24138. shape.x = x + w / 2;
  24139. shape.y = y + h / 2;
  24140. shape.width = w;
  24141. shape.height = h;
  24142. },
  24143. arrow: function (x, y, w, h, shape) {
  24144. shape.x = x + w / 2;
  24145. shape.y = y + h / 2;
  24146. shape.width = w;
  24147. shape.height = h;
  24148. },
  24149. triangle: function (x, y, w, h, shape) {
  24150. shape.cx = x + w / 2;
  24151. shape.cy = y + h / 2;
  24152. shape.width = w;
  24153. shape.height = h;
  24154. }
  24155. };
  24156. var symbolBuildProxies = {};
  24157. each(symbolCtors, function (Ctor, name) {
  24158. symbolBuildProxies[name] = new Ctor();
  24159. });
  24160. var SymbolClz = Path.extend({
  24161. type: 'symbol',
  24162. shape: {
  24163. symbolType: '',
  24164. x: 0,
  24165. y: 0,
  24166. width: 0,
  24167. height: 0
  24168. },
  24169. calculateTextPosition: function (out, config, rect) {
  24170. var res = calculateTextPosition(out, config, rect);
  24171. var shape = this.shape;
  24172. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  24173. res.y = rect.y + rect.height * 0.4;
  24174. }
  24175. return res;
  24176. },
  24177. buildPath: function (ctx, shape, inBundle) {
  24178. var symbolType = shape.symbolType;
  24179. if (symbolType !== 'none') {
  24180. var proxySymbol = symbolBuildProxies[symbolType];
  24181. if (!proxySymbol) {
  24182. // Default rect
  24183. symbolType = 'rect';
  24184. proxySymbol = symbolBuildProxies[symbolType];
  24185. }
  24186. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  24187. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  24188. }
  24189. }
  24190. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  24191. function symbolPathSetColor(color, innerColor) {
  24192. if (this.type !== 'image') {
  24193. var symbolStyle = this.style;
  24194. if (this.__isEmptyBrush) {
  24195. symbolStyle.stroke = color;
  24196. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView
  24197. symbolStyle.lineWidth = 2;
  24198. } else if (this.shape.symbolType === 'line') {
  24199. symbolStyle.stroke = color;
  24200. } else {
  24201. symbolStyle.fill = color;
  24202. }
  24203. this.markRedraw();
  24204. }
  24205. }
  24206. /**
  24207. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  24208. */
  24209. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  24210. keepAspect) {
  24211. // TODO Support image object, DynamicImage.
  24212. var isEmpty = symbolType.indexOf('empty') === 0;
  24213. if (isEmpty) {
  24214. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  24215. }
  24216. var symbolPath;
  24217. if (symbolType.indexOf('image://') === 0) {
  24218. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24219. } else if (symbolType.indexOf('path://') === 0) {
  24220. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24221. } else {
  24222. symbolPath = new SymbolClz({
  24223. shape: {
  24224. symbolType: symbolType,
  24225. x: x,
  24226. y: y,
  24227. width: w,
  24228. height: h
  24229. }
  24230. });
  24231. }
  24232. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  24233. symbolPath.setColor = symbolPathSetColor;
  24234. if (color) {
  24235. symbolPath.setColor(color);
  24236. }
  24237. return symbolPath;
  24238. }
  24239. function normalizeSymbolSize(symbolSize) {
  24240. if (!isArray(symbolSize)) {
  24241. symbolSize = [+symbolSize, +symbolSize];
  24242. }
  24243. return [symbolSize[0] || 0, symbolSize[1] || 0];
  24244. }
  24245. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  24246. if (symbolOffset == null) {
  24247. return;
  24248. }
  24249. if (!isArray(symbolOffset)) {
  24250. symbolOffset = [symbolOffset, symbolOffset];
  24251. }
  24252. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  24253. }
  24254. function createLinearGradient(ctx, obj, rect) {
  24255. var x = obj.x == null ? 0 : obj.x;
  24256. var x2 = obj.x2 == null ? 1 : obj.x2;
  24257. var y = obj.y == null ? 0 : obj.y;
  24258. var y2 = obj.y2 == null ? 0 : obj.y2;
  24259. if (!obj.global) {
  24260. x = x * rect.width + rect.x;
  24261. x2 = x2 * rect.width + rect.x;
  24262. y = y * rect.height + rect.y;
  24263. y2 = y2 * rect.height + rect.y;
  24264. }
  24265. x = isNaN(x) ? 0 : x;
  24266. x2 = isNaN(x2) ? 1 : x2;
  24267. y = isNaN(y) ? 0 : y;
  24268. y2 = isNaN(y2) ? 0 : y2;
  24269. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  24270. return canvasGradient;
  24271. }
  24272. function createRadialGradient(ctx, obj, rect) {
  24273. var width = rect.width;
  24274. var height = rect.height;
  24275. var min = Math.min(width, height);
  24276. var x = obj.x == null ? 0.5 : obj.x;
  24277. var y = obj.y == null ? 0.5 : obj.y;
  24278. var r = obj.r == null ? 0.5 : obj.r;
  24279. if (!obj.global) {
  24280. x = x * width + rect.x;
  24281. y = y * height + rect.y;
  24282. r = r * min;
  24283. }
  24284. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  24285. return canvasGradient;
  24286. }
  24287. function getCanvasGradient(ctx, obj, rect) {
  24288. var canvasGradient = obj.type === 'radial'
  24289. ? createRadialGradient(ctx, obj, rect)
  24290. : createLinearGradient(ctx, obj, rect);
  24291. var colorStops = obj.colorStops;
  24292. for (var i = 0; i < colorStops.length; i++) {
  24293. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  24294. }
  24295. return canvasGradient;
  24296. }
  24297. function isClipPathChanged(clipPaths, prevClipPaths) {
  24298. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  24299. return false;
  24300. }
  24301. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  24302. return true;
  24303. }
  24304. for (var i = 0; i < clipPaths.length; i++) {
  24305. if (clipPaths[i] !== prevClipPaths[i]) {
  24306. return true;
  24307. }
  24308. }
  24309. return false;
  24310. }
  24311. function normalizeLineDash(lineType, lineWidth) {
  24312. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  24313. return null;
  24314. }
  24315. lineWidth = lineWidth || 1;
  24316. return lineType === 'dashed'
  24317. ? [4 * lineWidth, 2 * lineWidth]
  24318. : lineType === 'dotted'
  24319. ? [lineWidth]
  24320. : isNumber(lineType)
  24321. ? [lineType] : isArray(lineType) ? lineType : null;
  24322. }
  24323. var pathProxyForDraw = new PathProxy(true);
  24324. function styleHasStroke(style) {
  24325. var stroke = style.stroke;
  24326. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  24327. }
  24328. function isValidStrokeFillStyle(strokeOrFill) {
  24329. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  24330. }
  24331. function styleHasFill(style) {
  24332. var fill = style.fill;
  24333. return fill != null && fill !== 'none';
  24334. }
  24335. function doFillPath(ctx, style) {
  24336. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  24337. var originalGlobalAlpha = ctx.globalAlpha;
  24338. ctx.globalAlpha = style.fillOpacity * style.opacity;
  24339. ctx.fill();
  24340. ctx.globalAlpha = originalGlobalAlpha;
  24341. }
  24342. else {
  24343. ctx.fill();
  24344. }
  24345. }
  24346. function doStrokePath(ctx, style) {
  24347. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  24348. var originalGlobalAlpha = ctx.globalAlpha;
  24349. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  24350. ctx.stroke();
  24351. ctx.globalAlpha = originalGlobalAlpha;
  24352. }
  24353. else {
  24354. ctx.stroke();
  24355. }
  24356. }
  24357. function createCanvasPattern(ctx, pattern, el) {
  24358. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  24359. if (isImageReady(image)) {
  24360. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  24361. if (typeof DOMMatrix === 'function'
  24362. && canvasPattern.setTransform) {
  24363. var matrix = new DOMMatrix();
  24364. matrix.rotateSelf(0, 0, (pattern.rotation || 0) / Math.PI * 180);
  24365. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  24366. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  24367. canvasPattern.setTransform(matrix);
  24368. }
  24369. return canvasPattern;
  24370. }
  24371. }
  24372. function brushPath(ctx, el, style, inBatch) {
  24373. var hasStroke = styleHasStroke(style);
  24374. var hasFill = styleHasFill(style);
  24375. var strokePercent = style.strokePercent;
  24376. var strokePart = strokePercent < 1;
  24377. var firstDraw = !el.path;
  24378. if ((!el.silent || strokePart) && firstDraw) {
  24379. el.createPathProxy();
  24380. }
  24381. var path = el.path || pathProxyForDraw;
  24382. if (!inBatch) {
  24383. var fill = style.fill;
  24384. var stroke = style.stroke;
  24385. var hasFillGradient = hasFill && !!fill.colorStops;
  24386. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  24387. var hasFillPattern = hasFill && !!fill.image;
  24388. var hasStrokePattern = hasStroke && !!stroke.image;
  24389. var fillGradient = void 0;
  24390. var strokeGradient = void 0;
  24391. var fillPattern = void 0;
  24392. var strokePattern = void 0;
  24393. var rect = void 0;
  24394. if (hasFillGradient || hasStrokeGradient) {
  24395. rect = el.getBoundingRect();
  24396. }
  24397. if (hasFillGradient) {
  24398. fillGradient = el.__dirty
  24399. ? getCanvasGradient(ctx, fill, rect)
  24400. : el.__canvasFillGradient;
  24401. el.__canvasFillGradient = fillGradient;
  24402. }
  24403. if (hasStrokeGradient) {
  24404. strokeGradient = el.__dirty
  24405. ? getCanvasGradient(ctx, stroke, rect)
  24406. : el.__canvasStrokeGradient;
  24407. el.__canvasStrokeGradient = strokeGradient;
  24408. }
  24409. if (hasFillPattern) {
  24410. fillPattern = (el.__dirty || !el.__canvasFillPattern)
  24411. ? createCanvasPattern(ctx, fill, el)
  24412. : el.__canvasFillPattern;
  24413. el.__canvasFillPattern = fillPattern;
  24414. }
  24415. if (hasStrokePattern) {
  24416. strokePattern = (el.__dirty || !el.__canvasStrokePattern)
  24417. ? createCanvasPattern(ctx, stroke, el)
  24418. : el.__canvasStrokePattern;
  24419. el.__canvasStrokePattern = fillPattern;
  24420. }
  24421. if (hasFillGradient) {
  24422. ctx.fillStyle = fillGradient;
  24423. }
  24424. else if (hasFillPattern) {
  24425. if (fillPattern) {
  24426. ctx.fillStyle = fillPattern;
  24427. }
  24428. else {
  24429. hasFill = false;
  24430. }
  24431. }
  24432. if (hasStrokeGradient) {
  24433. ctx.strokeStyle = strokeGradient;
  24434. }
  24435. else if (hasStrokePattern) {
  24436. if (strokePattern) {
  24437. ctx.strokeStyle = strokePattern;
  24438. }
  24439. else {
  24440. hasStroke = false;
  24441. }
  24442. }
  24443. }
  24444. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24445. var lineDashOffset = style.lineDashOffset;
  24446. var ctxLineDash = !!ctx.setLineDash;
  24447. var scale = el.getGlobalScale();
  24448. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  24449. if (lineDash) {
  24450. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24451. if (lineScale_1 && lineScale_1 !== 1) {
  24452. lineDash = map(lineDash, function (rawVal) {
  24453. return rawVal / lineScale_1;
  24454. });
  24455. lineDashOffset /= lineScale_1;
  24456. }
  24457. }
  24458. var needsRebuild = true;
  24459. if (firstDraw || (el.__dirty & SHAPE_CHANGED_BIT)
  24460. || (lineDash && !ctxLineDash && hasStroke)) {
  24461. path.setDPR(ctx.dpr);
  24462. if (strokePart) {
  24463. path.setContext(null);
  24464. }
  24465. else {
  24466. path.setContext(ctx);
  24467. needsRebuild = false;
  24468. }
  24469. path.reset();
  24470. if (lineDash && !ctxLineDash) {
  24471. path.setLineDash(lineDash);
  24472. path.setLineDashOffset(lineDashOffset);
  24473. }
  24474. el.buildPath(path, el.shape, inBatch);
  24475. path.toStatic();
  24476. el.pathUpdated();
  24477. }
  24478. if (needsRebuild) {
  24479. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  24480. }
  24481. if (lineDash && ctxLineDash) {
  24482. ctx.setLineDash(lineDash);
  24483. ctx.lineDashOffset = lineDashOffset;
  24484. }
  24485. if (!inBatch) {
  24486. if (style.strokeFirst) {
  24487. if (hasStroke) {
  24488. doStrokePath(ctx, style);
  24489. }
  24490. if (hasFill) {
  24491. doFillPath(ctx, style);
  24492. }
  24493. }
  24494. else {
  24495. if (hasFill) {
  24496. doFillPath(ctx, style);
  24497. }
  24498. if (hasStroke) {
  24499. doStrokePath(ctx, style);
  24500. }
  24501. }
  24502. }
  24503. if (lineDash && ctxLineDash) {
  24504. ctx.setLineDash([]);
  24505. }
  24506. }
  24507. function brushImage(ctx, el, style) {
  24508. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24509. if (!image || !isImageReady(image)) {
  24510. return;
  24511. }
  24512. var x = style.x || 0;
  24513. var y = style.y || 0;
  24514. var width = el.getWidth();
  24515. var height = el.getHeight();
  24516. var aspect = image.width / image.height;
  24517. if (width == null && height != null) {
  24518. width = height * aspect;
  24519. }
  24520. else if (height == null && width != null) {
  24521. height = width / aspect;
  24522. }
  24523. else if (width == null && height == null) {
  24524. width = image.width;
  24525. height = image.height;
  24526. }
  24527. if (style.sWidth && style.sHeight) {
  24528. var sx = style.sx || 0;
  24529. var sy = style.sy || 0;
  24530. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  24531. }
  24532. else if (style.sx && style.sy) {
  24533. var sx = style.sx;
  24534. var sy = style.sy;
  24535. var sWidth = width - sx;
  24536. var sHeight = height - sy;
  24537. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  24538. }
  24539. else {
  24540. ctx.drawImage(image, x, y, width, height);
  24541. }
  24542. }
  24543. function brushText(ctx, el, style) {
  24544. var text = style.text;
  24545. text != null && (text += '');
  24546. if (text) {
  24547. ctx.font = style.font || DEFAULT_FONT;
  24548. ctx.textAlign = style.textAlign;
  24549. ctx.textBaseline = style.textBaseline;
  24550. var hasLineDash = void 0;
  24551. if (ctx.setLineDash) {
  24552. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24553. var lineDashOffset = style.lineDashOffset;
  24554. if (lineDash) {
  24555. var lineScale_2 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24556. if (lineScale_2 && lineScale_2 !== 1) {
  24557. lineDash = map(lineDash, function (rawVal) {
  24558. return rawVal / lineScale_2;
  24559. });
  24560. lineDashOffset /= lineScale_2;
  24561. }
  24562. ctx.setLineDash(lineDash);
  24563. ctx.lineDashOffset = lineDashOffset;
  24564. hasLineDash = true;
  24565. }
  24566. }
  24567. if (style.strokeFirst) {
  24568. if (styleHasStroke(style)) {
  24569. ctx.strokeText(text, style.x, style.y);
  24570. }
  24571. if (styleHasFill(style)) {
  24572. ctx.fillText(text, style.x, style.y);
  24573. }
  24574. }
  24575. else {
  24576. if (styleHasFill(style)) {
  24577. ctx.fillText(text, style.x, style.y);
  24578. }
  24579. if (styleHasStroke(style)) {
  24580. ctx.strokeText(text, style.x, style.y);
  24581. }
  24582. }
  24583. if (hasLineDash) {
  24584. ctx.setLineDash([]);
  24585. }
  24586. }
  24587. }
  24588. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  24589. var STROKE_PROPS = [
  24590. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  24591. ];
  24592. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  24593. var styleChanged = false;
  24594. if (!forceSetAll) {
  24595. prevStyle = prevStyle || {};
  24596. if (style === prevStyle) {
  24597. return false;
  24598. }
  24599. }
  24600. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24601. if (!styleChanged) {
  24602. flushPathDrawn(ctx, scope);
  24603. styleChanged = true;
  24604. }
  24605. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  24606. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  24607. }
  24608. if (forceSetAll || style.blend !== prevStyle.blend) {
  24609. if (!styleChanged) {
  24610. flushPathDrawn(ctx, scope);
  24611. styleChanged = true;
  24612. }
  24613. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  24614. }
  24615. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  24616. var propName = SHADOW_NUMBER_PROPS[i];
  24617. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24618. if (!styleChanged) {
  24619. flushPathDrawn(ctx, scope);
  24620. styleChanged = true;
  24621. }
  24622. ctx[propName] = ctx.dpr * (style[propName] || 0);
  24623. }
  24624. }
  24625. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  24626. if (!styleChanged) {
  24627. flushPathDrawn(ctx, scope);
  24628. styleChanged = true;
  24629. }
  24630. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  24631. }
  24632. return styleChanged;
  24633. }
  24634. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  24635. var style = getStyle(el, scope.inHover);
  24636. var prevStyle = forceSetAll
  24637. ? null
  24638. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  24639. if (style === prevStyle) {
  24640. return false;
  24641. }
  24642. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  24643. if (forceSetAll || style.fill !== prevStyle.fill) {
  24644. if (!styleChanged) {
  24645. flushPathDrawn(ctx, scope);
  24646. styleChanged = true;
  24647. }
  24648. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  24649. }
  24650. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  24651. if (!styleChanged) {
  24652. flushPathDrawn(ctx, scope);
  24653. styleChanged = true;
  24654. }
  24655. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  24656. }
  24657. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24658. if (!styleChanged) {
  24659. flushPathDrawn(ctx, scope);
  24660. styleChanged = true;
  24661. }
  24662. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  24663. }
  24664. if (el.hasStroke()) {
  24665. var lineWidth = style.lineWidth;
  24666. var newLineWidth = lineWidth / ((style.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1);
  24667. if (ctx.lineWidth !== newLineWidth) {
  24668. if (!styleChanged) {
  24669. flushPathDrawn(ctx, scope);
  24670. styleChanged = true;
  24671. }
  24672. ctx.lineWidth = newLineWidth;
  24673. }
  24674. }
  24675. for (var i = 0; i < STROKE_PROPS.length; i++) {
  24676. var prop = STROKE_PROPS[i];
  24677. var propName = prop[0];
  24678. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24679. if (!styleChanged) {
  24680. flushPathDrawn(ctx, scope);
  24681. styleChanged = true;
  24682. }
  24683. ctx[propName] = style[propName] || prop[1];
  24684. }
  24685. }
  24686. return styleChanged;
  24687. }
  24688. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  24689. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  24690. }
  24691. function setContextTransform(ctx, el) {
  24692. var m = el.transform;
  24693. var dpr = ctx.dpr || 1;
  24694. if (m) {
  24695. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  24696. }
  24697. else {
  24698. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  24699. }
  24700. }
  24701. function updateClipStatus(clipPaths, ctx, scope) {
  24702. var allClipped = false;
  24703. for (var i = 0; i < clipPaths.length; i++) {
  24704. var clipPath = clipPaths[i];
  24705. allClipped = allClipped || clipPath.isZeroArea();
  24706. setContextTransform(ctx, clipPath);
  24707. ctx.beginPath();
  24708. clipPath.buildPath(ctx, clipPath.shape);
  24709. ctx.clip();
  24710. }
  24711. scope.allClipped = allClipped;
  24712. }
  24713. function isTransformChanged(m0, m1) {
  24714. if (m0 && m1) {
  24715. return m0[0] !== m1[0]
  24716. || m0[1] !== m1[1]
  24717. || m0[2] !== m1[2]
  24718. || m0[3] !== m1[3]
  24719. || m0[4] !== m1[4]
  24720. || m0[5] !== m1[5];
  24721. }
  24722. else if (!m0 && !m1) {
  24723. return false;
  24724. }
  24725. return true;
  24726. }
  24727. var DRAW_TYPE_PATH = 1;
  24728. var DRAW_TYPE_IMAGE = 2;
  24729. var DRAW_TYPE_TEXT = 3;
  24730. var DRAW_TYPE_INCREMENTAL = 4;
  24731. function canPathBatch(style) {
  24732. var hasFill = styleHasFill(style);
  24733. var hasStroke = styleHasStroke(style);
  24734. return !(style.lineDash
  24735. || !(+hasFill ^ +hasStroke)
  24736. || (hasFill && typeof style.fill !== 'string')
  24737. || (hasStroke && typeof style.stroke !== 'string')
  24738. || style.strokePercent < 1
  24739. || style.strokeOpacity < 1
  24740. || style.fillOpacity < 1);
  24741. }
  24742. function flushPathDrawn(ctx, scope) {
  24743. scope.batchFill && ctx.fill();
  24744. scope.batchStroke && ctx.stroke();
  24745. scope.batchFill = '';
  24746. scope.batchStroke = '';
  24747. }
  24748. function getStyle(el, inHover) {
  24749. return inHover ? (el.__hoverStyle || el.style) : el.style;
  24750. }
  24751. function brushSingle(ctx, el) {
  24752. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  24753. }
  24754. function brush(ctx, el, scope, isLast) {
  24755. var m = el.transform;
  24756. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  24757. el.__dirty &= ~REDARAW_BIT;
  24758. el.__isRendered = false;
  24759. return;
  24760. }
  24761. var clipPaths = el.__clipPaths;
  24762. var prevElClipPaths = scope.prevElClipPaths;
  24763. var forceSetTransform = false;
  24764. var forceSetStyle = false;
  24765. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  24766. if (prevElClipPaths && prevElClipPaths.length) {
  24767. flushPathDrawn(ctx, scope);
  24768. ctx.restore();
  24769. forceSetStyle = forceSetTransform = true;
  24770. scope.prevElClipPaths = null;
  24771. scope.allClipped = false;
  24772. scope.prevEl = null;
  24773. }
  24774. if (clipPaths && clipPaths.length) {
  24775. flushPathDrawn(ctx, scope);
  24776. ctx.save();
  24777. updateClipStatus(clipPaths, ctx, scope);
  24778. forceSetTransform = true;
  24779. }
  24780. scope.prevElClipPaths = clipPaths;
  24781. }
  24782. if (scope.allClipped) {
  24783. el.__isRendered = false;
  24784. return;
  24785. }
  24786. el.beforeBrush && el.beforeBrush();
  24787. el.innerBeforeBrush();
  24788. var prevEl = scope.prevEl;
  24789. if (!prevEl) {
  24790. forceSetStyle = forceSetTransform = true;
  24791. }
  24792. var canBatchPath = el instanceof Path
  24793. && el.autoBatch
  24794. && canPathBatch(el.style);
  24795. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  24796. flushPathDrawn(ctx, scope);
  24797. setContextTransform(ctx, el);
  24798. }
  24799. else if (!canBatchPath) {
  24800. flushPathDrawn(ctx, scope);
  24801. }
  24802. var style = getStyle(el, scope.inHover);
  24803. if (el instanceof Path) {
  24804. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  24805. forceSetStyle = true;
  24806. scope.lastDrawType = DRAW_TYPE_PATH;
  24807. }
  24808. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24809. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  24810. ctx.beginPath();
  24811. }
  24812. brushPath(ctx, el, style, canBatchPath);
  24813. if (canBatchPath) {
  24814. scope.batchFill = style.fill || '';
  24815. scope.batchStroke = style.stroke || '';
  24816. }
  24817. }
  24818. else {
  24819. if (el instanceof TSpan) {
  24820. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  24821. forceSetStyle = true;
  24822. scope.lastDrawType = DRAW_TYPE_TEXT;
  24823. }
  24824. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24825. brushText(ctx, el, style);
  24826. }
  24827. else if (el instanceof ZRImage) {
  24828. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  24829. forceSetStyle = true;
  24830. scope.lastDrawType = DRAW_TYPE_IMAGE;
  24831. }
  24832. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  24833. brushImage(ctx, el, style);
  24834. }
  24835. else if (el instanceof IncrementalDisplayable) {
  24836. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  24837. forceSetStyle = true;
  24838. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  24839. }
  24840. brushIncremental(ctx, el, scope);
  24841. }
  24842. }
  24843. if (canBatchPath && isLast) {
  24844. flushPathDrawn(ctx, scope);
  24845. }
  24846. el.innerAfterBrush();
  24847. el.afterBrush && el.afterBrush();
  24848. scope.prevEl = el;
  24849. el.__dirty = 0;
  24850. el.__isRendered = true;
  24851. }
  24852. function brushIncremental(ctx, el, scope) {
  24853. var displayables = el.getDisplayables();
  24854. var temporalDisplayables = el.getTemporalDisplayables();
  24855. ctx.save();
  24856. var innerScope = {
  24857. prevElClipPaths: null,
  24858. prevEl: null,
  24859. allClipped: false,
  24860. viewWidth: scope.viewWidth,
  24861. viewHeight: scope.viewHeight,
  24862. inHover: scope.inHover
  24863. };
  24864. var i;
  24865. var len;
  24866. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  24867. var displayable = displayables[i];
  24868. displayable.beforeBrush && displayable.beforeBrush();
  24869. displayable.innerBeforeBrush();
  24870. brush(ctx, displayable, innerScope, i === len - 1);
  24871. displayable.innerAfterBrush();
  24872. displayable.afterBrush && displayable.afterBrush();
  24873. innerScope.prevEl = displayable;
  24874. }
  24875. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  24876. var displayable = temporalDisplayables[i_1];
  24877. displayable.beforeBrush && displayable.beforeBrush();
  24878. displayable.innerBeforeBrush();
  24879. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  24880. displayable.innerAfterBrush();
  24881. displayable.afterBrush && displayable.afterBrush();
  24882. innerScope.prevEl = displayable;
  24883. }
  24884. el.clearTemporalDisplayables();
  24885. el.notClear = true;
  24886. ctx.restore();
  24887. }
  24888. var decalMap = new WeakMap();
  24889. var decalCache = new LRU(100);
  24890. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  24891. /**
  24892. * Create or update pattern image from decal options
  24893. *
  24894. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  24895. * @return {Pattern} pattern with generated image, null if no decal
  24896. */
  24897. function createOrUpdatePatternFromDecal(decalObject, api) {
  24898. if (decalObject === 'none') {
  24899. return null;
  24900. }
  24901. var dpr = api.getDevicePixelRatio();
  24902. var zr = api.getZr();
  24903. var isSVG = zr.painter.type === 'svg';
  24904. if (decalObject.dirty) {
  24905. decalMap["delete"](decalObject);
  24906. }
  24907. var oldPattern = decalMap.get(decalObject);
  24908. if (oldPattern) {
  24909. return oldPattern;
  24910. }
  24911. var decalOpt = defaults(decalObject, {
  24912. symbol: 'rect',
  24913. symbolSize: 1,
  24914. symbolKeepAspect: true,
  24915. color: 'rgba(0, 0, 0, 0.2)',
  24916. backgroundColor: null,
  24917. dashArrayX: 5,
  24918. dashArrayY: 5,
  24919. rotation: 0,
  24920. maxTileWidth: 512,
  24921. maxTileHeight: 512
  24922. });
  24923. if (decalOpt.backgroundColor === 'none') {
  24924. decalOpt.backgroundColor = null;
  24925. }
  24926. var pattern = {
  24927. repeat: 'repeat'
  24928. };
  24929. setPatternnSource(pattern);
  24930. pattern.rotation = decalOpt.rotation;
  24931. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  24932. decalMap.set(decalObject, pattern);
  24933. decalObject.dirty = false;
  24934. return pattern;
  24935. function setPatternnSource(pattern) {
  24936. var keys = [dpr];
  24937. var isValidKey = true;
  24938. for (var i = 0; i < decalKeys.length; ++i) {
  24939. var value = decalOpt[decalKeys[i]];
  24940. var valueType = typeof value;
  24941. if (value != null && !isArray(value) && valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') {
  24942. isValidKey = false;
  24943. break;
  24944. }
  24945. keys.push(value);
  24946. }
  24947. var cacheKey;
  24948. if (isValidKey) {
  24949. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  24950. var cache = decalCache.get(cacheKey);
  24951. if (cache) {
  24952. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  24953. }
  24954. }
  24955. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  24956. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  24957. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  24958. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  24959. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  24960. var canvas = !isSVG && createCanvas();
  24961. var svgRoot = isSVG && zr.painter.createSVGElement('g');
  24962. var pSize = getPatternSize();
  24963. var ctx;
  24964. if (canvas) {
  24965. canvas.width = pSize.width * dpr;
  24966. canvas.height = pSize.height * dpr;
  24967. ctx = canvas.getContext('2d');
  24968. }
  24969. brushDecal();
  24970. if (isValidKey) {
  24971. decalCache.put(cacheKey, canvas || svgRoot);
  24972. }
  24973. pattern.image = canvas;
  24974. pattern.svgElement = svgRoot;
  24975. pattern.svgWidth = pSize.width;
  24976. pattern.svgHeight = pSize.height;
  24977. /**
  24978. * Get minumum length that can make a repeatable pattern.
  24979. *
  24980. * @return {Object} pattern width and height
  24981. */
  24982. function getPatternSize() {
  24983. /**
  24984. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  24985. * |--- --- --- --- --- ...
  24986. * |-- -- -- -- -- -- -- -- ...
  24987. * |--- --- --- --- --- ...
  24988. * |-- -- -- -- -- -- -- -- ...
  24989. * So the minumum length of X is 15,
  24990. * which is the least common multiple of `3 + 2` and `2 + 1`
  24991. * |--- --- --- |--- --- ...
  24992. * |-- -- -- -- -- |-- -- -- ...
  24993. */
  24994. var width = 1;
  24995. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  24996. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  24997. }
  24998. var symbolRepeats = 1;
  24999. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  25000. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  25001. }
  25002. width *= symbolRepeats;
  25003. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  25004. if ("development" !== 'production') {
  25005. var warn = function (attrName) {
  25006. /* eslint-disable-next-line */
  25007. 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.");
  25008. };
  25009. if (width > decalOpt.maxTileWidth) {
  25010. warn('maxTileWidth');
  25011. }
  25012. if (height > decalOpt.maxTileHeight) {
  25013. warn('maxTileHeight');
  25014. }
  25015. }
  25016. return {
  25017. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  25018. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  25019. };
  25020. }
  25021. function brushDecal() {
  25022. if (ctx) {
  25023. ctx.clearRect(0, 0, canvas.width, canvas.height);
  25024. if (decalOpt.backgroundColor) {
  25025. ctx.fillStyle = decalOpt.backgroundColor;
  25026. ctx.fillRect(0, 0, canvas.width, canvas.height);
  25027. }
  25028. }
  25029. var ySum = 0;
  25030. for (var i = 0; i < dashArrayY.length; ++i) {
  25031. ySum += dashArrayY[i];
  25032. }
  25033. if (ySum <= 0) {
  25034. // dashArrayY is 0, draw nothing
  25035. return;
  25036. }
  25037. var y = -lineBlockLengthY;
  25038. var yId = 0;
  25039. var yIdTotal = 0;
  25040. var xId0 = 0;
  25041. while (y < pSize.height) {
  25042. if (yId % 2 === 0) {
  25043. var symbolYId = yIdTotal / 2 % symbolArray.length;
  25044. var x = 0;
  25045. var xId1 = 0;
  25046. var xId1Total = 0;
  25047. while (x < pSize.width * 2) {
  25048. var xSum = 0;
  25049. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  25050. xSum += dashArrayX[xId0][i];
  25051. }
  25052. if (xSum <= 0) {
  25053. // Skip empty line
  25054. break;
  25055. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  25056. if (xId1 % 2 === 0) {
  25057. var size = (1 - decalOpt.symbolSize) * 0.5;
  25058. var left = x + dashArrayX[xId0][xId1] * size;
  25059. var top_1 = y + dashArrayY[yId] * size;
  25060. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  25061. var height = dashArrayY[yId] * decalOpt.symbolSize;
  25062. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  25063. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  25064. }
  25065. x += dashArrayX[xId0][xId1];
  25066. ++xId1Total;
  25067. ++xId1;
  25068. if (xId1 === dashArrayX[xId0].length) {
  25069. xId1 = 0;
  25070. }
  25071. }
  25072. ++xId0;
  25073. if (xId0 === dashArrayX.length) {
  25074. xId0 = 0;
  25075. }
  25076. }
  25077. y += dashArrayY[yId];
  25078. ++yIdTotal;
  25079. ++yId;
  25080. if (yId === dashArrayY.length) {
  25081. yId = 0;
  25082. }
  25083. }
  25084. function brushSymbol(x, y, width, height, symbolType) {
  25085. var scale = isSVG ? 1 : dpr;
  25086. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  25087. if (isSVG) {
  25088. svgRoot.appendChild(zr.painter.paintOne(symbol));
  25089. } else {
  25090. // Paint to canvas for all other renderers.
  25091. brushSingle(ctx, symbol);
  25092. }
  25093. }
  25094. }
  25095. }
  25096. }
  25097. /**
  25098. * Convert symbol array into normalized array
  25099. *
  25100. * @param {string | (string | string[])[]} symbol symbol input
  25101. * @return {string[][]} normolized symbol array
  25102. */
  25103. function normalizeSymbolArray(symbol) {
  25104. if (!symbol || symbol.length === 0) {
  25105. return [['rect']];
  25106. }
  25107. if (typeof symbol === 'string') {
  25108. return [[symbol]];
  25109. }
  25110. var isAllString = true;
  25111. for (var i = 0; i < symbol.length; ++i) {
  25112. if (typeof symbol[i] !== 'string') {
  25113. isAllString = false;
  25114. break;
  25115. }
  25116. }
  25117. if (isAllString) {
  25118. return normalizeSymbolArray([symbol]);
  25119. }
  25120. var result = [];
  25121. for (var i = 0; i < symbol.length; ++i) {
  25122. if (typeof symbol[i] === 'string') {
  25123. result.push([symbol[i]]);
  25124. } else {
  25125. result.push(symbol[i]);
  25126. }
  25127. }
  25128. return result;
  25129. }
  25130. /**
  25131. * Convert dash input into dashArray
  25132. *
  25133. * @param {DecalDashArrayX} dash dash input
  25134. * @return {number[][]} normolized dash array
  25135. */
  25136. function normalizeDashArrayX(dash) {
  25137. if (!dash || dash.length === 0) {
  25138. return [[0, 0]];
  25139. }
  25140. if (typeof dash === 'number') {
  25141. var dashValue = Math.ceil(dash);
  25142. return [[dashValue, dashValue]];
  25143. }
  25144. /**
  25145. * [20, 5] should be normalized into [[20, 5]],
  25146. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  25147. */
  25148. var isAllNumber = true;
  25149. for (var i = 0; i < dash.length; ++i) {
  25150. if (typeof dash[i] !== 'number') {
  25151. isAllNumber = false;
  25152. break;
  25153. }
  25154. }
  25155. if (isAllNumber) {
  25156. return normalizeDashArrayX([dash]);
  25157. }
  25158. var result = [];
  25159. for (var i = 0; i < dash.length; ++i) {
  25160. if (typeof dash[i] === 'number') {
  25161. var dashValue = Math.ceil(dash[i]);
  25162. result.push([dashValue, dashValue]);
  25163. } else {
  25164. var dashValue = map(dash[i], function (n) {
  25165. return Math.ceil(n);
  25166. });
  25167. if (dashValue.length % 2 === 1) {
  25168. // [4, 2, 1] means |---- - -- |---- - -- |
  25169. // so normalize it to be [4, 2, 1, 4, 2, 1]
  25170. result.push(dashValue.concat(dashValue));
  25171. } else {
  25172. result.push(dashValue);
  25173. }
  25174. }
  25175. }
  25176. return result;
  25177. }
  25178. /**
  25179. * Convert dash input into dashArray
  25180. *
  25181. * @param {DecalDashArrayY} dash dash input
  25182. * @return {number[]} normolized dash array
  25183. */
  25184. function normalizeDashArrayY(dash) {
  25185. if (!dash || typeof dash === 'object' && dash.length === 0) {
  25186. return [0, 0];
  25187. }
  25188. if (typeof dash === 'number') {
  25189. var dashValue_1 = Math.ceil(dash);
  25190. return [dashValue_1, dashValue_1];
  25191. }
  25192. var dashValue = map(dash, function (n) {
  25193. return Math.ceil(n);
  25194. });
  25195. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  25196. }
  25197. /**
  25198. * Get block length of each line. A block is the length of dash line and space.
  25199. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  25200. * that, so the block length of this line is 5.
  25201. *
  25202. * @param {number[][]} dash dash arrary of X or Y
  25203. * @return {number[]} block length of each line
  25204. */
  25205. function getLineBlockLengthX(dash) {
  25206. return map(dash, function (line) {
  25207. return getLineBlockLengthY(line);
  25208. });
  25209. }
  25210. function getLineBlockLengthY(dash) {
  25211. var blockLength = 0;
  25212. for (var i = 0; i < dash.length; ++i) {
  25213. blockLength += dash[i];
  25214. }
  25215. if (dash.length % 2 === 1) {
  25216. // [4, 2, 1] means |---- - -- |---- - -- |
  25217. // So total length is (4 + 2 + 1) * 2
  25218. return blockLength * 2;
  25219. }
  25220. return blockLength;
  25221. }
  25222. function decalVisual(ecModel, api) {
  25223. ecModel.eachRawSeries(function (seriesModel) {
  25224. if (ecModel.isSeriesFiltered(seriesModel)) {
  25225. return;
  25226. }
  25227. var data = seriesModel.getData();
  25228. if (data.hasItemVisual()) {
  25229. data.each(function (idx) {
  25230. var decal = data.getItemVisual(idx, 'decal');
  25231. if (decal) {
  25232. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  25233. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  25234. }
  25235. });
  25236. }
  25237. var decal = data.getVisual('decal');
  25238. if (decal) {
  25239. var style = data.getVisual('style');
  25240. style.decal = createOrUpdatePatternFromDecal(decal, api);
  25241. }
  25242. });
  25243. }
  25244. function parseXML(svg) {
  25245. if (isString(svg)) {
  25246. var parser = new DOMParser();
  25247. svg = parser.parseFromString(svg, 'text/xml');
  25248. }
  25249. var svgNode = svg;
  25250. if (svgNode.nodeType === 9) {
  25251. svgNode = svgNode.firstChild;
  25252. }
  25253. while (svgNode.nodeName.toLowerCase() !== 'svg' || svgNode.nodeType !== 1) {
  25254. svgNode = svgNode.nextSibling;
  25255. }
  25256. return svgNode;
  25257. }
  25258. var nodeParsers;
  25259. var INHERITABLE_STYLE_ATTRIBUTES_MAP = {
  25260. 'fill': 'fill',
  25261. 'stroke': 'stroke',
  25262. 'stroke-width': 'lineWidth',
  25263. 'opacity': 'opacity',
  25264. 'fill-opacity': 'fillOpacity',
  25265. 'stroke-opacity': 'strokeOpacity',
  25266. 'stroke-dasharray': 'lineDash',
  25267. 'stroke-dashoffset': 'lineDashOffset',
  25268. 'stroke-linecap': 'lineCap',
  25269. 'stroke-linejoin': 'lineJoin',
  25270. 'stroke-miterlimit': 'miterLimit',
  25271. 'font-family': 'fontFamily',
  25272. 'font-size': 'fontSize',
  25273. 'font-style': 'fontStyle',
  25274. 'font-weight': 'fontWeight',
  25275. 'text-anchor': 'textAlign',
  25276. 'visibility': 'visibility',
  25277. 'display': 'display'
  25278. };
  25279. var INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS = keys(INHERITABLE_STYLE_ATTRIBUTES_MAP);
  25280. var SELF_STYLE_ATTRIBUTES_MAP = {
  25281. 'alignment-baseline': 'textBaseline',
  25282. 'stop-color': 'stopColor'
  25283. };
  25284. var SELF_STYLE_ATTRIBUTES_MAP_KEYS = keys(SELF_STYLE_ATTRIBUTES_MAP);
  25285. var SVGParser = (function () {
  25286. function SVGParser() {
  25287. this._defs = {};
  25288. this._root = null;
  25289. }
  25290. SVGParser.prototype.parse = function (xml, opt) {
  25291. opt = opt || {};
  25292. var svg = parseXML(xml);
  25293. if (!svg) {
  25294. throw new Error('Illegal svg');
  25295. }
  25296. this._defsUsePending = [];
  25297. var root = new Group();
  25298. this._root = root;
  25299. var named = [];
  25300. var viewBox = svg.getAttribute('viewBox') || '';
  25301. var width = parseFloat((svg.getAttribute('width') || opt.width));
  25302. var height = parseFloat((svg.getAttribute('height') || opt.height));
  25303. isNaN(width) && (width = null);
  25304. isNaN(height) && (height = null);
  25305. parseAttributes(svg, root, null, true, false);
  25306. var child = svg.firstChild;
  25307. while (child) {
  25308. this._parseNode(child, root, named, null, false, false);
  25309. child = child.nextSibling;
  25310. }
  25311. applyDefs(this._defs, this._defsUsePending);
  25312. this._defsUsePending = [];
  25313. var viewBoxRect;
  25314. var viewBoxTransform;
  25315. if (viewBox) {
  25316. var viewBoxArr = splitNumberSequence(viewBox);
  25317. if (viewBoxArr.length >= 4) {
  25318. viewBoxRect = {
  25319. x: parseFloat((viewBoxArr[0] || 0)),
  25320. y: parseFloat((viewBoxArr[1] || 0)),
  25321. width: parseFloat(viewBoxArr[2]),
  25322. height: parseFloat(viewBoxArr[3])
  25323. };
  25324. }
  25325. }
  25326. if (viewBoxRect && width != null && height != null) {
  25327. viewBoxTransform = makeViewBoxTransform(viewBoxRect, { x: 0, y: 0, width: width, height: height });
  25328. if (!opt.ignoreViewBox) {
  25329. var elRoot = root;
  25330. root = new Group();
  25331. root.add(elRoot);
  25332. elRoot.scaleX = elRoot.scaleY = viewBoxTransform.scale;
  25333. elRoot.x = viewBoxTransform.x;
  25334. elRoot.y = viewBoxTransform.y;
  25335. }
  25336. }
  25337. if (!opt.ignoreRootClip && width != null && height != null) {
  25338. root.setClipPath(new Rect({
  25339. shape: { x: 0, y: 0, width: width, height: height }
  25340. }));
  25341. }
  25342. return {
  25343. root: root,
  25344. width: width,
  25345. height: height,
  25346. viewBoxRect: viewBoxRect,
  25347. viewBoxTransform: viewBoxTransform,
  25348. named: named
  25349. };
  25350. };
  25351. SVGParser.prototype._parseNode = function (xmlNode, parentGroup, named, namedFrom, isInDefs, isInText) {
  25352. var nodeName = xmlNode.nodeName.toLowerCase();
  25353. var el;
  25354. var namedFromForSub = namedFrom;
  25355. if (nodeName === 'defs') {
  25356. isInDefs = true;
  25357. }
  25358. if (nodeName === 'text') {
  25359. isInText = true;
  25360. }
  25361. if (nodeName === 'defs' || nodeName === 'switch') {
  25362. el = parentGroup;
  25363. }
  25364. else {
  25365. if (!isInDefs) {
  25366. var parser_1 = nodeParsers[nodeName];
  25367. if (parser_1 && hasOwn(nodeParsers, nodeName)) {
  25368. el = parser_1.call(this, xmlNode, parentGroup);
  25369. var nameAttr = xmlNode.getAttribute('name');
  25370. if (nameAttr) {
  25371. var newNamed = {
  25372. name: nameAttr,
  25373. namedFrom: null,
  25374. svgNodeTagLower: nodeName,
  25375. el: el
  25376. };
  25377. named.push(newNamed);
  25378. if (nodeName === 'g') {
  25379. namedFromForSub = newNamed;
  25380. }
  25381. }
  25382. else if (namedFrom) {
  25383. named.push({
  25384. name: namedFrom.name,
  25385. namedFrom: namedFrom,
  25386. svgNodeTagLower: nodeName,
  25387. el: el
  25388. });
  25389. }
  25390. parentGroup.add(el);
  25391. }
  25392. }
  25393. var parser = paintServerParsers[nodeName];
  25394. if (parser && hasOwn(paintServerParsers, nodeName)) {
  25395. var def = parser.call(this, xmlNode);
  25396. var id = xmlNode.getAttribute('id');
  25397. if (id) {
  25398. this._defs[id] = def;
  25399. }
  25400. }
  25401. }
  25402. if (el && el.isGroup) {
  25403. var child = xmlNode.firstChild;
  25404. while (child) {
  25405. if (child.nodeType === 1) {
  25406. this._parseNode(child, el, named, namedFromForSub, isInDefs, isInText);
  25407. }
  25408. else if (child.nodeType === 3 && isInText) {
  25409. this._parseText(child, el);
  25410. }
  25411. child = child.nextSibling;
  25412. }
  25413. }
  25414. };
  25415. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  25416. var text = new TSpan({
  25417. style: {
  25418. text: xmlNode.textContent
  25419. },
  25420. silent: true,
  25421. x: this._textX || 0,
  25422. y: this._textY || 0
  25423. });
  25424. inheritStyle(parentGroup, text);
  25425. parseAttributes(xmlNode, text, this._defsUsePending, false, false);
  25426. applyTextAlignment(text, parentGroup);
  25427. var textStyle = text.style;
  25428. var fontSize = textStyle.fontSize;
  25429. if (fontSize && fontSize < 9) {
  25430. textStyle.fontSize = 9;
  25431. text.scaleX *= fontSize / 9;
  25432. text.scaleY *= fontSize / 9;
  25433. }
  25434. var font = (textStyle.fontSize || textStyle.fontFamily) && [
  25435. textStyle.fontStyle,
  25436. textStyle.fontWeight,
  25437. (textStyle.fontSize || 12) + 'px',
  25438. textStyle.fontFamily || 'sans-serif'
  25439. ].join(' ');
  25440. textStyle.font = font;
  25441. var rect = text.getBoundingRect();
  25442. this._textX += rect.width;
  25443. parentGroup.add(text);
  25444. return text;
  25445. };
  25446. SVGParser.internalField = (function () {
  25447. nodeParsers = {
  25448. 'g': function (xmlNode, parentGroup) {
  25449. var g = new Group();
  25450. inheritStyle(parentGroup, g);
  25451. parseAttributes(xmlNode, g, this._defsUsePending, false, false);
  25452. return g;
  25453. },
  25454. 'rect': function (xmlNode, parentGroup) {
  25455. var rect = new Rect();
  25456. inheritStyle(parentGroup, rect);
  25457. parseAttributes(xmlNode, rect, this._defsUsePending, false, false);
  25458. rect.setShape({
  25459. x: parseFloat(xmlNode.getAttribute('x') || '0'),
  25460. y: parseFloat(xmlNode.getAttribute('y') || '0'),
  25461. width: parseFloat(xmlNode.getAttribute('width') || '0'),
  25462. height: parseFloat(xmlNode.getAttribute('height') || '0')
  25463. });
  25464. rect.silent = true;
  25465. return rect;
  25466. },
  25467. 'circle': function (xmlNode, parentGroup) {
  25468. var circle = new Circle();
  25469. inheritStyle(parentGroup, circle);
  25470. parseAttributes(xmlNode, circle, this._defsUsePending, false, false);
  25471. circle.setShape({
  25472. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  25473. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  25474. r: parseFloat(xmlNode.getAttribute('r') || '0')
  25475. });
  25476. circle.silent = true;
  25477. return circle;
  25478. },
  25479. 'line': function (xmlNode, parentGroup) {
  25480. var line = new Line();
  25481. inheritStyle(parentGroup, line);
  25482. parseAttributes(xmlNode, line, this._defsUsePending, false, false);
  25483. line.setShape({
  25484. x1: parseFloat(xmlNode.getAttribute('x1') || '0'),
  25485. y1: parseFloat(xmlNode.getAttribute('y1') || '0'),
  25486. x2: parseFloat(xmlNode.getAttribute('x2') || '0'),
  25487. y2: parseFloat(xmlNode.getAttribute('y2') || '0')
  25488. });
  25489. line.silent = true;
  25490. return line;
  25491. },
  25492. 'ellipse': function (xmlNode, parentGroup) {
  25493. var ellipse = new Ellipse();
  25494. inheritStyle(parentGroup, ellipse);
  25495. parseAttributes(xmlNode, ellipse, this._defsUsePending, false, false);
  25496. ellipse.setShape({
  25497. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  25498. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  25499. rx: parseFloat(xmlNode.getAttribute('rx') || '0'),
  25500. ry: parseFloat(xmlNode.getAttribute('ry') || '0')
  25501. });
  25502. ellipse.silent = true;
  25503. return ellipse;
  25504. },
  25505. 'polygon': function (xmlNode, parentGroup) {
  25506. var pointsStr = xmlNode.getAttribute('points');
  25507. var pointsArr;
  25508. if (pointsStr) {
  25509. pointsArr = parsePoints(pointsStr);
  25510. }
  25511. var polygon = new Polygon({
  25512. shape: {
  25513. points: pointsArr || []
  25514. },
  25515. silent: true
  25516. });
  25517. inheritStyle(parentGroup, polygon);
  25518. parseAttributes(xmlNode, polygon, this._defsUsePending, false, false);
  25519. return polygon;
  25520. },
  25521. 'polyline': function (xmlNode, parentGroup) {
  25522. var pointsStr = xmlNode.getAttribute('points');
  25523. var pointsArr;
  25524. if (pointsStr) {
  25525. pointsArr = parsePoints(pointsStr);
  25526. }
  25527. var polyline = new Polyline({
  25528. shape: {
  25529. points: pointsArr || []
  25530. },
  25531. silent: true
  25532. });
  25533. inheritStyle(parentGroup, polyline);
  25534. parseAttributes(xmlNode, polyline, this._defsUsePending, false, false);
  25535. return polyline;
  25536. },
  25537. 'image': function (xmlNode, parentGroup) {
  25538. var img = new ZRImage();
  25539. inheritStyle(parentGroup, img);
  25540. parseAttributes(xmlNode, img, this._defsUsePending, false, false);
  25541. img.setStyle({
  25542. image: xmlNode.getAttribute('xlink:href'),
  25543. x: +xmlNode.getAttribute('x'),
  25544. y: +xmlNode.getAttribute('y'),
  25545. width: +xmlNode.getAttribute('width'),
  25546. height: +xmlNode.getAttribute('height')
  25547. });
  25548. img.silent = true;
  25549. return img;
  25550. },
  25551. 'text': function (xmlNode, parentGroup) {
  25552. var x = xmlNode.getAttribute('x') || '0';
  25553. var y = xmlNode.getAttribute('y') || '0';
  25554. var dx = xmlNode.getAttribute('dx') || '0';
  25555. var dy = xmlNode.getAttribute('dy') || '0';
  25556. this._textX = parseFloat(x) + parseFloat(dx);
  25557. this._textY = parseFloat(y) + parseFloat(dy);
  25558. var g = new Group();
  25559. inheritStyle(parentGroup, g);
  25560. parseAttributes(xmlNode, g, this._defsUsePending, false, true);
  25561. return g;
  25562. },
  25563. 'tspan': function (xmlNode, parentGroup) {
  25564. var x = xmlNode.getAttribute('x');
  25565. var y = xmlNode.getAttribute('y');
  25566. if (x != null) {
  25567. this._textX = parseFloat(x);
  25568. }
  25569. if (y != null) {
  25570. this._textY = parseFloat(y);
  25571. }
  25572. var dx = xmlNode.getAttribute('dx') || '0';
  25573. var dy = xmlNode.getAttribute('dy') || '0';
  25574. var g = new Group();
  25575. inheritStyle(parentGroup, g);
  25576. parseAttributes(xmlNode, g, this._defsUsePending, false, true);
  25577. this._textX += parseFloat(dx);
  25578. this._textY += parseFloat(dy);
  25579. return g;
  25580. },
  25581. 'path': function (xmlNode, parentGroup) {
  25582. var d = xmlNode.getAttribute('d') || '';
  25583. var path = createFromString(d);
  25584. inheritStyle(parentGroup, path);
  25585. parseAttributes(xmlNode, path, this._defsUsePending, false, false);
  25586. path.silent = true;
  25587. return path;
  25588. }
  25589. };
  25590. })();
  25591. return SVGParser;
  25592. }());
  25593. var paintServerParsers = {
  25594. 'lineargradient': function (xmlNode) {
  25595. var x1 = parseInt(xmlNode.getAttribute('x1') || '0', 10);
  25596. var y1 = parseInt(xmlNode.getAttribute('y1') || '0', 10);
  25597. var x2 = parseInt(xmlNode.getAttribute('x2') || '10', 10);
  25598. var y2 = parseInt(xmlNode.getAttribute('y2') || '0', 10);
  25599. var gradient = new LinearGradient(x1, y1, x2, y2);
  25600. parsePaintServerUnit(xmlNode, gradient);
  25601. parseGradientColorStops(xmlNode, gradient);
  25602. return gradient;
  25603. },
  25604. 'radialgradient': function (xmlNode) {
  25605. var cx = parseInt(xmlNode.getAttribute('cx') || '0', 10);
  25606. var cy = parseInt(xmlNode.getAttribute('cy') || '0', 10);
  25607. var r = parseInt(xmlNode.getAttribute('r') || '0', 10);
  25608. var gradient = new RadialGradient(cx, cy, r);
  25609. parsePaintServerUnit(xmlNode, gradient);
  25610. parseGradientColorStops(xmlNode, gradient);
  25611. return gradient;
  25612. }
  25613. };
  25614. function parsePaintServerUnit(xmlNode, gradient) {
  25615. var gradientUnits = xmlNode.getAttribute('gradientUnits');
  25616. if (gradientUnits === 'userSpaceOnUse') {
  25617. gradient.global = true;
  25618. }
  25619. }
  25620. function parseGradientColorStops(xmlNode, gradient) {
  25621. var stop = xmlNode.firstChild;
  25622. while (stop) {
  25623. if (stop.nodeType === 1
  25624. && stop.nodeName.toLocaleLowerCase() === 'stop') {
  25625. var offsetStr = stop.getAttribute('offset');
  25626. var offset = void 0;
  25627. if (offsetStr && offsetStr.indexOf('%') > 0) {
  25628. offset = parseInt(offsetStr, 10) / 100;
  25629. }
  25630. else if (offsetStr) {
  25631. offset = parseFloat(offsetStr);
  25632. }
  25633. else {
  25634. offset = 0;
  25635. }
  25636. var styleVals = {};
  25637. parseInlineStyle(stop, styleVals, styleVals);
  25638. var stopColor = styleVals.stopColor
  25639. || stop.getAttribute('stop-color')
  25640. || '#000000';
  25641. gradient.colorStops.push({
  25642. offset: offset,
  25643. color: stopColor
  25644. });
  25645. }
  25646. stop = stop.nextSibling;
  25647. }
  25648. }
  25649. function inheritStyle(parent, child) {
  25650. if (parent && parent.__inheritedStyle) {
  25651. if (!child.__inheritedStyle) {
  25652. child.__inheritedStyle = {};
  25653. }
  25654. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  25655. }
  25656. }
  25657. function parsePoints(pointsString) {
  25658. var list = splitNumberSequence(pointsString);
  25659. var points = [];
  25660. for (var i = 0; i < list.length; i += 2) {
  25661. var x = parseFloat(list[i]);
  25662. var y = parseFloat(list[i + 1]);
  25663. points.push([x, y]);
  25664. }
  25665. return points;
  25666. }
  25667. function parseAttributes(xmlNode, el, defsUsePending, onlyInlineStyle, isTextGroup) {
  25668. var disp = el;
  25669. var inheritedStyle = disp.__inheritedStyle = disp.__inheritedStyle || {};
  25670. var selfStyle = {};
  25671. if (xmlNode.nodeType === 1) {
  25672. parseTransformAttribute(xmlNode, el);
  25673. parseInlineStyle(xmlNode, inheritedStyle, selfStyle);
  25674. if (!onlyInlineStyle) {
  25675. parseAttributeStyle(xmlNode, inheritedStyle, selfStyle);
  25676. }
  25677. }
  25678. disp.style = disp.style || {};
  25679. if (inheritedStyle.fill != null) {
  25680. disp.style.fill = getFillStrokeStyle(disp, 'fill', inheritedStyle.fill, defsUsePending);
  25681. }
  25682. if (inheritedStyle.stroke != null) {
  25683. disp.style.stroke = getFillStrokeStyle(disp, 'stroke', inheritedStyle.stroke, defsUsePending);
  25684. }
  25685. each([
  25686. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  25687. ], function (propName) {
  25688. if (inheritedStyle[propName] != null) {
  25689. disp.style[propName] = parseFloat(inheritedStyle[propName]);
  25690. }
  25691. });
  25692. each([
  25693. 'lineDashOffset', 'lineCap', 'lineJoin', 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign'
  25694. ], function (propName) {
  25695. if (inheritedStyle[propName] != null) {
  25696. disp.style[propName] = inheritedStyle[propName];
  25697. }
  25698. });
  25699. if (isTextGroup) {
  25700. disp.__selfStyle = selfStyle;
  25701. }
  25702. if (inheritedStyle.lineDash) {
  25703. disp.style.lineDash = map(splitNumberSequence(inheritedStyle.lineDash), function (str) {
  25704. return parseFloat(str);
  25705. });
  25706. }
  25707. if (inheritedStyle.visibility === 'hidden' || inheritedStyle.visibility === 'collapse') {
  25708. disp.invisible = true;
  25709. }
  25710. if (inheritedStyle.display === 'none') {
  25711. disp.ignore = true;
  25712. }
  25713. }
  25714. function applyTextAlignment(text, parentGroup) {
  25715. var parentSelfStyle = parentGroup.__selfStyle;
  25716. if (parentSelfStyle) {
  25717. var textBaseline = parentSelfStyle.textBaseline;
  25718. var zrTextBaseline = textBaseline;
  25719. if (!textBaseline || textBaseline === 'auto') {
  25720. zrTextBaseline = 'alphabetic';
  25721. }
  25722. else if (textBaseline === 'baseline') {
  25723. zrTextBaseline = 'alphabetic';
  25724. }
  25725. else if (textBaseline === 'before-edge' || textBaseline === 'text-before-edge') {
  25726. zrTextBaseline = 'top';
  25727. }
  25728. else if (textBaseline === 'after-edge' || textBaseline === 'text-after-edge') {
  25729. zrTextBaseline = 'bottom';
  25730. }
  25731. else if (textBaseline === 'central' || textBaseline === 'mathematical') {
  25732. zrTextBaseline = 'middle';
  25733. }
  25734. text.style.textBaseline = zrTextBaseline;
  25735. }
  25736. var parentInheritedStyle = parentGroup.__inheritedStyle;
  25737. if (parentInheritedStyle) {
  25738. var textAlign = parentInheritedStyle.textAlign;
  25739. var zrTextAlign = textAlign;
  25740. if (textAlign) {
  25741. if (textAlign === 'middle') {
  25742. zrTextAlign = 'center';
  25743. }
  25744. text.style.textAlign = zrTextAlign;
  25745. }
  25746. }
  25747. }
  25748. var urlRegex = /^url\(\s*#(.*?)\)/;
  25749. function getFillStrokeStyle(el, method, str, defsUsePending) {
  25750. var urlMatch = str && str.match(urlRegex);
  25751. if (urlMatch) {
  25752. var url = trim(urlMatch[1]);
  25753. defsUsePending.push([el, method, url]);
  25754. return;
  25755. }
  25756. if (str === 'none') {
  25757. str = null;
  25758. }
  25759. return str;
  25760. }
  25761. function applyDefs(defs, defsUsePending) {
  25762. for (var i = 0; i < defsUsePending.length; i++) {
  25763. var item = defsUsePending[i];
  25764. item[0].style[item[1]] = defs[item[2]];
  25765. }
  25766. }
  25767. var numberReg$1 = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  25768. function splitNumberSequence(rawStr) {
  25769. return rawStr.match(numberReg$1) || [];
  25770. }
  25771. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.eE,]*)\)/g;
  25772. var DEGREE_TO_ANGLE = Math.PI / 180;
  25773. function parseTransformAttribute(xmlNode, node) {
  25774. var transform = xmlNode.getAttribute('transform');
  25775. if (transform) {
  25776. transform = transform.replace(/,/g, ' ');
  25777. var transformOps_1 = [];
  25778. var mt = null;
  25779. transform.replace(transformRegex, function (str, type, value) {
  25780. transformOps_1.push(type, value);
  25781. return '';
  25782. });
  25783. for (var i = transformOps_1.length - 1; i > 0; i -= 2) {
  25784. var value = transformOps_1[i];
  25785. var type = transformOps_1[i - 1];
  25786. var valueArr = splitNumberSequence(value);
  25787. mt = mt || create$1();
  25788. switch (type) {
  25789. case 'translate':
  25790. translate(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || '0')]);
  25791. break;
  25792. case 'scale':
  25793. scale$1(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || valueArr[0])]);
  25794. break;
  25795. case 'rotate':
  25796. rotate(mt, mt, -parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  25797. break;
  25798. case 'skewX':
  25799. var sx = Math.tan(parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  25800. mul$1(mt, [1, 0, sx, 1, 0, 0], mt);
  25801. break;
  25802. case 'skewY':
  25803. var sy = Math.tan(parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  25804. mul$1(mt, [1, sy, 0, 1, 0, 0], mt);
  25805. break;
  25806. case 'matrix':
  25807. mt[0] = parseFloat(valueArr[0]);
  25808. mt[1] = parseFloat(valueArr[1]);
  25809. mt[2] = parseFloat(valueArr[2]);
  25810. mt[3] = parseFloat(valueArr[3]);
  25811. mt[4] = parseFloat(valueArr[4]);
  25812. mt[5] = parseFloat(valueArr[5]);
  25813. break;
  25814. }
  25815. }
  25816. node.setLocalTransform(mt);
  25817. }
  25818. }
  25819. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  25820. function parseInlineStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
  25821. var style = xmlNode.getAttribute('style');
  25822. if (!style) {
  25823. return;
  25824. }
  25825. styleRegex.lastIndex = 0;
  25826. var styleRegResult;
  25827. while ((styleRegResult = styleRegex.exec(style)) != null) {
  25828. var svgStlAttr = styleRegResult[1];
  25829. var zrInheritableStlAttr = hasOwn(INHERITABLE_STYLE_ATTRIBUTES_MAP, svgStlAttr)
  25830. ? INHERITABLE_STYLE_ATTRIBUTES_MAP[svgStlAttr]
  25831. : null;
  25832. if (zrInheritableStlAttr) {
  25833. inheritableStyleResult[zrInheritableStlAttr] = styleRegResult[2];
  25834. }
  25835. var zrSelfStlAttr = hasOwn(SELF_STYLE_ATTRIBUTES_MAP, svgStlAttr)
  25836. ? SELF_STYLE_ATTRIBUTES_MAP[svgStlAttr]
  25837. : null;
  25838. if (zrSelfStlAttr) {
  25839. selfStyleResult[zrSelfStlAttr] = styleRegResult[2];
  25840. }
  25841. }
  25842. }
  25843. function parseAttributeStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
  25844. for (var i = 0; i < INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
  25845. var svgAttrName = INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS[i];
  25846. var attrValue = xmlNode.getAttribute(svgAttrName);
  25847. if (attrValue != null) {
  25848. inheritableStyleResult[INHERITABLE_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
  25849. }
  25850. }
  25851. for (var i = 0; i < SELF_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
  25852. var svgAttrName = SELF_STYLE_ATTRIBUTES_MAP_KEYS[i];
  25853. var attrValue = xmlNode.getAttribute(svgAttrName);
  25854. if (attrValue != null) {
  25855. selfStyleResult[SELF_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
  25856. }
  25857. }
  25858. }
  25859. function makeViewBoxTransform(viewBoxRect, boundingRect) {
  25860. var scaleX = boundingRect.width / viewBoxRect.width;
  25861. var scaleY = boundingRect.height / viewBoxRect.height;
  25862. var scale = Math.min(scaleX, scaleY);
  25863. return {
  25864. scale: scale,
  25865. x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + (boundingRect.x + boundingRect.width / 2),
  25866. y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + (boundingRect.y + boundingRect.height / 2)
  25867. };
  25868. }
  25869. function parseSVG(xml, opt) {
  25870. var parser = new SVGParser();
  25871. return parser.parse(xml, opt);
  25872. }
  25873. var EPSILON$3 = 1e-8;
  25874. function isAroundEqual$1(a, b) {
  25875. return Math.abs(a - b) < EPSILON$3;
  25876. }
  25877. function contain$1(points, x, y) {
  25878. var w = 0;
  25879. var p = points[0];
  25880. if (!p) {
  25881. return false;
  25882. }
  25883. for (var i = 1; i < points.length; i++) {
  25884. var p2 = points[i];
  25885. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  25886. p = p2;
  25887. }
  25888. var p0 = points[0];
  25889. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  25890. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  25891. }
  25892. return w !== 0;
  25893. }
  25894. var TMP_TRANSFORM = [];
  25895. var Region =
  25896. /** @class */
  25897. function () {
  25898. function Region(name) {
  25899. this.name = name;
  25900. }
  25901. /**
  25902. * Get center point in data unit. That is,
  25903. * for GeoJSONRegion, the unit is lat/lng,
  25904. * for GeoSVGRegion, the unit is SVG local coord.
  25905. */
  25906. Region.prototype.getCenter = function () {
  25907. return;
  25908. };
  25909. return Region;
  25910. }();
  25911. var GeoJSONRegion =
  25912. /** @class */
  25913. function (_super) {
  25914. __extends(GeoJSONRegion, _super);
  25915. function GeoJSONRegion(name, geometries, cp) {
  25916. var _this = _super.call(this, name) || this;
  25917. _this.type = 'geoJSON';
  25918. _this.geometries = geometries;
  25919. if (!cp) {
  25920. var rect = _this.getBoundingRect();
  25921. cp = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  25922. } else {
  25923. cp = [cp[0], cp[1]];
  25924. }
  25925. _this._center = cp;
  25926. return _this;
  25927. }
  25928. GeoJSONRegion.prototype.getBoundingRect = function () {
  25929. var rect = this._rect;
  25930. if (rect) {
  25931. return rect;
  25932. }
  25933. var MAX_NUMBER = Number.MAX_VALUE;
  25934. var min$1 = [MAX_NUMBER, MAX_NUMBER];
  25935. var max$1 = [-MAX_NUMBER, -MAX_NUMBER];
  25936. var min2 = [];
  25937. var max2 = [];
  25938. var geometries = this.geometries;
  25939. var i = 0;
  25940. for (; i < geometries.length; i++) {
  25941. // Only support polygon
  25942. if (geometries[i].type !== 'polygon') {
  25943. continue;
  25944. } // Doesn't consider hole
  25945. var exterior = geometries[i].exterior;
  25946. fromPoints(exterior, min2, max2);
  25947. min(min$1, min$1, min2);
  25948. max(max$1, max$1, max2);
  25949. } // No data
  25950. if (i === 0) {
  25951. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  25952. }
  25953. return this._rect = new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  25954. };
  25955. GeoJSONRegion.prototype.contain = function (coord) {
  25956. var rect = this.getBoundingRect();
  25957. var geometries = this.geometries;
  25958. if (!rect.contain(coord[0], coord[1])) {
  25959. return false;
  25960. }
  25961. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  25962. // Only support polygon.
  25963. if (geometries[i].type !== 'polygon') {
  25964. continue;
  25965. }
  25966. var exterior = geometries[i].exterior;
  25967. var interiors = geometries[i].interiors;
  25968. if (contain$1(exterior, coord[0], coord[1])) {
  25969. // Not in the region if point is in the hole.
  25970. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  25971. if (contain$1(interiors[k], coord[0], coord[1])) {
  25972. continue loopGeo;
  25973. }
  25974. }
  25975. return true;
  25976. }
  25977. }
  25978. return false;
  25979. };
  25980. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  25981. var rect = this.getBoundingRect();
  25982. var aspect = rect.width / rect.height;
  25983. if (!width) {
  25984. width = aspect * height;
  25985. } else if (!height) {
  25986. height = width / aspect;
  25987. }
  25988. var target = new BoundingRect(x, y, width, height);
  25989. var transform = rect.calculateTransform(target);
  25990. var geometries = this.geometries;
  25991. for (var i = 0; i < geometries.length; i++) {
  25992. // Only support polygon.
  25993. if (geometries[i].type !== 'polygon') {
  25994. continue;
  25995. }
  25996. var exterior = geometries[i].exterior;
  25997. var interiors = geometries[i].interiors;
  25998. for (var p = 0; p < exterior.length; p++) {
  25999. applyTransform(exterior[p], exterior[p], transform);
  26000. }
  26001. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  26002. for (var p = 0; p < interiors[h].length; p++) {
  26003. applyTransform(interiors[h][p], interiors[h][p], transform);
  26004. }
  26005. }
  26006. }
  26007. rect = this._rect;
  26008. rect.copy(target); // Update center
  26009. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  26010. };
  26011. GeoJSONRegion.prototype.cloneShallow = function (name) {
  26012. name == null && (name = this.name);
  26013. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  26014. newRegion._rect = this._rect;
  26015. newRegion.transformTo = null; // Simply avoid to be called.
  26016. return newRegion;
  26017. };
  26018. GeoJSONRegion.prototype.getCenter = function () {
  26019. return this._center;
  26020. };
  26021. GeoJSONRegion.prototype.setCenter = function (center) {
  26022. this._center = center;
  26023. };
  26024. return GeoJSONRegion;
  26025. }(Region);
  26026. var GeoSVGRegion =
  26027. /** @class */
  26028. function (_super) {
  26029. __extends(GeoSVGRegion, _super);
  26030. function GeoSVGRegion(name, elOnlyForCalculate) {
  26031. var _this = _super.call(this, name) || this;
  26032. _this.type = 'geoSVG';
  26033. _this._elOnlyForCalculate = elOnlyForCalculate;
  26034. return _this;
  26035. }
  26036. GeoSVGRegion.prototype.getCenter = function () {
  26037. var center = this._center;
  26038. if (!center) {
  26039. // In most cases there are no need to calculate this center.
  26040. // So calculate only when called.
  26041. center = this._center = this._calculateCenter();
  26042. }
  26043. return center;
  26044. };
  26045. GeoSVGRegion.prototype._calculateCenter = function () {
  26046. var el = this._elOnlyForCalculate;
  26047. var rect = el.getBoundingRect();
  26048. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  26049. var mat = identity(TMP_TRANSFORM);
  26050. var target = el;
  26051. while (target && !target.isGeoSVGGraphicRoot) {
  26052. mul$1(mat, target.getLocalTransform(), mat);
  26053. target = target.parent;
  26054. }
  26055. invert(mat, mat);
  26056. applyTransform(center, center, mat);
  26057. return center;
  26058. };
  26059. return GeoSVGRegion;
  26060. }(Region);
  26061. /**
  26062. * "region available" means that: enable users to set attribute `name="xxx"` on those tags
  26063. * to make it be a region.
  26064. * 1. region styles and its label styles can be defined in echarts opton:
  26065. * ```js
  26066. * geo: {
  26067. * regions: [{
  26068. * name: 'xxx',
  26069. * itemStyle: { ... },
  26070. * label: { ... }
  26071. * }, {
  26072. * ...
  26073. * },
  26074. * ...]
  26075. * };
  26076. * ```
  26077. * 2. name can be duplicated in different SVG tag. All of the tags with the same name share
  26078. * a region option. For exampel if there are two <path> representing two lung lobes. They have
  26079. * no common parents but both of them need to display label "lung" inside.
  26080. */
  26081. var REGION_AVAILABLE_SVG_TAG_MAP = createHashMap(['rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path', // <text> <tspan> are also enabled becuase some SVG might paint text itself,
  26082. // but still need to trigger events or tooltip.
  26083. 'text', 'tspan', // <g> is also enabled because this case: if multiple tags share one name
  26084. // and need label displayed, every tags will display the name, which is not
  26085. // expected. So we can put them into a <g name="xxx">. Thereby only one label
  26086. // displayed and located based on the bounding rect of the <g>.
  26087. 'g']);
  26088. var GeoSVGResource =
  26089. /** @class */
  26090. function () {
  26091. function GeoSVGResource(mapName, svg) {
  26092. this.type = 'geoSVG'; // All used graphics. key: hostKey, value: root
  26093. this._usedGraphicMap = createHashMap(); // All unused graphics.
  26094. this._freedGraphics = [];
  26095. this._mapName = mapName; // Only perform parse to XML object here, which might be time
  26096. // consiming for large SVG.
  26097. // Although convert XML to zrender element is also time consiming,
  26098. // if we do it here, the clone of zrender elements has to be
  26099. // required. So we do it once for each geo instance, util real
  26100. // performance issues call for optimizing it.
  26101. this._parsedXML = parseXML(svg);
  26102. }
  26103. GeoSVGResource.prototype.load = function ()
  26104. /* nameMap: NameMap */
  26105. {
  26106. // In the "load" stage, graphic need to be built to
  26107. // get boundingRect for geo coordinate system.
  26108. var firstGraphic = this._firstGraphic; // Create the return data structure only when first graphic created.
  26109. // Because they will be used in geo coordinate system update stage,
  26110. // and `regions` will be mounted at `geo` coordinate system,
  26111. // in which there is no "view" info, so that it should better not to
  26112. // make references to graphic elements.
  26113. if (!firstGraphic) {
  26114. firstGraphic = this._firstGraphic = this._buildGraphic(this._parsedXML);
  26115. this._freedGraphics.push(firstGraphic);
  26116. this._boundingRect = this._firstGraphic.boundingRect.clone(); // PENDING: `nameMap` will not be supported until some real requirement come.
  26117. // if (nameMap) {
  26118. // named = applyNameMap(named, nameMap);
  26119. // }
  26120. var _a = createRegions(firstGraphic.named),
  26121. regions = _a.regions,
  26122. regionsMap = _a.regionsMap;
  26123. this._regions = regions;
  26124. this._regionsMap = regionsMap;
  26125. }
  26126. return {
  26127. boundingRect: this._boundingRect,
  26128. regions: this._regions,
  26129. regionsMap: this._regionsMap
  26130. };
  26131. };
  26132. GeoSVGResource.prototype._buildGraphic = function (svgXML) {
  26133. var result;
  26134. var rootFromParse;
  26135. try {
  26136. result = svgXML && parseSVG(svgXML, {
  26137. ignoreViewBox: true,
  26138. ignoreRootClip: true
  26139. }) || {};
  26140. rootFromParse = result.root;
  26141. assert(rootFromParse != null);
  26142. } catch (e) {
  26143. throw new Error('Invalid svg format\n' + e.message);
  26144. } // Note: we keep the covenant that the root has no transform. So always add an extra root.
  26145. var root = new Group();
  26146. root.add(rootFromParse);
  26147. root.isGeoSVGGraphicRoot = true; // [THE_RULE_OF_VIEWPORT_AND_VIEWBOX]
  26148. //
  26149. // Consider: `<svg width="..." height="..." viewBox="...">`
  26150. // - the `width/height` we call it `svgWidth/svgHeight` for short.
  26151. // - `(0, 0, svgWidth, svgHeight)` defines the viewport of the SVG, or say,
  26152. // "viewport boundingRect", or `boundingRect` for short.
  26153. // - `viewBox` defines the transform from the real content ot the viewport.
  26154. // `viewBox` has the same unit as the content of SVG.
  26155. // If `viewBox` exists, a transform is defined, so the unit of `svgWidth/svgHeight` become
  26156. // different from the content of SVG. Otherwise, they are the same.
  26157. //
  26158. // If both `svgWidth/svgHeight/viewBox` are specified in a SVG file, the transform rule will be:
  26159. // 0. `boundingRect` is `(0, 0, svgWidth, svgHeight)`. Set it to Geo['_rect'] (View['_rect']).
  26160. // 1. Make a transform from `viewBox` to `boundingRect`.
  26161. // Note: only suport `preserveAspectRatio 'xMidYMid'` here. That is, this transform will preserve
  26162. // the aspect ratio.
  26163. // 2. Make a transform from boundingRect to Geo['_viewRect'] (View['_viewRect'])
  26164. // (`Geo`/`View` will do this job).
  26165. // Note: this transform might not preserve aspect radio, which depending on how users specify
  26166. // viewRect in echarts option (e.g., `geo.left/top/width/height` will not preserve aspect ratio,
  26167. // but `geo.layoutCenter/layoutSize` will preserve aspect ratio).
  26168. //
  26169. // If `svgWidth/svgHeight` not specified, we use `viewBox` as the `boundingRect` to make the SVG
  26170. // layout look good.
  26171. //
  26172. // If neither `svgWidth/svgHeight` nor `viewBox` are not specified, we calculate the boundingRect
  26173. // of the SVG content and use them to make SVG layout look good.
  26174. var svgWidth = result.width;
  26175. var svgHeight = result.height;
  26176. var viewBoxRect = result.viewBoxRect;
  26177. var boundingRect = this._boundingRect;
  26178. if (!boundingRect) {
  26179. var bRectX = void 0;
  26180. var bRectY = void 0;
  26181. var bRectWidth = void 0;
  26182. var bRectHeight = void 0;
  26183. if (svgWidth != null) {
  26184. bRectX = 0;
  26185. bRectWidth = svgWidth;
  26186. } else if (viewBoxRect) {
  26187. bRectX = viewBoxRect.x;
  26188. bRectWidth = viewBoxRect.width;
  26189. }
  26190. if (svgHeight != null) {
  26191. bRectY = 0;
  26192. bRectHeight = svgHeight;
  26193. } else if (viewBoxRect) {
  26194. bRectY = viewBoxRect.y;
  26195. bRectHeight = viewBoxRect.height;
  26196. } // If both viewBox and svgWidth/svgHeight not specified,
  26197. // we have to determine how to layout those element to make them look good.
  26198. if (bRectX == null || bRectY == null) {
  26199. var calculatedBoundingRect = rootFromParse.getBoundingRect();
  26200. if (bRectX == null) {
  26201. bRectX = calculatedBoundingRect.x;
  26202. bRectWidth = calculatedBoundingRect.width;
  26203. }
  26204. if (bRectY == null) {
  26205. bRectY = calculatedBoundingRect.y;
  26206. bRectHeight = calculatedBoundingRect.height;
  26207. }
  26208. }
  26209. boundingRect = this._boundingRect = new BoundingRect(bRectX, bRectY, bRectWidth, bRectHeight);
  26210. }
  26211. if (viewBoxRect) {
  26212. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect); // Only support `preserveAspectRatio 'xMidYMid'`
  26213. rootFromParse.scaleX = rootFromParse.scaleY = viewBoxTransform.scale;
  26214. rootFromParse.x = viewBoxTransform.x;
  26215. rootFromParse.y = viewBoxTransform.y;
  26216. } // SVG needs to clip based on `viewBox`. And some SVG files really rely on this feature.
  26217. // They do not strictly confine all of the content inside a display rect, but deliberately
  26218. // use a `viewBox` to define a displayable rect.
  26219. // PENDING:
  26220. // The drawback of the `setClipPath` here is: the region label (genereted by echarts) near the
  26221. // edge might also be clipped, because region labels are put as `textContent` of the SVG path.
  26222. root.setClipPath(new Rect({
  26223. shape: boundingRect.plain()
  26224. }));
  26225. var named = [];
  26226. each(result.named, function (namedItem) {
  26227. if (REGION_AVAILABLE_SVG_TAG_MAP.get(namedItem.svgNodeTagLower) != null) {
  26228. named.push(namedItem);
  26229. setSilent(namedItem.el);
  26230. }
  26231. });
  26232. return {
  26233. root: root,
  26234. boundingRect: boundingRect,
  26235. named: named
  26236. };
  26237. };
  26238. /**
  26239. * Consider:
  26240. * (1) One graphic element can not be shared by different `geoView` running simultaneously.
  26241. * Notice, also need to consider multiple echarts instances share a `mapRecord`.
  26242. * (2) Converting SVG to graphic elements is time consuming.
  26243. * (3) In the current architecture, `load` should be called frequently to get boundingRect,
  26244. * and it is called without view info.
  26245. * So we maintain graphic elements in this module, and enables `view` to use/return these
  26246. * graphics from/to the pool with it's uid.
  26247. */
  26248. GeoSVGResource.prototype.useGraphic = function (hostKey
  26249. /*, nameMap: NameMap */
  26250. ) {
  26251. var usedRootMap = this._usedGraphicMap;
  26252. var svgGraphic = usedRootMap.get(hostKey);
  26253. if (svgGraphic) {
  26254. return svgGraphic;
  26255. }
  26256. svgGraphic = this._freedGraphics.pop() // use the first boundingRect to avoid duplicated boundingRect calculation.
  26257. || this._buildGraphic(this._parsedXML);
  26258. usedRootMap.set(hostKey, svgGraphic); // PENDING: `nameMap` will not be supported until some real requirement come.
  26259. // `nameMap` can only be obtained from echarts option.
  26260. // The original `named` must not be modified.
  26261. // if (nameMap) {
  26262. // svgGraphic = extend({}, svgGraphic);
  26263. // svgGraphic.named = applyNameMap(svgGraphic.named, nameMap);
  26264. // }
  26265. return svgGraphic;
  26266. };
  26267. GeoSVGResource.prototype.freeGraphic = function (hostKey) {
  26268. var usedRootMap = this._usedGraphicMap;
  26269. var svgGraphic = usedRootMap.get(hostKey);
  26270. if (svgGraphic) {
  26271. usedRootMap.removeKey(hostKey);
  26272. this._freedGraphics.push(svgGraphic);
  26273. }
  26274. };
  26275. return GeoSVGResource;
  26276. }();
  26277. function setSilent(el) {
  26278. // Only named element has silent: false, other elements should
  26279. // act as background and has no user interaction.
  26280. el.silent = false; // text|tspan will be converted to group.
  26281. if (el.isGroup) {
  26282. el.traverse(function (child) {
  26283. child.silent = false;
  26284. });
  26285. }
  26286. }
  26287. function createRegions(named) {
  26288. var regions = [];
  26289. var regionsMap = createHashMap(); // Create resions only for the first graphic.
  26290. each(named, function (namedItem) {
  26291. // Region has feature to calculate center for tooltip or other features.
  26292. // If there is a <g name="xxx">, the center should be the center of the
  26293. // bounding rect of the g.
  26294. if (namedItem.namedFrom != null) {
  26295. return;
  26296. }
  26297. var region = new GeoSVGRegion(namedItem.name, namedItem.el); // PENDING: if `nameMap` supported, this region can not be mounted on
  26298. // `this`, but can only be created each time `load()` called.
  26299. regions.push(region); // PENDING: if multiple tag named with the same name, only one will be
  26300. // found by `_regionsMap`. `_regionsMap` is used to find a coordinate
  26301. // by name. We use `region.getCenter()` as the coordinate.
  26302. regionsMap.set(namedItem.name, region);
  26303. });
  26304. return {
  26305. regions: regions,
  26306. regionsMap: regionsMap
  26307. };
  26308. } // PENDING: `nameMap` will not be supported until some real requirement come.
  26309. // /**
  26310. // * Use the alias in geoNameMap.
  26311. // * The input `named` must not be modified.
  26312. // */
  26313. // function applyNameMap(
  26314. // named: GeoSVGGraphicRecord['named'],
  26315. // nameMap: NameMap
  26316. // ): GeoSVGGraphicRecord['named'] {
  26317. // const result = [] as GeoSVGGraphicRecord['named'];
  26318. // for (let i = 0; i < named.length; i++) {
  26319. // let regionGraphic = named[i];
  26320. // const name = regionGraphic.name;
  26321. // if (nameMap && nameMap.hasOwnProperty(name)) {
  26322. // regionGraphic = extend({}, regionGraphic);
  26323. // regionGraphic.name = name;
  26324. // }
  26325. // result.push(regionGraphic);
  26326. // }
  26327. // return result;
  26328. // }
  26329. function decode(json) {
  26330. if (!json.UTF8Encoding) {
  26331. return json;
  26332. }
  26333. var jsonCompressed = json;
  26334. var encodeScale = jsonCompressed.UTF8Scale;
  26335. if (encodeScale == null) {
  26336. encodeScale = 1024;
  26337. }
  26338. var features = jsonCompressed.features;
  26339. for (var f = 0; f < features.length; f++) {
  26340. var feature = features[f];
  26341. var geometry = feature.geometry;
  26342. if (geometry.type === 'Polygon') {
  26343. var coordinates = geometry.coordinates;
  26344. for (var c = 0; c < coordinates.length; c++) {
  26345. coordinates[c] = decodePolygon(coordinates[c], geometry.encodeOffsets[c], encodeScale);
  26346. }
  26347. } else if (geometry.type === 'MultiPolygon') {
  26348. var coordinates = geometry.coordinates;
  26349. for (var c = 0; c < coordinates.length; c++) {
  26350. var coordinate = coordinates[c];
  26351. for (var c2 = 0; c2 < coordinate.length; c2++) {
  26352. coordinate[c2] = decodePolygon(coordinate[c2], geometry.encodeOffsets[c][c2], encodeScale);
  26353. }
  26354. }
  26355. }
  26356. } // Has been decoded
  26357. jsonCompressed.UTF8Encoding = false;
  26358. return jsonCompressed;
  26359. }
  26360. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  26361. var result = [];
  26362. var prevX = encodeOffsets[0];
  26363. var prevY = encodeOffsets[1];
  26364. for (var i = 0; i < coordinate.length; i += 2) {
  26365. var x = coordinate.charCodeAt(i) - 64;
  26366. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  26367. x = x >> 1 ^ -(x & 1);
  26368. y = y >> 1 ^ -(y & 1); // Delta deocding
  26369. x += prevX;
  26370. y += prevY;
  26371. prevX = x;
  26372. prevY = y; // Dequantize
  26373. result.push([x / encodeScale, y / encodeScale]);
  26374. }
  26375. return result;
  26376. }
  26377. function parseGeoJSON(geoJson, nameProperty) {
  26378. geoJson = decode(geoJson);
  26379. return map(filter(geoJson.features, function (featureObj) {
  26380. // Output of mapshaper may have geometry null
  26381. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  26382. }), function (featureObj) {
  26383. var properties = featureObj.properties;
  26384. var geo = featureObj.geometry;
  26385. var geometries = [];
  26386. if (geo.type === 'Polygon') {
  26387. var coordinates = geo.coordinates;
  26388. geometries.push({
  26389. type: 'polygon',
  26390. // According to the GeoJSON specification.
  26391. // First must be exterior, and the rest are all interior(holes).
  26392. exterior: coordinates[0],
  26393. interiors: coordinates.slice(1)
  26394. });
  26395. }
  26396. if (geo.type === 'MultiPolygon') {
  26397. var coordinates = geo.coordinates;
  26398. each(coordinates, function (item) {
  26399. if (item[0]) {
  26400. geometries.push({
  26401. type: 'polygon',
  26402. exterior: item[0],
  26403. interiors: item.slice(1)
  26404. });
  26405. }
  26406. });
  26407. }
  26408. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  26409. region.properties = properties;
  26410. return region;
  26411. });
  26412. }
  26413. var geoCoord = [126, 25];
  26414. var nanhaiName = '南海诸岛';
  26415. 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]]];
  26416. for (var i = 0; i < points$1.length; i++) {
  26417. for (var k = 0; k < points$1[i].length; k++) {
  26418. points$1[i][k][0] /= 10.5;
  26419. points$1[i][k][1] /= -10.5 / 0.75;
  26420. points$1[i][k][0] += geoCoord[0];
  26421. points$1[i][k][1] += geoCoord[1];
  26422. }
  26423. }
  26424. function fixNanhai(mapType, regions) {
  26425. if (mapType === 'china') {
  26426. for (var i = 0; i < regions.length; i++) {
  26427. // Already exists.
  26428. if (regions[i].name === nanhaiName) {
  26429. return;
  26430. }
  26431. }
  26432. regions.push(new GeoJSONRegion(nanhaiName, map(points$1, function (exterior) {
  26433. return {
  26434. type: 'polygon',
  26435. exterior: exterior
  26436. };
  26437. }), geoCoord));
  26438. }
  26439. }
  26440. /*
  26441. * Licensed to the Apache Software Foundation (ASF) under one
  26442. * or more contributor license agreements. See the NOTICE file
  26443. * distributed with this work for additional information
  26444. * regarding copyright ownership. The ASF licenses this file
  26445. * to you under the Apache License, Version 2.0 (the
  26446. * "License"); you may not use this file except in compliance
  26447. * with the License. You may obtain a copy of the License at
  26448. *
  26449. * http://www.apache.org/licenses/LICENSE-2.0
  26450. *
  26451. * Unless required by applicable law or agreed to in writing,
  26452. * software distributed under the License is distributed on an
  26453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26454. * KIND, either express or implied. See the License for the
  26455. * specific language governing permissions and limitations
  26456. * under the License.
  26457. */
  26458. /**
  26459. * AUTO-GENERATED FILE. DO NOT MODIFY.
  26460. */
  26461. /*
  26462. * Licensed to the Apache Software Foundation (ASF) under one
  26463. * or more contributor license agreements. See the NOTICE file
  26464. * distributed with this work for additional information
  26465. * regarding copyright ownership. The ASF licenses this file
  26466. * to you under the Apache License, Version 2.0 (the
  26467. * "License"); you may not use this file except in compliance
  26468. * with the License. You may obtain a copy of the License at
  26469. *
  26470. * http://www.apache.org/licenses/LICENSE-2.0
  26471. *
  26472. * Unless required by applicable law or agreed to in writing,
  26473. * software distributed under the License is distributed on an
  26474. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26475. * KIND, either express or implied. See the License for the
  26476. * specific language governing permissions and limitations
  26477. * under the License.
  26478. */
  26479. var coordsOffsetMap = {
  26480. '南海诸岛': [32, 80],
  26481. // 全国
  26482. '广东': [0, -10],
  26483. '香港': [10, 5],
  26484. '澳门': [-10, 10],
  26485. //'北京': [-10, 0],
  26486. '天津': [5, 5]
  26487. };
  26488. function fixTextCoords(mapType, region) {
  26489. if (mapType === 'china') {
  26490. var coordFix = coordsOffsetMap[region.name];
  26491. if (coordFix) {
  26492. var cp = region.getCenter();
  26493. cp[0] += coordFix[0] / 10.5;
  26494. cp[1] += -coordFix[1] / (10.5 / 0.75);
  26495. region.setCenter(cp);
  26496. }
  26497. }
  26498. }
  26499. /*
  26500. * Licensed to the Apache Software Foundation (ASF) under one
  26501. * or more contributor license agreements. See the NOTICE file
  26502. * distributed with this work for additional information
  26503. * regarding copyright ownership. The ASF licenses this file
  26504. * to you under the Apache License, Version 2.0 (the
  26505. * "License"); you may not use this file except in compliance
  26506. * with the License. You may obtain a copy of the License at
  26507. *
  26508. * http://www.apache.org/licenses/LICENSE-2.0
  26509. *
  26510. * Unless required by applicable law or agreed to in writing,
  26511. * software distributed under the License is distributed on an
  26512. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26513. * KIND, either express or implied. See the License for the
  26514. * specific language governing permissions and limitations
  26515. * under the License.
  26516. */
  26517. /**
  26518. * AUTO-GENERATED FILE. DO NOT MODIFY.
  26519. */
  26520. /*
  26521. * Licensed to the Apache Software Foundation (ASF) under one
  26522. * or more contributor license agreements. See the NOTICE file
  26523. * distributed with this work for additional information
  26524. * regarding copyright ownership. The ASF licenses this file
  26525. * to you under the Apache License, Version 2.0 (the
  26526. * "License"); you may not use this file except in compliance
  26527. * with the License. You may obtain a copy of the License at
  26528. *
  26529. * http://www.apache.org/licenses/LICENSE-2.0
  26530. *
  26531. * Unless required by applicable law or agreed to in writing,
  26532. * software distributed under the License is distributed on an
  26533. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26534. * KIND, either express or implied. See the License for the
  26535. * specific language governing permissions and limitations
  26536. * under the License.
  26537. */
  26538. var geoCoordMap = {
  26539. 'Russia': [100, 60],
  26540. 'United States': [-99, 38],
  26541. 'United States of America': [-99, 38]
  26542. };
  26543. function fixGeoCoords(mapType, region) {
  26544. if (mapType === 'world') {
  26545. var geoCoord = geoCoordMap[region.name];
  26546. if (geoCoord) {
  26547. var cp = [geoCoord[0], geoCoord[1]];
  26548. region.setCenter(cp);
  26549. }
  26550. }
  26551. }
  26552. /*
  26553. * Licensed to the Apache Software Foundation (ASF) under one
  26554. * or more contributor license agreements. See the NOTICE file
  26555. * distributed with this work for additional information
  26556. * regarding copyright ownership. The ASF licenses this file
  26557. * to you under the Apache License, Version 2.0 (the
  26558. * "License"); you may not use this file except in compliance
  26559. * with the License. You may obtain a copy of the License at
  26560. *
  26561. * http://www.apache.org/licenses/LICENSE-2.0
  26562. *
  26563. * Unless required by applicable law or agreed to in writing,
  26564. * software distributed under the License is distributed on an
  26565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26566. * KIND, either express or implied. See the License for the
  26567. * specific language governing permissions and limitations
  26568. * under the License.
  26569. */
  26570. /**
  26571. * AUTO-GENERATED FILE. DO NOT MODIFY.
  26572. */
  26573. /*
  26574. * Licensed to the Apache Software Foundation (ASF) under one
  26575. * or more contributor license agreements. See the NOTICE file
  26576. * distributed with this work for additional information
  26577. * regarding copyright ownership. The ASF licenses this file
  26578. * to you under the Apache License, Version 2.0 (the
  26579. * "License"); you may not use this file except in compliance
  26580. * with the License. You may obtain a copy of the License at
  26581. *
  26582. * http://www.apache.org/licenses/LICENSE-2.0
  26583. *
  26584. * Unless required by applicable law or agreed to in writing,
  26585. * software distributed under the License is distributed on an
  26586. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26587. * KIND, either express or implied. See the License for the
  26588. * specific language governing permissions and limitations
  26589. * under the License.
  26590. */
  26591. // Fix for 钓鱼岛
  26592. // let Region = require('../Region');
  26593. // let zrUtil = require('zrender/lib/core/util');
  26594. // let geoCoord = [126, 25];
  26595. var points$2 = [[[123.45165252685547, 25.73527164402261], [123.49731445312499, 25.73527164402261], [123.49731445312499, 25.750734064600884], [123.45165252685547, 25.750734064600884], [123.45165252685547, 25.73527164402261]]];
  26596. function fixDiaoyuIsland(mapType, region) {
  26597. if (mapType === 'china' && region.name === '台湾') {
  26598. region.geometries.push({
  26599. type: 'polygon',
  26600. exterior: points$2[0]
  26601. });
  26602. }
  26603. }
  26604. var DEFAULT_NAME_PROPERTY = 'name';
  26605. var GeoJSONResource =
  26606. /** @class */
  26607. function () {
  26608. function GeoJSONResource(mapName, geoJSON, specialAreas) {
  26609. this.type = 'geoJSON';
  26610. this._parsedMap = createHashMap();
  26611. this._mapName = mapName;
  26612. this._specialAreas = specialAreas; // PENDING: delay the parse to the first usage to rapid up the FMP?
  26613. this._geoJSON = parseInput(geoJSON);
  26614. }
  26615. /**
  26616. * @param nameMap can be null/undefined
  26617. * @param nameProperty can be null/undefined
  26618. */
  26619. GeoJSONResource.prototype.load = function (nameMap, nameProperty) {
  26620. nameProperty = nameProperty || DEFAULT_NAME_PROPERTY;
  26621. var parsed = this._parsedMap.get(nameProperty);
  26622. if (!parsed) {
  26623. var rawRegions = this._parseToRegions(nameProperty);
  26624. parsed = this._parsedMap.set(nameProperty, {
  26625. regions: rawRegions,
  26626. boundingRect: calculateBoundingRect(rawRegions)
  26627. });
  26628. }
  26629. var regionsMap = createHashMap();
  26630. var finalRegions = [];
  26631. each(parsed.regions, function (region) {
  26632. var regionName = region.name; // Try use the alias in geoNameMap
  26633. if (nameMap && nameMap.hasOwnProperty(regionName)) {
  26634. region = region.cloneShallow(regionName = nameMap[regionName]);
  26635. }
  26636. finalRegions.push(region);
  26637. regionsMap.set(regionName, region);
  26638. });
  26639. return {
  26640. regions: finalRegions,
  26641. boundingRect: parsed.boundingRect || new BoundingRect(0, 0, 0, 0),
  26642. regionsMap: regionsMap
  26643. };
  26644. };
  26645. GeoJSONResource.prototype._parseToRegions = function (nameProperty) {
  26646. var mapName = this._mapName;
  26647. var geoJSON = this._geoJSON;
  26648. var rawRegions; // https://jsperf.com/try-catch-performance-overhead
  26649. try {
  26650. rawRegions = geoJSON ? parseGeoJSON(geoJSON, nameProperty) : [];
  26651. } catch (e) {
  26652. throw new Error('Invalid geoJson format\n' + e.message);
  26653. }
  26654. fixNanhai(mapName, rawRegions);
  26655. each(rawRegions, function (region) {
  26656. var regionName = region.name;
  26657. fixTextCoords(mapName, region);
  26658. fixGeoCoords(mapName, region);
  26659. fixDiaoyuIsland(mapName, region); // Some area like Alaska in USA map needs to be tansformed
  26660. // to look better
  26661. var specialArea = this._specialAreas && this._specialAreas[regionName];
  26662. if (specialArea) {
  26663. region.transformTo(specialArea.left, specialArea.top, specialArea.width, specialArea.height);
  26664. }
  26665. }, this);
  26666. return rawRegions;
  26667. };
  26668. /**
  26669. * Only for exporting to users.
  26670. * **MUST NOT** used internally.
  26671. */
  26672. GeoJSONResource.prototype.getMapForUser = function () {
  26673. return {
  26674. // For backward compatibility, use geoJson
  26675. // PENDING: it has been returning them without clone.
  26676. // do we need to avoid outsite modification?
  26677. geoJson: this._geoJSON,
  26678. geoJSON: this._geoJSON,
  26679. specialAreas: this._specialAreas
  26680. };
  26681. };
  26682. return GeoJSONResource;
  26683. }();
  26684. function calculateBoundingRect(regions) {
  26685. var rect;
  26686. for (var i = 0; i < regions.length; i++) {
  26687. var regionRect = regions[i].getBoundingRect();
  26688. rect = rect || regionRect.clone();
  26689. rect.union(regionRect);
  26690. }
  26691. return rect;
  26692. }
  26693. function parseInput(source) {
  26694. return !isString(source) ? source : typeof JSON !== 'undefined' && JSON.parse ? JSON.parse(source) : new Function('return (' + source + ');')();
  26695. }
  26696. var storage = createHashMap();
  26697. var geoSourceManager = {
  26698. /**
  26699. * Compatible with previous `echarts.registerMap`.
  26700. *
  26701. * @usage
  26702. * ```js
  26703. *
  26704. * echarts.registerMap('USA', geoJson, specialAreas);
  26705. *
  26706. * echarts.registerMap('USA', {
  26707. * geoJson: geoJson,
  26708. * specialAreas: {...}
  26709. * });
  26710. * echarts.registerMap('USA', {
  26711. * geoJSON: geoJson,
  26712. * specialAreas: {...}
  26713. * });
  26714. *
  26715. * echarts.registerMap('airport', {
  26716. * svg: svg
  26717. * }
  26718. * ```
  26719. *
  26720. * Note:
  26721. * Do not support that register multiple geoJSON or SVG
  26722. * one map name. Because different geoJSON and SVG have
  26723. * different unit. It's not easy to make sure how those
  26724. * units are mapping/normalize.
  26725. * If intending to use multiple geoJSON or SVG, we can
  26726. * use multiple geo coordinate system.
  26727. */
  26728. registerMap: function (mapName, rawDef, rawSpecialAreas) {
  26729. if (rawDef.svg) {
  26730. var resource = new GeoSVGResource(mapName, rawDef.svg);
  26731. storage.set(mapName, resource);
  26732. } else {
  26733. // Recommend:
  26734. // echarts.registerMap('eu', { geoJSON: xxx, specialAreas: xxx });
  26735. // Backward compatibility:
  26736. // echarts.registerMap('eu', geoJSON, specialAreas);
  26737. // echarts.registerMap('eu', { geoJson: xxx, specialAreas: xxx });
  26738. var geoJSON = rawDef.geoJson || rawDef.geoJSON;
  26739. if (geoJSON && !rawDef.features) {
  26740. rawSpecialAreas = rawDef.specialAreas;
  26741. } else {
  26742. geoJSON = rawDef;
  26743. }
  26744. var resource = new GeoJSONResource(mapName, geoJSON, rawSpecialAreas);
  26745. storage.set(mapName, resource);
  26746. }
  26747. },
  26748. getGeoResource: function (mapName) {
  26749. return storage.get(mapName);
  26750. },
  26751. /**
  26752. * Only for exporting to users.
  26753. * **MUST NOT** used internally.
  26754. */
  26755. getMapForUser: function (mapName) {
  26756. var resource = storage.get(mapName); // Do not support return SVG until some real requirement come.
  26757. return resource && resource.type === 'geoJSON' && resource.getMapForUser();
  26758. },
  26759. load: function (mapName, nameMap, nameProperty) {
  26760. var resource = storage.get(mapName);
  26761. if (!resource) {
  26762. if ("development" !== 'production') {
  26763. console.error('Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.');
  26764. }
  26765. return;
  26766. }
  26767. return resource.load(nameMap, nameProperty);
  26768. }
  26769. };
  26770. var lifecycle = new Eventful();
  26771. var hasWindow = typeof window !== 'undefined';
  26772. var version$1 = '5.2.0';
  26773. var dependencies = {
  26774. zrender: '5.2.0'
  26775. };
  26776. var TEST_FRAME_REMAIN_TIME = 1;
  26777. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  26778. // So data stack stage should be in front of data processing stage.
  26779. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  26780. // put at the begining of data processing.
  26781. var PRIORITY_PROCESSOR_FILTER = 1000;
  26782. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  26783. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  26784. var PRIORITY_VISUAL_LAYOUT = 1000;
  26785. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  26786. var PRIORITY_VISUAL_GLOBAL = 2000;
  26787. var PRIORITY_VISUAL_CHART = 3000;
  26788. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  26789. // overwrite the viusal result of component (like `visualMap`)
  26790. // using data item specific setting (like itemStyle.xxx on data item)
  26791. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  26792. // visual result like `symbolSize`.
  26793. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  26794. var PRIORITY_VISUAL_BRUSH = 5000;
  26795. var PRIORITY_VISUAL_ARIA = 6000;
  26796. var PRIORITY_VISUAL_DECAL = 7000;
  26797. var PRIORITY = {
  26798. PROCESSOR: {
  26799. FILTER: PRIORITY_PROCESSOR_FILTER,
  26800. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  26801. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  26802. },
  26803. VISUAL: {
  26804. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  26805. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  26806. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  26807. CHART: PRIORITY_VISUAL_CHART,
  26808. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  26809. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  26810. BRUSH: PRIORITY_VISUAL_BRUSH,
  26811. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  26812. ARIA: PRIORITY_VISUAL_ARIA,
  26813. DECAL: PRIORITY_VISUAL_DECAL
  26814. }
  26815. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  26816. // where they must not be invoked nestedly, except the only case: invoke
  26817. // dispatchAction with updateMethod "none" in main process.
  26818. // This flag is used to carry out this rule.
  26819. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  26820. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  26821. var PENDING_UPDATE = '__pendingUpdate';
  26822. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  26823. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  26824. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  26825. var CONNECT_STATUS_PENDING = 0;
  26826. var CONNECT_STATUS_UPDATING = 1;
  26827. var CONNECT_STATUS_UPDATED = 2;
  26828. function createRegisterEventWithLowercaseECharts(method) {
  26829. return function () {
  26830. var args = [];
  26831. for (var _i = 0; _i < arguments.length; _i++) {
  26832. args[_i] = arguments[_i];
  26833. }
  26834. if (this.isDisposed()) {
  26835. disposedWarning(this.id);
  26836. return;
  26837. }
  26838. return toLowercaseNameAndCallEventful(this, method, args);
  26839. };
  26840. }
  26841. function createRegisterEventWithLowercaseMessageCenter(method) {
  26842. return function () {
  26843. var args = [];
  26844. for (var _i = 0; _i < arguments.length; _i++) {
  26845. args[_i] = arguments[_i];
  26846. }
  26847. return toLowercaseNameAndCallEventful(this, method, args);
  26848. };
  26849. }
  26850. function toLowercaseNameAndCallEventful(host, method, args) {
  26851. // `args[0]` is event name. Event name is all lowercase.
  26852. args[0] = args[0] && args[0].toLowerCase();
  26853. return Eventful.prototype[method].apply(host, args);
  26854. }
  26855. var MessageCenter =
  26856. /** @class */
  26857. function (_super) {
  26858. __extends(MessageCenter, _super);
  26859. function MessageCenter() {
  26860. return _super !== null && _super.apply(this, arguments) || this;
  26861. }
  26862. return MessageCenter;
  26863. }(Eventful);
  26864. var messageCenterProto = MessageCenter.prototype;
  26865. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  26866. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  26867. // Internal method names for class ECharts
  26868. // ---------------------------------------
  26869. var prepare;
  26870. var prepareView;
  26871. var updateDirectly;
  26872. var updateMethods;
  26873. var doConvertPixel;
  26874. var updateStreamModes;
  26875. var doDispatchAction;
  26876. var flushPendingActions;
  26877. var triggerUpdatedEvent;
  26878. var bindRenderedEvent;
  26879. var bindMouseEvent;
  26880. var clearColorPalette;
  26881. var render;
  26882. var renderComponents;
  26883. var renderSeries;
  26884. var createExtensionAPI;
  26885. var enableConnect;
  26886. var markStatusToUpdate;
  26887. var applyChangedStates;
  26888. var ECharts =
  26889. /** @class */
  26890. function (_super) {
  26891. __extends(ECharts, _super);
  26892. function ECharts(dom, // Theme name or themeOption.
  26893. theme, opts) {
  26894. var _this = _super.call(this, new ECEventProcessor()) || this;
  26895. _this._chartsViews = [];
  26896. _this._chartsMap = {};
  26897. _this._componentsViews = [];
  26898. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  26899. _this._pendingActions = [];
  26900. opts = opts || {}; // Get theme by name
  26901. if (typeof theme === 'string') {
  26902. theme = themeStorage[theme];
  26903. }
  26904. _this._dom = dom;
  26905. var defaultRenderer = 'canvas';
  26906. var defaultUseDirtyRect = false;
  26907. if ("development" !== 'production') {
  26908. var root =
  26909. /* eslint-disable-next-line */
  26910. hasWindow ? window : global;
  26911. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  26912. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  26913. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  26914. }
  26915. var zr = _this._zr = init(dom, {
  26916. renderer: opts.renderer || defaultRenderer,
  26917. devicePixelRatio: opts.devicePixelRatio,
  26918. width: opts.width,
  26919. height: opts.height,
  26920. useDirtyRect: opts.useDirtyRect == null ? defaultUseDirtyRect : opts.useDirtyRect
  26921. }); // Expect 60 fps.
  26922. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  26923. theme = clone(theme);
  26924. theme && globalBackwardCompat(theme, true);
  26925. _this._theme = theme;
  26926. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  26927. _this._coordSysMgr = new CoordinateSystemManager();
  26928. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  26929. function prioritySortFunc(a, b) {
  26930. return a.__prio - b.__prio;
  26931. }
  26932. sort(visualFuncs, prioritySortFunc);
  26933. sort(dataProcessorFuncs, prioritySortFunc);
  26934. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  26935. _this._messageCenter = new MessageCenter(); // Init mouse events
  26936. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  26937. _this.resize = bind(_this.resize, _this);
  26938. zr.animation.on('frame', _this._onframe, _this);
  26939. bindRenderedEvent(zr, _this);
  26940. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  26941. setAsPrimitive(_this);
  26942. return _this;
  26943. }
  26944. ECharts.prototype._onframe = function () {
  26945. if (this._disposed) {
  26946. return;
  26947. }
  26948. applyChangedStates(this);
  26949. var scheduler = this._scheduler; // Lazy update
  26950. if (this[PENDING_UPDATE]) {
  26951. var silent = this[PENDING_UPDATE].silent;
  26952. this[IN_MAIN_PROCESS_KEY] = true;
  26953. prepare(this);
  26954. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams); // At present, in each frame, zrender performs:
  26955. // (1) animation step forward.
  26956. // (2) trigger('frame') (where this `_onframe` is called)
  26957. // (3) zrender flush (render).
  26958. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  26959. // will render the final state of the elements before the real animation started.
  26960. this._zr.flush();
  26961. this[IN_MAIN_PROCESS_KEY] = false;
  26962. this[PENDING_UPDATE] = null;
  26963. flushPendingActions.call(this, silent);
  26964. triggerUpdatedEvent.call(this, silent);
  26965. } // Avoid do both lazy update and progress in one frame.
  26966. else if (scheduler.unfinished) {
  26967. // Stream progress.
  26968. var remainTime = TEST_FRAME_REMAIN_TIME;
  26969. var ecModel = this._model;
  26970. var api = this._api;
  26971. scheduler.unfinished = false;
  26972. do {
  26973. var startTime = +new Date();
  26974. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  26975. scheduler.performDataProcessorTasks(ecModel);
  26976. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  26977. // each frame is not a good user experience. So we follow the rule that
  26978. // the extent of the coordinate system is determin in the first frame (the
  26979. // frame is executed immedietely after task reset.
  26980. // this._coordSysMgr.update(ecModel, api);
  26981. // console.log('--- ec frame visual ---', remainTime);
  26982. scheduler.performVisualTasks(ecModel);
  26983. renderSeries(this, this._model, api, 'remain', {});
  26984. remainTime -= +new Date() - startTime;
  26985. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  26986. if (!scheduler.unfinished) {
  26987. this._zr.flush();
  26988. } // Else, zr flushing be ensue within the same frame,
  26989. // because zr flushing is after onframe event.
  26990. }
  26991. };
  26992. ECharts.prototype.getDom = function () {
  26993. return this._dom;
  26994. };
  26995. ECharts.prototype.getId = function () {
  26996. return this.id;
  26997. };
  26998. ECharts.prototype.getZr = function () {
  26999. return this._zr;
  27000. };
  27001. /* eslint-disable-next-line */
  27002. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  27003. if ("development" !== 'production') {
  27004. assert(!this[IN_MAIN_PROCESS_KEY], '`setOption` should not be called during main process.');
  27005. }
  27006. if (this._disposed) {
  27007. disposedWarning(this.id);
  27008. return;
  27009. }
  27010. var silent;
  27011. var replaceMerge;
  27012. var transitionOpt;
  27013. if (isObject(notMerge)) {
  27014. lazyUpdate = notMerge.lazyUpdate;
  27015. silent = notMerge.silent;
  27016. replaceMerge = notMerge.replaceMerge;
  27017. transitionOpt = notMerge.transition;
  27018. notMerge = notMerge.notMerge;
  27019. }
  27020. this[IN_MAIN_PROCESS_KEY] = true;
  27021. if (!this._model || notMerge) {
  27022. var optionManager = new OptionManager(this._api);
  27023. var theme = this._theme;
  27024. var ecModel = this._model = new GlobalModel();
  27025. ecModel.scheduler = this._scheduler;
  27026. ecModel.init(null, null, null, theme, this._locale, optionManager);
  27027. }
  27028. this._model.setOption(option, {
  27029. replaceMerge: replaceMerge
  27030. }, optionPreprocessorFuncs);
  27031. var updateParams = {
  27032. seriesTransition: transitionOpt,
  27033. optionChanged: true
  27034. };
  27035. if (lazyUpdate) {
  27036. this[PENDING_UPDATE] = {
  27037. silent: silent,
  27038. updateParams: updateParams
  27039. };
  27040. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  27041. // It should wake it up to make sure zrender start to render at the next frame.
  27042. this.getZr().wakeUp();
  27043. } else {
  27044. prepare(this);
  27045. updateMethods.update.call(this, null, updateParams); // Ensure zr refresh sychronously, and then pixel in canvas can be
  27046. // fetched after `setOption`.
  27047. this._zr.flush();
  27048. this[PENDING_UPDATE] = null;
  27049. this[IN_MAIN_PROCESS_KEY] = false;
  27050. flushPendingActions.call(this, silent);
  27051. triggerUpdatedEvent.call(this, silent);
  27052. }
  27053. };
  27054. /**
  27055. * @DEPRECATED
  27056. */
  27057. ECharts.prototype.setTheme = function () {
  27058. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  27059. }; // We don't want developers to use getModel directly.
  27060. ECharts.prototype.getModel = function () {
  27061. return this._model;
  27062. };
  27063. ECharts.prototype.getOption = function () {
  27064. return this._model && this._model.getOption();
  27065. };
  27066. ECharts.prototype.getWidth = function () {
  27067. return this._zr.getWidth();
  27068. };
  27069. ECharts.prototype.getHeight = function () {
  27070. return this._zr.getHeight();
  27071. };
  27072. ECharts.prototype.getDevicePixelRatio = function () {
  27073. return this._zr.painter.dpr
  27074. /* eslint-disable-next-line */
  27075. || hasWindow && window.devicePixelRatio || 1;
  27076. };
  27077. /**
  27078. * Get canvas which has all thing rendered
  27079. */
  27080. ECharts.prototype.getRenderedCanvas = function (opts) {
  27081. if (!env.canvasSupported) {
  27082. return;
  27083. }
  27084. opts = opts || {};
  27085. return this._zr.painter.getRenderedCanvas({
  27086. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  27087. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  27088. });
  27089. };
  27090. /**
  27091. * Get svg data url
  27092. */
  27093. ECharts.prototype.getSvgDataURL = function () {
  27094. if (!env.svgSupported) {
  27095. return;
  27096. }
  27097. var zr = this._zr;
  27098. var list = zr.storage.getDisplayList(); // Stop animations
  27099. each(list, function (el) {
  27100. el.stopAnimation(null, true);
  27101. });
  27102. return zr.painter.toDataURL();
  27103. };
  27104. ECharts.prototype.getDataURL = function (opts) {
  27105. if (this._disposed) {
  27106. disposedWarning(this.id);
  27107. return;
  27108. }
  27109. opts = opts || {};
  27110. var excludeComponents = opts.excludeComponents;
  27111. var ecModel = this._model;
  27112. var excludesComponentViews = [];
  27113. var self = this;
  27114. each(excludeComponents, function (componentType) {
  27115. ecModel.eachComponent({
  27116. mainType: componentType
  27117. }, function (component) {
  27118. var view = self._componentsMap[component.__viewId];
  27119. if (!view.group.ignore) {
  27120. excludesComponentViews.push(view);
  27121. view.group.ignore = true;
  27122. }
  27123. });
  27124. });
  27125. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.getRenderedCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  27126. each(excludesComponentViews, function (view) {
  27127. view.group.ignore = false;
  27128. });
  27129. return url;
  27130. };
  27131. ECharts.prototype.getConnectedDataURL = function (opts) {
  27132. if (this._disposed) {
  27133. disposedWarning(this.id);
  27134. return;
  27135. }
  27136. if (!env.canvasSupported) {
  27137. return;
  27138. }
  27139. var isSvg = opts.type === 'svg';
  27140. var groupId = this.group;
  27141. var mathMin = Math.min;
  27142. var mathMax = Math.max;
  27143. var MAX_NUMBER = Infinity;
  27144. if (connectedGroups[groupId]) {
  27145. var left_1 = MAX_NUMBER;
  27146. var top_1 = MAX_NUMBER;
  27147. var right_1 = -MAX_NUMBER;
  27148. var bottom_1 = -MAX_NUMBER;
  27149. var canvasList_1 = [];
  27150. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  27151. each(instances$1, function (chart, id) {
  27152. if (chart.group === groupId) {
  27153. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.getRenderedCanvas(clone(opts));
  27154. var boundingRect = chart.getDom().getBoundingClientRect();
  27155. left_1 = mathMin(boundingRect.left, left_1);
  27156. top_1 = mathMin(boundingRect.top, top_1);
  27157. right_1 = mathMax(boundingRect.right, right_1);
  27158. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  27159. canvasList_1.push({
  27160. dom: canvas,
  27161. left: boundingRect.left,
  27162. top: boundingRect.top
  27163. });
  27164. }
  27165. });
  27166. left_1 *= dpr_1;
  27167. top_1 *= dpr_1;
  27168. right_1 *= dpr_1;
  27169. bottom_1 *= dpr_1;
  27170. var width = right_1 - left_1;
  27171. var height = bottom_1 - top_1;
  27172. var targetCanvas = createCanvas();
  27173. var zr_1 = init(targetCanvas, {
  27174. renderer: isSvg ? 'svg' : 'canvas'
  27175. });
  27176. zr_1.resize({
  27177. width: width,
  27178. height: height
  27179. });
  27180. if (isSvg) {
  27181. var content_1 = '';
  27182. each(canvasList_1, function (item) {
  27183. var x = item.left - left_1;
  27184. var y = item.top - top_1;
  27185. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  27186. });
  27187. zr_1.painter.getSvgRoot().innerHTML = content_1;
  27188. if (opts.connectedBackgroundColor) {
  27189. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  27190. }
  27191. zr_1.refreshImmediately();
  27192. return zr_1.painter.toDataURL();
  27193. } else {
  27194. // Background between the charts
  27195. if (opts.connectedBackgroundColor) {
  27196. zr_1.add(new Rect({
  27197. shape: {
  27198. x: 0,
  27199. y: 0,
  27200. width: width,
  27201. height: height
  27202. },
  27203. style: {
  27204. fill: opts.connectedBackgroundColor
  27205. }
  27206. }));
  27207. }
  27208. each(canvasList_1, function (item) {
  27209. var img = new ZRImage({
  27210. style: {
  27211. x: item.left * dpr_1 - left_1,
  27212. y: item.top * dpr_1 - top_1,
  27213. image: item.dom
  27214. }
  27215. });
  27216. zr_1.add(img);
  27217. });
  27218. zr_1.refreshImmediately();
  27219. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  27220. }
  27221. } else {
  27222. return this.getDataURL(opts);
  27223. }
  27224. };
  27225. ECharts.prototype.convertToPixel = function (finder, value) {
  27226. return doConvertPixel(this, 'convertToPixel', finder, value);
  27227. };
  27228. ECharts.prototype.convertFromPixel = function (finder, value) {
  27229. return doConvertPixel(this, 'convertFromPixel', finder, value);
  27230. };
  27231. /**
  27232. * Is the specified coordinate systems or components contain the given pixel point.
  27233. * @param {Array|number} value
  27234. * @return {boolean} result
  27235. */
  27236. ECharts.prototype.containPixel = function (finder, value) {
  27237. if (this._disposed) {
  27238. disposedWarning(this.id);
  27239. return;
  27240. }
  27241. var ecModel = this._model;
  27242. var result;
  27243. var findResult = parseFinder(ecModel, finder);
  27244. each(findResult, function (models, key) {
  27245. key.indexOf('Models') >= 0 && each(models, function (model) {
  27246. var coordSys = model.coordinateSystem;
  27247. if (coordSys && coordSys.containPoint) {
  27248. result = result || !!coordSys.containPoint(value);
  27249. } else if (key === 'seriesModels') {
  27250. var view = this._chartsMap[model.__viewId];
  27251. if (view && view.containPoint) {
  27252. result = result || view.containPoint(value, model);
  27253. } else {
  27254. if ("development" !== 'production') {
  27255. console.warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  27256. }
  27257. }
  27258. } else {
  27259. if ("development" !== 'production') {
  27260. console.warn(key + ': containPoint is not supported');
  27261. }
  27262. }
  27263. }, this);
  27264. }, this);
  27265. return !!result;
  27266. };
  27267. /**
  27268. * Get visual from series or data.
  27269. * @param finder
  27270. * If string, e.g., 'series', means {seriesIndex: 0}.
  27271. * If Object, could contain some of these properties below:
  27272. * {
  27273. * seriesIndex / seriesId / seriesName,
  27274. * dataIndex / dataIndexInside
  27275. * }
  27276. * If dataIndex is not specified, series visual will be fetched,
  27277. * but not data item visual.
  27278. * If all of seriesIndex, seriesId, seriesName are not specified,
  27279. * visual will be fetched from first series.
  27280. * @param visualType 'color', 'symbol', 'symbolSize'
  27281. */
  27282. ECharts.prototype.getVisual = function (finder, visualType) {
  27283. var ecModel = this._model;
  27284. var parsedFinder = parseFinder(ecModel, finder, {
  27285. defaultMainType: 'series'
  27286. });
  27287. var seriesModel = parsedFinder.seriesModel;
  27288. if ("development" !== 'production') {
  27289. if (!seriesModel) {
  27290. console.warn('There is no specified seires model');
  27291. }
  27292. }
  27293. var data = seriesModel.getData();
  27294. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  27295. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  27296. };
  27297. /**
  27298. * Get view of corresponding component model
  27299. */
  27300. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  27301. return this._componentsMap[componentModel.__viewId];
  27302. };
  27303. /**
  27304. * Get view of corresponding series model
  27305. */
  27306. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  27307. return this._chartsMap[seriesModel.__viewId];
  27308. };
  27309. ECharts.prototype._initEvents = function () {
  27310. var _this = this;
  27311. each(MOUSE_EVENT_NAMES, function (eveName) {
  27312. var handler = function (e) {
  27313. var ecModel = _this.getModel();
  27314. var el = e.target;
  27315. var params;
  27316. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  27317. if (isGlobalOut) {
  27318. params = {};
  27319. } else {
  27320. el && findEventDispatcher(el, function (parent) {
  27321. var ecData = getECData(parent);
  27322. if (ecData && ecData.dataIndex != null) {
  27323. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  27324. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {};
  27325. return true;
  27326. } // If element has custom eventData of components
  27327. else if (ecData.eventData) {
  27328. params = extend({}, ecData.eventData);
  27329. return true;
  27330. }
  27331. }, true);
  27332. } // Contract: if params prepared in mouse event,
  27333. // these properties must be specified:
  27334. // {
  27335. // componentType: string (component main type)
  27336. // componentIndex: number
  27337. // }
  27338. // Otherwise event query can not work.
  27339. if (params) {
  27340. var componentType = params.componentType;
  27341. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  27342. // markLine/markPoint/markArea, the componentType is
  27343. // 'markLine'/'markPoint'/'markArea', but we should better
  27344. // enable them to be queried by seriesIndex, since their
  27345. // option is set in each series.
  27346. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  27347. componentType = 'series';
  27348. componentIndex = params.seriesIndex;
  27349. }
  27350. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  27351. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  27352. if ("development" !== 'production') {
  27353. // `event.componentType` and `event[componentTpype + 'Index']` must not
  27354. // be missed, otherwise there is no way to distinguish source component.
  27355. // See `dataFormat.getDataParams`.
  27356. if (!isGlobalOut && !(model && view)) {
  27357. console.warn('model or view can not be found by params');
  27358. }
  27359. }
  27360. params.event = e;
  27361. params.type = eveName;
  27362. _this._$eventProcessor.eventInfo = {
  27363. targetEl: el,
  27364. packedEvent: params,
  27365. model: model,
  27366. view: view
  27367. };
  27368. _this.trigger(eveName, params);
  27369. }
  27370. }; // Consider that some component (like tooltip, brush, ...)
  27371. // register zr event handler, but user event handler might
  27372. // do anything, such as call `setOption` or `dispatchAction`,
  27373. // which probably update any of the content and probably
  27374. // cause problem if it is called previous other inner handlers.
  27375. handler.zrEventfulCallAtLast = true;
  27376. _this._zr.on(eveName, handler, _this);
  27377. });
  27378. each(eventActionMap, function (actionType, eventType) {
  27379. _this._messageCenter.on(eventType, function (event) {
  27380. this.trigger(eventType, event);
  27381. }, _this);
  27382. }); // Extra events
  27383. // TODO register?
  27384. each(['selectchanged'], function (eventType) {
  27385. _this._messageCenter.on(eventType, function (event) {
  27386. this.trigger(eventType, event);
  27387. }, _this);
  27388. });
  27389. handleLegacySelectEvents(this._messageCenter, this, this._api);
  27390. };
  27391. ECharts.prototype.isDisposed = function () {
  27392. return this._disposed;
  27393. };
  27394. ECharts.prototype.clear = function () {
  27395. if (this._disposed) {
  27396. disposedWarning(this.id);
  27397. return;
  27398. }
  27399. this.setOption({
  27400. series: []
  27401. }, true);
  27402. };
  27403. ECharts.prototype.dispose = function () {
  27404. if (this._disposed) {
  27405. disposedWarning(this.id);
  27406. return;
  27407. }
  27408. this._disposed = true;
  27409. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  27410. var chart = this;
  27411. var api = chart._api;
  27412. var ecModel = chart._model;
  27413. each(chart._componentsViews, function (component) {
  27414. component.dispose(ecModel, api);
  27415. });
  27416. each(chart._chartsViews, function (chart) {
  27417. chart.dispose(ecModel, api);
  27418. }); // Dispose after all views disposed
  27419. chart._zr.dispose(); // Set properties to null.
  27420. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  27421. 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;
  27422. delete instances$1[chart.id];
  27423. };
  27424. /**
  27425. * Resize the chart
  27426. */
  27427. ECharts.prototype.resize = function (opts) {
  27428. if ("development" !== 'production') {
  27429. assert(!this[IN_MAIN_PROCESS_KEY], '`resize` should not be called during main process.');
  27430. }
  27431. if (this._disposed) {
  27432. disposedWarning(this.id);
  27433. return;
  27434. }
  27435. this._zr.resize(opts);
  27436. var ecModel = this._model; // Resize loading effect
  27437. this._loadingFX && this._loadingFX.resize();
  27438. if (!ecModel) {
  27439. return;
  27440. }
  27441. var needPrepare = ecModel.resetOption('media');
  27442. var silent = opts && opts.silent; // There is some real cases that:
  27443. // chart.setOption(option, { lazyUpdate: true });
  27444. // chart.resize();
  27445. if (this[PENDING_UPDATE]) {
  27446. if (silent == null) {
  27447. silent = this[PENDING_UPDATE].silent;
  27448. }
  27449. needPrepare = true;
  27450. this[PENDING_UPDATE] = null;
  27451. }
  27452. this[IN_MAIN_PROCESS_KEY] = true;
  27453. needPrepare && prepare(this);
  27454. updateMethods.update.call(this, {
  27455. type: 'resize',
  27456. animation: extend({
  27457. // Disable animation
  27458. duration: 0
  27459. }, opts && opts.animation)
  27460. });
  27461. this[IN_MAIN_PROCESS_KEY] = false;
  27462. flushPendingActions.call(this, silent);
  27463. triggerUpdatedEvent.call(this, silent);
  27464. };
  27465. ECharts.prototype.showLoading = function (name, cfg) {
  27466. if (this._disposed) {
  27467. disposedWarning(this.id);
  27468. return;
  27469. }
  27470. if (isObject(name)) {
  27471. cfg = name;
  27472. name = '';
  27473. }
  27474. name = name || 'default';
  27475. this.hideLoading();
  27476. if (!loadingEffects[name]) {
  27477. if ("development" !== 'production') {
  27478. console.warn('Loading effects ' + name + ' not exists.');
  27479. }
  27480. return;
  27481. }
  27482. var el = loadingEffects[name](this._api, cfg);
  27483. var zr = this._zr;
  27484. this._loadingFX = el;
  27485. zr.add(el);
  27486. };
  27487. /**
  27488. * Hide loading effect
  27489. */
  27490. ECharts.prototype.hideLoading = function () {
  27491. if (this._disposed) {
  27492. disposedWarning(this.id);
  27493. return;
  27494. }
  27495. this._loadingFX && this._zr.remove(this._loadingFX);
  27496. this._loadingFX = null;
  27497. };
  27498. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  27499. var payload = extend({}, eventObj);
  27500. payload.type = eventActionMap[eventObj.type];
  27501. return payload;
  27502. };
  27503. /**
  27504. * @param opt If pass boolean, means opt.silent
  27505. * @param opt.silent Default `false`. Whether trigger events.
  27506. * @param opt.flush Default `undefined`.
  27507. * true: Flush immediately, and then pixel in canvas can be fetched
  27508. * immediately. Caution: it might affect performance.
  27509. * false: Not flush.
  27510. * undefined: Auto decide whether perform flush.
  27511. */
  27512. ECharts.prototype.dispatchAction = function (payload, opt) {
  27513. if (this._disposed) {
  27514. disposedWarning(this.id);
  27515. return;
  27516. }
  27517. if (!isObject(opt)) {
  27518. opt = {
  27519. silent: !!opt
  27520. };
  27521. }
  27522. if (!actions[payload.type]) {
  27523. return;
  27524. } // Avoid dispatch action before setOption. Especially in `connect`.
  27525. if (!this._model) {
  27526. return;
  27527. } // May dispatchAction in rendering procedure
  27528. if (this[IN_MAIN_PROCESS_KEY]) {
  27529. this._pendingActions.push(payload);
  27530. return;
  27531. }
  27532. var silent = opt.silent;
  27533. doDispatchAction.call(this, payload, silent);
  27534. var flush = opt.flush;
  27535. if (flush) {
  27536. this._zr.flush();
  27537. } else if (flush !== false && env.browser.weChat) {
  27538. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  27539. // hang when sliding page (on touch event), which cause that zr does not
  27540. // refresh util user interaction finished, which is not expected.
  27541. // But `dispatchAction` may be called too frequently when pan on touch
  27542. // screen, which impacts performance if do not throttle them.
  27543. this._throttledZrFlush();
  27544. }
  27545. flushPendingActions.call(this, silent);
  27546. triggerUpdatedEvent.call(this, silent);
  27547. };
  27548. ECharts.prototype.updateLabelLayout = function () {
  27549. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  27550. // Not adding series labels.
  27551. // TODO
  27552. updatedSeries: []
  27553. });
  27554. };
  27555. ECharts.prototype.appendData = function (params) {
  27556. if (this._disposed) {
  27557. disposedWarning(this.id);
  27558. return;
  27559. }
  27560. var seriesIndex = params.seriesIndex;
  27561. var ecModel = this.getModel();
  27562. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  27563. if ("development" !== 'production') {
  27564. assert(params.data && seriesModel);
  27565. }
  27566. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  27567. // system, util some scenario require that. In the expected usage of
  27568. // `appendData`, the initial extent of coordinate system should better
  27569. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  27570. // the extent changed while `appendData`, the location of the painted
  27571. // graphic elements have to be changed, which make the usage of
  27572. // `appendData` meaningless.
  27573. this._scheduler.unfinished = true;
  27574. this.getZr().wakeUp();
  27575. }; // A work around for no `internal` modifier in ts yet but
  27576. // need to strictly hide private methods to JS users.
  27577. ECharts.internalField = function () {
  27578. prepare = function (ecIns) {
  27579. var scheduler = ecIns._scheduler;
  27580. scheduler.restorePipelines(ecIns._model);
  27581. scheduler.prepareStageTasks();
  27582. prepareView(ecIns, true);
  27583. prepareView(ecIns, false);
  27584. scheduler.plan();
  27585. };
  27586. /**
  27587. * Prepare view instances of charts and components
  27588. */
  27589. prepareView = function (ecIns, isComponent) {
  27590. var ecModel = ecIns._model;
  27591. var scheduler = ecIns._scheduler;
  27592. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  27593. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  27594. var zr = ecIns._zr;
  27595. var api = ecIns._api;
  27596. for (var i = 0; i < viewList.length; i++) {
  27597. viewList[i].__alive = false;
  27598. }
  27599. isComponent ? ecModel.eachComponent(function (componentType, model) {
  27600. componentType !== 'series' && doPrepare(model);
  27601. }) : ecModel.eachSeries(doPrepare);
  27602. function doPrepare(model) {
  27603. // By defaut view will be reused if possible for the case that `setOption` with "notMerge"
  27604. // mode and need to enable transition animation. (Usually, when they have the same id, or
  27605. // especially no id but have the same type & name & index. See the `model.id` generation
  27606. // rule in `makeIdAndName` and `viewId` generation rule here).
  27607. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  27608. // the new model has nothing to do with the old model.
  27609. var requireNewView = model.__requireNewView; // This command should not work twice.
  27610. model.__requireNewView = false; // Consider: id same and type changed.
  27611. var viewId = '_ec_' + model.id + '_' + model.type;
  27612. var view = !requireNewView && viewMap[viewId];
  27613. if (!view) {
  27614. var classType = parseClassType(model.type);
  27615. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  27616. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  27617. // For backward compat, still support a chart type declared as only subType
  27618. // like "liquidfill", but recommend "series.liquidfill"
  27619. // But need a base class to make a type series.
  27620. ChartView.getClass(classType.sub);
  27621. if ("development" !== 'production') {
  27622. assert(Clazz, classType.sub + ' does not exist.');
  27623. }
  27624. view = new Clazz();
  27625. view.init(ecModel, api);
  27626. viewMap[viewId] = view;
  27627. viewList.push(view);
  27628. zr.add(view.group);
  27629. }
  27630. model.__viewId = view.__id = viewId;
  27631. view.__alive = true;
  27632. view.__model = model;
  27633. view.group.__ecComponentInfo = {
  27634. mainType: model.mainType,
  27635. index: model.componentIndex
  27636. };
  27637. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  27638. }
  27639. for (var i = 0; i < viewList.length;) {
  27640. var view = viewList[i];
  27641. if (!view.__alive) {
  27642. !isComponent && view.renderTask.dispose();
  27643. zr.remove(view.group);
  27644. view.dispose(ecModel, api);
  27645. viewList.splice(i, 1);
  27646. if (viewMap[view.__id] === view) {
  27647. delete viewMap[view.__id];
  27648. }
  27649. view.__id = view.group.__ecComponentInfo = null;
  27650. } else {
  27651. i++;
  27652. }
  27653. }
  27654. };
  27655. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  27656. var ecModel = ecIns._model;
  27657. ecModel.setUpdatePayload(payload); // broadcast
  27658. if (!mainType) {
  27659. // FIXME
  27660. // Chart will not be update directly here, except set dirty.
  27661. // But there is no such scenario now.
  27662. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  27663. return;
  27664. }
  27665. var query = {};
  27666. query[mainType + 'Id'] = payload[mainType + 'Id'];
  27667. query[mainType + 'Index'] = payload[mainType + 'Index'];
  27668. query[mainType + 'Name'] = payload[mainType + 'Name'];
  27669. var condition = {
  27670. mainType: mainType,
  27671. query: query
  27672. };
  27673. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  27674. var excludeSeriesId = payload.excludeSeriesId;
  27675. var excludeSeriesIdMap;
  27676. if (excludeSeriesId != null) {
  27677. excludeSeriesIdMap = createHashMap();
  27678. each(normalizeToArray(excludeSeriesId), function (id) {
  27679. var modelId = convertOptionIdName(id, null);
  27680. if (modelId != null) {
  27681. excludeSeriesIdMap.set(modelId, true);
  27682. }
  27683. });
  27684. }
  27685. if (isHighDownPayload(payload)) {
  27686. allLeaveBlur(ecIns._api);
  27687. } // If dispatchAction before setOption, do nothing.
  27688. ecModel && ecModel.eachComponent(condition, function (model) {
  27689. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) !== null;
  27690. if (isExcluded) {
  27691. return;
  27692. }
  27693. if (isHighDownPayload(payload)) {
  27694. if (model instanceof SeriesModel) {
  27695. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur) {
  27696. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  27697. }
  27698. } else {
  27699. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  27700. focusSelf = _a.focusSelf,
  27701. dispatchers = _a.dispatchers;
  27702. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  27703. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  27704. } // PENDING:
  27705. // Whether to put this "enter emphasis" code in `ComponentView`,
  27706. // which will be the same as `ChartView` but might be not necessary
  27707. // and will be far from this logic.
  27708. if (dispatchers) {
  27709. each(dispatchers, function (dispatcher) {
  27710. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  27711. });
  27712. }
  27713. }
  27714. } else if (isSelectChangePayload(payload)) {
  27715. // TODO geo
  27716. if (model instanceof SeriesModel) {
  27717. toggleSelectionFromPayload(model, payload, ecIns._api);
  27718. updateSeriesElementSelection(model);
  27719. markStatusToUpdate(ecIns);
  27720. }
  27721. }
  27722. }, ecIns);
  27723. ecModel && ecModel.eachComponent(condition, function (model) {
  27724. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) !== null;
  27725. if (isExcluded) {
  27726. return;
  27727. }
  27728. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  27729. }, ecIns);
  27730. function callView(view) {
  27731. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  27732. }
  27733. };
  27734. updateMethods = {
  27735. prepareAndUpdate: function (payload) {
  27736. prepare(this);
  27737. updateMethods.update.call(this, payload, {
  27738. // Needs to mark option changed if newOption is given.
  27739. // It's from MagicType.
  27740. // TODO If use a separate flag optionChanged in payload?
  27741. optionChanged: payload.newOption != null
  27742. });
  27743. },
  27744. update: function (payload, updateParams) {
  27745. var ecModel = this._model;
  27746. var api = this._api;
  27747. var zr = this._zr;
  27748. var coordSysMgr = this._coordSysMgr;
  27749. var scheduler = this._scheduler; // update before setOption
  27750. if (!ecModel) {
  27751. return;
  27752. }
  27753. ecModel.setUpdatePayload(payload);
  27754. scheduler.restoreData(ecModel, payload);
  27755. scheduler.performSeriesTasks(ecModel); // TODO
  27756. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  27757. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  27758. // Create new coordinate system each update
  27759. // In LineView may save the old coordinate system and use it to get the orignal point
  27760. coordSysMgr.create(ecModel, api);
  27761. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  27762. // stream modes after data processing, where the filtered data is used to
  27763. // deteming whether use progressive rendering.
  27764. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  27765. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  27766. // the drawback is the full coord info can not be fetched. Fortunately this full
  27767. // coord is not requied in stream mode updater currently.
  27768. coordSysMgr.update(ecModel, api);
  27769. clearColorPalette(ecModel);
  27770. scheduler.performVisualTasks(ecModel, payload);
  27771. render(this, ecModel, api, payload, updateParams); // Set background
  27772. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  27773. var darkMode = ecModel.get('darkMode'); // In IE8
  27774. if (!env.canvasSupported) {
  27775. var colorArr = parse(backgroundColor);
  27776. backgroundColor = stringify(colorArr, 'rgb');
  27777. if (colorArr[3] === 0) {
  27778. backgroundColor = 'transparent';
  27779. }
  27780. } else {
  27781. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  27782. if (darkMode != null && darkMode !== 'auto') {
  27783. zr.setDarkMode(darkMode);
  27784. }
  27785. }
  27786. lifecycle.trigger('afterupdate', ecModel, api);
  27787. },
  27788. updateTransform: function (payload) {
  27789. var _this = this;
  27790. var ecModel = this._model;
  27791. var api = this._api; // update before setOption
  27792. if (!ecModel) {
  27793. return;
  27794. }
  27795. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  27796. var componentDirtyList = [];
  27797. ecModel.eachComponent(function (componentType, componentModel) {
  27798. if (componentType === 'series') {
  27799. return;
  27800. }
  27801. var componentView = _this.getViewOfComponentModel(componentModel);
  27802. if (componentView && componentView.__alive) {
  27803. if (componentView.updateTransform) {
  27804. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  27805. result && result.update && componentDirtyList.push(componentView);
  27806. } else {
  27807. componentDirtyList.push(componentView);
  27808. }
  27809. }
  27810. });
  27811. var seriesDirtyMap = createHashMap();
  27812. ecModel.eachSeries(function (seriesModel) {
  27813. var chartView = _this._chartsMap[seriesModel.__viewId];
  27814. if (chartView.updateTransform) {
  27815. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  27816. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  27817. } else {
  27818. seriesDirtyMap.set(seriesModel.uid, 1);
  27819. }
  27820. });
  27821. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  27822. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  27823. this._scheduler.performVisualTasks(ecModel, payload, {
  27824. setDirty: true,
  27825. dirtyMap: seriesDirtyMap
  27826. }); // Currently, not call render of components. Geo render cost a lot.
  27827. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  27828. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  27829. lifecycle.trigger('afterupdate', ecModel, api);
  27830. },
  27831. updateView: function (payload) {
  27832. var ecModel = this._model; // update before setOption
  27833. if (!ecModel) {
  27834. return;
  27835. }
  27836. ecModel.setUpdatePayload(payload);
  27837. ChartView.markUpdateMethod(payload, 'updateView');
  27838. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  27839. this._scheduler.performVisualTasks(ecModel, payload, {
  27840. setDirty: true
  27841. });
  27842. render(this, ecModel, this._api, payload, {});
  27843. lifecycle.trigger('afterupdate', ecModel, this._api);
  27844. },
  27845. updateVisual: function (payload) {
  27846. // updateMethods.update.call(this, payload);
  27847. var _this = this;
  27848. var ecModel = this._model; // update before setOption
  27849. if (!ecModel) {
  27850. return;
  27851. }
  27852. ecModel.setUpdatePayload(payload); // clear all visual
  27853. ecModel.eachSeries(function (seriesModel) {
  27854. seriesModel.getData().clearAllVisual();
  27855. }); // Perform visual
  27856. ChartView.markUpdateMethod(payload, 'updateVisual');
  27857. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  27858. this._scheduler.performVisualTasks(ecModel, payload, {
  27859. visualType: 'visual',
  27860. setDirty: true
  27861. });
  27862. ecModel.eachComponent(function (componentType, componentModel) {
  27863. if (componentType !== 'series') {
  27864. var componentView = _this.getViewOfComponentModel(componentModel);
  27865. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  27866. }
  27867. });
  27868. ecModel.eachSeries(function (seriesModel) {
  27869. var chartView = _this._chartsMap[seriesModel.__viewId];
  27870. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  27871. });
  27872. lifecycle.trigger('afterupdate', ecModel, this._api);
  27873. },
  27874. updateLayout: function (payload) {
  27875. updateMethods.update.call(this, payload);
  27876. }
  27877. };
  27878. doConvertPixel = function (ecIns, methodName, finder, value) {
  27879. if (ecIns._disposed) {
  27880. disposedWarning(ecIns.id);
  27881. return;
  27882. }
  27883. var ecModel = ecIns._model;
  27884. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  27885. var result;
  27886. var parsedFinder = parseFinder(ecModel, finder);
  27887. for (var i = 0; i < coordSysList.length; i++) {
  27888. var coordSys = coordSysList[i];
  27889. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  27890. return result;
  27891. }
  27892. }
  27893. if ("development" !== 'production') {
  27894. console.warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  27895. }
  27896. };
  27897. updateStreamModes = function (ecIns, ecModel) {
  27898. var chartsMap = ecIns._chartsMap;
  27899. var scheduler = ecIns._scheduler;
  27900. ecModel.eachSeries(function (seriesModel) {
  27901. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  27902. });
  27903. };
  27904. doDispatchAction = function (payload, silent) {
  27905. var _this = this;
  27906. var ecModel = this.getModel();
  27907. var payloadType = payload.type;
  27908. var escapeConnect = payload.escapeConnect;
  27909. var actionWrap = actions[payloadType];
  27910. var actionInfo = actionWrap.actionInfo;
  27911. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  27912. var updateMethod = cptTypeTmp.pop();
  27913. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  27914. this[IN_MAIN_PROCESS_KEY] = true;
  27915. var payloads = [payload];
  27916. var batched = false; // Batch action
  27917. if (payload.batch) {
  27918. batched = true;
  27919. payloads = map(payload.batch, function (item) {
  27920. item = defaults(extend({}, item), payload);
  27921. item.batch = null;
  27922. return item;
  27923. });
  27924. }
  27925. var eventObjBatch = [];
  27926. var eventObj;
  27927. var isSelectChange = isSelectChangePayload(payload);
  27928. var isHighDown = isHighDownPayload(payload);
  27929. each(payloads, function (batchItem) {
  27930. // Action can specify the event by return it.
  27931. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  27932. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  27933. eventObj.type = actionInfo.event || eventObj.type;
  27934. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  27935. if (isHighDown) {
  27936. var _a = preParseFinder(payload),
  27937. queryOptionMap = _a.queryOptionMap,
  27938. mainTypeSpecified = _a.mainTypeSpecified;
  27939. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  27940. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  27941. markStatusToUpdate(_this);
  27942. } else if (isSelectChange) {
  27943. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  27944. // geo still use 'geoselect'.
  27945. updateDirectly(_this, updateMethod, batchItem, 'series');
  27946. markStatusToUpdate(_this);
  27947. } else if (cptType) {
  27948. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  27949. }
  27950. });
  27951. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  27952. // Still dirty
  27953. if (this[PENDING_UPDATE]) {
  27954. prepare(this);
  27955. updateMethods.update.call(this, payload);
  27956. this[PENDING_UPDATE] = null;
  27957. } else {
  27958. updateMethods[updateMethod].call(this, payload);
  27959. }
  27960. } // Follow the rule of action batch
  27961. if (batched) {
  27962. eventObj = {
  27963. type: actionInfo.event || payloadType,
  27964. escapeConnect: escapeConnect,
  27965. batch: eventObjBatch
  27966. };
  27967. } else {
  27968. eventObj = eventObjBatch[0];
  27969. }
  27970. this[IN_MAIN_PROCESS_KEY] = false;
  27971. if (!silent) {
  27972. var messageCenter = this._messageCenter;
  27973. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  27974. if (isSelectChange) {
  27975. var newObj = {
  27976. type: 'selectchanged',
  27977. escapeConnect: escapeConnect,
  27978. selected: getAllSelectedIndices(ecModel),
  27979. isFromClick: payload.isFromClick || false,
  27980. fromAction: payload.type,
  27981. fromActionPayload: payload
  27982. };
  27983. messageCenter.trigger(newObj.type, newObj);
  27984. }
  27985. }
  27986. };
  27987. flushPendingActions = function (silent) {
  27988. var pendingActions = this._pendingActions;
  27989. while (pendingActions.length) {
  27990. var payload = pendingActions.shift();
  27991. doDispatchAction.call(this, payload, silent);
  27992. }
  27993. };
  27994. triggerUpdatedEvent = function (silent) {
  27995. !silent && this.trigger('updated');
  27996. };
  27997. /**
  27998. * Event `rendered` is triggered when zr
  27999. * rendered. It is useful for realtime
  28000. * snapshot (reflect animation).
  28001. *
  28002. * Event `finished` is triggered when:
  28003. * (1) zrender rendering finished.
  28004. * (2) initial animation finished.
  28005. * (3) progressive rendering finished.
  28006. * (4) no pending action.
  28007. * (5) no delayed setOption needs to be processed.
  28008. */
  28009. bindRenderedEvent = function (zr, ecIns) {
  28010. zr.on('rendered', function (params) {
  28011. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatly,
  28012. // so it should only be triggered when rendering indeed happend
  28013. // in zrender. (Consider the case that dipatchAction is keep
  28014. // triggering when mouse move).
  28015. if ( // Although zr is dirty if initial animation is not finished
  28016. // and this checking is called on frame, we also check
  28017. // animation finished for robustness.
  28018. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  28019. ecIns.trigger('finished');
  28020. }
  28021. });
  28022. };
  28023. bindMouseEvent = function (zr, ecIns) {
  28024. zr.on('mouseover', function (e) {
  28025. var el = e.target;
  28026. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  28027. if (dispatcher) {
  28028. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  28029. markStatusToUpdate(ecIns);
  28030. }
  28031. }).on('mouseout', function (e) {
  28032. var el = e.target;
  28033. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  28034. if (dispatcher) {
  28035. handleGlboalMouseOutForHighDown(dispatcher, e, ecIns._api);
  28036. markStatusToUpdate(ecIns);
  28037. }
  28038. }).on('click', function (e) {
  28039. var el = e.target;
  28040. var dispatcher = findEventDispatcher(el, function (target) {
  28041. return getECData(target).dataIndex != null;
  28042. }, true);
  28043. if (dispatcher) {
  28044. var actionType = dispatcher.selected ? 'unselect' : 'select';
  28045. var ecData = getECData(dispatcher);
  28046. ecIns._api.dispatchAction({
  28047. type: actionType,
  28048. dataType: ecData.dataType,
  28049. dataIndexInside: ecData.dataIndex,
  28050. seriesIndex: ecData.seriesIndex,
  28051. isFromClick: true
  28052. });
  28053. }
  28054. });
  28055. };
  28056. clearColorPalette = function (ecModel) {
  28057. ecModel.clearColorPalette();
  28058. ecModel.eachSeries(function (seriesModel) {
  28059. seriesModel.clearColorPalette();
  28060. });
  28061. };
  28062. render = function (ecIns, ecModel, api, payload, updateParams) {
  28063. renderComponents(ecIns, ecModel, api, payload, updateParams);
  28064. each(ecIns._chartsViews, function (chart) {
  28065. chart.__alive = false;
  28066. });
  28067. renderSeries(ecIns, ecModel, api, payload, updateParams); // Remove groups of unrendered charts
  28068. each(ecIns._chartsViews, function (chart) {
  28069. if (!chart.__alive) {
  28070. chart.remove(ecModel, api);
  28071. }
  28072. });
  28073. };
  28074. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  28075. each(dirtyList || ecIns._componentsViews, function (componentView) {
  28076. var componentModel = componentView.__model;
  28077. clearStates(componentModel, componentView);
  28078. componentView.render(componentModel, ecModel, api, payload);
  28079. updateZ(componentModel, componentView);
  28080. updateStates(componentModel, componentView);
  28081. });
  28082. };
  28083. /**
  28084. * Render each chart and component
  28085. */
  28086. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  28087. // Render all charts
  28088. var scheduler = ecIns._scheduler;
  28089. updateParams = extend(updateParams || {}, {
  28090. updatedSeries: ecModel.getSeries()
  28091. }); // TODO progressive?
  28092. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  28093. var unfinished = false;
  28094. ecModel.eachSeries(function (seriesModel) {
  28095. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  28096. chartView.__alive = true;
  28097. var renderTask = chartView.renderTask;
  28098. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  28099. clearStates(seriesModel, chartView);
  28100. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  28101. renderTask.dirty();
  28102. }
  28103. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  28104. unfinished = true;
  28105. }
  28106. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  28107. // increamental render (alway render from the __startIndex each frame)
  28108. // chartView.group.markRedraw();
  28109. updateBlend(seriesModel, chartView);
  28110. updateSeriesElementSelection(seriesModel);
  28111. });
  28112. scheduler.unfinished = unfinished || scheduler.unfinished;
  28113. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams); // transition after label is layouted.
  28114. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  28115. ecModel.eachSeries(function (seriesModel) {
  28116. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  28117. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  28118. // label should be in normal status when layouting.
  28119. updateStates(seriesModel, chartView);
  28120. }); // If use hover layer
  28121. updateHoverLayerStatus(ecIns, ecModel);
  28122. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  28123. };
  28124. markStatusToUpdate = function (ecIns) {
  28125. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  28126. ecIns.getZr().wakeUp();
  28127. };
  28128. applyChangedStates = function (ecIns) {
  28129. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  28130. return;
  28131. }
  28132. ecIns.getZr().storage.traverse(function (el) {
  28133. // Not applied on removed elements, it may still in fading.
  28134. if (isElementRemoved(el)) {
  28135. return;
  28136. }
  28137. applyElementStates(el);
  28138. });
  28139. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  28140. };
  28141. function applyElementStates(el) {
  28142. var newStates = [];
  28143. var oldStates = el.currentStates; // Keep other states.
  28144. for (var i = 0; i < oldStates.length; i++) {
  28145. var stateName = oldStates[i];
  28146. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  28147. newStates.push(stateName);
  28148. }
  28149. } // Only use states when it's exists.
  28150. if (el.selected && el.states.select) {
  28151. newStates.push('select');
  28152. }
  28153. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  28154. newStates.push('emphasis');
  28155. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  28156. newStates.push('blur');
  28157. }
  28158. el.useStates(newStates);
  28159. }
  28160. function updateHoverLayerStatus(ecIns, ecModel) {
  28161. var zr = ecIns._zr;
  28162. var storage = zr.storage;
  28163. var elCount = 0;
  28164. storage.traverse(function (el) {
  28165. if (!el.isGroup) {
  28166. elCount++;
  28167. }
  28168. });
  28169. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  28170. ecModel.eachSeries(function (seriesModel) {
  28171. if (seriesModel.preventUsingHoverLayer) {
  28172. return;
  28173. }
  28174. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  28175. if (chartView.__alive) {
  28176. chartView.group.traverse(function (el) {
  28177. if (el.states.emphasis) {
  28178. el.states.emphasis.hoverLayer = true;
  28179. }
  28180. });
  28181. }
  28182. });
  28183. }
  28184. }
  28185. /**
  28186. * Update chart and blend.
  28187. */
  28188. function updateBlend(seriesModel, chartView) {
  28189. var blendMode = seriesModel.get('blendMode') || null;
  28190. if ("development" !== 'production') {
  28191. if (!env.canvasSupported && blendMode && blendMode !== 'source-over') {
  28192. console.warn('Only canvas support blendMode');
  28193. }
  28194. }
  28195. chartView.group.traverse(function (el) {
  28196. // FIXME marker and other components
  28197. if (!el.isGroup) {
  28198. // DONT mark the element dirty. In case element is incremental and don't wan't to rerender.
  28199. el.style.blend = blendMode;
  28200. }
  28201. if (el.eachPendingDisplayable) {
  28202. el.eachPendingDisplayable(function (displayable) {
  28203. displayable.style.blend = blendMode;
  28204. });
  28205. }
  28206. });
  28207. }
  28208. function updateZ(model, view) {
  28209. if (model.preventAutoZ) {
  28210. return;
  28211. } // Set z and zlevel
  28212. _updateZ(view.group, model.get('z') || 0, model.get('zlevel') || 0, -Infinity);
  28213. }
  28214. function _updateZ(el, z, zlevel, maxZ2) {
  28215. // Group may also have textContent
  28216. var label = el.getTextContent();
  28217. var labelLine = el.getTextGuideLine();
  28218. var isGroup = el.isGroup;
  28219. if (isGroup) {
  28220. // set z & zlevel of children elements of Group
  28221. // el.traverse((childEl: Element) => _updateZ(childEl, z, zlevel));
  28222. var children = el.childrenRef();
  28223. for (var i = 0; i < children.length; i++) {
  28224. maxZ2 = Math.max(_updateZ(children[i], z, zlevel, maxZ2), maxZ2);
  28225. }
  28226. } else {
  28227. // not Group
  28228. el.z = z;
  28229. el.zlevel = zlevel;
  28230. maxZ2 = Math.max(el.z2, maxZ2);
  28231. } // always set z and zlevel if label/labelLine exists
  28232. if (label) {
  28233. label.z = z;
  28234. label.zlevel = zlevel; // lift z2 of text content
  28235. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  28236. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  28237. }
  28238. if (labelLine) {
  28239. var textGuideLineConfig = el.textGuideLineConfig;
  28240. labelLine.z = z;
  28241. labelLine.zlevel = zlevel;
  28242. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  28243. }
  28244. return maxZ2;
  28245. } // Clear states without animation.
  28246. // TODO States on component.
  28247. function clearStates(model, view) {
  28248. view.group.traverse(function (el) {
  28249. // Not applied on removed elements, it may still in fading.
  28250. if (isElementRemoved(el)) {
  28251. return;
  28252. }
  28253. var textContent = el.getTextContent();
  28254. var textGuide = el.getTextGuideLine();
  28255. if (el.stateTransition) {
  28256. el.stateTransition = null;
  28257. }
  28258. if (textContent && textContent.stateTransition) {
  28259. textContent.stateTransition = null;
  28260. }
  28261. if (textGuide && textGuide.stateTransition) {
  28262. textGuide.stateTransition = null;
  28263. } // TODO If el is incremental.
  28264. if (el.hasState()) {
  28265. el.prevStates = el.currentStates;
  28266. el.clearStates();
  28267. } else if (el.prevStates) {
  28268. el.prevStates = null;
  28269. }
  28270. });
  28271. }
  28272. function updateStates(model, view) {
  28273. var stateAnimationModel = model.getModel('stateAnimation');
  28274. var enableAnimation = model.isAnimationEnabled();
  28275. var duration = stateAnimationModel.get('duration');
  28276. var stateTransition = duration > 0 ? {
  28277. duration: duration,
  28278. delay: stateAnimationModel.get('delay'),
  28279. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  28280. } : null;
  28281. view.group.traverse(function (el) {
  28282. if (el.states && el.states.emphasis) {
  28283. // Not applied on removed elements, it may still in fading.
  28284. if (isElementRemoved(el)) {
  28285. return;
  28286. }
  28287. if (el instanceof Path) {
  28288. savePathStates(el);
  28289. } // Only updated on changed element. In case element is incremental and don't wan't to rerender.
  28290. // TODO, a more proper way?
  28291. if (el.__dirty) {
  28292. var prevStates = el.prevStates; // Restore states without animation
  28293. if (prevStates) {
  28294. el.useStates(prevStates);
  28295. }
  28296. } // Update state transition and enable animation again.
  28297. if (enableAnimation) {
  28298. el.stateTransition = stateTransition;
  28299. var textContent = el.getTextContent();
  28300. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  28301. if (textContent) {
  28302. textContent.stateTransition = stateTransition;
  28303. }
  28304. if (textGuide) {
  28305. textGuide.stateTransition = stateTransition;
  28306. }
  28307. } // The use higlighted and selected flag to toggle states.
  28308. if (el.__dirty) {
  28309. applyElementStates(el);
  28310. }
  28311. }
  28312. });
  28313. }
  28314. createExtensionAPI = function (ecIns) {
  28315. return new (
  28316. /** @class */
  28317. function (_super) {
  28318. __extends(class_1, _super);
  28319. function class_1() {
  28320. return _super !== null && _super.apply(this, arguments) || this;
  28321. }
  28322. class_1.prototype.getCoordinateSystems = function () {
  28323. return ecIns._coordSysMgr.getCoordinateSystems();
  28324. };
  28325. class_1.prototype.getComponentByElement = function (el) {
  28326. while (el) {
  28327. var modelInfo = el.__ecComponentInfo;
  28328. if (modelInfo != null) {
  28329. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  28330. }
  28331. el = el.parent;
  28332. }
  28333. };
  28334. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  28335. enterEmphasis(el, highlightDigit);
  28336. markStatusToUpdate(ecIns);
  28337. };
  28338. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  28339. leaveEmphasis(el, highlightDigit);
  28340. markStatusToUpdate(ecIns);
  28341. };
  28342. class_1.prototype.enterBlur = function (el) {
  28343. enterBlur(el);
  28344. markStatusToUpdate(ecIns);
  28345. };
  28346. class_1.prototype.leaveBlur = function (el) {
  28347. leaveBlur(el);
  28348. markStatusToUpdate(ecIns);
  28349. };
  28350. class_1.prototype.enterSelect = function (el) {
  28351. enterSelect(el);
  28352. markStatusToUpdate(ecIns);
  28353. };
  28354. class_1.prototype.leaveSelect = function (el) {
  28355. leaveSelect(el);
  28356. markStatusToUpdate(ecIns);
  28357. };
  28358. class_1.prototype.getModel = function () {
  28359. return ecIns.getModel();
  28360. };
  28361. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  28362. return ecIns.getViewOfComponentModel(componentModel);
  28363. };
  28364. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  28365. return ecIns.getViewOfSeriesModel(seriesModel);
  28366. };
  28367. return class_1;
  28368. }(ExtensionAPI))(ecIns);
  28369. };
  28370. enableConnect = function (chart) {
  28371. function updateConnectedChartsStatus(charts, status) {
  28372. for (var i = 0; i < charts.length; i++) {
  28373. var otherChart = charts[i];
  28374. otherChart[CONNECT_STATUS_KEY] = status;
  28375. }
  28376. }
  28377. each(eventActionMap, function (actionType, eventType) {
  28378. chart._messageCenter.on(eventType, function (event) {
  28379. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  28380. if (event && event.escapeConnect) {
  28381. return;
  28382. }
  28383. var action_1 = chart.makeActionFromEvent(event);
  28384. var otherCharts_1 = [];
  28385. each(instances$1, function (otherChart) {
  28386. if (otherChart !== chart && otherChart.group === chart.group) {
  28387. otherCharts_1.push(otherChart);
  28388. }
  28389. });
  28390. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  28391. each(otherCharts_1, function (otherChart) {
  28392. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  28393. otherChart.dispatchAction(action_1);
  28394. }
  28395. });
  28396. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  28397. }
  28398. });
  28399. });
  28400. };
  28401. }();
  28402. return ECharts;
  28403. }(Eventful);
  28404. var echartsProto = ECharts.prototype;
  28405. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  28406. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  28407. /**
  28408. * @deprecated
  28409. */
  28410. // @ts-ignore
  28411. echartsProto.one = function (eventName, cb, ctx) {
  28412. var self = this;
  28413. deprecateLog('ECharts#one is deprecated.');
  28414. function wrapped() {
  28415. var args2 = [];
  28416. for (var _i = 0; _i < arguments.length; _i++) {
  28417. args2[_i] = arguments[_i];
  28418. }
  28419. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  28420. self.off(eventName, wrapped);
  28421. }
  28422. this.on.call(this, eventName, wrapped, ctx);
  28423. }; // /**
  28424. // * Encode visual infomation from data after data processing
  28425. // *
  28426. // * @param {module:echarts/model/Global} ecModel
  28427. // * @param {object} layout
  28428. // * @param {boolean} [layoutFilter] `true`: only layout,
  28429. // * `false`: only not layout,
  28430. // * `null`/`undefined`: all.
  28431. // * @param {string} taskBaseTag
  28432. // * @private
  28433. // */
  28434. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  28435. // each(visualFuncs, function (visual, index) {
  28436. // let isLayout = visual.isLayout;
  28437. // if (layoutFilter == null
  28438. // || (layoutFilter === false && !isLayout)
  28439. // || (layoutFilter === true && isLayout)
  28440. // ) {
  28441. // visual.func(ecModel, api, payload);
  28442. // }
  28443. // });
  28444. // }
  28445. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  28446. function disposedWarning(id) {
  28447. if ("development" !== 'production') {
  28448. console.warn('Instance ' + id + ' has been disposed');
  28449. }
  28450. }
  28451. var actions = {};
  28452. /**
  28453. * Map eventType to actionType
  28454. */
  28455. var eventActionMap = {};
  28456. var dataProcessorFuncs = [];
  28457. var optionPreprocessorFuncs = [];
  28458. var visualFuncs = [];
  28459. var themeStorage = {};
  28460. var loadingEffects = {};
  28461. var instances$1 = {};
  28462. var connectedGroups = {};
  28463. var idBase = +new Date() - 0;
  28464. var groupIdBase = +new Date() - 0;
  28465. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  28466. /**
  28467. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  28468. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  28469. * @param opts.width Use clientWidth of the input `dom` by default.
  28470. * Can be 'auto' (the same as null/undefined)
  28471. * @param opts.height Use clientHeight of the input `dom` by default.
  28472. * Can be 'auto' (the same as null/undefined)
  28473. * @param opts.locale Specify the locale.
  28474. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  28475. */
  28476. function init$1(dom, theme, opts) {
  28477. if ("development" !== 'production') {
  28478. if (!dom) {
  28479. throw new Error('Initialize failed: invalid dom.');
  28480. }
  28481. }
  28482. var existInstance = getInstanceByDom(dom);
  28483. if (existInstance) {
  28484. if ("development" !== 'production') {
  28485. console.warn('There is a chart instance already initialized on the dom.');
  28486. }
  28487. return existInstance;
  28488. }
  28489. if ("development" !== 'production') {
  28490. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  28491. console.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.');
  28492. }
  28493. }
  28494. var chart = new ECharts(dom, theme, opts);
  28495. chart.id = 'ec_' + idBase++;
  28496. instances$1[chart.id] = chart;
  28497. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  28498. enableConnect(chart);
  28499. lifecycle.trigger('afterinit', chart);
  28500. return chart;
  28501. }
  28502. /**
  28503. * @usage
  28504. * (A)
  28505. * ```js
  28506. * let chart1 = echarts.init(dom1);
  28507. * let chart2 = echarts.init(dom2);
  28508. * chart1.group = 'xxx';
  28509. * chart2.group = 'xxx';
  28510. * echarts.connect('xxx');
  28511. * ```
  28512. * (B)
  28513. * ```js
  28514. * let chart1 = echarts.init(dom1);
  28515. * let chart2 = echarts.init(dom2);
  28516. * echarts.connect('xxx', [chart1, chart2]);
  28517. * ```
  28518. */
  28519. function connect(groupId) {
  28520. // Is array of charts
  28521. if (isArray(groupId)) {
  28522. var charts = groupId;
  28523. groupId = null; // If any chart has group
  28524. each(charts, function (chart) {
  28525. if (chart.group != null) {
  28526. groupId = chart.group;
  28527. }
  28528. });
  28529. groupId = groupId || 'g_' + groupIdBase++;
  28530. each(charts, function (chart) {
  28531. chart.group = groupId;
  28532. });
  28533. }
  28534. connectedGroups[groupId] = true;
  28535. return groupId;
  28536. }
  28537. /**
  28538. * @deprecated
  28539. */
  28540. function disConnect(groupId) {
  28541. connectedGroups[groupId] = false;
  28542. }
  28543. /**
  28544. * Alias and backword compat
  28545. */
  28546. var disconnect = disConnect;
  28547. /**
  28548. * Dispose a chart instance
  28549. */
  28550. function dispose$1(chart) {
  28551. if (typeof chart === 'string') {
  28552. chart = instances$1[chart];
  28553. } else if (!(chart instanceof ECharts)) {
  28554. // Try to treat as dom
  28555. chart = getInstanceByDom(chart);
  28556. }
  28557. if (chart instanceof ECharts && !chart.isDisposed()) {
  28558. chart.dispose();
  28559. }
  28560. }
  28561. function getInstanceByDom(dom) {
  28562. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  28563. }
  28564. function getInstanceById(key) {
  28565. return instances$1[key];
  28566. }
  28567. /**
  28568. * Register theme
  28569. */
  28570. function registerTheme(name, theme) {
  28571. themeStorage[name] = theme;
  28572. }
  28573. /**
  28574. * Register option preprocessor
  28575. */
  28576. function registerPreprocessor(preprocessorFunc) {
  28577. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  28578. optionPreprocessorFuncs.push(preprocessorFunc);
  28579. }
  28580. }
  28581. function registerProcessor(priority, processor) {
  28582. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  28583. }
  28584. /**
  28585. * Register postIniter
  28586. * @param {Function} postInitFunc
  28587. */
  28588. function registerPostInit(postInitFunc) {
  28589. registerUpdateLifecycle('afterinit', postInitFunc);
  28590. }
  28591. /**
  28592. * Register postUpdater
  28593. * @param {Function} postUpdateFunc
  28594. */
  28595. function registerPostUpdate(postUpdateFunc) {
  28596. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  28597. }
  28598. function registerUpdateLifecycle(name, cb) {
  28599. lifecycle.on(name, cb);
  28600. }
  28601. function registerAction(actionInfo, eventName, action) {
  28602. if (typeof eventName === 'function') {
  28603. action = eventName;
  28604. eventName = '';
  28605. }
  28606. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  28607. event: eventName
  28608. }][0]; // Event name is all lowercase
  28609. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  28610. eventName = actionInfo.event;
  28611. if (eventActionMap[eventName]) {
  28612. // Already registered.
  28613. return;
  28614. } // Validate action type and event name.
  28615. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  28616. if (!actions[actionType]) {
  28617. actions[actionType] = {
  28618. action: action,
  28619. actionInfo: actionInfo
  28620. };
  28621. }
  28622. eventActionMap[eventName] = actionType;
  28623. }
  28624. function registerCoordinateSystem(type, coordSysCreator) {
  28625. CoordinateSystemManager.register(type, coordSysCreator);
  28626. }
  28627. /**
  28628. * Get dimensions of specified coordinate system.
  28629. * @param {string} type
  28630. * @return {Array.<string|Object>}
  28631. */
  28632. function getCoordinateSystemDimensions(type) {
  28633. var coordSysCreator = CoordinateSystemManager.get(type);
  28634. if (coordSysCreator) {
  28635. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  28636. }
  28637. }
  28638. function registerLayout(priority, layoutTask) {
  28639. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  28640. }
  28641. function registerVisual(priority, visualTask) {
  28642. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  28643. }
  28644. var registeredTasks = [];
  28645. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  28646. if (isFunction(priority) || isObject(priority)) {
  28647. fn = priority;
  28648. priority = defaultPriority;
  28649. }
  28650. if ("development" !== 'production') {
  28651. if (isNaN(priority) || priority == null) {
  28652. throw new Error('Illegal priority');
  28653. } // Check duplicate
  28654. each(targetList, function (wrap) {
  28655. assert(wrap.__raw !== fn);
  28656. });
  28657. } // Already registered
  28658. if (indexOf(registeredTasks, fn) >= 0) {
  28659. return;
  28660. }
  28661. registeredTasks.push(fn);
  28662. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  28663. stageHandler.__prio = priority;
  28664. stageHandler.__raw = fn;
  28665. targetList.push(stageHandler);
  28666. }
  28667. function registerLoading(name, loadingFx) {
  28668. loadingEffects[name] = loadingFx;
  28669. }
  28670. /**
  28671. * ZRender need a canvas context to do measureText.
  28672. * But in node environment canvas may be created by node-canvas.
  28673. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  28674. *
  28675. * Be careful of using it in the browser.
  28676. *
  28677. * @example
  28678. * let Canvas = require('canvas');
  28679. * let echarts = require('echarts');
  28680. * echarts.setCanvasCreator(function () {
  28681. * // Small size is enough.
  28682. * return new Canvas(32, 32);
  28683. * });
  28684. */
  28685. function setCanvasCreator(creator) {
  28686. $override('createCanvas', creator);
  28687. }
  28688. /**
  28689. * The parameters and usage: see `geoSourceManager.registerMap`.
  28690. * Compatible with previous `echarts.registerMap`.
  28691. */
  28692. function registerMap(mapName, geoJson, specialAreas) {
  28693. geoSourceManager.registerMap(mapName, geoJson, specialAreas);
  28694. }
  28695. function getMap(mapName) {
  28696. return geoSourceManager.getMapForUser(mapName);
  28697. }
  28698. var registerTransform = registerExternalTransform;
  28699. /**
  28700. * Globa dispatchAction to a specified chart instance.
  28701. */
  28702. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  28703. // if (!payload || !payload.chartId) {
  28704. // // Must have chartId to find chart
  28705. // return;
  28706. // }
  28707. // const chart = instances[payload.chartId];
  28708. // if (chart) {
  28709. // chart.dispatchAction(payload, opt);
  28710. // }
  28711. // }
  28712. // Buitlin global visual
  28713. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  28714. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  28715. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  28716. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  28717. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  28718. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  28719. registerPreprocessor(globalBackwardCompat);
  28720. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  28721. registerLoading('default', defaultLoading); // Default actions
  28722. registerAction({
  28723. type: HIGHLIGHT_ACTION_TYPE,
  28724. event: HIGHLIGHT_ACTION_TYPE,
  28725. update: HIGHLIGHT_ACTION_TYPE
  28726. }, noop);
  28727. registerAction({
  28728. type: DOWNPLAY_ACTION_TYPE,
  28729. event: DOWNPLAY_ACTION_TYPE,
  28730. update: DOWNPLAY_ACTION_TYPE
  28731. }, noop);
  28732. registerAction({
  28733. type: SELECT_ACTION_TYPE,
  28734. event: SELECT_ACTION_TYPE,
  28735. update: SELECT_ACTION_TYPE
  28736. }, noop);
  28737. registerAction({
  28738. type: UNSELECT_ACTION_TYPE,
  28739. event: UNSELECT_ACTION_TYPE,
  28740. update: UNSELECT_ACTION_TYPE
  28741. }, noop);
  28742. registerAction({
  28743. type: TOGGLE_SELECT_ACTION_TYPE,
  28744. event: TOGGLE_SELECT_ACTION_TYPE,
  28745. update: TOGGLE_SELECT_ACTION_TYPE
  28746. }, noop); // Default theme
  28747. registerTheme('light', lightTheme);
  28748. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  28749. // be mounted on `echarts` is the extension `dataTool` is imported.
  28750. var dataTool = {};
  28751. var extensions = [];
  28752. var extensionRegisters = {
  28753. registerPreprocessor: registerPreprocessor,
  28754. registerProcessor: registerProcessor,
  28755. registerPostInit: registerPostInit,
  28756. registerPostUpdate: registerPostUpdate,
  28757. registerUpdateLifecycle: registerUpdateLifecycle,
  28758. registerAction: registerAction,
  28759. registerCoordinateSystem: registerCoordinateSystem,
  28760. registerLayout: registerLayout,
  28761. registerVisual: registerVisual,
  28762. registerTransform: registerTransform,
  28763. registerLoading: registerLoading,
  28764. registerMap: registerMap,
  28765. PRIORITY: PRIORITY,
  28766. ComponentModel: ComponentModel,
  28767. ComponentView: ComponentView,
  28768. SeriesModel: SeriesModel,
  28769. ChartView: ChartView,
  28770. // TODO Use ComponentModel and SeriesModel instead of Constructor
  28771. registerComponentModel: function (ComponentModelClass) {
  28772. ComponentModel.registerClass(ComponentModelClass);
  28773. },
  28774. registerComponentView: function (ComponentViewClass) {
  28775. ComponentView.registerClass(ComponentViewClass);
  28776. },
  28777. registerSeriesModel: function (SeriesModelClass) {
  28778. SeriesModel.registerClass(SeriesModelClass);
  28779. },
  28780. registerChartView: function (ChartViewClass) {
  28781. ChartView.registerClass(ChartViewClass);
  28782. },
  28783. registerSubTypeDefaulter: function (componentType, defaulter) {
  28784. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  28785. },
  28786. registerPainter: function (painterType, PainterCtor) {
  28787. registerPainter(painterType, PainterCtor);
  28788. }
  28789. };
  28790. function use(ext) {
  28791. if (isArray(ext)) {
  28792. // use([ChartLine, ChartBar]);
  28793. each(ext, function (singleExt) {
  28794. use(singleExt);
  28795. });
  28796. return;
  28797. }
  28798. if (indexOf(extensions, ext) >= 0) {
  28799. return;
  28800. }
  28801. extensions.push(ext);
  28802. if (isFunction(ext)) {
  28803. ext = {
  28804. install: ext
  28805. };
  28806. }
  28807. ext.install(extensionRegisters);
  28808. }
  28809. /*
  28810. * Licensed to the Apache Software Foundation (ASF) under one
  28811. * or more contributor license agreements. See the NOTICE file
  28812. * distributed with this work for additional information
  28813. * regarding copyright ownership. The ASF licenses this file
  28814. * to you under the Apache License, Version 2.0 (the
  28815. * "License"); you may not use this file except in compliance
  28816. * with the License. You may obtain a copy of the License at
  28817. *
  28818. * http://www.apache.org/licenses/LICENSE-2.0
  28819. *
  28820. * Unless required by applicable law or agreed to in writing,
  28821. * software distributed under the License is distributed on an
  28822. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28823. * KIND, either express or implied. See the License for the
  28824. * specific language governing permissions and limitations
  28825. * under the License.
  28826. */
  28827. /**
  28828. * AUTO-GENERATED FILE. DO NOT MODIFY.
  28829. */
  28830. /*
  28831. * Licensed to the Apache Software Foundation (ASF) under one
  28832. * or more contributor license agreements. See the NOTICE file
  28833. * distributed with this work for additional information
  28834. * regarding copyright ownership. The ASF licenses this file
  28835. * to you under the Apache License, Version 2.0 (the
  28836. * "License"); you may not use this file except in compliance
  28837. * with the License. You may obtain a copy of the License at
  28838. *
  28839. * http://www.apache.org/licenses/LICENSE-2.0
  28840. *
  28841. * Unless required by applicable law or agreed to in writing,
  28842. * software distributed under the License is distributed on an
  28843. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28844. * KIND, either express or implied. See the License for the
  28845. * specific language governing permissions and limitations
  28846. * under the License.
  28847. */
  28848. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  28849. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  28850. }
  28851. function defaultKeyGetter(item) {
  28852. return item;
  28853. }
  28854. var DataDiffer =
  28855. /** @class */
  28856. function () {
  28857. /**
  28858. * @param context Can be visited by this.context in callback.
  28859. */
  28860. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  28861. diffMode) {
  28862. this._old = oldArr;
  28863. this._new = newArr;
  28864. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  28865. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  28866. this.context = context;
  28867. this._diffModeMultiple = diffMode === 'multiple';
  28868. }
  28869. /**
  28870. * Callback function when add a data
  28871. */
  28872. DataDiffer.prototype.add = function (func) {
  28873. this._add = func;
  28874. return this;
  28875. };
  28876. /**
  28877. * Callback function when update a data
  28878. */
  28879. DataDiffer.prototype.update = function (func) {
  28880. this._update = func;
  28881. return this;
  28882. };
  28883. /**
  28884. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  28885. */
  28886. DataDiffer.prototype.updateManyToOne = function (func) {
  28887. this._updateManyToOne = func;
  28888. return this;
  28889. };
  28890. /**
  28891. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  28892. */
  28893. DataDiffer.prototype.updateOneToMany = function (func) {
  28894. this._updateOneToMany = func;
  28895. return this;
  28896. };
  28897. /**
  28898. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  28899. */
  28900. DataDiffer.prototype.updateManyToMany = function (func) {
  28901. this._updateManyToMany = func;
  28902. return this;
  28903. };
  28904. /**
  28905. * Callback function when remove a data
  28906. */
  28907. DataDiffer.prototype.remove = function (func) {
  28908. this._remove = func;
  28909. return this;
  28910. };
  28911. DataDiffer.prototype.execute = function () {
  28912. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  28913. };
  28914. DataDiffer.prototype._executeOneToOne = function () {
  28915. var oldArr = this._old;
  28916. var newArr = this._new;
  28917. var newDataIndexMap = {};
  28918. var oldDataKeyArr = new Array(oldArr.length);
  28919. var newDataKeyArr = new Array(newArr.length);
  28920. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  28921. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  28922. for (var i = 0; i < oldArr.length; i++) {
  28923. var oldKey = oldDataKeyArr[i];
  28924. var newIdxMapVal = newDataIndexMap[oldKey];
  28925. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  28926. if (newIdxMapValLen > 1) {
  28927. // Consider there is duplicate key (for example, use dataItem.name as key).
  28928. // We should make sure every item in newArr and oldArr can be visited.
  28929. var newIdx = newIdxMapVal.shift();
  28930. if (newIdxMapVal.length === 1) {
  28931. newDataIndexMap[oldKey] = newIdxMapVal[0];
  28932. }
  28933. this._update && this._update(newIdx, i);
  28934. } else if (newIdxMapValLen === 1) {
  28935. newDataIndexMap[oldKey] = null;
  28936. this._update && this._update(newIdxMapVal, i);
  28937. } else {
  28938. this._remove && this._remove(i);
  28939. }
  28940. }
  28941. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  28942. };
  28943. /**
  28944. * For example, consider the case:
  28945. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  28946. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  28947. * Where:
  28948. * o0, o1, n0 has key 'a' (many to one)
  28949. * o5, n4, n5, n6 has key 'b' (one to many)
  28950. * o2, n1 has key 'c' (one to one)
  28951. * n2, n3 has key 'd' (add)
  28952. * o3, o4 has key 'e' (remove)
  28953. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  28954. * Then:
  28955. * (The order of the following directives are not ensured.)
  28956. * this._updateManyToOne(n0, [o0, o1]);
  28957. * this._updateOneToMany([n4, n5, n6], o5);
  28958. * this._update(n1, o2);
  28959. * this._remove(o3);
  28960. * this._remove(o4);
  28961. * this._remove(o6);
  28962. * this._remove(o7);
  28963. * this._add(n2);
  28964. * this._add(n3);
  28965. * this._add(n7);
  28966. * this._add(n8);
  28967. */
  28968. DataDiffer.prototype._executeMultiple = function () {
  28969. var oldArr = this._old;
  28970. var newArr = this._new;
  28971. var oldDataIndexMap = {};
  28972. var newDataIndexMap = {};
  28973. var oldDataKeyArr = [];
  28974. var newDataKeyArr = [];
  28975. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  28976. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  28977. for (var i = 0; i < oldDataKeyArr.length; i++) {
  28978. var oldKey = oldDataKeyArr[i];
  28979. var oldIdxMapVal = oldDataIndexMap[oldKey];
  28980. var newIdxMapVal = newDataIndexMap[oldKey];
  28981. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  28982. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  28983. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  28984. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  28985. newDataIndexMap[oldKey] = null;
  28986. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  28987. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  28988. newDataIndexMap[oldKey] = null;
  28989. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  28990. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  28991. newDataIndexMap[oldKey] = null;
  28992. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  28993. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  28994. newDataIndexMap[oldKey] = null;
  28995. } else if (oldIdxMapValLen > 1) {
  28996. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  28997. this._remove && this._remove(oldIdxMapVal[i_1]);
  28998. }
  28999. } else {
  29000. this._remove && this._remove(oldIdxMapVal);
  29001. }
  29002. }
  29003. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  29004. };
  29005. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  29006. for (var i = 0; i < newDataKeyArr.length; i++) {
  29007. var newKey = newDataKeyArr[i];
  29008. var newIdxMapVal = newDataIndexMap[newKey];
  29009. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  29010. if (idxMapValLen > 1) {
  29011. for (var j = 0; j < idxMapValLen; j++) {
  29012. this._add && this._add(newIdxMapVal[j]);
  29013. }
  29014. } else if (idxMapValLen === 1) {
  29015. this._add && this._add(newIdxMapVal);
  29016. } // Support both `newDataKeyArr` are duplication removed or not removed.
  29017. newDataIndexMap[newKey] = null;
  29018. }
  29019. };
  29020. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  29021. map, // In 'byKey', the output `keyArr` is duplication removed.
  29022. // In 'byIndex', the output `keyArr` is not duplication removed and
  29023. // its indices are accurately corresponding to `arr`.
  29024. keyArr, keyGetterName) {
  29025. var cbModeMultiple = this._diffModeMultiple;
  29026. for (var i = 0; i < arr.length; i++) {
  29027. // Add prefix to avoid conflict with Object.prototype.
  29028. var key = '_ec_' + this[keyGetterName](arr[i], i);
  29029. if (!cbModeMultiple) {
  29030. keyArr[i] = key;
  29031. }
  29032. if (!map) {
  29033. continue;
  29034. }
  29035. var idxMapVal = map[key];
  29036. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  29037. if (idxMapValLen === 0) {
  29038. // Simple optimize: in most cases, one index has one key,
  29039. // do not need array.
  29040. map[key] = i;
  29041. if (cbModeMultiple) {
  29042. keyArr.push(key);
  29043. }
  29044. } else if (idxMapValLen === 1) {
  29045. map[key] = [idxMapVal, i];
  29046. } else {
  29047. idxMapVal.push(i);
  29048. }
  29049. }
  29050. };
  29051. return DataDiffer;
  29052. }();
  29053. var DimensionUserOuput =
  29054. /** @class */
  29055. function () {
  29056. function DimensionUserOuput(encode, dimRequest) {
  29057. this._encode = encode;
  29058. this._schema = dimRequest;
  29059. }
  29060. DimensionUserOuput.prototype.get = function () {
  29061. return {
  29062. // Do not generate full dimension name until fist used.
  29063. fullDimensions: this._getFullDimensionNames(),
  29064. encode: this._encode
  29065. };
  29066. };
  29067. /**
  29068. * Get all data store dimension names.
  29069. * Theoretically a series data store is defined both by series and used dataset (if any).
  29070. * If some dimensions are omitted for performance reason in `this.dimensions`,
  29071. * the dimension name may not be auto-generated if user does not specify a dimension name.
  29072. * In this case, the dimension name is `null`/`undefined`.
  29073. */
  29074. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  29075. if (!this._cachedDimNames) {
  29076. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  29077. }
  29078. return this._cachedDimNames;
  29079. };
  29080. return DimensionUserOuput;
  29081. }();
  29082. function summarizeDimensions(data, schema) {
  29083. var summary = {};
  29084. var encode = summary.encode = {};
  29085. var notExtraCoordDimMap = createHashMap();
  29086. var defaultedLabel = [];
  29087. var defaultedTooltip = [];
  29088. var userOutputEncode = {};
  29089. each(data.dimensions, function (dimName) {
  29090. var dimItem = data.getDimensionInfo(dimName);
  29091. var coordDim = dimItem.coordDim;
  29092. if (coordDim) {
  29093. if ("development" !== 'production') {
  29094. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  29095. }
  29096. var coordDimIndex = dimItem.coordDimIndex;
  29097. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  29098. if (!dimItem.isExtraCoord) {
  29099. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  29100. // because when dataset is used, it is hard to guess which dimension
  29101. // can be value dimension. If both show x, y on label is not look good,
  29102. // and conventionally y axis is focused more.
  29103. if (mayLabelDimType(dimItem.type)) {
  29104. defaultedLabel[0] = dimName;
  29105. } // User output encode do not contain generated coords.
  29106. // And it only has index. User can use index to retrieve value from the raw item array.
  29107. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  29108. }
  29109. if (dimItem.defaultTooltip) {
  29110. defaultedTooltip.push(dimName);
  29111. }
  29112. }
  29113. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  29114. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  29115. var dimIndex = dimItem.otherDims[otherDim];
  29116. if (dimIndex != null && dimIndex !== false) {
  29117. encodeArr[dimIndex] = dimItem.name;
  29118. }
  29119. });
  29120. });
  29121. var dataDimsOnCoord = [];
  29122. var encodeFirstDimNotExtra = {};
  29123. notExtraCoordDimMap.each(function (v, coordDim) {
  29124. var dimArr = encode[coordDim];
  29125. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  29126. // dim canot on more than one coordDim.
  29127. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  29128. });
  29129. summary.dataDimsOnCoord = dataDimsOnCoord;
  29130. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  29131. return data.getDimensionInfo(dimName).storeDimIndex;
  29132. });
  29133. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  29134. var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set
  29135. // in this way. Use label.formatter instead. May be remove this approach someday.
  29136. if (encodeLabel && encodeLabel.length) {
  29137. defaultedLabel = encodeLabel.slice();
  29138. }
  29139. var encodeTooltip = encode.tooltip;
  29140. if (encodeTooltip && encodeTooltip.length) {
  29141. defaultedTooltip = encodeTooltip.slice();
  29142. } else if (!defaultedTooltip.length) {
  29143. defaultedTooltip = defaultedLabel.slice();
  29144. }
  29145. encode.defaultedLabel = defaultedLabel;
  29146. encode.defaultedTooltip = defaultedTooltip;
  29147. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  29148. return summary;
  29149. }
  29150. function getOrCreateEncodeArr(encode, dim) {
  29151. if (!encode.hasOwnProperty(dim)) {
  29152. encode[dim] = [];
  29153. }
  29154. return encode[dim];
  29155. } // FIXME:TS should be type `AxisType`
  29156. function getDimensionTypeByAxis(axisType) {
  29157. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  29158. }
  29159. function mayLabelDimType(dimType) {
  29160. // In most cases, ordinal and time do not suitable for label.
  29161. // Ordinal info can be displayed on axis. Time is too long.
  29162. return !(dimType === 'ordinal' || dimType === 'time');
  29163. } // function findTheLastDimMayLabel(data) {
  29164. // // Get last value dim
  29165. // let dimensions = data.dimensions.slice();
  29166. // let valueType;
  29167. // let valueDim;
  29168. // while (dimensions.length && (
  29169. // valueDim = dimensions.pop(),
  29170. // valueType = data.getDimensionInfo(valueDim).type,
  29171. // valueType === 'ordinal' || valueType === 'time'
  29172. // )) {} // jshint ignore:line
  29173. // return valueDim;
  29174. // }
  29175. var SeriesDimensionDefine =
  29176. /** @class */
  29177. function () {
  29178. /**
  29179. * @param opt All of the fields will be shallow copied.
  29180. */
  29181. function SeriesDimensionDefine(opt) {
  29182. /**
  29183. * The format of `otherDims` is:
  29184. * ```js
  29185. * {
  29186. * tooltip?: number
  29187. * label?: number
  29188. * itemName?: number
  29189. * seriesName?: number
  29190. * }
  29191. * ```
  29192. *
  29193. * A `series.encode` can specified these fields:
  29194. * ```js
  29195. * encode: {
  29196. * // "3, 1, 5" is the index of data dimension.
  29197. * tooltip: [3, 1, 5],
  29198. * label: [0, 3],
  29199. * ...
  29200. * }
  29201. * ```
  29202. * `otherDims` is the parse result of the `series.encode` above, like:
  29203. * ```js
  29204. * // Suppose the index of this data dimension is `3`.
  29205. * this.otherDims = {
  29206. * // `3` is at the index `0` of the `encode.tooltip`
  29207. * tooltip: 0,
  29208. * // `3` is at the index `1` of the `encode.label`
  29209. * label: 1
  29210. * };
  29211. * ```
  29212. *
  29213. * This prop should never be `null`/`undefined` after initialized.
  29214. */
  29215. this.otherDims = {};
  29216. if (opt != null) {
  29217. extend(this, opt);
  29218. }
  29219. }
  29220. return SeriesDimensionDefine;
  29221. }();
  29222. var inner$4 = makeInner();
  29223. var dimTypeShort = {
  29224. float: 'f',
  29225. int: 'i',
  29226. ordinal: 'o',
  29227. number: 'n',
  29228. time: 't'
  29229. };
  29230. /**
  29231. * Represents the dimension requirement of a series.
  29232. *
  29233. * NOTICE:
  29234. * When there are too many dimensions in dataset and many series, only the used dimensions
  29235. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  29236. * But users may query data by other unused dimension names.
  29237. * In this case, users can only query data if and only if they have defined dimension names
  29238. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  29239. * `source` dimensions.
  29240. */
  29241. var SeriesDataSchema =
  29242. /** @class */
  29243. function () {
  29244. function SeriesDataSchema(opt) {
  29245. this.dimensions = opt.dimensions;
  29246. this._dimOmitted = opt.dimensionOmitted;
  29247. this.source = opt.source;
  29248. this._fullDimCount = opt.fullDimensionCount;
  29249. this._updateDimOmitted(opt.dimensionOmitted);
  29250. }
  29251. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  29252. return this._dimOmitted;
  29253. };
  29254. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  29255. this._dimOmitted = dimensionOmitted;
  29256. if (!dimensionOmitted) {
  29257. return;
  29258. }
  29259. if (!this._dimNameMap) {
  29260. this._dimNameMap = ensureSourceDimNameMap(this.source);
  29261. }
  29262. };
  29263. /**
  29264. * @caution Can only be used when `dimensionOmitted: true`.
  29265. *
  29266. * Get index by user defined dimension name (i.e., not internal generate name).
  29267. * That is, get index from `dimensionsDefine`.
  29268. * If no `dimensionsDefine`, or no name get, return -1.
  29269. */
  29270. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  29271. return retrieve2(this._dimNameMap.get(dimName), -1);
  29272. };
  29273. /**
  29274. * @caution Can only be used when `dimensionOmitted: true`.
  29275. *
  29276. * Notice: may return `null`/`undefined` if user not specify dimension names.
  29277. */
  29278. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  29279. var dimensionsDefine = this.source.dimensionsDefine;
  29280. if (dimensionsDefine) {
  29281. return dimensionsDefine[dimIndex];
  29282. }
  29283. };
  29284. SeriesDataSchema.prototype.makeStoreSchema = function () {
  29285. var dimCount = this._fullDimCount;
  29286. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  29287. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount); // If source don't have dimensions or series don't omit unsed dimensions.
  29288. // Generate from seriesDimList directly
  29289. var dimHash = '';
  29290. var dims = [];
  29291. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  29292. var property = void 0;
  29293. var type = void 0;
  29294. var ordinalMeta = void 0;
  29295. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  29296. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  29297. property = willRetrieveDataByName ? seriesDimDef.name : null;
  29298. type = seriesDimDef.type;
  29299. ordinalMeta = seriesDimDef.ordinalMeta;
  29300. seriesDimIdx++;
  29301. } else {
  29302. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  29303. if (sourceDimDef) {
  29304. property = willRetrieveDataByName ? sourceDimDef.name : null;
  29305. type = sourceDimDef.type;
  29306. }
  29307. }
  29308. dims.push({
  29309. property: property,
  29310. type: type,
  29311. ordinalMeta: ordinalMeta
  29312. }); // If retrieving data by index,
  29313. // use <index, type, ordinalMeta> to determine whether data can be shared.
  29314. // (Becuase in this case there might be no dimension name defined in dataset, but indices always exists).
  29315. // (indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  29316. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  29317. // use <property, type, ordinalMeta> in hash.
  29318. if (willRetrieveDataByName && property != null // For data stack, we have make sure each series has its own dim on this store.
  29319. // So we do not add property to hash to make sure they can share this store.
  29320. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  29321. dimHash += makeHashStrict // Use escape character '`' in case that property name contains '$'.
  29322. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2') // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  29323. : property;
  29324. }
  29325. dimHash += '$';
  29326. dimHash += dimTypeShort[type] || 'f';
  29327. if (ordinalMeta) {
  29328. dimHash += ordinalMeta.uid;
  29329. }
  29330. dimHash += '$';
  29331. } // Source from endpoint(usually series) will be read differently
  29332. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  29333. // So we use this three props as key.
  29334. var source = this.source;
  29335. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  29336. return {
  29337. dimensions: dims,
  29338. hash: hash
  29339. };
  29340. };
  29341. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  29342. var result = [];
  29343. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  29344. var name_1 = void 0;
  29345. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  29346. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  29347. if (!seriesDimDef.isCalculationCoord) {
  29348. name_1 = seriesDimDef.name;
  29349. }
  29350. seriesDimIdx++;
  29351. } else {
  29352. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  29353. if (sourceDimDef) {
  29354. name_1 = sourceDimDef.name;
  29355. }
  29356. }
  29357. result.push(name_1);
  29358. }
  29359. return result;
  29360. };
  29361. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  29362. this.dimensions.push(dimDef);
  29363. dimDef.isCalculationCoord = true;
  29364. this._fullDimCount++; // If append dimension on a data store, consider the store
  29365. // might be shared by different series, series dimensions not
  29366. // really map to store dimensions.
  29367. this._updateDimOmitted(true);
  29368. };
  29369. return SeriesDataSchema;
  29370. }();
  29371. function isSeriesDataSchema(schema) {
  29372. return schema instanceof SeriesDataSchema;
  29373. }
  29374. function createDimNameMap(dimsDef) {
  29375. var dataDimNameMap = createHashMap();
  29376. for (var i = 0; i < (dimsDef || []).length; i++) {
  29377. var dimDefItemRaw = dimsDef[i];
  29378. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  29379. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  29380. dataDimNameMap.set(userDimName, i);
  29381. }
  29382. }
  29383. return dataDimNameMap;
  29384. }
  29385. function ensureSourceDimNameMap(source) {
  29386. var innerSource = inner$4(source);
  29387. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  29388. }
  29389. function shouldOmitUnusedDimensions(dimCount) {
  29390. return dimCount > 30;
  29391. }
  29392. var isObject$2 = isObject;
  29393. var map$1 = map;
  29394. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array; // Use prefix to avoid index to be the same as otherIdList[idx],
  29395. // which will cause weird udpate animation.
  29396. var ID_PREFIX = 'e\0\0';
  29397. var INDEX_NOT_FOUND = -1; // type SeriesDimensionIndex = DimensionIndex;
  29398. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  29399. var CLONE_PROPERTIES = ['_approximateExtent']; // -----------------------------
  29400. // Internal method declarations:
  29401. // -----------------------------
  29402. var prepareInvertedIndex;
  29403. var getId;
  29404. var getIdNameFromStore;
  29405. var normalizeDimensions;
  29406. var transferProperties;
  29407. var cloneListForMapAndSample;
  29408. var makeIdFromName;
  29409. var SeriesData =
  29410. /** @class */
  29411. function () {
  29412. /**
  29413. * @param dimensionsInput.dimensions
  29414. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  29415. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  29416. */
  29417. function SeriesData(dimensionsInput, hostModel) {
  29418. this.type = 'list';
  29419. this._dimOmitted = false;
  29420. this._nameList = [];
  29421. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  29422. // Never used yet (not used yet).
  29423. // private _optionModels: Model[] = [];
  29424. // Global visual properties after visual coding
  29425. this._visual = {}; // Globel layout properties.
  29426. this._layout = {}; // Item visual properties after visual coding
  29427. this._itemVisuals = []; // Item layout properties after layout
  29428. this._itemLayouts = []; // Graphic elemnents
  29429. this._graphicEls = []; // key: dim, value: extent
  29430. this._approximateExtent = {};
  29431. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  29432. // (in type `OptionDataItemObject`).
  29433. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  29434. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  29435. this.hasItemOption = false; // Methods that create a new list based on this list should be listed here.
  29436. // Notice that those method should `RETURN` the new list.
  29437. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  29438. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  29439. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  29440. var dimensions;
  29441. var assignStoreDimIdx = false;
  29442. if (isSeriesDataSchema(dimensionsInput)) {
  29443. dimensions = dimensionsInput.dimensions;
  29444. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  29445. this._schema = dimensionsInput;
  29446. } else {
  29447. assignStoreDimIdx = true;
  29448. dimensions = dimensionsInput;
  29449. }
  29450. dimensions = dimensions || ['x', 'y'];
  29451. var dimensionInfos = {};
  29452. var dimensionNames = [];
  29453. var invertedIndicesMap = {};
  29454. var needsHasOwn = false;
  29455. var emptyObj = {};
  29456. for (var i = 0; i < dimensions.length; i++) {
  29457. // Use the original dimensions[i], where other flag props may exists.
  29458. var dimInfoInput = dimensions[i];
  29459. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  29460. name: dimInfoInput
  29461. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  29462. var dimensionName = dimensionInfo.name;
  29463. dimensionInfo.type = dimensionInfo.type || 'float';
  29464. if (!dimensionInfo.coordDim) {
  29465. dimensionInfo.coordDim = dimensionName;
  29466. dimensionInfo.coordDimIndex = 0;
  29467. }
  29468. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  29469. dimensionNames.push(dimensionName);
  29470. dimensionInfos[dimensionName] = dimensionInfo;
  29471. if (emptyObj[dimensionName] != null) {
  29472. needsHasOwn = true;
  29473. }
  29474. if (dimensionInfo.createInvertedIndices) {
  29475. invertedIndicesMap[dimensionName] = [];
  29476. }
  29477. if (otherDims.itemName === 0) {
  29478. this._nameDimIdx = i;
  29479. }
  29480. if (otherDims.itemId === 0) {
  29481. this._idDimIdx = i;
  29482. }
  29483. if ("development" !== 'production') {
  29484. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  29485. }
  29486. if (assignStoreDimIdx) {
  29487. dimensionInfo.storeDimIndex = i;
  29488. }
  29489. }
  29490. this.dimensions = dimensionNames;
  29491. this._dimInfos = dimensionInfos;
  29492. this._initGetDimensionInfo(needsHasOwn);
  29493. this.hostModel = hostModel;
  29494. this._invertedIndicesMap = invertedIndicesMap;
  29495. if (this._dimOmitted) {
  29496. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  29497. each(dimensionNames, function (dimName) {
  29498. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  29499. });
  29500. }
  29501. }
  29502. /**
  29503. *
  29504. * Get concrete dimension name by dimension name or dimension index.
  29505. * If input a dimension name, do not validate whether the dimension name exits.
  29506. *
  29507. * @caution
  29508. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  29509. * Because only those dimensions will have auto-generated dimension names if not
  29510. * have a user-specified name, and other dimensions will get a return of null/undefined.
  29511. *
  29512. * @notice Becuause of this reason, should better use `getDimensionIndex` instead, for examples:
  29513. * ```js
  29514. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  29515. * ```
  29516. *
  29517. * @return Concrete dim name.
  29518. */
  29519. SeriesData.prototype.getDimension = function (dim) {
  29520. var dimIdx = this._recognizeDimIndex(dim);
  29521. if (dimIdx == null) {
  29522. return dim;
  29523. }
  29524. dimIdx = dim;
  29525. if (!this._dimOmitted) {
  29526. return this.dimensions[dimIdx];
  29527. } // Retrieve from series dimension definition becuase it probably contains
  29528. // generated dimension name (like 'x', 'y').
  29529. var dimName = this._dimIdxToName.get(dimIdx);
  29530. if (dimName != null) {
  29531. return dimName;
  29532. }
  29533. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  29534. if (sourceDimDef) {
  29535. return sourceDimDef.name;
  29536. }
  29537. };
  29538. /**
  29539. * Get dimension index in data store. Return -1 if not found.
  29540. * Can be used to index value from getRawValue.
  29541. */
  29542. SeriesData.prototype.getDimensionIndex = function (dim) {
  29543. var dimIdx = this._recognizeDimIndex(dim);
  29544. if (dimIdx != null) {
  29545. return dimIdx;
  29546. }
  29547. if (dim == null) {
  29548. return -1;
  29549. }
  29550. var dimInfo = this._getDimInfo(dim);
  29551. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  29552. };
  29553. /**
  29554. * The meanings of the input parameter `dim`:
  29555. *
  29556. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  29557. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  29558. * + If dim is a number-like string (e.g., `"1"`):
  29559. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  29560. * it means that concrete name.
  29561. * + If not, it will be converted to a number, which means the index of the dimension.
  29562. * (why? because of the backward compatbility. We have been tolerating number-like string in
  29563. * dimension setting, although now it seems that it is not a good idea.)
  29564. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  29565. * if no dimension name is defined as `"1"`.
  29566. * + If dim is a not-number-like string, it means the concrete dim name.
  29567. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  29568. * or customized in `dimensions` property of option like `"age"`.
  29569. *
  29570. * @return recogonized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  29571. */
  29572. SeriesData.prototype._recognizeDimIndex = function (dim) {
  29573. if (typeof dim === 'number' // If being a number-like string but not being defined as a dimension name.
  29574. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  29575. return +dim;
  29576. }
  29577. };
  29578. SeriesData.prototype._getStoreDimIndex = function (dim) {
  29579. var dimIdx = this.getDimensionIndex(dim);
  29580. if ("development" !== 'production') {
  29581. if (dimIdx == null) {
  29582. throw new Error('Unkown dimension ' + dim);
  29583. }
  29584. }
  29585. return dimIdx;
  29586. };
  29587. /**
  29588. * Get type and calculation info of particular dimension
  29589. * @param dim
  29590. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  29591. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  29592. */
  29593. SeriesData.prototype.getDimensionInfo = function (dim) {
  29594. // Do not clone, because there may be categories in dimInfo.
  29595. return this._getDimInfo(this.getDimension(dim));
  29596. };
  29597. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  29598. var dimensionInfos = this._dimInfos;
  29599. this._getDimInfo = needsHasOwn ? function (dimName) {
  29600. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  29601. } : function (dimName) {
  29602. return dimensionInfos[dimName];
  29603. };
  29604. };
  29605. /**
  29606. * concrete dimension name list on coord.
  29607. */
  29608. SeriesData.prototype.getDimensionsOnCoord = function () {
  29609. return this._dimSummary.dataDimsOnCoord.slice();
  29610. };
  29611. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  29612. var dimensionsSummary = this._dimSummary;
  29613. if (idx == null) {
  29614. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  29615. }
  29616. var dims = dimensionsSummary.encode[coordDim];
  29617. return dims ? dims[idx] : null;
  29618. };
  29619. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  29620. var dimensionsSummary = this._dimSummary;
  29621. var dims = dimensionsSummary.encode[coordDim];
  29622. return (dims || []).slice();
  29623. };
  29624. SeriesData.prototype.getStore = function () {
  29625. return this._store;
  29626. };
  29627. /**
  29628. * Initialize from data
  29629. * @param data source or data or data store.
  29630. * @param nameList The name of a datum is used on data diff and
  29631. * default label/tooltip.
  29632. * A name can be specified in encode.itemName,
  29633. * or dataItem.name (only for series option data),
  29634. * or provided in nameList from outside.
  29635. */
  29636. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  29637. var _this = this;
  29638. var store;
  29639. if (data instanceof DataStore) {
  29640. store = data;
  29641. }
  29642. if (!store) {
  29643. var dimensions = this.dimensions;
  29644. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  29645. store = new DataStore();
  29646. var dimensionInfos = map$1(dimensions, function (dimName) {
  29647. return {
  29648. type: _this._dimInfos[dimName].type,
  29649. property: dimName
  29650. };
  29651. });
  29652. store.initData(provider, dimensionInfos, dimValueGetter);
  29653. }
  29654. this._store = store; // Reset
  29655. this._nameList = (nameList || []).slice();
  29656. this._idList = [];
  29657. this._nameRepeatCount = {};
  29658. this._doInit(0, store.count()); // Cache summary info for fast visit. See "dimensionHelper".
  29659. // Needs to be initialized after store is prepared.
  29660. this._dimSummary = summarizeDimensions(this, this._schema);
  29661. this.userOutput = this._dimSummary.userOutput;
  29662. };
  29663. /**
  29664. * Caution: Can be only called on raw data (before `this._indices` created).
  29665. */
  29666. SeriesData.prototype.appendData = function (data) {
  29667. var range = this._store.appendData(data);
  29668. this._doInit(range[0], range[1]);
  29669. };
  29670. /**
  29671. * Caution: Can be only called on raw data (before `this._indices` created).
  29672. * This method does not modify `rawData` (`dataProvider`), but only
  29673. * add values to store.
  29674. *
  29675. * The final count will be increased by `Math.max(values.length, names.length)`.
  29676. *
  29677. * @param values That is the SourceType: 'arrayRows', like
  29678. * [
  29679. * [12, 33, 44],
  29680. * [NaN, 43, 1],
  29681. * ['-', 'asdf', 0]
  29682. * ]
  29683. * Each item is exaclty cooresponding to a dimension.
  29684. */
  29685. SeriesData.prototype.appendValues = function (values, names) {
  29686. var _a = this._store.appendValues(values, names.length),
  29687. start = _a.start,
  29688. end = _a.end;
  29689. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  29690. this._updateOrdinalMeta();
  29691. if (names) {
  29692. for (var idx = start; idx < end; idx++) {
  29693. var sourceIdx = idx - start;
  29694. this._nameList[idx] = names[sourceIdx];
  29695. if (shouldMakeIdFromName) {
  29696. makeIdFromName(this, idx);
  29697. }
  29698. }
  29699. }
  29700. };
  29701. SeriesData.prototype._updateOrdinalMeta = function () {
  29702. var store = this._store;
  29703. var dimensions = this.dimensions;
  29704. for (var i = 0; i < dimensions.length; i++) {
  29705. var dimInfo = this._dimInfos[dimensions[i]];
  29706. if (dimInfo.ordinalMeta) {
  29707. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  29708. }
  29709. }
  29710. };
  29711. SeriesData.prototype._shouldMakeIdFromName = function () {
  29712. var provider = this._store.getProvider();
  29713. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  29714. };
  29715. SeriesData.prototype._doInit = function (start, end) {
  29716. if (start >= end) {
  29717. return;
  29718. }
  29719. var store = this._store;
  29720. var provider = store.getProvider();
  29721. this._updateOrdinalMeta();
  29722. var nameList = this._nameList;
  29723. var idList = this._idList;
  29724. var sourceFormat = provider.getSource().sourceFormat;
  29725. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL; // Each data item is value
  29726. // [1, 2]
  29727. // 2
  29728. // Bar chart, line chart which uses category axis
  29729. // only gives the 'y' value. 'x' value is the indices of category
  29730. // Use a tempValue to normalize the value to be a (x, y) value
  29731. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  29732. // This kind of ids and names are always stored `_nameList` and `_idList`.
  29733. if (isFormatOriginal && !provider.pure) {
  29734. var sharedDataItem = [];
  29735. for (var idx = start; idx < end; idx++) {
  29736. // NOTICE: Try not to write things into dataItem
  29737. var dataItem = provider.getItem(idx, sharedDataItem);
  29738. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  29739. this.hasItemOption = true;
  29740. }
  29741. if (dataItem) {
  29742. var itemName = dataItem.name;
  29743. if (nameList[idx] == null && itemName != null) {
  29744. nameList[idx] = convertOptionIdName(itemName, null);
  29745. }
  29746. var itemId = dataItem.id;
  29747. if (idList[idx] == null && itemId != null) {
  29748. idList[idx] = convertOptionIdName(itemId, null);
  29749. }
  29750. }
  29751. }
  29752. }
  29753. if (this._shouldMakeIdFromName()) {
  29754. for (var idx = start; idx < end; idx++) {
  29755. makeIdFromName(this, idx);
  29756. }
  29757. }
  29758. prepareInvertedIndex(this);
  29759. };
  29760. /**
  29761. * PENDING: In fact currently this function is only used to short-circuit
  29762. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  29763. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  29764. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  29765. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  29766. * But if we add "custom data filter" in future, which is not "axis related", this method may
  29767. * be still needed.
  29768. *
  29769. * Optimize for the scenario that data is filtered by a given extent.
  29770. * Consider that if data amount is more than hundreds of thousand,
  29771. * extent calculation will cost more than 10ms and the cache will
  29772. * be erased because of the filtering.
  29773. */
  29774. SeriesData.prototype.getApproximateExtent = function (dim) {
  29775. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  29776. };
  29777. /**
  29778. * Calculate extent on a filtered data might be time consuming.
  29779. * Approximate extent is only used for: calculte extent of filtered data outside.
  29780. */
  29781. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  29782. dim = this.getDimension(dim);
  29783. this._approximateExtent[dim] = extent.slice();
  29784. };
  29785. SeriesData.prototype.getCalculationInfo = function (key) {
  29786. return this._calculationInfo[key];
  29787. };
  29788. SeriesData.prototype.setCalculationInfo = function (key, value) {
  29789. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  29790. };
  29791. /**
  29792. * @return Never be null/undefined. `number` will be converted to string. Becuase:
  29793. * In most cases, name is used in display, where returning a string is more convenient.
  29794. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  29795. * rule that name `2` equals to name `'2'`.
  29796. */
  29797. SeriesData.prototype.getName = function (idx) {
  29798. var rawIndex = this.getRawIndex(idx);
  29799. var name = this._nameList[rawIndex];
  29800. if (name == null && this._nameDimIdx != null) {
  29801. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  29802. }
  29803. if (name == null) {
  29804. name = '';
  29805. }
  29806. return name;
  29807. };
  29808. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  29809. var ordinal = this._store.get(dimIdx, idx);
  29810. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  29811. if (ordinalMeta) {
  29812. return ordinalMeta.categories[ordinal];
  29813. }
  29814. return ordinal;
  29815. };
  29816. /**
  29817. * @return Never null/undefined. `number` will be converted to string. Becuase:
  29818. * In all cases having encountered at present, id is used in making diff comparison, which
  29819. * are usually based on hash map. We can keep the rule that the internal id are always string
  29820. * (treat `2` is the same as `'2'`) to make the related logic simple.
  29821. */
  29822. SeriesData.prototype.getId = function (idx) {
  29823. return getId(this, this.getRawIndex(idx));
  29824. };
  29825. SeriesData.prototype.count = function () {
  29826. return this._store.count();
  29827. };
  29828. /**
  29829. * Get value. Return NaN if idx is out of range.
  29830. *
  29831. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  29832. */
  29833. SeriesData.prototype.get = function (dim, idx) {
  29834. var store = this._store;
  29835. var dimInfo = this._dimInfos[dim];
  29836. if (dimInfo) {
  29837. return store.get(dimInfo.storeDimIndex, idx);
  29838. }
  29839. };
  29840. /**
  29841. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  29842. */
  29843. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  29844. var store = this._store;
  29845. var dimInfo = this._dimInfos[dim];
  29846. if (dimInfo) {
  29847. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  29848. }
  29849. };
  29850. SeriesData.prototype.getIndices = function () {
  29851. return this._store.getIndices();
  29852. };
  29853. SeriesData.prototype.getDataExtent = function (dim) {
  29854. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  29855. };
  29856. SeriesData.prototype.getSum = function (dim) {
  29857. return this._store.getSum(this._getStoreDimIndex(dim));
  29858. };
  29859. SeriesData.prototype.getMedian = function (dim) {
  29860. return this._store.getMedian(this._getStoreDimIndex(dim));
  29861. };
  29862. SeriesData.prototype.getValues = function (dimensions, idx) {
  29863. var _this = this;
  29864. var store = this._store;
  29865. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  29866. return _this._getStoreDimIndex(dim);
  29867. }), idx) : store.getValues(dimensions);
  29868. };
  29869. /**
  29870. * If value is NaN. Inlcuding '-'
  29871. * Only check the coord dimensions.
  29872. */
  29873. SeriesData.prototype.hasValue = function (idx) {
  29874. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  29875. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  29876. // Ordinal type originally can be string or number.
  29877. // But when an ordinal type is used on coord, it can
  29878. // not be string but only number. So we can also use isNaN.
  29879. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  29880. return false;
  29881. }
  29882. }
  29883. return true;
  29884. };
  29885. /**
  29886. * Retreive the index with given name
  29887. */
  29888. SeriesData.prototype.indexOfName = function (name) {
  29889. for (var i = 0, len = this._store.count(); i < len; i++) {
  29890. if (this.getName(i) === name) {
  29891. return i;
  29892. }
  29893. }
  29894. return -1;
  29895. };
  29896. SeriesData.prototype.getRawIndex = function (idx) {
  29897. return this._store.getRawIndex(idx);
  29898. };
  29899. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  29900. return this._store.indexOfRawIndex(rawIndex);
  29901. };
  29902. /**
  29903. * Only support the dimension which inverted index created.
  29904. * Do not support other cases until required.
  29905. * @param dim concrete dim
  29906. * @param value ordinal index
  29907. * @return rawIndex
  29908. */
  29909. SeriesData.prototype.rawIndexOf = function (dim, value) {
  29910. var invertedIndices = dim && this._invertedIndicesMap[dim];
  29911. if ("development" !== 'production') {
  29912. if (!invertedIndices) {
  29913. throw new Error('Do not supported yet');
  29914. }
  29915. }
  29916. var rawIndex = invertedIndices[value];
  29917. if (rawIndex == null || isNaN(rawIndex)) {
  29918. return INDEX_NOT_FOUND;
  29919. }
  29920. return rawIndex;
  29921. };
  29922. /**
  29923. * Retreive the index of nearest value
  29924. * @param dim
  29925. * @param value
  29926. * @param [maxDistance=Infinity]
  29927. * @return If and only if multiple indices has
  29928. * the same value, they are put to the result.
  29929. */
  29930. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  29931. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  29932. };
  29933. SeriesData.prototype.each = function (dims, cb, ctx) {
  29934. if (typeof dims === 'function') {
  29935. ctx = cb;
  29936. cb = dims;
  29937. dims = [];
  29938. } // ctxCompat just for compat echarts3
  29939. var fCtx = ctx || this;
  29940. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29941. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29942. };
  29943. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  29944. if (typeof dims === 'function') {
  29945. ctx = cb;
  29946. cb = dims;
  29947. dims = [];
  29948. } // ctxCompat just for compat echarts3
  29949. var fCtx = ctx || this;
  29950. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29951. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29952. return this;
  29953. };
  29954. /**
  29955. * Select data in range. (For optimization of filter)
  29956. * (Manually inline code, support 5 million data filtering in data zoom.)
  29957. */
  29958. SeriesData.prototype.selectRange = function (range) {
  29959. var _this = this;
  29960. var innerRange = {};
  29961. var dims = keys(range);
  29962. each(dims, function (dim) {
  29963. var dimIdx = _this._getStoreDimIndex(dim);
  29964. innerRange[dimIdx] = range[dim];
  29965. });
  29966. this._store = this._store.selectRange(innerRange);
  29967. return this;
  29968. };
  29969. /* eslint-enable max-len */
  29970. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  29971. if (typeof dims === 'function') {
  29972. ctx = cb;
  29973. cb = dims;
  29974. dims = [];
  29975. } // ctxCompat just for compat echarts3
  29976. ctx = ctx || this;
  29977. var result = [];
  29978. this.each(dims, function () {
  29979. result.push(cb && cb.apply(this, arguments));
  29980. }, ctx);
  29981. return result;
  29982. };
  29983. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  29984. var fCtx = ctx || ctxCompat || this;
  29985. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  29986. var list = cloneListForMapAndSample(this);
  29987. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  29988. return list;
  29989. };
  29990. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  29991. var _this = this; // ctxCompat just for compat echarts3
  29992. var fCtx = ctx || ctxCompat || this;
  29993. if ("development" !== 'production') {
  29994. each(normalizeDimensions(dims), function (dim) {
  29995. var dimInfo = _this.getDimensionInfo(dim);
  29996. if (!dimInfo.isCalculationCoord) {
  29997. console.error('Danger: only stack dimension can be modified');
  29998. }
  29999. });
  30000. }
  30001. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this); // If do shallow clone here, if there are too many stacked series,
  30002. // it still cost lots of memory, becuase `_store.dimensions` are not shared.
  30003. // We should consider there probably be shallow clone happen in each sereis
  30004. // in consequent filter/map.
  30005. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  30006. };
  30007. /**
  30008. * Large data down sampling on given dimension
  30009. * @param sampleIndex Sample index for name and id
  30010. */
  30011. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  30012. var list = cloneListForMapAndSample(this);
  30013. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  30014. return list;
  30015. };
  30016. /**
  30017. * Large data down sampling using largest-triangle-three-buckets
  30018. * @param {string} valueDimension
  30019. * @param {number} targetCount
  30020. */
  30021. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  30022. var list = cloneListForMapAndSample(this);
  30023. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  30024. return list;
  30025. };
  30026. SeriesData.prototype.getRawDataItem = function (idx) {
  30027. return this._store.getRawDataItem(idx);
  30028. };
  30029. /**
  30030. * Get model of one data item.
  30031. */
  30032. // TODO: Type of data item
  30033. SeriesData.prototype.getItemModel = function (idx) {
  30034. var hostModel = this.hostModel;
  30035. var dataItem = this.getRawDataItem(idx);
  30036. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  30037. };
  30038. /**
  30039. * Create a data differ
  30040. */
  30041. SeriesData.prototype.diff = function (otherList) {
  30042. var thisList = this;
  30043. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  30044. return getId(otherList, idx);
  30045. }, function (idx) {
  30046. return getId(thisList, idx);
  30047. });
  30048. };
  30049. /**
  30050. * Get visual property.
  30051. */
  30052. SeriesData.prototype.getVisual = function (key) {
  30053. var visual = this._visual;
  30054. return visual && visual[key];
  30055. };
  30056. SeriesData.prototype.setVisual = function (kvObj, val) {
  30057. this._visual = this._visual || {};
  30058. if (isObject$2(kvObj)) {
  30059. extend(this._visual, kvObj);
  30060. } else {
  30061. this._visual[kvObj] = val;
  30062. }
  30063. };
  30064. /**
  30065. * Get visual property of single data item
  30066. */
  30067. // eslint-disable-next-line
  30068. SeriesData.prototype.getItemVisual = function (idx, key) {
  30069. var itemVisual = this._itemVisuals[idx];
  30070. var val = itemVisual && itemVisual[key];
  30071. if (val == null) {
  30072. // Use global visual property
  30073. return this.getVisual(key);
  30074. }
  30075. return val;
  30076. };
  30077. /**
  30078. * If exists visual property of single data item
  30079. */
  30080. SeriesData.prototype.hasItemVisual = function () {
  30081. return this._itemVisuals.length > 0;
  30082. };
  30083. /**
  30084. * Make sure itemVisual property is unique
  30085. */
  30086. // TODO: use key to save visual to reduce memory.
  30087. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  30088. var itemVisuals = this._itemVisuals;
  30089. var itemVisual = itemVisuals[idx];
  30090. if (!itemVisual) {
  30091. itemVisual = itemVisuals[idx] = {};
  30092. }
  30093. var val = itemVisual[key];
  30094. if (val == null) {
  30095. val = this.getVisual(key); // TODO Performance?
  30096. if (isArray(val)) {
  30097. val = val.slice();
  30098. } else if (isObject$2(val)) {
  30099. val = extend({}, val);
  30100. }
  30101. itemVisual[key] = val;
  30102. }
  30103. return val;
  30104. }; // eslint-disable-next-line
  30105. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  30106. var itemVisual = this._itemVisuals[idx] || {};
  30107. this._itemVisuals[idx] = itemVisual;
  30108. if (isObject$2(key)) {
  30109. extend(itemVisual, key);
  30110. } else {
  30111. itemVisual[key] = value;
  30112. }
  30113. };
  30114. /**
  30115. * Clear itemVisuals and list visual.
  30116. */
  30117. SeriesData.prototype.clearAllVisual = function () {
  30118. this._visual = {};
  30119. this._itemVisuals = [];
  30120. };
  30121. SeriesData.prototype.setLayout = function (key, val) {
  30122. if (isObject$2(key)) {
  30123. for (var name_1 in key) {
  30124. if (key.hasOwnProperty(name_1)) {
  30125. this.setLayout(name_1, key[name_1]);
  30126. }
  30127. }
  30128. return;
  30129. }
  30130. this._layout[key] = val;
  30131. };
  30132. /**
  30133. * Get layout property.
  30134. */
  30135. SeriesData.prototype.getLayout = function (key) {
  30136. return this._layout[key];
  30137. };
  30138. /**
  30139. * Get layout of single data item
  30140. */
  30141. SeriesData.prototype.getItemLayout = function (idx) {
  30142. return this._itemLayouts[idx];
  30143. };
  30144. /**
  30145. * Set layout of single data item
  30146. */
  30147. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  30148. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  30149. };
  30150. /**
  30151. * Clear all layout of single data item
  30152. */
  30153. SeriesData.prototype.clearItemLayouts = function () {
  30154. this._itemLayouts.length = 0;
  30155. };
  30156. /**
  30157. * Set graphic element relative to data. It can be set as null
  30158. */
  30159. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  30160. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  30161. setCommonECData(seriesIndex, this.dataType, idx, el);
  30162. this._graphicEls[idx] = el;
  30163. };
  30164. SeriesData.prototype.getItemGraphicEl = function (idx) {
  30165. return this._graphicEls[idx];
  30166. };
  30167. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  30168. each(this._graphicEls, function (el, idx) {
  30169. if (el) {
  30170. cb && cb.call(context, el, idx);
  30171. }
  30172. });
  30173. };
  30174. /**
  30175. * Shallow clone a new list except visual and layout properties, and graph elements.
  30176. * New list only change the indices.
  30177. */
  30178. SeriesData.prototype.cloneShallow = function (list) {
  30179. if (!list) {
  30180. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  30181. }
  30182. transferProperties(list, this);
  30183. list._store = this._store;
  30184. return list;
  30185. };
  30186. /**
  30187. * Wrap some method to add more feature
  30188. */
  30189. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  30190. var originalMethod = this[methodName];
  30191. if (typeof originalMethod !== 'function') {
  30192. return;
  30193. }
  30194. this.__wrappedMethods = this.__wrappedMethods || [];
  30195. this.__wrappedMethods.push(methodName);
  30196. this[methodName] = function () {
  30197. var res = originalMethod.apply(this, arguments);
  30198. return injectFunction.apply(this, [res].concat(slice(arguments)));
  30199. };
  30200. }; // ----------------------------------------------------------
  30201. // A work around for internal method visiting private member.
  30202. // ----------------------------------------------------------
  30203. SeriesData.internalField = function () {
  30204. prepareInvertedIndex = function (data) {
  30205. var invertedIndicesMap = data._invertedIndicesMap;
  30206. each(invertedIndicesMap, function (invertedIndices, dim) {
  30207. var dimInfo = data._dimInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  30208. var ordinalMeta = dimInfo.ordinalMeta;
  30209. var store = data._store;
  30210. if (ordinalMeta) {
  30211. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  30212. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  30213. for (var i = 0; i < invertedIndices.length; i++) {
  30214. invertedIndices[i] = INDEX_NOT_FOUND;
  30215. }
  30216. for (var i = 0; i < store.count(); i++) {
  30217. // Only support the case that all values are distinct.
  30218. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  30219. }
  30220. }
  30221. });
  30222. };
  30223. getIdNameFromStore = function (data, dimIdx, idx) {
  30224. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  30225. };
  30226. /**
  30227. * @see the comment of `List['getId']`.
  30228. */
  30229. getId = function (data, rawIndex) {
  30230. var id = data._idList[rawIndex];
  30231. if (id == null && data._idDimIdx != null) {
  30232. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  30233. }
  30234. if (id == null) {
  30235. id = ID_PREFIX + rawIndex;
  30236. }
  30237. return id;
  30238. };
  30239. normalizeDimensions = function (dimensions) {
  30240. if (!isArray(dimensions)) {
  30241. dimensions = dimensions != null ? [dimensions] : [];
  30242. }
  30243. return dimensions;
  30244. };
  30245. /**
  30246. * Data in excludeDimensions is copied, otherwise transfered.
  30247. */
  30248. cloneListForMapAndSample = function (original) {
  30249. 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
  30250. transferProperties(list, original);
  30251. return list;
  30252. };
  30253. transferProperties = function (target, source) {
  30254. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  30255. if (source.hasOwnProperty(propName)) {
  30256. target[propName] = source[propName];
  30257. }
  30258. });
  30259. target.__wrappedMethods = source.__wrappedMethods;
  30260. each(CLONE_PROPERTIES, function (propName) {
  30261. target[propName] = clone(source[propName]);
  30262. });
  30263. target._calculationInfo = extend({}, source._calculationInfo);
  30264. };
  30265. makeIdFromName = function (data, idx) {
  30266. var nameList = data._nameList;
  30267. var idList = data._idList;
  30268. var nameDimIdx = data._nameDimIdx;
  30269. var idDimIdx = data._idDimIdx;
  30270. var name = nameList[idx];
  30271. var id = idList[idx];
  30272. if (name == null && nameDimIdx != null) {
  30273. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  30274. }
  30275. if (id == null && idDimIdx != null) {
  30276. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  30277. }
  30278. if (id == null && name != null) {
  30279. var nameRepeatCount = data._nameRepeatCount;
  30280. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  30281. id = name;
  30282. if (nmCnt > 1) {
  30283. id += '__ec__' + nmCnt;
  30284. }
  30285. idList[idx] = id;
  30286. }
  30287. };
  30288. }();
  30289. return SeriesData;
  30290. }();
  30291. /**
  30292. * For outside usage compat (like echarts-gl are using it).
  30293. */
  30294. function createDimensions(source, opt) {
  30295. return prepareSeriesDataSchema(source, opt).dimensions;
  30296. }
  30297. /**
  30298. * This method builds the relationship between:
  30299. * + "what the coord sys or series requires (see `coordDimensions`)",
  30300. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  30301. * + "what the data source provids (see `source`)".
  30302. *
  30303. * Some guess strategy will be adapted if user does not define something.
  30304. * If no 'value' dimension specified, the first no-named dimension will be
  30305. * named as 'value'.
  30306. *
  30307. * @return The results are always sorted by `storeDimIndex` asc.
  30308. */
  30309. function prepareSeriesDataSchema( // TODO: TYPE completeDimensions type
  30310. source, opt) {
  30311. if (!isSourceInstance(source)) {
  30312. source = createSourceFromSeriesDataOption(source);
  30313. }
  30314. opt = opt || {};
  30315. var sysDims = opt.coordDimensions || [];
  30316. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  30317. var coordDimNameMap = createHashMap();
  30318. var resultList = [];
  30319. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount); // Try to ignore unsed dimensions if sharing a high dimension datastore
  30320. // 30 is an experience value.
  30321. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  30322. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  30323. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  30324. var encodeDef = opt.encodeDefine;
  30325. if (!encodeDef && opt.encodeDefaulter) {
  30326. encodeDef = opt.encodeDefaulter(source, dimCount);
  30327. }
  30328. var encodeDefMap = createHashMap(encodeDef);
  30329. var indicesMap = new CtorInt32Array(dimCount);
  30330. for (var i = 0; i < indicesMap.length; i++) {
  30331. indicesMap[i] = -1;
  30332. }
  30333. function getResultItem(dimIdx) {
  30334. var idx = indicesMap[dimIdx];
  30335. if (idx < 0) {
  30336. var dimDefItemRaw = dimsDef[dimIdx];
  30337. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  30338. name: dimDefItemRaw
  30339. };
  30340. var resultItem = new SeriesDimensionDefine();
  30341. var userDimName = dimDefItem.name;
  30342. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  30343. // Only if `series.dimensions` is defined in option
  30344. // displayName, will be set, and dimension will be diplayed vertically in
  30345. // tooltip by default.
  30346. resultItem.name = resultItem.displayName = userDimName;
  30347. }
  30348. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  30349. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  30350. var newIdx = resultList.length;
  30351. indicesMap[dimIdx] = newIdx;
  30352. resultItem.storeDimIndex = dimIdx;
  30353. resultList.push(resultItem);
  30354. return resultItem;
  30355. }
  30356. return resultList[idx];
  30357. }
  30358. if (!omitUnusedDimensions) {
  30359. for (var i = 0; i < dimCount; i++) {
  30360. getResultItem(i);
  30361. }
  30362. } // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  30363. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  30364. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  30365. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  30366. // this case.
  30367. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  30368. encodeDefMap.set(coordDim, false);
  30369. return;
  30370. }
  30371. var validDataDims = encodeDefMap.set(coordDim, []);
  30372. each(dataDims, function (resultDimIdxOrName, idx) {
  30373. // The input resultDimIdx can be dim name or index.
  30374. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  30375. if (resultDimIdx != null && resultDimIdx < dimCount) {
  30376. validDataDims[idx] = resultDimIdx;
  30377. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  30378. }
  30379. });
  30380. }); // Apply templetes and default order from `sysDims`.
  30381. var availDimIdx = 0;
  30382. each(sysDims, function (sysDimItemRaw) {
  30383. var coordDim;
  30384. var sysDimItemDimsDef;
  30385. var sysDimItemOtherDims;
  30386. var sysDimItem;
  30387. if (isString(sysDimItemRaw)) {
  30388. coordDim = sysDimItemRaw;
  30389. sysDimItem = {};
  30390. } else {
  30391. sysDimItem = sysDimItemRaw;
  30392. coordDim = sysDimItem.name;
  30393. var ordinalMeta = sysDimItem.ordinalMeta;
  30394. sysDimItem.ordinalMeta = null;
  30395. sysDimItem = extend({}, sysDimItem);
  30396. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  30397. sysDimItemDimsDef = sysDimItem.dimsDef;
  30398. sysDimItemOtherDims = sysDimItem.otherDims;
  30399. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  30400. }
  30401. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  30402. if (dataDims === false) {
  30403. return;
  30404. }
  30405. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  30406. if (!dataDims.length) {
  30407. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  30408. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  30409. availDimIdx++;
  30410. }
  30411. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  30412. }
  30413. } // Apply templates.
  30414. each(dataDims, function (resultDimIdx, coordDimIndex) {
  30415. var resultItem = getResultItem(resultDimIdx); // Coordinate system has a higher priority on dim type than source.
  30416. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  30417. resultItem.type = sysDimItem.type;
  30418. }
  30419. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  30420. if (resultItem.name == null && sysDimItemDimsDef) {
  30421. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  30422. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  30423. name: sysDimItemDimsDefItem
  30424. });
  30425. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  30426. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  30427. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  30428. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  30429. });
  30430. });
  30431. function applyDim(resultItem, coordDim, coordDimIndex) {
  30432. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  30433. resultItem.otherDims[coordDim] = coordDimIndex;
  30434. } else {
  30435. resultItem.coordDim = coordDim;
  30436. resultItem.coordDimIndex = coordDimIndex;
  30437. coordDimNameMap.set(coordDim, true);
  30438. }
  30439. } // Make sure the first extra dim is 'value'.
  30440. var generateCoord = opt.generateCoord;
  30441. var generateCoordCount = opt.generateCoordCount;
  30442. var fromZero = generateCoordCount != null;
  30443. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  30444. var extra = generateCoord || 'value';
  30445. function ifNoNameFillWithCoordName(resultItem) {
  30446. if (resultItem.name == null) {
  30447. // Duplication will be removed in the next step.
  30448. resultItem.name = resultItem.coordDim;
  30449. }
  30450. } // Set dim `name` and other `coordDim` and other props.
  30451. if (!omitUnusedDimensions) {
  30452. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  30453. var resultItem = getResultItem(resultDimIdx);
  30454. var coordDim = resultItem.coordDim;
  30455. if (coordDim == null) {
  30456. // TODO no need to generate coordDim for isExtraCoord?
  30457. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  30458. resultItem.coordDimIndex = 0; // Series specified generateCoord is using out.
  30459. if (!generateCoord || generateCoordCount <= 0) {
  30460. resultItem.isExtraCoord = true;
  30461. }
  30462. generateCoordCount--;
  30463. }
  30464. ifNoNameFillWithCoordName(resultItem);
  30465. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  30466. // {
  30467. // dataset: {source: [
  30468. // ['2001', 123],
  30469. // ['2002', 456],
  30470. // ...
  30471. // ['The others', 987],
  30472. // ]},
  30473. // series: {type: 'pie'}
  30474. // }
  30475. // The first colum should better be treated as a "ordinal" although it
  30476. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  30477. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  30478. resultItem.type = 'ordinal';
  30479. }
  30480. }
  30481. } else {
  30482. each(resultList, function (resultItem) {
  30483. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  30484. ifNoNameFillWithCoordName(resultItem);
  30485. }); // Sort dimensions: there are some rule that use the last dim as label,
  30486. // and for some latter travel process easier.
  30487. resultList.sort(function (item0, item1) {
  30488. return item0.storeDimIndex - item1.storeDimIndex;
  30489. });
  30490. }
  30491. removeDuplication(resultList);
  30492. return new SeriesDataSchema({
  30493. source: source,
  30494. dimensions: resultList,
  30495. fullDimensionCount: dimCount,
  30496. dimensionOmitted: omitUnusedDimensions
  30497. });
  30498. }
  30499. function removeDuplication(result) {
  30500. var duplicationMap = createHashMap();
  30501. for (var i = 0; i < result.length; i++) {
  30502. var dim = result[i];
  30503. var dimOriginalName = dim.name;
  30504. var count = duplicationMap.get(dimOriginalName) || 0;
  30505. if (count > 0) {
  30506. // Starts from 0.
  30507. dim.name = dimOriginalName + (count - 1);
  30508. }
  30509. count++;
  30510. duplicationMap.set(dimOriginalName, count);
  30511. }
  30512. } // ??? TODO
  30513. // Originally detect dimCount by data[0]. Should we
  30514. // optimize it to only by sysDims and dimensions and encode.
  30515. // So only necessary dims will be initialized.
  30516. // But
  30517. // (1) custom series should be considered. where other dims
  30518. // may be visited.
  30519. // (2) sometimes user need to calcualte bubble size or use visualMap
  30520. // on other dimensions besides coordSys needed.
  30521. // So, dims that is not used by system, should be shared in data store?
  30522. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  30523. // Note that the result dimCount should not small than columns count
  30524. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  30525. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  30526. each(sysDims, function (sysDimItem) {
  30527. var sysDimItemDimsDef;
  30528. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  30529. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  30530. }
  30531. });
  30532. return dimCount;
  30533. }
  30534. function genCoordDimName(name, map, fromZero) {
  30535. var mapData = map.data;
  30536. if (fromZero || mapData.hasOwnProperty(name)) {
  30537. var i = 0;
  30538. while (mapData.hasOwnProperty(name + i)) {
  30539. i++;
  30540. }
  30541. name += i;
  30542. }
  30543. map.set(name, true);
  30544. return name;
  30545. }
  30546. /**
  30547. * @class
  30548. * For example:
  30549. * {
  30550. * coordSysName: 'cartesian2d',
  30551. * coordSysDims: ['x', 'y', ...],
  30552. * axisMap: HashMap({
  30553. * x: xAxisModel,
  30554. * y: yAxisModel
  30555. * }),
  30556. * categoryAxisMap: HashMap({
  30557. * x: xAxisModel,
  30558. * y: undefined
  30559. * }),
  30560. * // The index of the first category axis in `coordSysDims`.
  30561. * // `null/undefined` means no category axis exists.
  30562. * firstCategoryDimIndex: 1,
  30563. * // To replace user specified encode.
  30564. * }
  30565. */
  30566. var CoordSysInfo =
  30567. /** @class */
  30568. function () {
  30569. function CoordSysInfo(coordSysName) {
  30570. this.coordSysDims = [];
  30571. this.axisMap = createHashMap();
  30572. this.categoryAxisMap = createHashMap();
  30573. this.coordSysName = coordSysName;
  30574. }
  30575. return CoordSysInfo;
  30576. }();
  30577. function getCoordSysInfoBySeries(seriesModel) {
  30578. var coordSysName = seriesModel.get('coordinateSystem');
  30579. var result = new CoordSysInfo(coordSysName);
  30580. var fetch = fetchers[coordSysName];
  30581. if (fetch) {
  30582. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  30583. return result;
  30584. }
  30585. }
  30586. var fetchers = {
  30587. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  30588. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  30589. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  30590. if ("development" !== 'production') {
  30591. if (!xAxisModel) {
  30592. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  30593. }
  30594. if (!yAxisModel) {
  30595. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  30596. }
  30597. }
  30598. result.coordSysDims = ['x', 'y'];
  30599. axisMap.set('x', xAxisModel);
  30600. axisMap.set('y', yAxisModel);
  30601. if (isCategory(xAxisModel)) {
  30602. categoryAxisMap.set('x', xAxisModel);
  30603. result.firstCategoryDimIndex = 0;
  30604. }
  30605. if (isCategory(yAxisModel)) {
  30606. categoryAxisMap.set('y', yAxisModel);
  30607. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  30608. }
  30609. },
  30610. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  30611. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  30612. if ("development" !== 'production') {
  30613. if (!singleAxisModel) {
  30614. throw new Error('singleAxis should be specified.');
  30615. }
  30616. }
  30617. result.coordSysDims = ['single'];
  30618. axisMap.set('single', singleAxisModel);
  30619. if (isCategory(singleAxisModel)) {
  30620. categoryAxisMap.set('single', singleAxisModel);
  30621. result.firstCategoryDimIndex = 0;
  30622. }
  30623. },
  30624. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  30625. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  30626. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  30627. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  30628. if ("development" !== 'production') {
  30629. if (!angleAxisModel) {
  30630. throw new Error('angleAxis option not found');
  30631. }
  30632. if (!radiusAxisModel) {
  30633. throw new Error('radiusAxis option not found');
  30634. }
  30635. }
  30636. result.coordSysDims = ['radius', 'angle'];
  30637. axisMap.set('radius', radiusAxisModel);
  30638. axisMap.set('angle', angleAxisModel);
  30639. if (isCategory(radiusAxisModel)) {
  30640. categoryAxisMap.set('radius', radiusAxisModel);
  30641. result.firstCategoryDimIndex = 0;
  30642. }
  30643. if (isCategory(angleAxisModel)) {
  30644. categoryAxisMap.set('angle', angleAxisModel);
  30645. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  30646. }
  30647. },
  30648. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  30649. result.coordSysDims = ['lng', 'lat'];
  30650. },
  30651. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  30652. var ecModel = seriesModel.ecModel;
  30653. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  30654. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  30655. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  30656. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  30657. var axisDim = coordSysDims[index];
  30658. axisMap.set(axisDim, axisModel);
  30659. if (isCategory(axisModel)) {
  30660. categoryAxisMap.set(axisDim, axisModel);
  30661. if (result.firstCategoryDimIndex == null) {
  30662. result.firstCategoryDimIndex = index;
  30663. }
  30664. }
  30665. });
  30666. }
  30667. };
  30668. function isCategory(axisModel) {
  30669. return axisModel.get('type') === 'category';
  30670. }
  30671. /**
  30672. * Note that it is too complicated to support 3d stack by value
  30673. * (have to create two-dimension inverted index), so in 3d case
  30674. * we just support that stacked by index.
  30675. *
  30676. * @param seriesModel
  30677. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  30678. * The input will be modified.
  30679. * @param opt
  30680. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  30681. * @param opt.byIndex=false
  30682. * @return calculationInfo
  30683. * {
  30684. * stackedDimension: string
  30685. * stackedByDimension: string
  30686. * isStackedByIndex: boolean
  30687. * stackedOverDimension: string
  30688. * stackResultDimension: string
  30689. * }
  30690. */
  30691. function enableDataStack(seriesModel, dimensionsInput, opt) {
  30692. opt = opt || {};
  30693. var byIndex = opt.byIndex;
  30694. var stackedCoordDimension = opt.stackedCoordDimension;
  30695. var dimensionDefineList;
  30696. var schema;
  30697. var store;
  30698. if (isLegacyDimensionsInput(dimensionsInput)) {
  30699. dimensionDefineList = dimensionsInput;
  30700. } else {
  30701. schema = dimensionsInput.schema;
  30702. dimensionDefineList = schema.dimensions;
  30703. store = dimensionsInput.store;
  30704. } // Compatibal: when `stack` is set as '', do not stack.
  30705. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  30706. var stackedByDimInfo;
  30707. var stackedDimInfo;
  30708. var stackResultDimension;
  30709. var stackedOverDimension;
  30710. each(dimensionDefineList, function (dimensionInfo, index) {
  30711. if (isString(dimensionInfo)) {
  30712. dimensionDefineList[index] = dimensionInfo = {
  30713. name: dimensionInfo
  30714. };
  30715. }
  30716. if (mayStack && !dimensionInfo.isExtraCoord) {
  30717. // Find the first ordinal dimension as the stackedByDimInfo.
  30718. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  30719. stackedByDimInfo = dimensionInfo;
  30720. } // Find the first stackable dimension as the stackedDimInfo.
  30721. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  30722. stackedDimInfo = dimensionInfo;
  30723. }
  30724. }
  30725. });
  30726. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  30727. // Compatible with previous design, value axis (time axis) only stack by index.
  30728. // It may make sense if the user provides elaborately constructed data.
  30729. byIndex = true;
  30730. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  30731. // That put stack logic in List is for using conveniently in echarts extensions, but it
  30732. // might not be a good way.
  30733. if (stackedDimInfo) {
  30734. // Use a weird name that not duplicated with other names.
  30735. // Also need to use seriesModel.id as postfix because different
  30736. // series may share same data store. The stack dimension needs to be distinguished.
  30737. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  30738. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id; // Create inverted index to fast query index by value.
  30739. if (stackedByDimInfo) {
  30740. stackedByDimInfo.createInvertedIndices = true;
  30741. }
  30742. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  30743. var stackedDimType = stackedDimInfo.type;
  30744. var stackedDimCoordIndex_1 = 0;
  30745. each(dimensionDefineList, function (dimensionInfo) {
  30746. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  30747. stackedDimCoordIndex_1++;
  30748. }
  30749. });
  30750. var stackedOverDimensionDefine = {
  30751. name: stackResultDimension,
  30752. coordDim: stackedDimCoordDim_1,
  30753. coordDimIndex: stackedDimCoordIndex_1,
  30754. type: stackedDimType,
  30755. isExtraCoord: true,
  30756. isCalculationCoord: true,
  30757. storeDimIndex: dimensionDefineList.length
  30758. };
  30759. var stackResultDimensionDefine = {
  30760. name: stackedOverDimension,
  30761. // This dimension contains stack base (generally, 0), so do not set it as
  30762. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  30763. coordDim: stackedOverDimension,
  30764. coordDimIndex: stackedDimCoordIndex_1 + 1,
  30765. type: stackedDimType,
  30766. isExtraCoord: true,
  30767. isCalculationCoord: true,
  30768. storeDimIndex: dimensionDefineList.length + 1
  30769. };
  30770. if (schema) {
  30771. if (store) {
  30772. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  30773. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  30774. }
  30775. schema.appendCalculationDimension(stackedOverDimensionDefine);
  30776. schema.appendCalculationDimension(stackResultDimensionDefine);
  30777. } else {
  30778. dimensionDefineList.push(stackedOverDimensionDefine);
  30779. dimensionDefineList.push(stackResultDimensionDefine);
  30780. }
  30781. }
  30782. return {
  30783. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  30784. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  30785. isStackedByIndex: byIndex,
  30786. stackedOverDimension: stackedOverDimension,
  30787. stackResultDimension: stackResultDimension
  30788. };
  30789. }
  30790. function isLegacyDimensionsInput(dimensionsInput) {
  30791. return !isSeriesDataSchema(dimensionsInput.schema);
  30792. }
  30793. function isDimensionStacked(data, stackedDim) {
  30794. // Each single series only maps to one pair of axis. So we do not need to
  30795. // check stackByDim, whatever stacked by a dimension or stacked by index.
  30796. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  30797. }
  30798. function getStackedDimension(data, targetDim) {
  30799. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  30800. }
  30801. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  30802. var coordSysName = seriesModel.get('coordinateSystem');
  30803. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  30804. var coordSysDimDefs;
  30805. if (coordSysInfo && coordSysInfo.coordSysDims) {
  30806. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  30807. var dimInfo = {
  30808. name: dim
  30809. };
  30810. var axisModel = coordSysInfo.axisMap.get(dim);
  30811. if (axisModel) {
  30812. var axisType = axisModel.get('type');
  30813. dimInfo.type = getDimensionTypeByAxis(axisType);
  30814. }
  30815. return dimInfo;
  30816. });
  30817. }
  30818. if (!coordSysDimDefs) {
  30819. // Get dimensions from registered coordinate system
  30820. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  30821. }
  30822. return coordSysDimDefs;
  30823. }
  30824. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  30825. var firstCategoryDimIndex;
  30826. var hasNameEncode;
  30827. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  30828. var coordDim = dimInfo.coordDim;
  30829. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  30830. if (categoryAxisModel) {
  30831. if (firstCategoryDimIndex == null) {
  30832. firstCategoryDimIndex = dimIndex;
  30833. }
  30834. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  30835. if (createInvertedIndices) {
  30836. dimInfo.createInvertedIndices = true;
  30837. }
  30838. }
  30839. if (dimInfo.otherDims.itemName != null) {
  30840. hasNameEncode = true;
  30841. }
  30842. });
  30843. if (!hasNameEncode && firstCategoryDimIndex != null) {
  30844. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  30845. }
  30846. return firstCategoryDimIndex;
  30847. }
  30848. /**
  30849. * Caution: there are side effects to `sourceManager` in this method.
  30850. * Should better only be called in `Series['getInitialData']`.
  30851. */
  30852. function createSeriesData(sourceRaw, seriesModel, opt) {
  30853. opt = opt || {};
  30854. var sourceManager = seriesModel.getSourceManager();
  30855. var source;
  30856. var isOriginalSource = false;
  30857. if (sourceRaw) {
  30858. isOriginalSource = true;
  30859. source = createSourceFromSeriesDataOption(sourceRaw);
  30860. } else {
  30861. source = sourceManager.getSource(); // Is series.data. not dataset.
  30862. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  30863. }
  30864. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  30865. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  30866. var useEncodeDefaulter = opt.useEncodeDefaulter;
  30867. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  30868. var createDimensionOptions = {
  30869. coordDimensions: coordSysDimDefs,
  30870. generateCoord: opt.generateCoord,
  30871. encodeDefine: seriesModel.getEncode(),
  30872. encodeDefaulter: encodeDefaulter,
  30873. canOmitUnusedDimensions: !isOriginalSource
  30874. };
  30875. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  30876. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  30877. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  30878. var stackCalculationInfo = enableDataStack(seriesModel, {
  30879. schema: schema,
  30880. store: store
  30881. });
  30882. var data = new SeriesData(schema, seriesModel);
  30883. data.setCalculationInfo(stackCalculationInfo);
  30884. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  30885. // Use dataIndex as ordinal value in categoryAxis
  30886. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  30887. } : null;
  30888. data.hasItemOption = false;
  30889. data.initData( // Try to reuse the data store in sourceManager if using dataset.
  30890. isOriginalSource ? source : store, null, dimValueGetter);
  30891. return data;
  30892. }
  30893. function isNeedCompleteOrdinalData(source) {
  30894. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  30895. var sampleItem = firstDataNotNull(source.data || []);
  30896. return sampleItem != null && !isArray(getDataItemValue(sampleItem));
  30897. }
  30898. }
  30899. function firstDataNotNull(arr) {
  30900. var i = 0;
  30901. while (i < arr.length && arr[i] == null) {
  30902. i++;
  30903. }
  30904. return arr[i];
  30905. }
  30906. var Scale =
  30907. /** @class */
  30908. function () {
  30909. function Scale(setting) {
  30910. this._setting = setting || {};
  30911. this._extent = [Infinity, -Infinity];
  30912. }
  30913. Scale.prototype.getSetting = function (name) {
  30914. return this._setting[name];
  30915. };
  30916. /**
  30917. * Set extent from data
  30918. */
  30919. Scale.prototype.unionExtent = function (other) {
  30920. var extent = this._extent;
  30921. other[0] < extent[0] && (extent[0] = other[0]);
  30922. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  30923. // this.setExtent(extent[0], extent[1]);
  30924. };
  30925. /**
  30926. * Set extent from data
  30927. */
  30928. Scale.prototype.unionExtentFromData = function (data, dim) {
  30929. this.unionExtent(data.getApproximateExtent(dim));
  30930. };
  30931. /**
  30932. * Get extent
  30933. *
  30934. * Extent is always in increase order.
  30935. */
  30936. Scale.prototype.getExtent = function () {
  30937. return this._extent.slice();
  30938. };
  30939. /**
  30940. * Set extent
  30941. */
  30942. Scale.prototype.setExtent = function (start, end) {
  30943. var thisExtent = this._extent;
  30944. if (!isNaN(start)) {
  30945. thisExtent[0] = start;
  30946. }
  30947. if (!isNaN(end)) {
  30948. thisExtent[1] = end;
  30949. }
  30950. };
  30951. /**
  30952. * If value is in extent range
  30953. */
  30954. Scale.prototype.isInExtentRange = function (value) {
  30955. return this._extent[0] <= value && this._extent[1] >= value;
  30956. };
  30957. /**
  30958. * When axis extent depends on data and no data exists,
  30959. * axis ticks should not be drawn, which is named 'blank'.
  30960. */
  30961. Scale.prototype.isBlank = function () {
  30962. return this._isBlank;
  30963. };
  30964. /**
  30965. * When axis extent depends on data and no data exists,
  30966. * axis ticks should not be drawn, which is named 'blank'.
  30967. */
  30968. Scale.prototype.setBlank = function (isBlank) {
  30969. this._isBlank = isBlank;
  30970. };
  30971. return Scale;
  30972. }();
  30973. enableClassManagement(Scale);
  30974. var uidBase = 0;
  30975. var OrdinalMeta =
  30976. /** @class */
  30977. function () {
  30978. function OrdinalMeta(opt) {
  30979. this.categories = opt.categories || [];
  30980. this._needCollect = opt.needCollect;
  30981. this._deduplication = opt.deduplication;
  30982. this.uid = ++uidBase;
  30983. }
  30984. OrdinalMeta.createByAxisModel = function (axisModel) {
  30985. var option = axisModel.option;
  30986. var data = option.data;
  30987. var categories = data && map(data, getName);
  30988. return new OrdinalMeta({
  30989. categories: categories,
  30990. needCollect: !categories,
  30991. // deduplication is default in axis.
  30992. deduplication: option.dedplication !== false
  30993. });
  30994. };
  30995. OrdinalMeta.prototype.getOrdinal = function (category) {
  30996. // @ts-ignore
  30997. return this._getOrCreateMap().get(category);
  30998. };
  30999. /**
  31000. * @return The ordinal. If not found, return NaN.
  31001. */
  31002. OrdinalMeta.prototype.parseAndCollect = function (category) {
  31003. var index;
  31004. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  31005. // This feature is only supported when !needCollect, because we should
  31006. // consider a common case: a value is 2017, which is a number but is
  31007. // expected to be tread as a category. This case usually happen in dataset,
  31008. // where it happent to be no need of the index feature.
  31009. if (typeof category !== 'string' && !needCollect) {
  31010. return category;
  31011. } // Optimize for the scenario:
  31012. // category is ['2012-01-01', '2012-01-02', ...], where the input
  31013. // data has been ensured not duplicate and is large data.
  31014. // Notice, if a dataset dimension provide categroies, usually echarts
  31015. // should remove duplication except user tell echarts dont do that
  31016. // (set axis.deduplication = false), because echarts do not know whether
  31017. // the values in the category dimension has duplication (consider the
  31018. // parallel-aqi example)
  31019. if (needCollect && !this._deduplication) {
  31020. index = this.categories.length;
  31021. this.categories[index] = category;
  31022. return index;
  31023. }
  31024. var map = this._getOrCreateMap(); // @ts-ignore
  31025. index = map.get(category);
  31026. if (index == null) {
  31027. if (needCollect) {
  31028. index = this.categories.length;
  31029. this.categories[index] = category; // @ts-ignore
  31030. map.set(category, index);
  31031. } else {
  31032. index = NaN;
  31033. }
  31034. }
  31035. return index;
  31036. }; // Consider big data, do not create map until needed.
  31037. OrdinalMeta.prototype._getOrCreateMap = function () {
  31038. return this._map || (this._map = createHashMap(this.categories));
  31039. };
  31040. return OrdinalMeta;
  31041. }();
  31042. function getName(obj) {
  31043. if (isObject(obj) && obj.value != null) {
  31044. return obj.value;
  31045. } else {
  31046. return obj + '';
  31047. }
  31048. }
  31049. var roundNumber = round;
  31050. /**
  31051. * @param extent Both extent[0] and extent[1] should be valid number.
  31052. * Should be extent[0] < extent[1].
  31053. * @param splitNumber splitNumber should be >= 1.
  31054. */
  31055. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  31056. var result = {};
  31057. var span = extent[1] - extent[0];
  31058. var interval = result.interval = nice(span / splitNumber, true);
  31059. if (minInterval != null && interval < minInterval) {
  31060. interval = result.interval = minInterval;
  31061. }
  31062. if (maxInterval != null && interval > maxInterval) {
  31063. interval = result.interval = maxInterval;
  31064. } // Tow more digital for tick.
  31065. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  31066. var niceTickExtent = result.niceTickExtent = [roundNumber(Math.ceil(extent[0] / interval) * interval, precision), roundNumber(Math.floor(extent[1] / interval) * interval, precision)];
  31067. fixExtent(niceTickExtent, extent);
  31068. return result;
  31069. }
  31070. /**
  31071. * @return interval precision
  31072. */
  31073. function getIntervalPrecision(interval) {
  31074. // Tow more digital for tick.
  31075. return getPrecision(interval) + 2;
  31076. }
  31077. function clamp(niceTickExtent, idx, extent) {
  31078. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  31079. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  31080. function fixExtent(niceTickExtent, extent) {
  31081. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  31082. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  31083. clamp(niceTickExtent, 0, extent);
  31084. clamp(niceTickExtent, 1, extent);
  31085. if (niceTickExtent[0] > niceTickExtent[1]) {
  31086. niceTickExtent[0] = niceTickExtent[1];
  31087. }
  31088. }
  31089. function contain$2(val, extent) {
  31090. return val >= extent[0] && val <= extent[1];
  31091. }
  31092. function normalize$1(val, extent) {
  31093. if (extent[1] === extent[0]) {
  31094. return 0.5;
  31095. }
  31096. return (val - extent[0]) / (extent[1] - extent[0]);
  31097. }
  31098. function scale$2(val, extent) {
  31099. return val * (extent[1] - extent[0]) + extent[0];
  31100. }
  31101. var OrdinalScale =
  31102. /** @class */
  31103. function (_super) {
  31104. __extends(OrdinalScale, _super);
  31105. function OrdinalScale(setting) {
  31106. var _this = _super.call(this, setting) || this;
  31107. _this.type = 'ordinal';
  31108. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  31109. // import approach to get OrdinalMeta class.
  31110. if (!ordinalMeta) {
  31111. ordinalMeta = new OrdinalMeta({});
  31112. }
  31113. if (isArray(ordinalMeta)) {
  31114. ordinalMeta = new OrdinalMeta({
  31115. categories: map(ordinalMeta, function (item) {
  31116. return isObject(item) ? item.value : item;
  31117. })
  31118. });
  31119. }
  31120. _this._ordinalMeta = ordinalMeta;
  31121. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  31122. return _this;
  31123. }
  31124. OrdinalScale.prototype.parse = function (val) {
  31125. return typeof val === 'string' ? this._ordinalMeta.getOrdinal(val) // val might be float.
  31126. : Math.round(val);
  31127. };
  31128. OrdinalScale.prototype.contain = function (rank) {
  31129. rank = this.parse(rank);
  31130. return contain$2(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  31131. };
  31132. /**
  31133. * Normalize given rank or name to linear [0, 1]
  31134. * @param val raw ordinal number.
  31135. * @return normalized value in [0, 1].
  31136. */
  31137. OrdinalScale.prototype.normalize = function (val) {
  31138. val = this._getTickNumber(this.parse(val));
  31139. return normalize$1(val, this._extent);
  31140. };
  31141. /**
  31142. * @param val normalized value in [0, 1].
  31143. * @return raw ordinal number.
  31144. */
  31145. OrdinalScale.prototype.scale = function (val) {
  31146. val = Math.round(scale$2(val, this._extent));
  31147. return this.getRawOrdinalNumber(val);
  31148. };
  31149. OrdinalScale.prototype.getTicks = function () {
  31150. var ticks = [];
  31151. var extent = this._extent;
  31152. var rank = extent[0];
  31153. while (rank <= extent[1]) {
  31154. ticks.push({
  31155. value: rank
  31156. });
  31157. rank++;
  31158. }
  31159. return ticks;
  31160. };
  31161. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  31162. // Not support.
  31163. return;
  31164. };
  31165. /**
  31166. * @see `Ordinal['_ordinalNumbersByTick']`
  31167. */
  31168. OrdinalScale.prototype.setSortInfo = function (info) {
  31169. if (info == null) {
  31170. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  31171. return;
  31172. }
  31173. var infoOrdinalNumbers = info.ordinalNumbers;
  31174. var ordinalsByTick = this._ordinalNumbersByTick = [];
  31175. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  31176. var tickNum = 0;
  31177. var allCategoryLen = this._ordinalMeta.categories.length;
  31178. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  31179. var ordinalNumber = infoOrdinalNumbers[tickNum];
  31180. ordinalsByTick[tickNum] = ordinalNumber;
  31181. ticksByOrdinal[ordinalNumber] = tickNum;
  31182. } // Handle that `series.data` only covers part of the `axis.category.data`.
  31183. var unusedOrdinal = 0;
  31184. for (; tickNum < allCategoryLen; ++tickNum) {
  31185. while (ticksByOrdinal[unusedOrdinal] != null) {
  31186. unusedOrdinal++;
  31187. }
  31188. ordinalsByTick.push(unusedOrdinal);
  31189. ticksByOrdinal[unusedOrdinal] = tickNum;
  31190. }
  31191. };
  31192. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  31193. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  31194. // where ordinal numbers are used as tick value directly.
  31195. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  31196. };
  31197. /**
  31198. * @usage
  31199. * ```js
  31200. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  31201. *
  31202. * // case0
  31203. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  31204. * // case1
  31205. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  31206. * // case2
  31207. * const coord = axis.dataToCoord(ordinalNumber);
  31208. * ```
  31209. *
  31210. * @param {OrdinalNumber} tickNumber index of display
  31211. */
  31212. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  31213. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  31214. // where ordinal numbers are used as tick value directly.
  31215. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  31216. };
  31217. /**
  31218. * Get item on tick
  31219. */
  31220. OrdinalScale.prototype.getLabel = function (tick) {
  31221. if (!this.isBlank()) {
  31222. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  31223. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  31224. // Return empty if it's not exist.
  31225. return cateogry == null ? '' : cateogry + '';
  31226. }
  31227. };
  31228. OrdinalScale.prototype.count = function () {
  31229. return this._extent[1] - this._extent[0] + 1;
  31230. };
  31231. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  31232. this.unionExtent(data.getApproximateExtent(dim));
  31233. };
  31234. /**
  31235. * @override
  31236. * If value is in extent range
  31237. */
  31238. OrdinalScale.prototype.isInExtentRange = function (value) {
  31239. value = this._getTickNumber(value);
  31240. return this._extent[0] <= value && this._extent[1] >= value;
  31241. };
  31242. OrdinalScale.prototype.getOrdinalMeta = function () {
  31243. return this._ordinalMeta;
  31244. };
  31245. OrdinalScale.prototype.niceTicks = function () {};
  31246. OrdinalScale.prototype.niceExtent = function () {};
  31247. OrdinalScale.type = 'ordinal';
  31248. return OrdinalScale;
  31249. }(Scale);
  31250. Scale.registerClass(OrdinalScale);
  31251. var roundNumber$1 = round;
  31252. var IntervalScale =
  31253. /** @class */
  31254. function (_super) {
  31255. __extends(IntervalScale, _super);
  31256. function IntervalScale() {
  31257. var _this = _super !== null && _super.apply(this, arguments) || this;
  31258. _this.type = 'interval'; // Step is calculated in adjustExtent.
  31259. _this._interval = 0;
  31260. _this._intervalPrecision = 2;
  31261. return _this;
  31262. }
  31263. IntervalScale.prototype.parse = function (val) {
  31264. return val;
  31265. };
  31266. IntervalScale.prototype.contain = function (val) {
  31267. return contain$2(val, this._extent);
  31268. };
  31269. IntervalScale.prototype.normalize = function (val) {
  31270. return normalize$1(val, this._extent);
  31271. };
  31272. IntervalScale.prototype.scale = function (val) {
  31273. return scale$2(val, this._extent);
  31274. };
  31275. IntervalScale.prototype.setExtent = function (start, end) {
  31276. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  31277. if (!isNaN(start)) {
  31278. thisExtent[0] = parseFloat(start);
  31279. }
  31280. if (!isNaN(end)) {
  31281. thisExtent[1] = parseFloat(end);
  31282. }
  31283. };
  31284. IntervalScale.prototype.unionExtent = function (other) {
  31285. var extent = this._extent;
  31286. other[0] < extent[0] && (extent[0] = other[0]);
  31287. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  31288. this.setExtent(extent[0], extent[1]);
  31289. };
  31290. IntervalScale.prototype.getInterval = function () {
  31291. return this._interval;
  31292. };
  31293. IntervalScale.prototype.setInterval = function (interval) {
  31294. this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent
  31295. // We assume user wan't to set both interval, min, max to get a better result
  31296. this._niceExtent = this._extent.slice();
  31297. this._intervalPrecision = getIntervalPrecision(interval);
  31298. };
  31299. /**
  31300. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  31301. */
  31302. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  31303. var interval = this._interval;
  31304. var extent = this._extent;
  31305. var niceTickExtent = this._niceExtent;
  31306. var intervalPrecision = this._intervalPrecision;
  31307. var ticks = []; // If interval is 0, return [];
  31308. if (!interval) {
  31309. return ticks;
  31310. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  31311. var safeLimit = 10000;
  31312. if (extent[0] < niceTickExtent[0]) {
  31313. if (expandToNicedExtent) {
  31314. ticks.push({
  31315. value: roundNumber$1(niceTickExtent[0] - interval, intervalPrecision)
  31316. });
  31317. } else {
  31318. ticks.push({
  31319. value: extent[0]
  31320. });
  31321. }
  31322. }
  31323. var tick = niceTickExtent[0];
  31324. while (tick <= niceTickExtent[1]) {
  31325. ticks.push({
  31326. value: tick
  31327. }); // Avoid rounding error
  31328. tick = roundNumber$1(tick + interval, intervalPrecision);
  31329. if (tick === ticks[ticks.length - 1].value) {
  31330. // Consider out of safe float point, e.g.,
  31331. // -3711126.9907707 + 2e-10 === -3711126.9907707
  31332. break;
  31333. }
  31334. if (ticks.length > safeLimit) {
  31335. return [];
  31336. }
  31337. } // Consider this case: the last item of ticks is smaller
  31338. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  31339. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  31340. if (extent[1] > lastNiceTick) {
  31341. if (expandToNicedExtent) {
  31342. ticks.push({
  31343. value: roundNumber$1(lastNiceTick + interval, intervalPrecision)
  31344. });
  31345. } else {
  31346. ticks.push({
  31347. value: extent[1]
  31348. });
  31349. }
  31350. }
  31351. return ticks;
  31352. };
  31353. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  31354. var ticks = this.getTicks(true);
  31355. var minorTicks = [];
  31356. var extent = this.getExtent();
  31357. for (var i = 1; i < ticks.length; i++) {
  31358. var nextTick = ticks[i];
  31359. var prevTick = ticks[i - 1];
  31360. var count = 0;
  31361. var minorTicksGroup = [];
  31362. var interval = nextTick.value - prevTick.value;
  31363. var minorInterval = interval / splitNumber;
  31364. while (count < splitNumber - 1) {
  31365. var minorTick = roundNumber$1(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  31366. if (minorTick > extent[0] && minorTick < extent[1]) {
  31367. minorTicksGroup.push(minorTick);
  31368. }
  31369. count++;
  31370. }
  31371. minorTicks.push(minorTicksGroup);
  31372. }
  31373. return minorTicks;
  31374. };
  31375. /**
  31376. * @param opt.precision If 'auto', use nice presision.
  31377. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  31378. */
  31379. IntervalScale.prototype.getLabel = function (data, opt) {
  31380. if (data == null) {
  31381. return '';
  31382. }
  31383. var precision = opt && opt.precision;
  31384. if (precision == null) {
  31385. precision = getPrecision(data.value) || 0;
  31386. } else if (precision === 'auto') {
  31387. // Should be more precise then tick.
  31388. precision = this._intervalPrecision;
  31389. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  31390. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  31391. var dataNum = roundNumber$1(data.value, precision, true);
  31392. return addCommas(dataNum);
  31393. };
  31394. /**
  31395. * @param splitNumber By default `5`.
  31396. */
  31397. IntervalScale.prototype.niceTicks = function (splitNumber, minInterval, maxInterval) {
  31398. splitNumber = splitNumber || 5;
  31399. var extent = this._extent;
  31400. var span = extent[1] - extent[0];
  31401. if (!isFinite(span)) {
  31402. return;
  31403. } // User may set axis min 0 and data are all negative
  31404. // FIXME If it needs to reverse ?
  31405. if (span < 0) {
  31406. span = -span;
  31407. extent.reverse();
  31408. }
  31409. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  31410. this._intervalPrecision = result.intervalPrecision;
  31411. this._interval = result.interval;
  31412. this._niceExtent = result.niceTickExtent;
  31413. };
  31414. IntervalScale.prototype.niceExtent = function (opt) {
  31415. var extent = this._extent; // If extent start and end are same, expand them
  31416. if (extent[0] === extent[1]) {
  31417. if (extent[0] !== 0) {
  31418. // Expand extent
  31419. var expandSize = extent[0]; // In the fowllowing case
  31420. // Axis has been fixed max 100
  31421. // Plus data are all 100 and axis extent are [100, 100].
  31422. // Extend to the both side will cause expanded max is larger than fixed max.
  31423. // So only expand to the smaller side.
  31424. if (!opt.fixMax) {
  31425. extent[1] += expandSize / 2;
  31426. extent[0] -= expandSize / 2;
  31427. } else {
  31428. extent[0] -= expandSize / 2;
  31429. }
  31430. } else {
  31431. extent[1] = 1;
  31432. }
  31433. }
  31434. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  31435. if (!isFinite(span)) {
  31436. extent[0] = 0;
  31437. extent[1] = 1;
  31438. }
  31439. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  31440. var interval = this._interval;
  31441. if (!opt.fixMin) {
  31442. extent[0] = roundNumber$1(Math.floor(extent[0] / interval) * interval);
  31443. }
  31444. if (!opt.fixMax) {
  31445. extent[1] = roundNumber$1(Math.ceil(extent[1] / interval) * interval);
  31446. }
  31447. };
  31448. IntervalScale.type = 'interval';
  31449. return IntervalScale;
  31450. }(Scale);
  31451. Scale.registerClass(IntervalScale);
  31452. var STACK_PREFIX = '__ec_stack_';
  31453. var LARGE_BAR_MIN_WIDTH = 0.5;
  31454. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  31455. function getSeriesStackId(seriesModel) {
  31456. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  31457. }
  31458. function getAxisKey(axis) {
  31459. return axis.dim + axis.index;
  31460. }
  31461. /**
  31462. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  31463. */
  31464. function getLayoutOnAxis(opt) {
  31465. var params = [];
  31466. var baseAxis = opt.axis;
  31467. var axisKey = 'axis0';
  31468. if (baseAxis.type !== 'category') {
  31469. return;
  31470. }
  31471. var bandWidth = baseAxis.getBandWidth();
  31472. for (var i = 0; i < opt.count || 0; i++) {
  31473. params.push(defaults({
  31474. bandWidth: bandWidth,
  31475. axisKey: axisKey,
  31476. stackId: STACK_PREFIX + i
  31477. }, opt));
  31478. }
  31479. var widthAndOffsets = doCalBarWidthAndOffset(params);
  31480. var result = [];
  31481. for (var i = 0; i < opt.count; i++) {
  31482. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  31483. item.offsetCenter = item.offset + item.width / 2;
  31484. result.push(item);
  31485. }
  31486. return result;
  31487. }
  31488. function prepareLayoutBarSeries(seriesType, ecModel) {
  31489. var seriesModels = [];
  31490. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31491. // Check series coordinate, do layout for cartesian2d only
  31492. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  31493. seriesModels.push(seriesModel);
  31494. }
  31495. });
  31496. return seriesModels;
  31497. }
  31498. /**
  31499. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  31500. * values.
  31501. * This works for time axes, value axes, and log axes.
  31502. * For a single time axis, return value is in the form like
  31503. * {'x_0': [1000000]}.
  31504. * The value of 1000000 is in milliseconds.
  31505. */
  31506. function getValueAxesMinGaps(barSeries) {
  31507. /**
  31508. * Map from axis.index to values.
  31509. * For a single time axis, axisValues is in the form like
  31510. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  31511. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  31512. * series.
  31513. */
  31514. var axisValues = {};
  31515. each(barSeries, function (seriesModel) {
  31516. var cartesian = seriesModel.coordinateSystem;
  31517. var baseAxis = cartesian.getBaseAxis();
  31518. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  31519. return;
  31520. }
  31521. var data = seriesModel.getData();
  31522. var key = baseAxis.dim + '_' + baseAxis.index;
  31523. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  31524. var store = data.getStore();
  31525. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  31526. var value = store.get(dimIdx, i);
  31527. if (!axisValues[key]) {
  31528. // No previous data for the axis
  31529. axisValues[key] = [value];
  31530. } else {
  31531. // No value in previous series
  31532. axisValues[key].push(value);
  31533. } // Ignore duplicated time values in the same axis
  31534. }
  31535. });
  31536. var axisMinGaps = {};
  31537. for (var key in axisValues) {
  31538. if (axisValues.hasOwnProperty(key)) {
  31539. var valuesInAxis = axisValues[key];
  31540. if (valuesInAxis) {
  31541. // Sort axis values into ascending order to calculate gaps
  31542. valuesInAxis.sort(function (a, b) {
  31543. return a - b;
  31544. });
  31545. var min = null;
  31546. for (var j = 1; j < valuesInAxis.length; ++j) {
  31547. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  31548. if (delta > 0) {
  31549. // Ignore 0 delta because they are of the same axis value
  31550. min = min === null ? delta : Math.min(min, delta);
  31551. }
  31552. } // Set to null if only have one data
  31553. axisMinGaps[key] = min;
  31554. }
  31555. }
  31556. }
  31557. return axisMinGaps;
  31558. }
  31559. function makeColumnLayout(barSeries) {
  31560. var axisMinGaps = getValueAxesMinGaps(barSeries);
  31561. var seriesInfoList = [];
  31562. each(barSeries, function (seriesModel) {
  31563. var cartesian = seriesModel.coordinateSystem;
  31564. var baseAxis = cartesian.getBaseAxis();
  31565. var axisExtent = baseAxis.getExtent();
  31566. var bandWidth;
  31567. if (baseAxis.type === 'category') {
  31568. bandWidth = baseAxis.getBandWidth();
  31569. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  31570. var key = baseAxis.dim + '_' + baseAxis.index;
  31571. var minGap = axisMinGaps[key];
  31572. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  31573. var scale = baseAxis.scale.getExtent();
  31574. var scaleSpan = Math.abs(scale[1] - scale[0]);
  31575. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  31576. } else {
  31577. var data = seriesModel.getData();
  31578. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  31579. }
  31580. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  31581. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  31582. var barMinWidth = parsePercent$1( // barMinWidth by default is 1 in cartesian. Because in value axis,
  31583. // the auto-calculated bar width might be less than 1.
  31584. seriesModel.get('barMinWidth') || 1, bandWidth);
  31585. var barGap = seriesModel.get('barGap');
  31586. var barCategoryGap = seriesModel.get('barCategoryGap');
  31587. seriesInfoList.push({
  31588. bandWidth: bandWidth,
  31589. barWidth: barWidth,
  31590. barMaxWidth: barMaxWidth,
  31591. barMinWidth: barMinWidth,
  31592. barGap: barGap,
  31593. barCategoryGap: barCategoryGap,
  31594. axisKey: getAxisKey(baseAxis),
  31595. stackId: getSeriesStackId(seriesModel)
  31596. });
  31597. });
  31598. return doCalBarWidthAndOffset(seriesInfoList);
  31599. }
  31600. function doCalBarWidthAndOffset(seriesInfoList) {
  31601. // Columns info on each category axis. Key is cartesian name
  31602. var columnsMap = {};
  31603. each(seriesInfoList, function (seriesInfo, idx) {
  31604. var axisKey = seriesInfo.axisKey;
  31605. var bandWidth = seriesInfo.bandWidth;
  31606. var columnsOnAxis = columnsMap[axisKey] || {
  31607. bandWidth: bandWidth,
  31608. remainedWidth: bandWidth,
  31609. autoWidthCount: 0,
  31610. categoryGap: null,
  31611. gap: '20%',
  31612. stacks: {}
  31613. };
  31614. var stacks = columnsOnAxis.stacks;
  31615. columnsMap[axisKey] = columnsOnAxis;
  31616. var stackId = seriesInfo.stackId;
  31617. if (!stacks[stackId]) {
  31618. columnsOnAxis.autoWidthCount++;
  31619. }
  31620. stacks[stackId] = stacks[stackId] || {
  31621. width: 0,
  31622. maxWidth: 0
  31623. }; // Caution: In a single coordinate system, these barGrid attributes
  31624. // will be shared by series. Consider that they have default values,
  31625. // only the attributes set on the last series will work.
  31626. // Do not change this fact unless there will be a break change.
  31627. var barWidth = seriesInfo.barWidth;
  31628. if (barWidth && !stacks[stackId].width) {
  31629. // See #6312, do not restrict width.
  31630. stacks[stackId].width = barWidth;
  31631. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  31632. columnsOnAxis.remainedWidth -= barWidth;
  31633. }
  31634. var barMaxWidth = seriesInfo.barMaxWidth;
  31635. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  31636. var barMinWidth = seriesInfo.barMinWidth;
  31637. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  31638. var barGap = seriesInfo.barGap;
  31639. barGap != null && (columnsOnAxis.gap = barGap);
  31640. var barCategoryGap = seriesInfo.barCategoryGap;
  31641. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  31642. });
  31643. var result = {};
  31644. each(columnsMap, function (columnsOnAxis, coordSysName) {
  31645. result[coordSysName] = {};
  31646. var stacks = columnsOnAxis.stacks;
  31647. var bandWidth = columnsOnAxis.bandWidth;
  31648. var categoryGapPercent = columnsOnAxis.categoryGap;
  31649. if (categoryGapPercent == null) {
  31650. var columnCount = keys(stacks).length; // More columns in one group
  31651. // the spaces between group is smaller. Or the column will be too thin.
  31652. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  31653. }
  31654. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  31655. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  31656. var remainedWidth = columnsOnAxis.remainedWidth;
  31657. var autoWidthCount = columnsOnAxis.autoWidthCount;
  31658. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  31659. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  31660. each(stacks, function (column) {
  31661. var maxWidth = column.maxWidth;
  31662. var minWidth = column.minWidth;
  31663. if (!column.width) {
  31664. var finalWidth = autoWidth;
  31665. if (maxWidth && maxWidth < finalWidth) {
  31666. finalWidth = Math.min(maxWidth, remainedWidth);
  31667. } // `minWidth` has higher priority. `minWidth` decide that wheter the
  31668. // bar is able to be visible. So `minWidth` should not be restricted
  31669. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  31670. // the extreme cases for `value` axis, bars are allowed to overlap
  31671. // with each other if `minWidth` specified.
  31672. if (minWidth && minWidth > finalWidth) {
  31673. finalWidth = minWidth;
  31674. }
  31675. if (finalWidth !== autoWidth) {
  31676. column.width = finalWidth;
  31677. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  31678. autoWidthCount--;
  31679. }
  31680. } else {
  31681. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  31682. // CSS does. Becuase barWidth can be a percent value, where
  31683. // `barMaxWidth` can be used to restrict the final width.
  31684. var finalWidth = column.width;
  31685. if (maxWidth) {
  31686. finalWidth = Math.min(finalWidth, maxWidth);
  31687. } // `minWidth` has higher priority, as described above
  31688. if (minWidth) {
  31689. finalWidth = Math.max(finalWidth, minWidth);
  31690. }
  31691. column.width = finalWidth;
  31692. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  31693. autoWidthCount--;
  31694. }
  31695. }); // Recalculate width again
  31696. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  31697. autoWidth = Math.max(autoWidth, 0);
  31698. var widthSum = 0;
  31699. var lastColumn;
  31700. each(stacks, function (column, idx) {
  31701. if (!column.width) {
  31702. column.width = autoWidth;
  31703. }
  31704. lastColumn = column;
  31705. widthSum += column.width * (1 + barGapPercent);
  31706. });
  31707. if (lastColumn) {
  31708. widthSum -= lastColumn.width * barGapPercent;
  31709. }
  31710. var offset = -widthSum / 2;
  31711. each(stacks, function (column, stackId) {
  31712. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  31713. bandWidth: bandWidth,
  31714. offset: offset,
  31715. width: column.width
  31716. };
  31717. offset += column.width * (1 + barGapPercent);
  31718. });
  31719. });
  31720. return result;
  31721. }
  31722. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  31723. if (barWidthAndOffset && axis) {
  31724. var result = barWidthAndOffset[getAxisKey(axis)];
  31725. if (result != null && seriesModel != null) {
  31726. return result[getSeriesStackId(seriesModel)];
  31727. }
  31728. return result;
  31729. }
  31730. }
  31731. function layout(seriesType, ecModel) {
  31732. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  31733. var barWidthAndOffset = makeColumnLayout(seriesModels);
  31734. var lastStackCoords = {};
  31735. each(seriesModels, function (seriesModel) {
  31736. var data = seriesModel.getData();
  31737. var cartesian = seriesModel.coordinateSystem;
  31738. var baseAxis = cartesian.getBaseAxis();
  31739. var stackId = getSeriesStackId(seriesModel);
  31740. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  31741. var columnOffset = columnLayoutInfo.offset;
  31742. var columnWidth = columnLayoutInfo.width;
  31743. var valueAxis = cartesian.getOtherAxis(baseAxis);
  31744. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  31745. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  31746. data.setLayout({
  31747. bandWidth: columnLayoutInfo.bandWidth,
  31748. offset: columnOffset,
  31749. size: columnWidth
  31750. });
  31751. var valueDim = data.mapDimension(valueAxis.dim);
  31752. var baseDim = data.mapDimension(baseAxis.dim);
  31753. var stacked = isDimensionStacked(data, valueDim);
  31754. var isValueAxisH = valueAxis.isHorizontal();
  31755. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  31756. var store = data.getStore();
  31757. var valueDimIdx = data.getDimensionIndex(valueDim);
  31758. var baseDimIdx = data.getDimensionIndex(baseDim);
  31759. for (var idx = 0, len = store.count(); idx < len; idx++) {
  31760. var value = store.get(valueDimIdx, idx);
  31761. var baseValue = store.get(baseDimIdx, idx);
  31762. var sign = value >= 0 ? 'p' : 'n';
  31763. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  31764. // stackResultDimension directly.
  31765. if (stacked) {
  31766. // Only ordinal axis can be stacked.
  31767. if (!lastStackCoords[stackId][baseValue]) {
  31768. lastStackCoords[stackId][baseValue] = {
  31769. p: valueAxisStart,
  31770. n: valueAxisStart // Negative stack
  31771. };
  31772. } // Should also consider #4243
  31773. baseCoord = lastStackCoords[stackId][baseValue][sign];
  31774. }
  31775. var x = void 0;
  31776. var y = void 0;
  31777. var width = void 0;
  31778. var height = void 0;
  31779. if (isValueAxisH) {
  31780. var coord = cartesian.dataToPoint([value, baseValue]);
  31781. x = baseCoord;
  31782. y = coord[1] + columnOffset;
  31783. width = coord[0] - valueAxisStart;
  31784. height = columnWidth;
  31785. if (Math.abs(width) < barMinHeight) {
  31786. width = (width < 0 ? -1 : 1) * barMinHeight;
  31787. } // Ignore stack from NaN value
  31788. if (!isNaN(width)) {
  31789. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  31790. }
  31791. } else {
  31792. var coord = cartesian.dataToPoint([baseValue, value]);
  31793. x = coord[0] + columnOffset;
  31794. y = baseCoord;
  31795. width = columnWidth;
  31796. height = coord[1] - valueAxisStart;
  31797. if (Math.abs(height) < barMinHeight) {
  31798. // Include zero to has a positive bar
  31799. height = (height <= 0 ? -1 : 1) * barMinHeight;
  31800. } // Ignore stack from NaN value
  31801. if (!isNaN(height)) {
  31802. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  31803. }
  31804. }
  31805. data.setItemLayout(idx, {
  31806. x: x,
  31807. y: y,
  31808. width: width,
  31809. height: height
  31810. });
  31811. }
  31812. });
  31813. } // TODO: Do not support stack in large mode yet.
  31814. var largeLayout = {
  31815. seriesType: 'bar',
  31816. plan: createRenderPlanner(),
  31817. reset: function (seriesModel) {
  31818. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  31819. return;
  31820. }
  31821. var data = seriesModel.getData();
  31822. var cartesian = seriesModel.coordinateSystem;
  31823. var coordLayout = cartesian.master.getRect();
  31824. var baseAxis = cartesian.getBaseAxis();
  31825. var valueAxis = cartesian.getOtherAxis(baseAxis);
  31826. var valueDimI = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  31827. var baseDimI = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  31828. var valueAxisHorizontal = valueAxis.isHorizontal();
  31829. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  31830. var barWidth = retrieveColumnLayout(makeColumnLayout([seriesModel]), baseAxis, seriesModel).width;
  31831. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) {
  31832. // jshint ignore:line
  31833. barWidth = LARGE_BAR_MIN_WIDTH;
  31834. }
  31835. return {
  31836. progress: function (params, data) {
  31837. var count = params.count;
  31838. var largePoints = new LargeArr(count * 2);
  31839. var largeBackgroundPoints = new LargeArr(count * 2);
  31840. var largeDataIndices = new LargeArr(count);
  31841. var dataIndex;
  31842. var coord = [];
  31843. var valuePair = [];
  31844. var pointsOffset = 0;
  31845. var idxOffset = 0;
  31846. var store = data.getStore();
  31847. while ((dataIndex = params.next()) != null) {
  31848. valuePair[valueDimIdx] = store.get(valueDimI, dataIndex);
  31849. valuePair[1 - valueDimIdx] = store.get(baseDimI, dataIndex);
  31850. coord = cartesian.dataToPoint(valuePair, null); // Data index might not be in order, depends on `progressiveChunkMode`.
  31851. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];
  31852. largePoints[pointsOffset++] = coord[0];
  31853. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coord[1] : coordLayout.y + coordLayout.height;
  31854. largePoints[pointsOffset++] = coord[1];
  31855. largeDataIndices[idxOffset++] = dataIndex;
  31856. }
  31857. data.setLayout({
  31858. largePoints: largePoints,
  31859. largeDataIndices: largeDataIndices,
  31860. largeBackgroundPoints: largeBackgroundPoints,
  31861. barWidth: barWidth,
  31862. valueAxisStart: getValueAxisStart(baseAxis, valueAxis),
  31863. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  31864. valueAxisHorizontal: valueAxisHorizontal
  31865. });
  31866. }
  31867. };
  31868. }
  31869. };
  31870. function isOnCartesian(seriesModel) {
  31871. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  31872. }
  31873. function isInLargeMode(seriesModel) {
  31874. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  31875. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  31876. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  31877. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  31878. }
  31879. var bisect = function (a, x, lo, hi) {
  31880. while (lo < hi) {
  31881. var mid = lo + hi >>> 1;
  31882. if (a[mid][1] < x) {
  31883. lo = mid + 1;
  31884. } else {
  31885. hi = mid;
  31886. }
  31887. }
  31888. return lo;
  31889. };
  31890. var TimeScale =
  31891. /** @class */
  31892. function (_super) {
  31893. __extends(TimeScale, _super);
  31894. function TimeScale(settings) {
  31895. var _this = _super.call(this, settings) || this;
  31896. _this.type = 'time';
  31897. return _this;
  31898. }
  31899. /**
  31900. * Get label is mainly for other components like dataZoom, tooltip.
  31901. */
  31902. TimeScale.prototype.getLabel = function (tick) {
  31903. var useUTC = this.getSetting('useUTC');
  31904. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  31905. };
  31906. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  31907. var isUTC = this.getSetting('useUTC');
  31908. var lang = this.getSetting('locale');
  31909. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  31910. };
  31911. /**
  31912. * @override
  31913. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  31914. */
  31915. TimeScale.prototype.getTicks = function (expandToNicedExtent) {
  31916. var interval = this._interval;
  31917. var extent = this._extent;
  31918. var ticks = []; // If interval is 0, return [];
  31919. if (!interval) {
  31920. return ticks;
  31921. }
  31922. ticks.push({
  31923. value: extent[0],
  31924. level: 0
  31925. });
  31926. var useUTC = this.getSetting('useUTC');
  31927. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  31928. ticks = ticks.concat(innerTicks);
  31929. ticks.push({
  31930. value: extent[1],
  31931. level: 0
  31932. });
  31933. return ticks;
  31934. };
  31935. TimeScale.prototype.niceExtent = function (opt) {
  31936. var extent = this._extent; // If extent start and end are same, expand them
  31937. if (extent[0] === extent[1]) {
  31938. // Expand extent
  31939. extent[0] -= ONE_DAY;
  31940. extent[1] += ONE_DAY;
  31941. } // If there are no data and extent are [Infinity, -Infinity]
  31942. if (extent[1] === -Infinity && extent[0] === Infinity) {
  31943. var d = new Date();
  31944. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  31945. extent[0] = extent[1] - ONE_DAY;
  31946. }
  31947. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  31948. };
  31949. TimeScale.prototype.niceTicks = function (approxTickNum, minInterval, maxInterval) {
  31950. approxTickNum = approxTickNum || 10;
  31951. var extent = this._extent;
  31952. var span = extent[1] - extent[0];
  31953. this._approxInterval = span / approxTickNum;
  31954. if (minInterval != null && this._approxInterval < minInterval) {
  31955. this._approxInterval = minInterval;
  31956. }
  31957. if (maxInterval != null && this._approxInterval > maxInterval) {
  31958. this._approxInterval = maxInterval;
  31959. }
  31960. var scaleIntervalsLen = scaleIntervals.length;
  31961. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  31962. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  31963. // We check one more level to avoid the ticks are to sparse in some case.
  31964. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  31965. };
  31966. TimeScale.prototype.parse = function (val) {
  31967. // val might be float.
  31968. return typeof val === 'number' ? val : +parseDate(val);
  31969. };
  31970. TimeScale.prototype.contain = function (val) {
  31971. return contain$2(this.parse(val), this._extent);
  31972. };
  31973. TimeScale.prototype.normalize = function (val) {
  31974. return normalize$1(this.parse(val), this._extent);
  31975. };
  31976. TimeScale.prototype.scale = function (val) {
  31977. return scale$2(val, this._extent);
  31978. };
  31979. TimeScale.type = 'time';
  31980. return TimeScale;
  31981. }(IntervalScale);
  31982. /**
  31983. * This implementation was originally copied from "d3.js"
  31984. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  31985. * with some modifications made for this program.
  31986. * See the license statement at the head of this file.
  31987. */
  31988. var scaleIntervals = [// Format interval
  31989. ['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
  31990. ];
  31991. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  31992. var dateA = parseDate(valueA);
  31993. var dateB = parseDate(valueB);
  31994. var isSame = function (unit) {
  31995. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  31996. };
  31997. var isSameYear = function () {
  31998. return isSame('year');
  31999. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  32000. // const isSameQuater = () => isSameYear() && isSame('quarter');
  32001. var isSameMonth = function () {
  32002. return isSameYear() && isSame('month');
  32003. };
  32004. var isSameDay = function () {
  32005. return isSameMonth() && isSame('day');
  32006. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  32007. var isSameHour = function () {
  32008. return isSameDay() && isSame('hour');
  32009. };
  32010. var isSameMinute = function () {
  32011. return isSameHour() && isSame('minute');
  32012. };
  32013. var isSameSecond = function () {
  32014. return isSameMinute() && isSame('second');
  32015. };
  32016. var isSameMilliSecond = function () {
  32017. return isSameSecond() && isSame('millisecond');
  32018. };
  32019. switch (unit) {
  32020. case 'year':
  32021. return isSameYear();
  32022. case 'month':
  32023. return isSameMonth();
  32024. case 'day':
  32025. return isSameDay();
  32026. case 'hour':
  32027. return isSameHour();
  32028. case 'minute':
  32029. return isSameMinute();
  32030. case 'second':
  32031. return isSameSecond();
  32032. case 'millisecond':
  32033. return isSameMilliSecond();
  32034. }
  32035. } // const primaryUnitGetters = {
  32036. // year: fullYearGetterName(),
  32037. // month: monthGetterName(),
  32038. // day: dateGetterName(),
  32039. // hour: hoursGetterName(),
  32040. // minute: minutesGetterName(),
  32041. // second: secondsGetterName(),
  32042. // millisecond: millisecondsGetterName()
  32043. // };
  32044. // const primaryUnitUTCGetters = {
  32045. // year: fullYearGetterName(true),
  32046. // month: monthGetterName(true),
  32047. // day: dateGetterName(true),
  32048. // hour: hoursGetterName(true),
  32049. // minute: minutesGetterName(true),
  32050. // second: secondsGetterName(true),
  32051. // millisecond: millisecondsGetterName(true)
  32052. // };
  32053. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  32054. // step = step || 1;
  32055. // switch (getPrimaryTimeUnit(unitName)) {
  32056. // case 'year':
  32057. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  32058. // break;
  32059. // case 'month':
  32060. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  32061. // break;
  32062. // case 'day':
  32063. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  32064. // break;
  32065. // case 'hour':
  32066. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  32067. // break;
  32068. // case 'minute':
  32069. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  32070. // break;
  32071. // case 'second':
  32072. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  32073. // break;
  32074. // case 'millisecond':
  32075. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  32076. // break;
  32077. // }
  32078. // return date.getTime();
  32079. // }
  32080. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  32081. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  32082. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  32083. function getDateInterval(approxInterval, daysInMonth) {
  32084. approxInterval /= ONE_DAY;
  32085. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick betwen two month.
  32086. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  32087. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  32088. }
  32089. function getMonthInterval(approxInterval) {
  32090. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  32091. approxInterval /= APPROX_ONE_MONTH;
  32092. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  32093. }
  32094. function getHourInterval(approxInterval) {
  32095. approxInterval /= ONE_HOUR;
  32096. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  32097. }
  32098. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  32099. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  32100. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  32101. }
  32102. function getMillisecondsInterval(approxInterval) {
  32103. return nice(approxInterval, true);
  32104. }
  32105. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  32106. var outDate = new Date(date);
  32107. switch (getPrimaryTimeUnit(unitName)) {
  32108. case 'year':
  32109. case 'month':
  32110. outDate[monthSetterName(isUTC)](0);
  32111. case 'day':
  32112. outDate[dateSetterName(isUTC)](1);
  32113. case 'hour':
  32114. outDate[hoursSetterName(isUTC)](0);
  32115. case 'minute':
  32116. outDate[minutesSetterName(isUTC)](0);
  32117. case 'second':
  32118. outDate[secondsSetterName(isUTC)](0);
  32119. outDate[millisecondsSetterName(isUTC)](0);
  32120. }
  32121. return outDate.getTime();
  32122. }
  32123. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  32124. var safeLimit = 10000;
  32125. var unitNames = timeUnits;
  32126. var iter = 0;
  32127. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  32128. var date = new Date(minTimestamp);
  32129. var dateTime = minTimestamp;
  32130. var d = date[getMethodName](); // if (isDate) {
  32131. // d -= 1; // Starts with 0; PENDING
  32132. // }
  32133. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  32134. out.push({
  32135. value: dateTime
  32136. });
  32137. d += interval;
  32138. date[setMethodName](d);
  32139. dateTime = date.getTime();
  32140. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  32141. out.push({
  32142. value: dateTime,
  32143. notAdd: true
  32144. });
  32145. }
  32146. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  32147. var newAddedTicks = [];
  32148. var isFirstLevel = !lastLevelTicks.length;
  32149. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  32150. return;
  32151. }
  32152. if (isFirstLevel) {
  32153. lastLevelTicks = [{
  32154. // TODO Optimize. Not include so may ticks.
  32155. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  32156. }, {
  32157. value: extent[1]
  32158. }];
  32159. }
  32160. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  32161. var startTick = lastLevelTicks[i].value;
  32162. var endTick = lastLevelTicks[i + 1].value;
  32163. if (startTick === endTick) {
  32164. continue;
  32165. }
  32166. var interval = void 0;
  32167. var getterName = void 0;
  32168. var setterName = void 0;
  32169. var isDate = false;
  32170. switch (unitName) {
  32171. case 'year':
  32172. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  32173. getterName = fullYearGetterName(isUTC);
  32174. setterName = fullYearSetterName(isUTC);
  32175. break;
  32176. case 'half-year':
  32177. case 'quarter':
  32178. case 'month':
  32179. interval = getMonthInterval(approxInterval);
  32180. getterName = monthGetterName(isUTC);
  32181. setterName = monthSetterName(isUTC);
  32182. break;
  32183. case 'week': // PENDING If week is added. Ignore day.
  32184. case 'half-week':
  32185. case 'day':
  32186. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  32187. getterName = dateGetterName(isUTC);
  32188. setterName = dateSetterName(isUTC);
  32189. isDate = true;
  32190. break;
  32191. case 'half-day':
  32192. case 'quarter-day':
  32193. case 'hour':
  32194. interval = getHourInterval(approxInterval);
  32195. getterName = hoursGetterName(isUTC);
  32196. setterName = hoursSetterName(isUTC);
  32197. break;
  32198. case 'minute':
  32199. interval = getMinutesAndSecondsInterval(approxInterval, true);
  32200. getterName = minutesGetterName(isUTC);
  32201. setterName = minutesSetterName(isUTC);
  32202. break;
  32203. case 'second':
  32204. interval = getMinutesAndSecondsInterval(approxInterval, false);
  32205. getterName = secondsGetterName(isUTC);
  32206. setterName = secondsSetterName(isUTC);
  32207. break;
  32208. case 'millisecond':
  32209. interval = getMillisecondsInterval(approxInterval);
  32210. getterName = millisecondsGetterName(isUTC);
  32211. setterName = millisecondsSetterName(isUTC);
  32212. break;
  32213. }
  32214. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  32215. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  32216. // Add nearest years to the left extent.
  32217. levelTicks.unshift({
  32218. value: levelTicks[0].value - interval
  32219. });
  32220. }
  32221. }
  32222. for (var i = 0; i < newAddedTicks.length; i++) {
  32223. levelTicks.push(newAddedTicks[i]);
  32224. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  32225. return newAddedTicks;
  32226. }
  32227. var levelsTicks = [];
  32228. var currentLevelTicks = [];
  32229. var tickCount = 0;
  32230. var lastLevelTickCount = 0;
  32231. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  32232. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  32233. if (!isPrimaryTimeUnit(unitNames[i])) {
  32234. // TODO
  32235. continue;
  32236. }
  32237. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  32238. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  32239. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  32240. if (currentLevelTicks.length) {
  32241. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  32242. currentLevelTicks.sort(function (a, b) {
  32243. return a.value - b.value;
  32244. });
  32245. var levelTicksRemoveDuplicated = [];
  32246. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  32247. var tickValue = currentLevelTicks[i_1].value;
  32248. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  32249. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  32250. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  32251. tickCount++;
  32252. }
  32253. }
  32254. }
  32255. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  32256. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  32257. break;
  32258. } // Only treat primary time unit as one level.
  32259. levelsTicks.push(levelTicksRemoveDuplicated);
  32260. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  32261. break;
  32262. }
  32263. } // Reset if next unitName is primary
  32264. currentLevelTicks = [];
  32265. }
  32266. }
  32267. if ("development" !== 'production') {
  32268. if (iter >= safeLimit) {
  32269. warn('Exceed safe limit.');
  32270. }
  32271. }
  32272. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  32273. return filter(levelTicks, function (tick) {
  32274. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  32275. });
  32276. }), function (levelTicks) {
  32277. return levelTicks.length > 0;
  32278. });
  32279. var ticks = [];
  32280. var maxLevel = levelsTicksInExtent.length - 1;
  32281. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  32282. var levelTicks = levelsTicksInExtent[i];
  32283. for (var k = 0; k < levelTicks.length; ++k) {
  32284. ticks.push({
  32285. value: levelTicks[k].value,
  32286. level: maxLevel - i
  32287. });
  32288. }
  32289. }
  32290. ticks.sort(function (a, b) {
  32291. return a.value - b.value;
  32292. }); // Remove duplicates
  32293. var result = [];
  32294. for (var i = 0; i < ticks.length; ++i) {
  32295. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  32296. result.push(ticks[i]);
  32297. }
  32298. }
  32299. return result;
  32300. }
  32301. Scale.registerClass(TimeScale);
  32302. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  32303. var intervalScaleProto = IntervalScale.prototype;
  32304. var roundingErrorFix = round;
  32305. var mathFloor = Math.floor;
  32306. var mathCeil = Math.ceil;
  32307. var mathPow$1 = Math.pow;
  32308. var mathLog = Math.log;
  32309. var LogScale =
  32310. /** @class */
  32311. function (_super) {
  32312. __extends(LogScale, _super);
  32313. function LogScale() {
  32314. var _this = _super !== null && _super.apply(this, arguments) || this;
  32315. _this.type = 'log';
  32316. _this.base = 10;
  32317. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  32318. _this._interval = 0;
  32319. return _this;
  32320. }
  32321. /**
  32322. * @param Whether expand the ticks to niced extent.
  32323. */
  32324. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  32325. var originalScale = this._originalScale;
  32326. var extent = this._extent;
  32327. var originalExtent = originalScale.getExtent();
  32328. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  32329. return map(ticks, function (tick) {
  32330. var val = tick.value;
  32331. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  32332. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  32333. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  32334. return {
  32335. value: powVal
  32336. };
  32337. }, this);
  32338. };
  32339. LogScale.prototype.setExtent = function (start, end) {
  32340. var base = this.base;
  32341. start = mathLog(start) / mathLog(base);
  32342. end = mathLog(end) / mathLog(base);
  32343. intervalScaleProto.setExtent.call(this, start, end);
  32344. };
  32345. /**
  32346. * @return {number} end
  32347. */
  32348. LogScale.prototype.getExtent = function () {
  32349. var base = this.base;
  32350. var extent = scaleProto.getExtent.call(this);
  32351. extent[0] = mathPow$1(base, extent[0]);
  32352. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  32353. var originalScale = this._originalScale;
  32354. var originalExtent = originalScale.getExtent();
  32355. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  32356. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  32357. return extent;
  32358. };
  32359. LogScale.prototype.unionExtent = function (extent) {
  32360. this._originalScale.unionExtent(extent);
  32361. var base = this.base;
  32362. extent[0] = mathLog(extent[0]) / mathLog(base);
  32363. extent[1] = mathLog(extent[1]) / mathLog(base);
  32364. scaleProto.unionExtent.call(this, extent);
  32365. };
  32366. LogScale.prototype.unionExtentFromData = function (data, dim) {
  32367. // TODO
  32368. // filter value that <= 0
  32369. this.unionExtent(data.getApproximateExtent(dim));
  32370. };
  32371. /**
  32372. * Update interval and extent of intervals for nice ticks
  32373. * @param approxTickNum default 10 Given approx tick number
  32374. */
  32375. LogScale.prototype.niceTicks = function (approxTickNum) {
  32376. approxTickNum = approxTickNum || 10;
  32377. var extent = this._extent;
  32378. var span = extent[1] - extent[0];
  32379. if (span === Infinity || span <= 0) {
  32380. return;
  32381. }
  32382. var interval = quantity(span);
  32383. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  32384. if (err <= 0.5) {
  32385. interval *= 10;
  32386. } // Interval should be integer
  32387. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  32388. interval *= 10;
  32389. }
  32390. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  32391. this._interval = interval;
  32392. this._niceExtent = niceExtent;
  32393. };
  32394. LogScale.prototype.niceExtent = function (opt) {
  32395. intervalScaleProto.niceExtent.call(this, opt);
  32396. this._fixMin = opt.fixMin;
  32397. this._fixMax = opt.fixMax;
  32398. };
  32399. LogScale.prototype.parse = function (val) {
  32400. return val;
  32401. };
  32402. LogScale.prototype.contain = function (val) {
  32403. val = mathLog(val) / mathLog(this.base);
  32404. return contain$2(val, this._extent);
  32405. };
  32406. LogScale.prototype.normalize = function (val) {
  32407. val = mathLog(val) / mathLog(this.base);
  32408. return normalize$1(val, this._extent);
  32409. };
  32410. LogScale.prototype.scale = function (val) {
  32411. val = scale$2(val, this._extent);
  32412. return mathPow$1(this.base, val);
  32413. };
  32414. LogScale.type = 'log';
  32415. return LogScale;
  32416. }(Scale);
  32417. var proto = LogScale.prototype;
  32418. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  32419. proto.getLabel = intervalScaleProto.getLabel;
  32420. function fixRoundingError(val, originalVal) {
  32421. return roundingErrorFix(val, getPrecision(originalVal));
  32422. }
  32423. Scale.registerClass(LogScale);
  32424. var ScaleRawExtentInfo =
  32425. /** @class */
  32426. function () {
  32427. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  32428. originalExtent) {
  32429. this._prepareParams(scale, model, originalExtent);
  32430. }
  32431. /**
  32432. * Parameters depending on ouside (like model, user callback)
  32433. * are prepared and fixed here.
  32434. */
  32435. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  32436. dataExtent) {
  32437. if (dataExtent[1] < dataExtent[0]) {
  32438. dataExtent = [NaN, NaN];
  32439. }
  32440. this._dataMin = dataExtent[0];
  32441. this._dataMax = dataExtent[1];
  32442. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  32443. this._needCrossZero = model.getNeedCrossZero && model.getNeedCrossZero();
  32444. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  32445. if (isFunction(modelMinRaw)) {
  32446. // This callback alway provide users the full data extent (before data filtered).
  32447. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  32448. min: dataExtent[0],
  32449. max: dataExtent[1]
  32450. }));
  32451. } else if (modelMinRaw !== 'dataMin') {
  32452. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  32453. }
  32454. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  32455. if (isFunction(modelMaxRaw)) {
  32456. // This callback alway provide users the full data extent (before data filtered).
  32457. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  32458. min: dataExtent[0],
  32459. max: dataExtent[1]
  32460. }));
  32461. } else if (modelMaxRaw !== 'dataMax') {
  32462. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  32463. }
  32464. if (isOrdinal) {
  32465. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  32466. // and progressive rendering is using, here the category result might just only contain
  32467. // the processed chunk rather than the entire result.
  32468. this._axisDataLen = model.getCategories().length;
  32469. } else {
  32470. var boundaryGap = model.get('boundaryGap');
  32471. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  32472. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  32473. if ("development" !== 'production') {
  32474. 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.');
  32475. }
  32476. this._boundaryGapInner = [0, 0];
  32477. } else {
  32478. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  32479. }
  32480. }
  32481. };
  32482. /**
  32483. * Calculate extent by prepared parameters.
  32484. * This method has no external dependency and can be called duplicatedly,
  32485. * getting the same result.
  32486. * If parameters changed, should call this method to recalcuate.
  32487. */
  32488. ScaleRawExtentInfo.prototype.calculate = function () {
  32489. // Notice: When min/max is not set (that is, when there are null/undefined,
  32490. // which is the most common case), these cases should be ensured:
  32491. // (1) For 'ordinal', show all axis.data.
  32492. // (2) For others:
  32493. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  32494. // disabled).
  32495. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  32496. // be the result that originalExtent enlarged by boundaryGap.
  32497. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  32498. var isOrdinal = this._isOrdinal;
  32499. var dataMin = this._dataMin;
  32500. var dataMax = this._dataMax;
  32501. var axisDataLen = this._axisDataLen;
  32502. var boundaryGapInner = this._boundaryGapInner;
  32503. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  32504. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  32505. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  32506. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  32507. var minFixed = min != null;
  32508. var maxFixed = max != null;
  32509. if (min == null) {
  32510. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  32511. }
  32512. if (max == null) {
  32513. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  32514. }
  32515. (min == null || !isFinite(min)) && (min = NaN);
  32516. (max == null || !isFinite(max)) && (max = NaN);
  32517. if (min > max) {
  32518. min = NaN;
  32519. max = NaN;
  32520. }
  32521. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  32522. if (this._needCrossZero) {
  32523. // Axis is over zero and min is not set
  32524. if (min > 0 && max > 0 && !minFixed) {
  32525. min = 0; // minFixed = true;
  32526. } // Axis is under zero and max is not set
  32527. if (min < 0 && max < 0 && !maxFixed) {
  32528. max = 0; // maxFixed = true;
  32529. } // PENDING:
  32530. // When `needCrossZero` and all data is positive/negative, should it be ensured
  32531. // that the results processed by boundaryGap are positive/negative?
  32532. // If so, here `minFixed`/`maxFixed` need to be set.
  32533. }
  32534. var determinedMin = this._determinedMin;
  32535. var determinedMax = this._determinedMax;
  32536. if (determinedMin != null) {
  32537. min = determinedMin;
  32538. minFixed = true;
  32539. }
  32540. if (determinedMax != null) {
  32541. max = determinedMax;
  32542. maxFixed = true;
  32543. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  32544. // `NaN` means min/max axis is blank.
  32545. return {
  32546. min: min,
  32547. max: max,
  32548. minFixed: minFixed,
  32549. maxFixed: maxFixed,
  32550. isBlank: isBlank
  32551. };
  32552. };
  32553. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  32554. if ("development" !== 'production') {
  32555. assert(!this.frozen);
  32556. }
  32557. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  32558. };
  32559. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  32560. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  32561. if ("development" !== 'production') {
  32562. assert(!this.frozen // Earse them usually means logic flaw.
  32563. && this[attr] == null);
  32564. }
  32565. this[attr] = val;
  32566. };
  32567. ScaleRawExtentInfo.prototype.freeze = function () {
  32568. // @ts-ignore
  32569. this.frozen = true;
  32570. };
  32571. return ScaleRawExtentInfo;
  32572. }();
  32573. var DETERMINED_MIN_MAX_ATTR = {
  32574. min: '_determinedMin',
  32575. max: '_determinedMax'
  32576. };
  32577. var DATA_MIN_MAX_ATTR = {
  32578. min: '_dataMin',
  32579. max: '_dataMax'
  32580. };
  32581. /**
  32582. * Get scale min max and related info only depends on model settings.
  32583. * This method can be called after coordinate system created.
  32584. * For example, in data processing stage.
  32585. *
  32586. * Scale extent info probably be required multiple times during a workflow.
  32587. * For example:
  32588. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  32589. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  32590. * (3) `coordSys.update` use it to finally decide the scale extent.
  32591. * But the callback of `min`/`max` should not be called multiple times.
  32592. * The code below should not be implemented repeatedly either.
  32593. * So we cache the result in the scale instance, which will be recreated at the begining
  32594. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  32595. */
  32596. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  32597. originalExtent) {
  32598. // Do not permit to recreate.
  32599. var rawExtentInfo = scale.rawExtentInfo;
  32600. if (rawExtentInfo) {
  32601. return rawExtentInfo;
  32602. }
  32603. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  32604. scale.rawExtentInfo = rawExtentInfo;
  32605. return rawExtentInfo;
  32606. }
  32607. function parseAxisModelMinMax(scale, minMax) {
  32608. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  32609. }
  32610. /**
  32611. * Get axis scale extent before niced.
  32612. * Item of returned array can only be number (including Infinity and NaN).
  32613. *
  32614. * Caution:
  32615. * Precondition of calling this method:
  32616. * The scale extent has been initialized using series data extent via
  32617. * `scale.setExtent` or `scale.unionExtentFromData`;
  32618. */
  32619. function getScaleExtent(scale, model) {
  32620. var scaleType = scale.type;
  32621. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  32622. scale.setBlank(rawExtentResult.isBlank);
  32623. var min = rawExtentResult.min;
  32624. 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
  32625. // is base axis
  32626. // FIXME
  32627. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  32628. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  32629. // Should not depend on series type `bar`?
  32630. // (3) Fix that might overlap when using dataZoom.
  32631. // (4) Consider other chart types using `barGrid`?
  32632. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  32633. var ecModel = model.ecModel;
  32634. if (ecModel && scaleType === 'time'
  32635. /*|| scaleType === 'interval' */
  32636. ) {
  32637. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  32638. var isBaseAxisAndHasBarSeries_1 = false;
  32639. each(barSeriesModels, function (seriesModel) {
  32640. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  32641. });
  32642. if (isBaseAxisAndHasBarSeries_1) {
  32643. // Calculate placement of bars on axis. TODO should be decoupled
  32644. // with barLayout
  32645. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  32646. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  32647. min = adjustedScale.min;
  32648. max = adjustedScale.max;
  32649. }
  32650. }
  32651. return {
  32652. extent: [min, max],
  32653. // "fix" means "fixed", the value should not be
  32654. // changed in the subsequent steps.
  32655. fixMin: rawExtentResult.minFixed,
  32656. fixMax: rawExtentResult.maxFixed
  32657. };
  32658. }
  32659. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  32660. barWidthAndOffset) {
  32661. // Get Axis Length
  32662. var axisExtent = model.axis.getExtent();
  32663. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  32664. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  32665. if (barsOnCurrentAxis === undefined) {
  32666. return {
  32667. min: min,
  32668. max: max
  32669. };
  32670. }
  32671. var minOverflow = Infinity;
  32672. each(barsOnCurrentAxis, function (item) {
  32673. minOverflow = Math.min(item.offset, minOverflow);
  32674. });
  32675. var maxOverflow = -Infinity;
  32676. each(barsOnCurrentAxis, function (item) {
  32677. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  32678. });
  32679. minOverflow = Math.abs(minOverflow);
  32680. maxOverflow = Math.abs(maxOverflow);
  32681. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  32682. var oldRange = max - min;
  32683. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  32684. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  32685. max += overflowBuffer * (maxOverflow / totalOverFlow);
  32686. min -= overflowBuffer * (minOverflow / totalOverFlow);
  32687. return {
  32688. min: min,
  32689. max: max
  32690. };
  32691. } // Precondition of calling this method:
  32692. // The scale extent has been initailized using series data extent via
  32693. // `scale.setExtent` or `scale.unionExtentFromData`;
  32694. function niceScaleExtent(scale, model) {
  32695. var extentInfo = getScaleExtent(scale, model);
  32696. var extent = extentInfo.extent;
  32697. var splitNumber = model.get('splitNumber');
  32698. if (scale instanceof LogScale) {
  32699. scale.base = model.get('logBase');
  32700. }
  32701. var scaleType = scale.type;
  32702. scale.setExtent(extent[0], extent[1]);
  32703. scale.niceExtent({
  32704. splitNumber: splitNumber,
  32705. fixMin: extentInfo.fixMin,
  32706. fixMax: extentInfo.fixMax,
  32707. minInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('minInterval') : null,
  32708. maxInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('maxInterval') : null
  32709. }); // If some one specified the min, max. And the default calculated interval
  32710. // is not good enough. He can specify the interval. It is often appeared
  32711. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  32712. // to be 60.
  32713. // FIXME
  32714. var interval = model.get('interval');
  32715. if (interval != null) {
  32716. scale.setInterval && scale.setInterval(interval);
  32717. }
  32718. }
  32719. /**
  32720. * @param axisType Default retrieve from model.type
  32721. */
  32722. function createScaleByModel(model, axisType) {
  32723. axisType = axisType || model.get('type');
  32724. if (axisType) {
  32725. switch (axisType) {
  32726. // Buildin scale
  32727. case 'category':
  32728. return new OrdinalScale({
  32729. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  32730. extent: [Infinity, -Infinity]
  32731. });
  32732. case 'time':
  32733. return new TimeScale({
  32734. locale: model.ecModel.getLocaleModel(),
  32735. useUTC: model.ecModel.get('useUTC')
  32736. });
  32737. default:
  32738. // case 'value'/'interval', 'log', or others.
  32739. return new (Scale.getClass(axisType) || IntervalScale)();
  32740. }
  32741. }
  32742. }
  32743. /**
  32744. * Check if the axis cross 0
  32745. */
  32746. function ifAxisCrossZero(axis) {
  32747. var dataExtent = axis.scale.getExtent();
  32748. var min = dataExtent[0];
  32749. var max = dataExtent[1];
  32750. return !(min > 0 && max > 0 || min < 0 && max < 0);
  32751. }
  32752. /**
  32753. * @param axis
  32754. * @return Label formatter function.
  32755. * param: {number} tickValue,
  32756. * param: {number} idx, the index in all ticks.
  32757. * If category axis, this param is not required.
  32758. * return: {string} label string.
  32759. */
  32760. function makeLabelFormatter(axis) {
  32761. var labelFormatter = axis.getLabelModel().get('formatter');
  32762. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  32763. if (axis.scale.type === 'time') {
  32764. return function (tpl) {
  32765. return function (tick, idx) {
  32766. return axis.scale.getFormattedLabel(tick, idx, tpl);
  32767. };
  32768. }(labelFormatter);
  32769. } else if (typeof labelFormatter === 'string') {
  32770. return function (tpl) {
  32771. return function (tick) {
  32772. // For category axis, get raw value; for numeric axis,
  32773. // get formatted label like '1,333,444'.
  32774. var label = axis.scale.getLabel(tick);
  32775. var text = tpl.replace('{value}', label != null ? label : '');
  32776. return text;
  32777. };
  32778. }(labelFormatter);
  32779. } else if (typeof labelFormatter === 'function') {
  32780. return function (cb) {
  32781. return function (tick, idx) {
  32782. // The original intention of `idx` is "the index of the tick in all ticks".
  32783. // But the previous implementation of category axis do not consider the
  32784. // `axisLabel.interval`, which cause that, for example, the `interval` is
  32785. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  32786. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  32787. // the definition here for back compatibility.
  32788. if (categoryTickStart != null) {
  32789. idx = tick.value - categoryTickStart;
  32790. }
  32791. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  32792. level: tick.level
  32793. } : null);
  32794. };
  32795. }(labelFormatter);
  32796. } else {
  32797. return function (tick) {
  32798. return axis.scale.getLabel(tick);
  32799. };
  32800. }
  32801. }
  32802. function getAxisRawValue(axis, tick) {
  32803. // In category axis with data zoom, tick is not the original
  32804. // index of axis.data. So tick should not be exposed to user
  32805. // in category axis.
  32806. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  32807. }
  32808. /**
  32809. * @param axis
  32810. * @return Be null/undefined if no labels.
  32811. */
  32812. function estimateLabelUnionRect(axis) {
  32813. var axisModel = axis.model;
  32814. var scale = axis.scale;
  32815. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  32816. return;
  32817. }
  32818. var realNumberScaleTicks;
  32819. var tickCount;
  32820. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  32821. if (scale instanceof OrdinalScale) {
  32822. tickCount = scale.count();
  32823. } else {
  32824. realNumberScaleTicks = scale.getTicks();
  32825. tickCount = realNumberScaleTicks.length;
  32826. }
  32827. var axisLabelModel = axis.getLabelModel();
  32828. var labelFormatter = makeLabelFormatter(axis);
  32829. var rect;
  32830. var step = 1; // Simple optimization for large amount of labels
  32831. if (tickCount > 40) {
  32832. step = Math.ceil(tickCount / 40);
  32833. }
  32834. for (var i = 0; i < tickCount; i += step) {
  32835. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  32836. value: categoryScaleExtent[0] + i
  32837. };
  32838. var label = labelFormatter(tick, i);
  32839. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  32840. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  32841. rect ? rect.union(singleRect) : rect = singleRect;
  32842. }
  32843. return rect;
  32844. }
  32845. function rotateTextRect(textRect, rotate) {
  32846. var rotateRadians = rotate * Math.PI / 180;
  32847. var beforeWidth = textRect.width;
  32848. var beforeHeight = textRect.height;
  32849. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  32850. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  32851. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  32852. return rotatedRect;
  32853. }
  32854. /**
  32855. * @param model axisLabelModel or axisTickModel
  32856. * @return {number|String} Can be null|'auto'|number|function
  32857. */
  32858. function getOptionCategoryInterval(model) {
  32859. var interval = model.get('interval');
  32860. return interval == null ? 'auto' : interval;
  32861. }
  32862. /**
  32863. * Set `categoryInterval` as 0 implicitly indicates that
  32864. * show all labels reguardless of overlap.
  32865. * @param {Object} axis axisModel.axis
  32866. */
  32867. function shouldShowAllLabels(axis) {
  32868. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  32869. }
  32870. function getDataDimensionsOnAxis(data, axisDim) {
  32871. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  32872. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  32873. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  32874. // there has been stacked result dim?
  32875. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  32876. // For example, the extent of the original dimension
  32877. // is [0.1, 0.5], the extent of the `stackResultDimension`
  32878. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  32879. // because there is no graphic corresponding to [0.1, 0.5].
  32880. // See the case in `test/area-stack.html` `main1`, where area line
  32881. // stack needs `yAxis` not start from 0.
  32882. dataDimMap[getStackedDimension(data, dataDim)] = true;
  32883. });
  32884. return keys(dataDimMap);
  32885. }
  32886. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  32887. if (data) {
  32888. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  32889. var seriesExtent = data.getApproximateExtent(dim);
  32890. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  32891. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  32892. });
  32893. }
  32894. }
  32895. /*
  32896. * Licensed to the Apache Software Foundation (ASF) under one
  32897. * or more contributor license agreements. See the NOTICE file
  32898. * distributed with this work for additional information
  32899. * regarding copyright ownership. The ASF licenses this file
  32900. * to you under the Apache License, Version 2.0 (the
  32901. * "License"); you may not use this file except in compliance
  32902. * with the License. You may obtain a copy of the License at
  32903. *
  32904. * http://www.apache.org/licenses/LICENSE-2.0
  32905. *
  32906. * Unless required by applicable law or agreed to in writing,
  32907. * software distributed under the License is distributed on an
  32908. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32909. * KIND, either express or implied. See the License for the
  32910. * specific language governing permissions and limitations
  32911. * under the License.
  32912. */
  32913. /**
  32914. * AUTO-GENERATED FILE. DO NOT MODIFY.
  32915. */
  32916. /*
  32917. * Licensed to the Apache Software Foundation (ASF) under one
  32918. * or more contributor license agreements. See the NOTICE file
  32919. * distributed with this work for additional information
  32920. * regarding copyright ownership. The ASF licenses this file
  32921. * to you under the Apache License, Version 2.0 (the
  32922. * "License"); you may not use this file except in compliance
  32923. * with the License. You may obtain a copy of the License at
  32924. *
  32925. * http://www.apache.org/licenses/LICENSE-2.0
  32926. *
  32927. * Unless required by applicable law or agreed to in writing,
  32928. * software distributed under the License is distributed on an
  32929. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32930. * KIND, either express or implied. See the License for the
  32931. * specific language governing permissions and limitations
  32932. * under the License.
  32933. */
  32934. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  32935. var AxisModelCommonMixin =
  32936. /** @class */
  32937. function () {
  32938. function AxisModelCommonMixin() {}
  32939. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  32940. var option = this.option;
  32941. return !option.scale;
  32942. };
  32943. /**
  32944. * Should be implemented by each axis model if necessary.
  32945. * @return coordinate system model
  32946. */
  32947. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  32948. return;
  32949. };
  32950. return AxisModelCommonMixin;
  32951. }();
  32952. /**
  32953. * Create a muti dimension List structure from seriesModel.
  32954. */
  32955. function createList(seriesModel) {
  32956. return createSeriesData(null, seriesModel);
  32957. } // export function createGraph(seriesModel) {
  32958. var dataStack$1 = {
  32959. isDimensionStacked: isDimensionStacked,
  32960. enableDataStack: enableDataStack,
  32961. getStackedDimension: getStackedDimension
  32962. };
  32963. /**
  32964. * Create scale
  32965. * @param {Array.<number>} dataExtent
  32966. * @param {Object|module:echarts/Model} option If `optoin.type`
  32967. * is secified, it can only be `'value'` currently.
  32968. */
  32969. function createScale(dataExtent, option) {
  32970. var axisModel = option;
  32971. if (!(option instanceof Model)) {
  32972. axisModel = new Model(option); // FIXME
  32973. // Currently AxisModelCommonMixin has nothing to do with the
  32974. // the requirements of `axisHelper.createScaleByModel`. For
  32975. // example the method `getCategories` and `getOrdinalMeta`
  32976. // are required for `'category'` axis, and ecModel are required
  32977. // for `'time'` axis. But occationally echarts-gl happened
  32978. // to only use `'value'` axis.
  32979. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  32980. }
  32981. var scale = createScaleByModel(axisModel);
  32982. scale.setExtent(dataExtent[0], dataExtent[1]);
  32983. niceScaleExtent(scale, axisModel);
  32984. return scale;
  32985. }
  32986. /**
  32987. * Mixin common methods to axis model,
  32988. *
  32989. * Inlcude methods
  32990. * `getFormattedLabels() => Array.<string>`
  32991. * `getCategories() => Array.<string>`
  32992. * `getMin(origin: boolean) => number`
  32993. * `getMax(origin: boolean) => number`
  32994. * `getNeedCrossZero() => boolean`
  32995. */
  32996. function mixinAxisModelCommonMethods(Model) {
  32997. mixin(Model, AxisModelCommonMixin);
  32998. }
  32999. function createTextStyle$1(textStyleModel, opts) {
  33000. opts = opts || {};
  33001. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  33002. }
  33003. var helper = /*#__PURE__*/Object.freeze({
  33004. __proto__: null,
  33005. createList: createList,
  33006. getLayoutRect: getLayoutRect,
  33007. dataStack: dataStack$1,
  33008. createScale: createScale,
  33009. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  33010. getECData: getECData,
  33011. createTextStyle: createTextStyle$1,
  33012. createDimensions: createDimensions,
  33013. createSymbol: createSymbol,
  33014. enableHoverEmphasis: enableHoverEmphasis
  33015. });
  33016. var number = /*#__PURE__*/Object.freeze({
  33017. __proto__: null,
  33018. linearMap: linearMap,
  33019. round: round,
  33020. asc: asc,
  33021. getPrecision: getPrecision,
  33022. getPrecisionSafe: getPrecisionSafe,
  33023. getPixelPrecision: getPixelPrecision,
  33024. getPercentWithPrecision: getPercentWithPrecision,
  33025. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  33026. remRadian: remRadian,
  33027. isRadianAroundZero: isRadianAroundZero,
  33028. parseDate: parseDate,
  33029. quantity: quantity,
  33030. quantityExponent: quantityExponent,
  33031. nice: nice,
  33032. quantile: quantile,
  33033. reformIntervals: reformIntervals,
  33034. isNumeric: isNumeric,
  33035. numericToNumber: numericToNumber
  33036. });
  33037. var time = /*#__PURE__*/Object.freeze({
  33038. __proto__: null,
  33039. parse: parseDate,
  33040. format: format
  33041. });
  33042. var graphic$1 = /*#__PURE__*/Object.freeze({
  33043. __proto__: null,
  33044. extendShape: extendShape,
  33045. extendPath: extendPath,
  33046. makePath: makePath,
  33047. makeImage: makeImage,
  33048. mergePath: mergePath$1,
  33049. resizePath: resizePath,
  33050. createIcon: createIcon,
  33051. updateProps: updateProps,
  33052. initProps: initProps,
  33053. getTransform: getTransform,
  33054. clipPointsByRect: clipPointsByRect,
  33055. clipRectByRect: clipRectByRect,
  33056. registerShape: registerShape,
  33057. getShapeClass: getShapeClass,
  33058. Group: Group,
  33059. Image: ZRImage,
  33060. Text: ZRText,
  33061. Circle: Circle,
  33062. Ellipse: Ellipse,
  33063. Sector: Sector,
  33064. Ring: Ring,
  33065. Polygon: Polygon,
  33066. Polyline: Polyline,
  33067. Rect: Rect,
  33068. Line: Line,
  33069. BezierCurve: BezierCurve,
  33070. Arc: Arc,
  33071. IncrementalDisplayable: IncrementalDisplayable,
  33072. CompoundPath: CompoundPath,
  33073. LinearGradient: LinearGradient,
  33074. RadialGradient: RadialGradient,
  33075. BoundingRect: BoundingRect
  33076. });
  33077. var format$1 = /*#__PURE__*/Object.freeze({
  33078. __proto__: null,
  33079. addCommas: addCommas,
  33080. toCamelCase: toCamelCase,
  33081. normalizeCssArray: normalizeCssArray$1,
  33082. encodeHTML: encodeHTML,
  33083. formatTpl: formatTpl,
  33084. getTooltipMarker: getTooltipMarker,
  33085. formatTime: formatTime,
  33086. capitalFirst: capitalFirst,
  33087. truncateText: truncateText,
  33088. getTextRect: getTextRect
  33089. });
  33090. var util$1 = /*#__PURE__*/Object.freeze({
  33091. __proto__: null,
  33092. map: map,
  33093. each: each,
  33094. indexOf: indexOf,
  33095. inherits: inherits,
  33096. reduce: reduce,
  33097. filter: filter,
  33098. bind: bind,
  33099. curry: curry,
  33100. isArray: isArray,
  33101. isString: isString,
  33102. isObject: isObject,
  33103. isFunction: isFunction,
  33104. extend: extend,
  33105. defaults: defaults,
  33106. clone: clone,
  33107. merge: merge
  33108. });
  33109. var inner$5 = makeInner();
  33110. function createAxisLabels(axis) {
  33111. // Only ordinal scale support tick interval
  33112. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  33113. }
  33114. /**
  33115. * @param {module:echats/coord/Axis} axis
  33116. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  33117. * @return {Object} {
  33118. * ticks: Array.<number>
  33119. * tickCategoryInterval: number
  33120. * }
  33121. */
  33122. function createAxisTicks(axis, tickModel) {
  33123. // Only ordinal scale support tick interval
  33124. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  33125. ticks: map(axis.scale.getTicks(), function (tick) {
  33126. return tick.value;
  33127. })
  33128. };
  33129. }
  33130. function makeCategoryLabels(axis) {
  33131. var labelModel = axis.getLabelModel();
  33132. var result = makeCategoryLabelsActually(axis, labelModel);
  33133. return !labelModel.get('show') || axis.scale.isBlank() ? {
  33134. labels: [],
  33135. labelCategoryInterval: result.labelCategoryInterval
  33136. } : result;
  33137. }
  33138. function makeCategoryLabelsActually(axis, labelModel) {
  33139. var labelsCache = getListCache(axis, 'labels');
  33140. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  33141. var result = listCacheGet(labelsCache, optionLabelInterval);
  33142. if (result) {
  33143. return result;
  33144. }
  33145. var labels;
  33146. var numericLabelInterval;
  33147. if (isFunction(optionLabelInterval)) {
  33148. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  33149. } else {
  33150. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  33151. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  33152. } // Cache to avoid calling interval function repeatly.
  33153. return listCacheSet(labelsCache, optionLabelInterval, {
  33154. labels: labels,
  33155. labelCategoryInterval: numericLabelInterval
  33156. });
  33157. }
  33158. function makeCategoryTicks(axis, tickModel) {
  33159. var ticksCache = getListCache(axis, 'ticks');
  33160. var optionTickInterval = getOptionCategoryInterval(tickModel);
  33161. var result = listCacheGet(ticksCache, optionTickInterval);
  33162. if (result) {
  33163. return result;
  33164. }
  33165. var ticks;
  33166. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  33167. // we should not return all ticks.
  33168. if (!tickModel.get('show') || axis.scale.isBlank()) {
  33169. ticks = [];
  33170. }
  33171. if (isFunction(optionTickInterval)) {
  33172. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  33173. } // Always use label interval by default despite label show. Consider this
  33174. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  33175. // labels. `splitLine` and `axisTick` should be consistent in this case.
  33176. else if (optionTickInterval === 'auto') {
  33177. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  33178. tickCategoryInterval = labelsResult.labelCategoryInterval;
  33179. ticks = map(labelsResult.labels, function (labelItem) {
  33180. return labelItem.tickValue;
  33181. });
  33182. } else {
  33183. tickCategoryInterval = optionTickInterval;
  33184. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  33185. } // Cache to avoid calling interval function repeatly.
  33186. return listCacheSet(ticksCache, optionTickInterval, {
  33187. ticks: ticks,
  33188. tickCategoryInterval: tickCategoryInterval
  33189. });
  33190. }
  33191. function makeRealNumberLabels(axis) {
  33192. var ticks = axis.scale.getTicks();
  33193. var labelFormatter = makeLabelFormatter(axis);
  33194. return {
  33195. labels: map(ticks, function (tick, idx) {
  33196. return {
  33197. formattedLabel: labelFormatter(tick, idx),
  33198. rawLabel: axis.scale.getLabel(tick),
  33199. tickValue: tick.value
  33200. };
  33201. })
  33202. };
  33203. }
  33204. function getListCache(axis, prop) {
  33205. // Because key can be funciton, and cache size always be small, we use array cache.
  33206. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  33207. }
  33208. function listCacheGet(cache, key) {
  33209. for (var i = 0; i < cache.length; i++) {
  33210. if (cache[i].key === key) {
  33211. return cache[i].value;
  33212. }
  33213. }
  33214. }
  33215. function listCacheSet(cache, key, value) {
  33216. cache.push({
  33217. key: key,
  33218. value: value
  33219. });
  33220. return value;
  33221. }
  33222. function makeAutoCategoryInterval(axis) {
  33223. var result = inner$5(axis).autoInterval;
  33224. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  33225. }
  33226. /**
  33227. * Calculate interval for category axis ticks and labels.
  33228. * To get precise result, at least one of `getRotate` and `isHorizontal`
  33229. * should be implemented in axis.
  33230. */
  33231. function calculateCategoryInterval(axis) {
  33232. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  33233. var labelFormatter = makeLabelFormatter(axis);
  33234. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  33235. var ordinalScale = axis.scale;
  33236. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  33237. // avoid generating a long array by `getTicks`
  33238. // in large category data case.
  33239. var tickCount = ordinalScale.count();
  33240. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  33241. return 0;
  33242. }
  33243. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  33244. if (tickCount > 40) {
  33245. step = Math.max(1, Math.floor(tickCount / 40));
  33246. }
  33247. var tickValue = ordinalExtent[0];
  33248. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  33249. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  33250. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  33251. var maxW = 0;
  33252. var maxH = 0; // Caution: Performance sensitive for large category data.
  33253. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  33254. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33255. var width = 0;
  33256. var height = 0; // Not precise, do not consider align and vertical align
  33257. // and each distance from axis line yet.
  33258. var rect = getBoundingRect(labelFormatter({
  33259. value: tickValue
  33260. }), params.font, 'center', 'top'); // Magic number
  33261. width = rect.width * 1.3;
  33262. height = rect.height * 1.3; // Min size, void long loop.
  33263. maxW = Math.max(maxW, width, 7);
  33264. maxH = Math.max(maxH, height, 7);
  33265. }
  33266. var dw = maxW / unitW;
  33267. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  33268. isNaN(dw) && (dw = Infinity);
  33269. isNaN(dh) && (dh = Infinity);
  33270. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  33271. var cache = inner$5(axis.model);
  33272. var axisExtent = axis.getExtent();
  33273. var lastAutoInterval = cache.lastAutoInterval;
  33274. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  33275. // otherwise the calculated interval might jitter when the zoom
  33276. // window size is close to the interval-changing size.
  33277. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  33278. // The jitter will cause that sometimes the displayed labels are
  33279. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  33280. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  33281. // point is not the same when zooming in or zooming out.
  33282. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  33283. // be used. Otherwise some hiden labels might not be shown again.
  33284. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  33285. interval = lastAutoInterval;
  33286. } // Only update cache if cache not used, otherwise the
  33287. // changing of interval is too insensitive.
  33288. else {
  33289. cache.lastTickCount = tickCount;
  33290. cache.lastAutoInterval = interval;
  33291. cache.axisExtent0 = axisExtent[0];
  33292. cache.axisExtent1 = axisExtent[1];
  33293. }
  33294. return interval;
  33295. }
  33296. function fetchAutoCategoryIntervalCalculationParams(axis) {
  33297. var labelModel = axis.getLabelModel();
  33298. return {
  33299. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  33300. labelRotate: labelModel.get('rotate') || 0,
  33301. font: labelModel.getFont()
  33302. };
  33303. }
  33304. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  33305. var labelFormatter = makeLabelFormatter(axis);
  33306. var ordinalScale = axis.scale;
  33307. var ordinalExtent = ordinalScale.getExtent();
  33308. var labelModel = axis.getLabelModel();
  33309. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  33310. var step = Math.max((categoryInterval || 0) + 1, 1);
  33311. var startTick = ordinalExtent[0];
  33312. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  33313. // while zooming and moving while interval > 0. Otherwise the selection
  33314. // of displayable ticks and symbols probably keep changing.
  33315. // 3 is empirical value.
  33316. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  33317. startTick = Math.round(Math.ceil(startTick / step) * step);
  33318. } // (1) Only add min max label here but leave overlap checking
  33319. // to render stage, which also ensure the returned list
  33320. // suitable for splitLine and splitArea rendering.
  33321. // (2) Scales except category always contain min max label so
  33322. // do not need to perform this process.
  33323. var showAllLabel = shouldShowAllLabels(axis);
  33324. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  33325. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  33326. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  33327. addItem(ordinalExtent[0]);
  33328. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  33329. var tickValue = startTick;
  33330. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33331. addItem(tickValue);
  33332. }
  33333. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  33334. addItem(ordinalExtent[1]);
  33335. }
  33336. function addItem(tickValue) {
  33337. var tickObj = {
  33338. value: tickValue
  33339. };
  33340. result.push(onlyTick ? tickValue : {
  33341. formattedLabel: labelFormatter(tickObj),
  33342. rawLabel: ordinalScale.getLabel(tickObj),
  33343. tickValue: tickValue
  33344. });
  33345. }
  33346. return result;
  33347. }
  33348. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  33349. var ordinalScale = axis.scale;
  33350. var labelFormatter = makeLabelFormatter(axis);
  33351. var result = [];
  33352. each(ordinalScale.getTicks(), function (tick) {
  33353. var rawLabel = ordinalScale.getLabel(tick);
  33354. var tickValue = tick.value;
  33355. if (categoryInterval(tick.value, rawLabel)) {
  33356. result.push(onlyTick ? tickValue : {
  33357. formattedLabel: labelFormatter(tick),
  33358. rawLabel: rawLabel,
  33359. tickValue: tickValue
  33360. });
  33361. }
  33362. });
  33363. return result;
  33364. }
  33365. var NORMALIZED_EXTENT = [0, 1];
  33366. /**
  33367. * Base class of Axis.
  33368. */
  33369. var Axis =
  33370. /** @class */
  33371. function () {
  33372. function Axis(dim, scale, extent) {
  33373. this.onBand = false;
  33374. this.inverse = false;
  33375. this.dim = dim;
  33376. this.scale = scale;
  33377. this._extent = extent || [0, 0];
  33378. }
  33379. /**
  33380. * If axis extent contain given coord
  33381. */
  33382. Axis.prototype.contain = function (coord) {
  33383. var extent = this._extent;
  33384. var min = Math.min(extent[0], extent[1]);
  33385. var max = Math.max(extent[0], extent[1]);
  33386. return coord >= min && coord <= max;
  33387. };
  33388. /**
  33389. * If axis extent contain given data
  33390. */
  33391. Axis.prototype.containData = function (data) {
  33392. return this.scale.contain(data);
  33393. };
  33394. /**
  33395. * Get coord extent.
  33396. */
  33397. Axis.prototype.getExtent = function () {
  33398. return this._extent.slice();
  33399. };
  33400. /**
  33401. * Get precision used for formatting
  33402. */
  33403. Axis.prototype.getPixelPrecision = function (dataExtent) {
  33404. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  33405. };
  33406. /**
  33407. * Set coord extent
  33408. */
  33409. Axis.prototype.setExtent = function (start, end) {
  33410. var extent = this._extent;
  33411. extent[0] = start;
  33412. extent[1] = end;
  33413. };
  33414. /**
  33415. * Convert data to coord. Data is the rank if it has an ordinal scale
  33416. */
  33417. Axis.prototype.dataToCoord = function (data, clamp) {
  33418. var extent = this._extent;
  33419. var scale = this.scale;
  33420. data = scale.normalize(data);
  33421. if (this.onBand && scale.type === 'ordinal') {
  33422. extent = extent.slice();
  33423. fixExtentWithBands(extent, scale.count());
  33424. }
  33425. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  33426. };
  33427. /**
  33428. * Convert coord to data. Data is the rank if it has an ordinal scale
  33429. */
  33430. Axis.prototype.coordToData = function (coord, clamp) {
  33431. var extent = this._extent;
  33432. var scale = this.scale;
  33433. if (this.onBand && scale.type === 'ordinal') {
  33434. extent = extent.slice();
  33435. fixExtentWithBands(extent, scale.count());
  33436. }
  33437. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  33438. return this.scale.scale(t);
  33439. };
  33440. /**
  33441. * Convert pixel point to data in axis
  33442. */
  33443. Axis.prototype.pointToData = function (point, clamp) {
  33444. // Should be implemented in derived class if necessary.
  33445. return;
  33446. };
  33447. /**
  33448. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  33449. * `axis.getTicksCoords` considers `onBand`, which is used by
  33450. * `boundaryGap:true` of category axis and splitLine and splitArea.
  33451. * @param opt.tickModel default: axis.model.getModel('axisTick')
  33452. * @param opt.clamp If `true`, the first and the last
  33453. * tick must be at the axis end points. Otherwise, clip ticks
  33454. * that outside the axis extent.
  33455. */
  33456. Axis.prototype.getTicksCoords = function (opt) {
  33457. opt = opt || {};
  33458. var tickModel = opt.tickModel || this.getTickModel();
  33459. var result = createAxisTicks(this, tickModel);
  33460. var ticks = result.ticks;
  33461. var ticksCoords = map(ticks, function (tickVal) {
  33462. return {
  33463. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  33464. tickValue: tickVal
  33465. };
  33466. }, this);
  33467. var alignWithLabel = tickModel.get('alignWithLabel');
  33468. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  33469. return ticksCoords;
  33470. };
  33471. Axis.prototype.getMinorTicksCoords = function () {
  33472. if (this.scale.type === 'ordinal') {
  33473. // Category axis doesn't support minor ticks
  33474. return [];
  33475. }
  33476. var minorTickModel = this.model.getModel('minorTick');
  33477. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  33478. if (!(splitNumber > 0 && splitNumber < 100)) {
  33479. splitNumber = 5;
  33480. }
  33481. var minorTicks = this.scale.getMinorTicks(splitNumber);
  33482. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  33483. return map(minorTicksGroup, function (minorTick) {
  33484. return {
  33485. coord: this.dataToCoord(minorTick),
  33486. tickValue: minorTick
  33487. };
  33488. }, this);
  33489. }, this);
  33490. return minorTicksCoords;
  33491. };
  33492. Axis.prototype.getViewLabels = function () {
  33493. return createAxisLabels(this).labels;
  33494. };
  33495. Axis.prototype.getLabelModel = function () {
  33496. return this.model.getModel('axisLabel');
  33497. };
  33498. /**
  33499. * Notice here we only get the default tick model. For splitLine
  33500. * or splitArea, we should pass the splitLineModel or splitAreaModel
  33501. * manually when calling `getTicksCoords`.
  33502. * In GL, this method may be overrided to:
  33503. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  33504. */
  33505. Axis.prototype.getTickModel = function () {
  33506. return this.model.getModel('axisTick');
  33507. };
  33508. /**
  33509. * Get width of band
  33510. */
  33511. Axis.prototype.getBandWidth = function () {
  33512. var axisExtent = this._extent;
  33513. var dataExtent = this.scale.getExtent();
  33514. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  33515. len === 0 && (len = 1);
  33516. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  33517. return Math.abs(size) / len;
  33518. };
  33519. /**
  33520. * Only be called in category axis.
  33521. * Can be overrided, consider other axes like in 3D.
  33522. * @return Auto interval for cateogry axis tick and label
  33523. */
  33524. Axis.prototype.calculateCategoryInterval = function () {
  33525. return calculateCategoryInterval(this);
  33526. };
  33527. return Axis;
  33528. }();
  33529. function fixExtentWithBands(extent, nTick) {
  33530. var size = extent[1] - extent[0];
  33531. var len = nTick;
  33532. var margin = size / len / 2;
  33533. extent[0] += margin;
  33534. extent[1] -= margin;
  33535. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  33536. // |---1---|---2---|---3---|---4---|.
  33537. // So the displayed ticks and splitLine/splitArea should between
  33538. // each data item, otherwise cause misleading (e.g., split tow bars
  33539. // of a single data item when there are two bar series).
  33540. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  33541. // splitLine/spliteArea should layout appropriately corresponding
  33542. // to displayed labels. (So we should not use `getBandWidth` in this
  33543. // case).
  33544. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  33545. var ticksLen = ticksCoords.length;
  33546. if (!axis.onBand || alignWithLabel || !ticksLen) {
  33547. return;
  33548. }
  33549. var axisExtent = axis.getExtent();
  33550. var last;
  33551. var diffSize;
  33552. if (ticksLen === 1) {
  33553. ticksCoords[0].coord = axisExtent[0];
  33554. last = ticksCoords[1] = {
  33555. coord: axisExtent[0]
  33556. };
  33557. } else {
  33558. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  33559. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  33560. each(ticksCoords, function (ticksItem) {
  33561. ticksItem.coord -= shift_1 / 2;
  33562. });
  33563. var dataExtent = axis.scale.getExtent();
  33564. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  33565. last = {
  33566. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  33567. };
  33568. ticksCoords.push(last);
  33569. }
  33570. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  33571. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  33572. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  33573. }
  33574. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  33575. ticksCoords.unshift({
  33576. coord: axisExtent[0]
  33577. });
  33578. }
  33579. if (littleThan(axisExtent[1], last.coord)) {
  33580. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  33581. }
  33582. if (clamp && littleThan(last.coord, axisExtent[1])) {
  33583. ticksCoords.push({
  33584. coord: axisExtent[1]
  33585. });
  33586. }
  33587. function littleThan(a, b) {
  33588. // Avoid rounding error cause calculated tick coord different with extent.
  33589. // It may cause an extra unecessary tick added.
  33590. a = round(a);
  33591. b = round(b);
  33592. return inverse ? a > b : a < b;
  33593. }
  33594. }
  33595. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  33596. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  33597. // class Bar3DModel extends ComponentModel {}
  33598. // export function install(registers) { regsiters.registerComponentModel(Bar3DModel); }
  33599. // echarts.use(install);
  33600. function extendComponentModel(proto) {
  33601. var Model = ComponentModel.extend(proto);
  33602. ComponentModel.registerClass(Model);
  33603. return Model;
  33604. }
  33605. function extendComponentView(proto) {
  33606. var View = ComponentView.extend(proto);
  33607. ComponentView.registerClass(View);
  33608. return View;
  33609. }
  33610. function extendSeriesModel(proto) {
  33611. var Model = SeriesModel.extend(proto);
  33612. SeriesModel.registerClass(Model);
  33613. return Model;
  33614. }
  33615. function extendChartView(proto) {
  33616. var View = ChartView.extend(proto);
  33617. ChartView.registerClass(View);
  33618. return View;
  33619. }
  33620. var PI2$6 = Math.PI * 2;
  33621. var CMD$3 = PathProxy.CMD;
  33622. var DEFAULT_SEARCH_SPACE = ['top', 'right', 'bottom', 'left'];
  33623. function getCandidateAnchor(pos, distance, rect, outPt, outDir) {
  33624. var width = rect.width;
  33625. var height = rect.height;
  33626. switch (pos) {
  33627. case 'top':
  33628. outPt.set(rect.x + width / 2, rect.y - distance);
  33629. outDir.set(0, -1);
  33630. break;
  33631. case 'bottom':
  33632. outPt.set(rect.x + width / 2, rect.y + height + distance);
  33633. outDir.set(0, 1);
  33634. break;
  33635. case 'left':
  33636. outPt.set(rect.x - distance, rect.y + height / 2);
  33637. outDir.set(-1, 0);
  33638. break;
  33639. case 'right':
  33640. outPt.set(rect.x + width + distance, rect.y + height / 2);
  33641. outDir.set(1, 0);
  33642. break;
  33643. }
  33644. }
  33645. function projectPointToArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y, out) {
  33646. x -= cx;
  33647. y -= cy;
  33648. var d = Math.sqrt(x * x + y * y);
  33649. x /= d;
  33650. y /= d; // Intersect point.
  33651. var ox = x * r + cx;
  33652. var oy = y * r + cy;
  33653. if (Math.abs(startAngle - endAngle) % PI2$6 < 1e-4) {
  33654. // Is a circle
  33655. out[0] = ox;
  33656. out[1] = oy;
  33657. return d - r;
  33658. }
  33659. if (anticlockwise) {
  33660. var tmp = startAngle;
  33661. startAngle = normalizeRadian(endAngle);
  33662. endAngle = normalizeRadian(tmp);
  33663. } else {
  33664. startAngle = normalizeRadian(startAngle);
  33665. endAngle = normalizeRadian(endAngle);
  33666. }
  33667. if (startAngle > endAngle) {
  33668. endAngle += PI2$6;
  33669. }
  33670. var angle = Math.atan2(y, x);
  33671. if (angle < 0) {
  33672. angle += PI2$6;
  33673. }
  33674. if (angle >= startAngle && angle <= endAngle || angle + PI2$6 >= startAngle && angle + PI2$6 <= endAngle) {
  33675. // Project point is on the arc.
  33676. out[0] = ox;
  33677. out[1] = oy;
  33678. return d - r;
  33679. }
  33680. var x1 = r * Math.cos(startAngle) + cx;
  33681. var y1 = r * Math.sin(startAngle) + cy;
  33682. var x2 = r * Math.cos(endAngle) + cx;
  33683. var y2 = r * Math.sin(endAngle) + cy;
  33684. var d1 = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
  33685. var d2 = (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y);
  33686. if (d1 < d2) {
  33687. out[0] = x1;
  33688. out[1] = y1;
  33689. return Math.sqrt(d1);
  33690. } else {
  33691. out[0] = x2;
  33692. out[1] = y2;
  33693. return Math.sqrt(d2);
  33694. }
  33695. }
  33696. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  33697. var dx = x - x1;
  33698. var dy = y - y1;
  33699. var dx1 = x2 - x1;
  33700. var dy1 = y2 - y1;
  33701. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  33702. dx1 /= lineLen;
  33703. dy1 /= lineLen; // dot product
  33704. var projectedLen = dx * dx1 + dy * dy1;
  33705. var t = projectedLen / lineLen;
  33706. if (limitToEnds) {
  33707. t = Math.min(Math.max(t, 0), 1);
  33708. }
  33709. t *= lineLen;
  33710. var ox = out[0] = x1 + t * dx1;
  33711. var oy = out[1] = y1 + t * dy1;
  33712. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  33713. }
  33714. function projectPointToRect(x1, y1, width, height, x, y, out) {
  33715. if (width < 0) {
  33716. x1 = x1 + width;
  33717. width = -width;
  33718. }
  33719. if (height < 0) {
  33720. y1 = y1 + height;
  33721. height = -height;
  33722. }
  33723. var x2 = x1 + width;
  33724. var y2 = y1 + height;
  33725. var ox = out[0] = Math.min(Math.max(x, x1), x2);
  33726. var oy = out[1] = Math.min(Math.max(y, y1), y2);
  33727. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  33728. }
  33729. var tmpPt = [];
  33730. function nearestPointOnRect(pt, rect, out) {
  33731. var dist = projectPointToRect(rect.x, rect.y, rect.width, rect.height, pt.x, pt.y, tmpPt);
  33732. out.set(tmpPt[0], tmpPt[1]);
  33733. return dist;
  33734. }
  33735. /**
  33736. * Calculate min distance corresponding point.
  33737. * This method won't evaluate if point is in the path.
  33738. */
  33739. function nearestPointOnPath(pt, path, out) {
  33740. var xi = 0;
  33741. var yi = 0;
  33742. var x0 = 0;
  33743. var y0 = 0;
  33744. var x1;
  33745. var y1;
  33746. var minDist = Infinity;
  33747. var data = path.data;
  33748. var x = pt.x;
  33749. var y = pt.y;
  33750. for (var i = 0; i < data.length;) {
  33751. var cmd = data[i++];
  33752. if (i === 1) {
  33753. xi = data[i];
  33754. yi = data[i + 1];
  33755. x0 = xi;
  33756. y0 = yi;
  33757. }
  33758. var d = minDist;
  33759. switch (cmd) {
  33760. case CMD$3.M:
  33761. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  33762. // 在 closePath 的时候使用
  33763. x0 = data[i++];
  33764. y0 = data[i++];
  33765. xi = x0;
  33766. yi = y0;
  33767. break;
  33768. case CMD$3.L:
  33769. d = projectPointToLine(xi, yi, data[i], data[i + 1], x, y, tmpPt, true);
  33770. xi = data[i++];
  33771. yi = data[i++];
  33772. break;
  33773. case CMD$3.C:
  33774. d = cubicProjectPoint(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  33775. xi = data[i++];
  33776. yi = data[i++];
  33777. break;
  33778. case CMD$3.Q:
  33779. d = quadraticProjectPoint(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  33780. xi = data[i++];
  33781. yi = data[i++];
  33782. break;
  33783. case CMD$3.A:
  33784. // TODO Arc 判断的开销比较大
  33785. var cx = data[i++];
  33786. var cy = data[i++];
  33787. var rx = data[i++];
  33788. var ry = data[i++];
  33789. var theta = data[i++];
  33790. var dTheta = data[i++]; // TODO Arc 旋转
  33791. i += 1;
  33792. var anticlockwise = !!(1 - data[i++]);
  33793. x1 = Math.cos(theta) * rx + cx;
  33794. y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令
  33795. if (i <= 1) {
  33796. // 第一个命令起点还未定义
  33797. x0 = x1;
  33798. y0 = y1;
  33799. } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  33800. var _x = (x - cx) * ry / rx + cx;
  33801. d = projectPointToArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y, tmpPt);
  33802. xi = Math.cos(theta + dTheta) * rx + cx;
  33803. yi = Math.sin(theta + dTheta) * ry + cy;
  33804. break;
  33805. case CMD$3.R:
  33806. x0 = xi = data[i++];
  33807. y0 = yi = data[i++];
  33808. var width = data[i++];
  33809. var height = data[i++];
  33810. d = projectPointToRect(x0, y0, width, height, x, y, tmpPt);
  33811. break;
  33812. case CMD$3.Z:
  33813. d = projectPointToLine(xi, yi, x0, y0, x, y, tmpPt, true);
  33814. xi = x0;
  33815. yi = y0;
  33816. break;
  33817. }
  33818. if (d < minDist) {
  33819. minDist = d;
  33820. out.set(tmpPt[0], tmpPt[1]);
  33821. }
  33822. }
  33823. return minDist;
  33824. } // Temporal varible for intermediate usage.
  33825. var pt0 = new Point();
  33826. var pt1 = new Point();
  33827. var pt2 = new Point();
  33828. var dir = new Point();
  33829. var dir2 = new Point();
  33830. /**
  33831. * Calculate a proper guide line based on the label position and graphic element definition
  33832. * @param label
  33833. * @param labelRect
  33834. * @param target
  33835. * @param targetRect
  33836. */
  33837. function updateLabelLinePoints(target, labelLineModel) {
  33838. if (!target) {
  33839. return;
  33840. }
  33841. var labelLine = target.getTextGuideLine();
  33842. var label = target.getTextContent(); // Needs to create text guide in each charts.
  33843. if (!(label && labelLine)) {
  33844. return;
  33845. }
  33846. var labelGuideConfig = target.textGuideLineConfig || {};
  33847. var points = [[0, 0], [0, 0], [0, 0]];
  33848. var searchSpace = labelGuideConfig.candidates || DEFAULT_SEARCH_SPACE;
  33849. var labelRect = label.getBoundingRect().clone();
  33850. labelRect.applyTransform(label.getComputedTransform());
  33851. var minDist = Infinity;
  33852. var anchorPoint = labelGuideConfig.anchor;
  33853. var targetTransform = target.getComputedTransform();
  33854. var targetInversedTransform = targetTransform && invert([], targetTransform);
  33855. var len = labelLineModel.get('length2') || 0;
  33856. if (anchorPoint) {
  33857. pt2.copy(anchorPoint);
  33858. }
  33859. for (var i = 0; i < searchSpace.length; i++) {
  33860. var candidate = searchSpace[i];
  33861. getCandidateAnchor(candidate, 0, labelRect, pt0, dir);
  33862. Point.scaleAndAdd(pt1, pt0, dir, len); // Transform to target coord space.
  33863. pt1.transform(targetInversedTransform); // Note: getBoundingRect will ensure the `path` being created.
  33864. var boundingRect = target.getBoundingRect();
  33865. var dist = anchorPoint ? anchorPoint.distance(pt1) : target instanceof Path ? nearestPointOnPath(pt1, target.path, pt2) : nearestPointOnRect(pt1, boundingRect, pt2); // TODO pt2 is in the path
  33866. if (dist < minDist) {
  33867. minDist = dist; // Transform back to global space.
  33868. pt1.transform(targetTransform);
  33869. pt2.transform(targetTransform);
  33870. pt2.toArray(points[0]);
  33871. pt1.toArray(points[1]);
  33872. pt0.toArray(points[2]);
  33873. }
  33874. }
  33875. limitTurnAngle(points, labelLineModel.get('minTurnAngle'));
  33876. labelLine.setShape({
  33877. points: points
  33878. });
  33879. } // Temporal variable for the limitTurnAngle function
  33880. var tmpArr = [];
  33881. var tmpProjPoint = new Point();
  33882. /**
  33883. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  33884. * @param linePoints
  33885. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  33886. */
  33887. function limitTurnAngle(linePoints, minTurnAngle) {
  33888. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  33889. return;
  33890. }
  33891. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  33892. // /pt1----pt2 (label)
  33893. // /
  33894. // pt0/
  33895. pt0.fromArray(linePoints[0]);
  33896. pt1.fromArray(linePoints[1]);
  33897. pt2.fromArray(linePoints[2]);
  33898. Point.sub(dir, pt0, pt1);
  33899. Point.sub(dir2, pt2, pt1);
  33900. var len1 = dir.len();
  33901. var len2 = dir2.len();
  33902. if (len1 < 1e-3 || len2 < 1e-3) {
  33903. return;
  33904. }
  33905. dir.scale(1 / len1);
  33906. dir2.scale(1 / len2);
  33907. var angleCos = dir.dot(dir2);
  33908. var minTurnAngleCos = Math.cos(minTurnAngle);
  33909. if (minTurnAngleCos < angleCos) {
  33910. // Smaller than minTurnAngle
  33911. // Calculate project point of pt0 on pt1-pt2
  33912. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33913. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  33914. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  33915. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33916. if (isNaN(t)) {
  33917. return;
  33918. }
  33919. if (t < 0) {
  33920. Point.copy(tmpProjPoint, pt1);
  33921. } else if (t > 1) {
  33922. Point.copy(tmpProjPoint, pt2);
  33923. }
  33924. tmpProjPoint.toArray(linePoints[1]);
  33925. }
  33926. }
  33927. /**
  33928. * Limit the angle of line and the surface
  33929. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  33930. */
  33931. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  33932. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  33933. return;
  33934. }
  33935. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  33936. pt0.fromArray(linePoints[0]);
  33937. pt1.fromArray(linePoints[1]);
  33938. pt2.fromArray(linePoints[2]);
  33939. Point.sub(dir, pt1, pt0);
  33940. Point.sub(dir2, pt2, pt1);
  33941. var len1 = dir.len();
  33942. var len2 = dir2.len();
  33943. if (len1 < 1e-3 || len2 < 1e-3) {
  33944. return;
  33945. }
  33946. dir.scale(1 / len1);
  33947. dir2.scale(1 / len2);
  33948. var angleCos = dir.dot(surfaceNormal);
  33949. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  33950. if (angleCos < maxSurfaceAngleCos) {
  33951. // Calculate project point of pt0 on pt1-pt2
  33952. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33953. tmpProjPoint.fromArray(tmpArr);
  33954. var HALF_PI = Math.PI / 2;
  33955. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  33956. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  33957. if (newAngle >= HALF_PI) {
  33958. // parallel
  33959. Point.copy(tmpProjPoint, pt2);
  33960. } else {
  33961. // Calculate new projected length with limited minTurnAngle and get the new connect point
  33962. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  33963. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33964. if (isNaN(t)) {
  33965. return;
  33966. }
  33967. if (t < 0) {
  33968. Point.copy(tmpProjPoint, pt1);
  33969. } else if (t > 1) {
  33970. Point.copy(tmpProjPoint, pt2);
  33971. }
  33972. }
  33973. tmpProjPoint.toArray(linePoints[1]);
  33974. }
  33975. }
  33976. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  33977. var isNormal = stateName === 'normal';
  33978. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  33979. stateObj.ignore = ignore; // Set smooth
  33980. var smooth = stateModel.get('smooth');
  33981. if (smooth && smooth === true) {
  33982. smooth = 0.3;
  33983. }
  33984. stateObj.shape = stateObj.shape || {};
  33985. if (smooth > 0) {
  33986. stateObj.shape.smooth = smooth;
  33987. }
  33988. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  33989. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  33990. }
  33991. function buildLabelLinePath(path, shape) {
  33992. var smooth = shape.smooth;
  33993. var points = shape.points;
  33994. if (!points) {
  33995. return;
  33996. }
  33997. path.moveTo(points[0][0], points[0][1]);
  33998. if (smooth > 0 && points.length >= 3) {
  33999. var len1 = dist(points[0], points[1]);
  34000. var len2 = dist(points[1], points[2]);
  34001. if (!len1 || !len2) {
  34002. path.lineTo(points[1][0], points[1][1]);
  34003. path.lineTo(points[2][0], points[2][1]);
  34004. return;
  34005. }
  34006. var moveLen = Math.min(len1, len2) * smooth;
  34007. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  34008. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  34009. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  34010. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  34011. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  34012. } else {
  34013. for (var i = 1; i < points.length; i++) {
  34014. path.lineTo(points[i][0], points[i][1]);
  34015. }
  34016. }
  34017. }
  34018. /**
  34019. * Create a label line if necessary and set it's style.
  34020. */
  34021. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  34022. var labelLine = targetEl.getTextGuideLine();
  34023. var label = targetEl.getTextContent();
  34024. if (!label) {
  34025. // Not show label line if there is no label.
  34026. if (labelLine) {
  34027. targetEl.removeTextGuideLine();
  34028. }
  34029. return;
  34030. }
  34031. var normalModel = statesModels.normal;
  34032. var showNormal = normalModel.get('show');
  34033. var labelIgnoreNormal = label.ignore;
  34034. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  34035. var stateName = DISPLAY_STATES[i];
  34036. var stateModel = statesModels[stateName];
  34037. var isNormal = stateName === 'normal';
  34038. if (stateModel) {
  34039. var stateShow = stateModel.get('show');
  34040. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  34041. if (isLabelIgnored // Not show when label is not shown in this state.
  34042. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  34043. ) {
  34044. var stateObj = isNormal ? labelLine : labelLine && labelLine.states.normal;
  34045. if (stateObj) {
  34046. stateObj.ignore = true;
  34047. }
  34048. continue;
  34049. } // Create labelLine if not exists
  34050. if (!labelLine) {
  34051. labelLine = new Polyline();
  34052. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  34053. // NOTE: NORMAL should always been the first!
  34054. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  34055. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  34056. } // Use same state proxy.
  34057. if (targetEl.stateProxy) {
  34058. labelLine.stateProxy = targetEl.stateProxy;
  34059. }
  34060. }
  34061. setLabelLineState(labelLine, false, stateName, stateModel);
  34062. }
  34063. }
  34064. if (labelLine) {
  34065. defaults(labelLine.style, defaultStyle); // Not fill.
  34066. labelLine.style.fill = null;
  34067. var showAbove = normalModel.get('showAbove');
  34068. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  34069. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  34070. labelLine.buildPath = buildLabelLinePath;
  34071. }
  34072. }
  34073. function getLabelLineStatesModels(itemModel, labelLineName) {
  34074. labelLineName = labelLineName || 'labelLine';
  34075. var statesModels = {
  34076. normal: itemModel.getModel(labelLineName)
  34077. };
  34078. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  34079. var stateName = SPECIAL_STATES[i];
  34080. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  34081. }
  34082. return statesModels;
  34083. }
  34084. function prepareLayoutList(input) {
  34085. var list = [];
  34086. for (var i = 0; i < input.length; i++) {
  34087. var rawItem = input[i];
  34088. if (rawItem.defaultAttr.ignore) {
  34089. continue;
  34090. }
  34091. var label = rawItem.label;
  34092. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  34093. var localRect = label.getBoundingRect();
  34094. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  34095. var minMargin = label.style.margin || 0;
  34096. var globalRect = localRect.clone();
  34097. globalRect.applyTransform(transform);
  34098. globalRect.x -= minMargin / 2;
  34099. globalRect.y -= minMargin / 2;
  34100. globalRect.width += minMargin;
  34101. globalRect.height += minMargin;
  34102. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  34103. list.push({
  34104. label: label,
  34105. labelLine: rawItem.labelLine,
  34106. rect: globalRect,
  34107. localRect: localRect,
  34108. obb: obb,
  34109. priority: rawItem.priority,
  34110. defaultAttr: rawItem.defaultAttr,
  34111. layoutOption: rawItem.computedLayoutOption,
  34112. axisAligned: isAxisAligned,
  34113. transform: transform
  34114. });
  34115. }
  34116. return list;
  34117. }
  34118. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  34119. var len = list.length;
  34120. if (len < 2) {
  34121. return;
  34122. }
  34123. list.sort(function (a, b) {
  34124. return a.rect[xyDim] - b.rect[xyDim];
  34125. });
  34126. var lastPos = 0;
  34127. var delta;
  34128. var adjusted = false;
  34129. var totalShifts = 0;
  34130. for (var i = 0; i < len; i++) {
  34131. var item = list[i];
  34132. var rect = item.rect;
  34133. delta = rect[xyDim] - lastPos;
  34134. if (delta < 0) {
  34135. // shiftForward(i, len, -delta);
  34136. rect[xyDim] -= delta;
  34137. item.label[xyDim] -= delta;
  34138. adjusted = true;
  34139. }
  34140. var shift = Math.max(-delta, 0);
  34141. totalShifts += shift;
  34142. lastPos = rect[xyDim] + rect[sizeDim];
  34143. }
  34144. if (totalShifts > 0 && balanceShift) {
  34145. // Shift back to make the distribution more equally.
  34146. shiftList(-totalShifts / len, 0, len);
  34147. } // TODO bleedMargin?
  34148. var first = list[0];
  34149. var last = list[len - 1];
  34150. var minGap;
  34151. var maxGap;
  34152. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  34153. minGap < 0 && squeezeGaps(-minGap, 0.8);
  34154. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  34155. updateMinMaxGap();
  34156. takeBoundsGap(minGap, maxGap, 1);
  34157. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  34158. updateMinMaxGap();
  34159. if (minGap < 0) {
  34160. squeezeWhenBailout(-minGap);
  34161. }
  34162. if (maxGap < 0) {
  34163. squeezeWhenBailout(maxGap);
  34164. }
  34165. function updateMinMaxGap() {
  34166. minGap = first.rect[xyDim] - minBound;
  34167. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  34168. }
  34169. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  34170. if (gapThisBound < 0) {
  34171. // Move from other gap if can.
  34172. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  34173. if (moveFromMaxGap > 0) {
  34174. shiftList(moveFromMaxGap * moveDir, 0, len);
  34175. var remained = moveFromMaxGap + gapThisBound;
  34176. if (remained < 0) {
  34177. squeezeGaps(-remained * moveDir, 1);
  34178. }
  34179. } else {
  34180. squeezeGaps(-gapThisBound * moveDir, 1);
  34181. }
  34182. }
  34183. }
  34184. function shiftList(delta, start, end) {
  34185. if (delta !== 0) {
  34186. adjusted = true;
  34187. }
  34188. for (var i = start; i < end; i++) {
  34189. var item = list[i];
  34190. var rect = item.rect;
  34191. rect[xyDim] += delta;
  34192. item.label[xyDim] += delta;
  34193. }
  34194. } // Squeeze gaps if the labels exceed margin.
  34195. function squeezeGaps(delta, maxSqeezePercent) {
  34196. var gaps = [];
  34197. var totalGaps = 0;
  34198. for (var i = 1; i < len; i++) {
  34199. var prevItemRect = list[i - 1].rect;
  34200. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  34201. gaps.push(gap);
  34202. totalGaps += gap;
  34203. }
  34204. if (!totalGaps) {
  34205. return;
  34206. }
  34207. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  34208. if (delta > 0) {
  34209. for (var i = 0; i < len - 1; i++) {
  34210. // Distribute the shift delta to all gaps.
  34211. var movement = gaps[i] * squeezePercent; // Forward
  34212. shiftList(movement, 0, i + 1);
  34213. }
  34214. } else {
  34215. // Backward
  34216. for (var i = len - 1; i > 0; i--) {
  34217. // Distribute the shift delta to all gaps.
  34218. var movement = gaps[i - 1] * squeezePercent;
  34219. shiftList(-movement, i, len);
  34220. }
  34221. }
  34222. }
  34223. /**
  34224. * Squeeze to allow overlap if there is no more space available.
  34225. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  34226. */
  34227. function squeezeWhenBailout(delta) {
  34228. var dir = delta < 0 ? -1 : 1;
  34229. delta = Math.abs(delta);
  34230. var moveForEachLabel = Math.ceil(delta / (len - 1));
  34231. for (var i = 0; i < len - 1; i++) {
  34232. if (dir > 0) {
  34233. // Forward
  34234. shiftList(moveForEachLabel, 0, i + 1);
  34235. } else {
  34236. // Backward
  34237. shiftList(-moveForEachLabel, len - i - 1, len);
  34238. }
  34239. delta -= moveForEachLabel;
  34240. if (delta <= 0) {
  34241. return;
  34242. }
  34243. }
  34244. }
  34245. return adjusted;
  34246. }
  34247. /**
  34248. * Adjust labels on x direction to avoid overlap.
  34249. */
  34250. function shiftLayoutOnX(list, leftBound, rightBound, // If average the shifts on all labels and add them to 0
  34251. // TODO: Not sure if should enable it.
  34252. // Pros: The angle of lines will distribute more equally
  34253. // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly.
  34254. balanceShift) {
  34255. return shiftLayout(list, 'x', 'width', leftBound, rightBound, balanceShift);
  34256. }
  34257. /**
  34258. * Adjust labels on y direction to avoid overlap.
  34259. */
  34260. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  34261. balanceShift) {
  34262. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  34263. }
  34264. function hideOverlap(labelList) {
  34265. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  34266. labelList.sort(function (a, b) {
  34267. return b.priority - a.priority;
  34268. });
  34269. var globalRect = new BoundingRect(0, 0, 0, 0);
  34270. function hideEl(el) {
  34271. if (!el.ignore) {
  34272. // Show on emphasis.
  34273. var emphasisState = el.ensureState('emphasis');
  34274. if (emphasisState.ignore == null) {
  34275. emphasisState.ignore = false;
  34276. }
  34277. }
  34278. el.ignore = true;
  34279. }
  34280. for (var i = 0; i < labelList.length; i++) {
  34281. var labelItem = labelList[i];
  34282. var isAxisAligned = labelItem.axisAligned;
  34283. var localRect = labelItem.localRect;
  34284. var transform = labelItem.transform;
  34285. var label = labelItem.label;
  34286. var labelLine = labelItem.labelLine;
  34287. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  34288. globalRect.width -= 0.1;
  34289. globalRect.height -= 0.1;
  34290. globalRect.x += 0.05;
  34291. globalRect.y += 0.05;
  34292. var obb = labelItem.obb;
  34293. var overlapped = false;
  34294. for (var j = 0; j < displayedLabels.length; j++) {
  34295. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  34296. if (!globalRect.intersect(existsTextCfg.rect)) {
  34297. continue;
  34298. }
  34299. if (isAxisAligned && existsTextCfg.axisAligned) {
  34300. // Is overlapped
  34301. overlapped = true;
  34302. break;
  34303. }
  34304. if (!existsTextCfg.obb) {
  34305. // If self is not axis aligned. But other is.
  34306. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  34307. }
  34308. if (!obb) {
  34309. // If self is axis aligned. But other is not.
  34310. obb = new OrientedBoundingRect(localRect, transform);
  34311. }
  34312. if (obb.intersect(existsTextCfg.obb)) {
  34313. overlapped = true;
  34314. break;
  34315. }
  34316. } // TODO Callback to determine if this overlap should be handled?
  34317. if (overlapped) {
  34318. hideEl(label);
  34319. labelLine && hideEl(labelLine);
  34320. } else {
  34321. label.attr('ignore', labelItem.defaultAttr.ignore);
  34322. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  34323. displayedLabels.push(labelItem);
  34324. }
  34325. }
  34326. }
  34327. function cloneArr(points) {
  34328. if (points) {
  34329. var newPoints = [];
  34330. for (var i = 0; i < points.length; i++) {
  34331. newPoints.push(points[i].slice());
  34332. }
  34333. return newPoints;
  34334. }
  34335. }
  34336. function prepareLayoutCallbackParams(labelItem, hostEl) {
  34337. var label = labelItem.label;
  34338. var labelLine = hostEl && hostEl.getTextGuideLine();
  34339. return {
  34340. dataIndex: labelItem.dataIndex,
  34341. dataType: labelItem.dataType,
  34342. seriesIndex: labelItem.seriesModel.seriesIndex,
  34343. text: labelItem.label.style.text,
  34344. rect: labelItem.hostRect,
  34345. labelRect: labelItem.rect,
  34346. // x: labelAttr.x,
  34347. // y: labelAttr.y,
  34348. align: label.style.align,
  34349. verticalAlign: label.style.verticalAlign,
  34350. labelLinePoints: cloneArr(labelLine && labelLine.shape.points)
  34351. };
  34352. }
  34353. var LABEL_OPTION_TO_STYLE_KEYS = ['align', 'verticalAlign', 'width', 'height', 'fontSize'];
  34354. var dummyTransformable = new Transformable();
  34355. var labelLayoutInnerStore = makeInner();
  34356. var labelLineAnimationStore = makeInner();
  34357. function extendWithKeys(target, source, keys) {
  34358. for (var i = 0; i < keys.length; i++) {
  34359. var key = keys[i];
  34360. if (source[key] != null) {
  34361. target[key] = source[key];
  34362. }
  34363. }
  34364. }
  34365. var LABEL_LAYOUT_PROPS = ['x', 'y', 'rotation'];
  34366. var LabelManager =
  34367. /** @class */
  34368. function () {
  34369. function LabelManager() {
  34370. this._labelList = [];
  34371. this._chartViewList = [];
  34372. }
  34373. LabelManager.prototype.clearLabels = function () {
  34374. this._labelList = [];
  34375. this._chartViewList = [];
  34376. };
  34377. /**
  34378. * Add label to manager
  34379. */
  34380. LabelManager.prototype._addLabel = function (dataIndex, dataType, seriesModel, label, layoutOption) {
  34381. var labelStyle = label.style;
  34382. var hostEl = label.__hostTarget;
  34383. var textConfig = hostEl.textConfig || {}; // TODO: If label is in other state.
  34384. var labelTransform = label.getComputedTransform();
  34385. var labelRect = label.getBoundingRect().plain();
  34386. BoundingRect.applyTransform(labelRect, labelRect, labelTransform);
  34387. if (labelTransform) {
  34388. dummyTransformable.setLocalTransform(labelTransform);
  34389. } else {
  34390. // Identity transform.
  34391. dummyTransformable.x = dummyTransformable.y = dummyTransformable.rotation = dummyTransformable.originX = dummyTransformable.originY = 0;
  34392. dummyTransformable.scaleX = dummyTransformable.scaleY = 1;
  34393. }
  34394. var host = label.__hostTarget;
  34395. var hostRect;
  34396. if (host) {
  34397. hostRect = host.getBoundingRect().plain();
  34398. var transform = host.getComputedTransform();
  34399. BoundingRect.applyTransform(hostRect, hostRect, transform);
  34400. }
  34401. var labelGuide = hostRect && host.getTextGuideLine();
  34402. this._labelList.push({
  34403. label: label,
  34404. labelLine: labelGuide,
  34405. seriesModel: seriesModel,
  34406. dataIndex: dataIndex,
  34407. dataType: dataType,
  34408. layoutOption: layoutOption,
  34409. computedLayoutOption: null,
  34410. rect: labelRect,
  34411. hostRect: hostRect,
  34412. // Label with lower priority will be hidden when overlapped
  34413. // Use rect size as default priority
  34414. priority: hostRect ? hostRect.width * hostRect.height : 0,
  34415. // Save default label attributes.
  34416. // For restore if developers want get back to default value in callback.
  34417. defaultAttr: {
  34418. ignore: label.ignore,
  34419. labelGuideIgnore: labelGuide && labelGuide.ignore,
  34420. x: dummyTransformable.x,
  34421. y: dummyTransformable.y,
  34422. scaleX: dummyTransformable.scaleX,
  34423. scaleY: dummyTransformable.scaleY,
  34424. rotation: dummyTransformable.rotation,
  34425. style: {
  34426. x: labelStyle.x,
  34427. y: labelStyle.y,
  34428. align: labelStyle.align,
  34429. verticalAlign: labelStyle.verticalAlign,
  34430. width: labelStyle.width,
  34431. height: labelStyle.height,
  34432. fontSize: labelStyle.fontSize
  34433. },
  34434. cursor: label.cursor,
  34435. attachedPos: textConfig.position,
  34436. attachedRot: textConfig.rotation
  34437. }
  34438. });
  34439. };
  34440. LabelManager.prototype.addLabelsOfSeries = function (chartView) {
  34441. var _this = this;
  34442. this._chartViewList.push(chartView);
  34443. var seriesModel = chartView.__model;
  34444. var layoutOption = seriesModel.get('labelLayout');
  34445. /**
  34446. * Ignore layouting if it's not specified anything.
  34447. */
  34448. if (!(isFunction(layoutOption) || keys(layoutOption).length)) {
  34449. return;
  34450. }
  34451. chartView.group.traverse(function (child) {
  34452. if (child.ignore) {
  34453. return true; // Stop traverse descendants.
  34454. } // Only support label being hosted on graphic elements.
  34455. var textEl = child.getTextContent();
  34456. var ecData = getECData(child); // Can only attach the text on the element with dataIndex
  34457. if (textEl && !textEl.disableLabelLayout) {
  34458. _this._addLabel(ecData.dataIndex, ecData.dataType, seriesModel, textEl, layoutOption);
  34459. }
  34460. });
  34461. };
  34462. LabelManager.prototype.updateLayoutConfig = function (api) {
  34463. var width = api.getWidth();
  34464. var height = api.getHeight();
  34465. function createDragHandler(el, labelLineModel) {
  34466. return function () {
  34467. updateLabelLinePoints(el, labelLineModel);
  34468. };
  34469. }
  34470. for (var i = 0; i < this._labelList.length; i++) {
  34471. var labelItem = this._labelList[i];
  34472. var label = labelItem.label;
  34473. var hostEl = label.__hostTarget;
  34474. var defaultLabelAttr = labelItem.defaultAttr;
  34475. var layoutOption = void 0; // TODO A global layout option?
  34476. if (typeof labelItem.layoutOption === 'function') {
  34477. layoutOption = labelItem.layoutOption(prepareLayoutCallbackParams(labelItem, hostEl));
  34478. } else {
  34479. layoutOption = labelItem.layoutOption;
  34480. }
  34481. layoutOption = layoutOption || {};
  34482. labelItem.computedLayoutOption = layoutOption;
  34483. var degreeToRadian = Math.PI / 180; // TODO hostEl should always exists.
  34484. // Or label should not have parent because the x, y is all in global space.
  34485. if (hostEl) {
  34486. hostEl.setTextConfig({
  34487. // Force to set local false.
  34488. local: false,
  34489. // Ignore position and rotation config on the host el if x or y is changed.
  34490. position: layoutOption.x != null || layoutOption.y != null ? null : defaultLabelAttr.attachedPos,
  34491. // Ignore rotation config on the host el if rotation is changed.
  34492. rotation: layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.attachedRot,
  34493. offset: [layoutOption.dx || 0, layoutOption.dy || 0]
  34494. });
  34495. }
  34496. var needsUpdateLabelLine = false;
  34497. if (layoutOption.x != null) {
  34498. // TODO width of chart view.
  34499. label.x = parsePercent$1(layoutOption.x, width);
  34500. label.setStyle('x', 0); // Ignore movement in style. TODO: origin.
  34501. needsUpdateLabelLine = true;
  34502. } else {
  34503. label.x = defaultLabelAttr.x;
  34504. label.setStyle('x', defaultLabelAttr.style.x);
  34505. }
  34506. if (layoutOption.y != null) {
  34507. // TODO height of chart view.
  34508. label.y = parsePercent$1(layoutOption.y, height);
  34509. label.setStyle('y', 0); // Ignore movement in style.
  34510. needsUpdateLabelLine = true;
  34511. } else {
  34512. label.y = defaultLabelAttr.y;
  34513. label.setStyle('y', defaultLabelAttr.style.y);
  34514. }
  34515. if (layoutOption.labelLinePoints) {
  34516. var guideLine = hostEl.getTextGuideLine();
  34517. if (guideLine) {
  34518. guideLine.setShape({
  34519. points: layoutOption.labelLinePoints
  34520. }); // Not update
  34521. needsUpdateLabelLine = false;
  34522. }
  34523. }
  34524. var labelLayoutStore = labelLayoutInnerStore(label);
  34525. labelLayoutStore.needsUpdateLabelLine = needsUpdateLabelLine;
  34526. label.rotation = layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.rotation;
  34527. label.scaleX = defaultLabelAttr.scaleX;
  34528. label.scaleY = defaultLabelAttr.scaleY;
  34529. for (var k = 0; k < LABEL_OPTION_TO_STYLE_KEYS.length; k++) {
  34530. var key = LABEL_OPTION_TO_STYLE_KEYS[k];
  34531. label.setStyle(key, layoutOption[key] != null ? layoutOption[key] : defaultLabelAttr.style[key]);
  34532. }
  34533. if (layoutOption.draggable) {
  34534. label.draggable = true;
  34535. label.cursor = 'move';
  34536. if (hostEl) {
  34537. var hostModel = labelItem.seriesModel;
  34538. if (labelItem.dataIndex != null) {
  34539. var data = labelItem.seriesModel.getData(labelItem.dataType);
  34540. hostModel = data.getItemModel(labelItem.dataIndex);
  34541. }
  34542. label.on('drag', createDragHandler(hostEl, hostModel.getModel('labelLine')));
  34543. }
  34544. } else {
  34545. // TODO Other drag functions?
  34546. label.off('drag');
  34547. label.cursor = defaultLabelAttr.cursor;
  34548. }
  34549. }
  34550. };
  34551. LabelManager.prototype.layout = function (api) {
  34552. var width = api.getWidth();
  34553. var height = api.getHeight();
  34554. var labelList = prepareLayoutList(this._labelList);
  34555. var labelsNeedsAdjustOnX = filter(labelList, function (item) {
  34556. return item.layoutOption.moveOverlap === 'shiftX';
  34557. });
  34558. var labelsNeedsAdjustOnY = filter(labelList, function (item) {
  34559. return item.layoutOption.moveOverlap === 'shiftY';
  34560. });
  34561. shiftLayoutOnX(labelsNeedsAdjustOnX, 0, width);
  34562. shiftLayoutOnY(labelsNeedsAdjustOnY, 0, height);
  34563. var labelsNeedsHideOverlap = filter(labelList, function (item) {
  34564. return item.layoutOption.hideOverlap;
  34565. });
  34566. hideOverlap(labelsNeedsHideOverlap);
  34567. };
  34568. /**
  34569. * Process all labels. Not only labels with layoutOption.
  34570. */
  34571. LabelManager.prototype.processLabelsOverall = function () {
  34572. var _this = this;
  34573. each(this._chartViewList, function (chartView) {
  34574. var seriesModel = chartView.__model;
  34575. var ignoreLabelLineUpdate = chartView.ignoreLabelLineUpdate;
  34576. var animationEnabled = seriesModel.isAnimationEnabled();
  34577. chartView.group.traverse(function (child) {
  34578. if (child.ignore) {
  34579. return true; // Stop traverse descendants.
  34580. }
  34581. var needsUpdateLabelLine = !ignoreLabelLineUpdate;
  34582. var label = child.getTextContent();
  34583. if (!needsUpdateLabelLine && label) {
  34584. needsUpdateLabelLine = labelLayoutInnerStore(label).needsUpdateLabelLine;
  34585. }
  34586. if (needsUpdateLabelLine) {
  34587. _this._updateLabelLine(child, seriesModel);
  34588. }
  34589. if (animationEnabled) {
  34590. _this._animateLabels(child, seriesModel);
  34591. }
  34592. });
  34593. });
  34594. };
  34595. LabelManager.prototype._updateLabelLine = function (el, seriesModel) {
  34596. // Only support label being hosted on graphic elements.
  34597. var textEl = el.getTextContent(); // Update label line style.
  34598. var ecData = getECData(el);
  34599. var dataIndex = ecData.dataIndex; // Only support labelLine on the labels represent data.
  34600. if (textEl && dataIndex != null) {
  34601. var data = seriesModel.getData(ecData.dataType);
  34602. var itemModel = data.getItemModel(dataIndex);
  34603. var defaultStyle = {};
  34604. var visualStyle = data.getItemVisual(dataIndex, 'style');
  34605. var visualType = data.getVisual('drawType'); // Default to be same with main color
  34606. defaultStyle.stroke = visualStyle[visualType];
  34607. var labelLineModel = itemModel.getModel('labelLine');
  34608. setLabelLineStyle(el, getLabelLineStatesModels(itemModel), defaultStyle);
  34609. updateLabelLinePoints(el, labelLineModel);
  34610. }
  34611. };
  34612. LabelManager.prototype._animateLabels = function (el, seriesModel) {
  34613. var textEl = el.getTextContent();
  34614. var guideLine = el.getTextGuideLine(); // Animate
  34615. if (textEl && !textEl.ignore && !textEl.invisible && !el.disableLabelAnimation && !isElementRemoved(el)) {
  34616. var layoutStore = labelLayoutInnerStore(textEl);
  34617. var oldLayout = layoutStore.oldLayout;
  34618. var ecData = getECData(el);
  34619. var dataIndex = ecData.dataIndex;
  34620. var newProps = {
  34621. x: textEl.x,
  34622. y: textEl.y,
  34623. rotation: textEl.rotation
  34624. };
  34625. var data = seriesModel.getData(ecData.dataType);
  34626. if (!oldLayout) {
  34627. textEl.attr(newProps); // Disable fade in animation if value animation is enabled.
  34628. if (!labelInner(textEl).valueAnimation) {
  34629. var oldOpacity = retrieve2(textEl.style.opacity, 1); // Fade in animation
  34630. textEl.style.opacity = 0;
  34631. initProps(textEl, {
  34632. style: {
  34633. opacity: oldOpacity
  34634. }
  34635. }, seriesModel, dataIndex);
  34636. }
  34637. } else {
  34638. textEl.attr(oldLayout); // Make sure the animation from is in the right status.
  34639. var prevStates = el.prevStates;
  34640. if (prevStates) {
  34641. if (indexOf(prevStates, 'select') >= 0) {
  34642. textEl.attr(layoutStore.oldLayoutSelect);
  34643. }
  34644. if (indexOf(prevStates, 'emphasis') >= 0) {
  34645. textEl.attr(layoutStore.oldLayoutEmphasis);
  34646. }
  34647. }
  34648. updateProps(textEl, newProps, seriesModel, dataIndex);
  34649. }
  34650. layoutStore.oldLayout = newProps;
  34651. if (textEl.states.select) {
  34652. var layoutSelect = layoutStore.oldLayoutSelect = {};
  34653. extendWithKeys(layoutSelect, newProps, LABEL_LAYOUT_PROPS);
  34654. extendWithKeys(layoutSelect, textEl.states.select, LABEL_LAYOUT_PROPS);
  34655. }
  34656. if (textEl.states.emphasis) {
  34657. var layoutEmphasis = layoutStore.oldLayoutEmphasis = {};
  34658. extendWithKeys(layoutEmphasis, newProps, LABEL_LAYOUT_PROPS);
  34659. extendWithKeys(layoutEmphasis, textEl.states.emphasis, LABEL_LAYOUT_PROPS);
  34660. }
  34661. animateLabelValue(textEl, dataIndex, data, seriesModel, seriesModel);
  34662. }
  34663. if (guideLine && !guideLine.ignore && !guideLine.invisible) {
  34664. var layoutStore = labelLineAnimationStore(guideLine);
  34665. var oldLayout = layoutStore.oldLayout;
  34666. var newLayout = {
  34667. points: guideLine.shape.points
  34668. };
  34669. if (!oldLayout) {
  34670. guideLine.setShape(newLayout);
  34671. guideLine.style.strokePercent = 0;
  34672. initProps(guideLine, {
  34673. style: {
  34674. strokePercent: 1
  34675. }
  34676. }, seriesModel);
  34677. } else {
  34678. guideLine.attr({
  34679. shape: oldLayout
  34680. });
  34681. updateProps(guideLine, {
  34682. shape: newLayout
  34683. }, seriesModel);
  34684. }
  34685. layoutStore.oldLayout = newLayout;
  34686. }
  34687. };
  34688. return LabelManager;
  34689. }();
  34690. var getLabelManager = makeInner();
  34691. function installLabelLayout(registers) {
  34692. registers.registerUpdateLifecycle('series:beforeupdate', function (ecModel, api, params) {
  34693. // TODO api provide an namespace that can save stuff per instance
  34694. var labelManager = getLabelManager(api).labelManager;
  34695. if (!labelManager) {
  34696. labelManager = getLabelManager(api).labelManager = new LabelManager();
  34697. }
  34698. labelManager.clearLabels();
  34699. });
  34700. registers.registerUpdateLifecycle('series:layoutlabels', function (ecModel, api, params) {
  34701. var labelManager = getLabelManager(api).labelManager;
  34702. params.updatedSeries.forEach(function (series) {
  34703. labelManager.addLabelsOfSeries(api.getViewOfSeriesModel(series));
  34704. });
  34705. labelManager.updateLayoutConfig(api);
  34706. labelManager.layout(api);
  34707. labelManager.processLabelsOverall();
  34708. });
  34709. }
  34710. function createElement(name) {
  34711. return document.createElementNS('http://www.w3.org/2000/svg', name);
  34712. }
  34713. function normalizeColor(color) {
  34714. var opacity;
  34715. if (!color || color === 'transparent') {
  34716. color = 'none';
  34717. }
  34718. else if (typeof color === 'string' && color.indexOf('rgba') > -1) {
  34719. var arr = parse(color);
  34720. if (arr) {
  34721. color = 'rgb(' + arr[0] + ',' + arr[1] + ',' + arr[2] + ')';
  34722. opacity = arr[3];
  34723. }
  34724. }
  34725. return {
  34726. color: color,
  34727. opacity: opacity == null ? 1 : opacity
  34728. };
  34729. }
  34730. function diff(oldArr, newArr, equals) {
  34731. if (!equals) {
  34732. equals = function (a, b) {
  34733. return a === b;
  34734. };
  34735. }
  34736. oldArr = oldArr.slice();
  34737. newArr = newArr.slice();
  34738. var newLen = newArr.length;
  34739. var oldLen = oldArr.length;
  34740. var editLength = 1;
  34741. var maxEditLength = newLen + oldLen;
  34742. var bestPath = [{ newPos: -1, components: [] }];
  34743. var oldPos = extractCommon(bestPath[0], newArr, oldArr, 0, equals);
  34744. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  34745. var indices = [];
  34746. for (var i = 0; i < newArr.length; i++) {
  34747. indices.push(i);
  34748. }
  34749. return [{
  34750. indices: indices,
  34751. count: newArr.length,
  34752. added: false,
  34753. removed: false
  34754. }];
  34755. }
  34756. function execEditLength() {
  34757. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  34758. var basePath;
  34759. var addPath = bestPath[diagonalPath - 1];
  34760. var removePath = bestPath[diagonalPath + 1];
  34761. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  34762. if (addPath) {
  34763. bestPath[diagonalPath - 1] = undefined;
  34764. }
  34765. var canAdd = addPath && addPath.newPos + 1 < newLen;
  34766. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  34767. if (!canAdd && !canRemove) {
  34768. bestPath[diagonalPath] = undefined;
  34769. continue;
  34770. }
  34771. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  34772. basePath = clonePath$1(removePath);
  34773. pushComponent(basePath.components, false, true);
  34774. }
  34775. else {
  34776. basePath = addPath;
  34777. basePath.newPos++;
  34778. pushComponent(basePath.components, true, false);
  34779. }
  34780. oldPos = extractCommon(basePath, newArr, oldArr, diagonalPath, equals);
  34781. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  34782. return buildValues(basePath.components);
  34783. }
  34784. else {
  34785. bestPath[diagonalPath] = basePath;
  34786. }
  34787. }
  34788. editLength++;
  34789. }
  34790. while (editLength <= maxEditLength) {
  34791. var ret = execEditLength();
  34792. if (ret) {
  34793. return ret;
  34794. }
  34795. }
  34796. }
  34797. function extractCommon(basePath, newArr, oldArr, diagonalPath, equals) {
  34798. var newLen = newArr.length;
  34799. var oldLen = oldArr.length;
  34800. var newPos = basePath.newPos;
  34801. var oldPos = newPos - diagonalPath;
  34802. var commonCount = 0;
  34803. while (newPos + 1 < newLen && oldPos + 1 < oldLen && equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  34804. newPos++;
  34805. oldPos++;
  34806. commonCount++;
  34807. }
  34808. if (commonCount) {
  34809. basePath.components.push({
  34810. count: commonCount,
  34811. added: false,
  34812. removed: false,
  34813. indices: []
  34814. });
  34815. }
  34816. basePath.newPos = newPos;
  34817. return oldPos;
  34818. }
  34819. function pushComponent(components, added, removed) {
  34820. var last = components[components.length - 1];
  34821. if (last && last.added === added && last.removed === removed) {
  34822. components[components.length - 1] = {
  34823. count: last.count + 1,
  34824. added: added,
  34825. removed: removed,
  34826. indices: []
  34827. };
  34828. }
  34829. else {
  34830. components.push({
  34831. count: 1,
  34832. added: added,
  34833. removed: removed,
  34834. indices: []
  34835. });
  34836. }
  34837. }
  34838. function buildValues(components) {
  34839. var componentPos = 0;
  34840. var componentLen = components.length;
  34841. var newPos = 0;
  34842. var oldPos = 0;
  34843. for (; componentPos < componentLen; componentPos++) {
  34844. var component = components[componentPos];
  34845. if (!component.removed) {
  34846. var indices = [];
  34847. for (var i = newPos; i < newPos + component.count; i++) {
  34848. indices.push(i);
  34849. }
  34850. component.indices = indices;
  34851. newPos += component.count;
  34852. if (!component.added) {
  34853. oldPos += component.count;
  34854. }
  34855. }
  34856. else {
  34857. for (var i = oldPos; i < oldPos + component.count; i++) {
  34858. component.indices.push(i);
  34859. }
  34860. oldPos += component.count;
  34861. }
  34862. }
  34863. return components;
  34864. }
  34865. function clonePath$1(path) {
  34866. return { newPos: path.newPos, components: path.components.slice(0) };
  34867. }
  34868. function arrayDiff(oldArr, newArr, equal) {
  34869. return diff(oldArr, newArr, equal);
  34870. }
  34871. var NONE = 'none';
  34872. var mathRound = Math.round;
  34873. var mathSin$4 = Math.sin;
  34874. var mathCos$4 = Math.cos;
  34875. var PI$4 = Math.PI;
  34876. var PI2$7 = Math.PI * 2;
  34877. var degree = 180 / PI$4;
  34878. var EPSILON$4 = 1e-4;
  34879. function round3(val) {
  34880. return mathRound(val * 1e3) / 1e3;
  34881. }
  34882. function round4(val) {
  34883. return mathRound(val * 1e4) / 1e4;
  34884. }
  34885. function isAroundZero$1(val) {
  34886. return val < EPSILON$4 && val > -EPSILON$4;
  34887. }
  34888. function pathHasFill(style) {
  34889. var fill = style.fill;
  34890. return fill != null && fill !== NONE;
  34891. }
  34892. function pathHasStroke(style) {
  34893. var stroke = style.stroke;
  34894. return stroke != null && stroke !== NONE;
  34895. }
  34896. function setTransform(svgEl, m) {
  34897. if (m) {
  34898. attr(svgEl, 'transform', 'matrix('
  34899. + round3(m[0]) + ','
  34900. + round3(m[1]) + ','
  34901. + round3(m[2]) + ','
  34902. + round3(m[3]) + ','
  34903. + round4(m[4]) + ','
  34904. + round4(m[5])
  34905. + ')');
  34906. }
  34907. }
  34908. function attr(el, key, val) {
  34909. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  34910. el.setAttribute(key, val);
  34911. }
  34912. }
  34913. function attrXLink(el, key, val) {
  34914. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  34915. }
  34916. function attrXML(el, key, val) {
  34917. el.setAttributeNS('http://www.w3.org/XML/1998/namespace', key, val);
  34918. }
  34919. function bindStyle(svgEl, style, el) {
  34920. var opacity = style.opacity == null ? 1 : style.opacity;
  34921. if (el instanceof ZRImage) {
  34922. svgEl.style.opacity = opacity + '';
  34923. return;
  34924. }
  34925. if (pathHasFill(style)) {
  34926. var fill = normalizeColor(style.fill);
  34927. attr(svgEl, 'fill', fill.color);
  34928. attr(svgEl, 'fill-opacity', (style.fillOpacity != null
  34929. ? style.fillOpacity * fill.opacity * opacity
  34930. : fill.opacity * opacity) + '');
  34931. }
  34932. else {
  34933. attr(svgEl, 'fill', NONE);
  34934. }
  34935. if (pathHasStroke(style)) {
  34936. var stroke = normalizeColor(style.stroke);
  34937. attr(svgEl, 'stroke', stroke.color);
  34938. var strokeWidth = style.lineWidth;
  34939. var strokeScale_1 = style.strokeNoScale
  34940. ? el.getLineScale()
  34941. : 1;
  34942. attr(svgEl, 'stroke-width', (strokeScale_1 ? strokeWidth / strokeScale_1 : 0) + '');
  34943. attr(svgEl, 'paint-order', style.strokeFirst ? 'stroke' : 'fill');
  34944. attr(svgEl, 'stroke-opacity', (style.strokeOpacity != null
  34945. ? style.strokeOpacity * stroke.opacity * opacity
  34946. : stroke.opacity * opacity) + '');
  34947. var lineDash = style.lineDash && strokeWidth > 0 && normalizeLineDash(style.lineDash, strokeWidth);
  34948. if (lineDash) {
  34949. var lineDashOffset = style.lineDashOffset;
  34950. if (strokeScale_1 && strokeScale_1 !== 1) {
  34951. lineDash = map(lineDash, function (rawVal) {
  34952. return rawVal / strokeScale_1;
  34953. });
  34954. if (lineDashOffset) {
  34955. lineDashOffset /= strokeScale_1;
  34956. lineDashOffset = mathRound(lineDashOffset);
  34957. }
  34958. }
  34959. attr(svgEl, 'stroke-dasharray', lineDash.join(','));
  34960. attr(svgEl, 'stroke-dashoffset', (lineDashOffset || 0) + '');
  34961. }
  34962. else {
  34963. attr(svgEl, 'stroke-dasharray', '');
  34964. }
  34965. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  34966. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  34967. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit + '');
  34968. }
  34969. else {
  34970. attr(svgEl, 'stroke', NONE);
  34971. }
  34972. }
  34973. var SVGPathRebuilder = (function () {
  34974. function SVGPathRebuilder() {
  34975. }
  34976. SVGPathRebuilder.prototype.reset = function () {
  34977. this._d = [];
  34978. this._str = '';
  34979. };
  34980. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  34981. this._add('M', x, y);
  34982. };
  34983. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  34984. this._add('L', x, y);
  34985. };
  34986. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  34987. this._add('C', x, y, x2, y2, x3, y3);
  34988. };
  34989. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  34990. this._add('Q', x, y, x2, y2);
  34991. };
  34992. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  34993. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  34994. };
  34995. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  34996. var firstCmd = this._d.length === 0;
  34997. var dTheta = endAngle - startAngle;
  34998. var clockwise = !anticlockwise;
  34999. var dThetaPositive = Math.abs(dTheta);
  35000. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  35001. || (clockwise ? dTheta >= PI2$7 : -dTheta >= PI2$7);
  35002. var unifiedTheta = dTheta > 0 ? dTheta % PI2$7 : (dTheta % PI2$7 + PI2$7);
  35003. var large = false;
  35004. if (isCircle) {
  35005. large = true;
  35006. }
  35007. else if (isAroundZero$1(dThetaPositive)) {
  35008. large = false;
  35009. }
  35010. else {
  35011. large = (unifiedTheta >= PI$4) === !!clockwise;
  35012. }
  35013. var x0 = round4(cx + rx * mathCos$4(startAngle));
  35014. var y0 = round4(cy + ry * mathSin$4(startAngle));
  35015. if (isCircle) {
  35016. if (clockwise) {
  35017. dTheta = PI2$7 - 1e-4;
  35018. }
  35019. else {
  35020. dTheta = -PI2$7 + 1e-4;
  35021. }
  35022. large = true;
  35023. if (firstCmd) {
  35024. this._d.push('M', x0, y0);
  35025. }
  35026. }
  35027. var x = round4(cx + rx * mathCos$4(startAngle + dTheta));
  35028. var y = round4(cy + ry * mathSin$4(startAngle + dTheta));
  35029. if (isNaN(x0) || isNaN(y0) || isNaN(rx) || isNaN(ry) || isNaN(psi) || isNaN(degree) || isNaN(x) || isNaN(y)) {
  35030. return '';
  35031. }
  35032. this._d.push('A', round4(rx), round4(ry), mathRound(psi * degree), +large, +clockwise, x, y);
  35033. };
  35034. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  35035. this._add('M', x, y);
  35036. this._add('L', x + w, y);
  35037. this._add('L', x + w, y + h);
  35038. this._add('L', x, y + h);
  35039. this._add('L', x, y);
  35040. this._add('Z');
  35041. };
  35042. SVGPathRebuilder.prototype.closePath = function () {
  35043. if (this._d.length > 0) {
  35044. this._add('Z');
  35045. }
  35046. };
  35047. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  35048. this._d.push(cmd);
  35049. for (var i = 1; i < arguments.length; i++) {
  35050. var val = arguments[i];
  35051. if (isNaN(val)) {
  35052. this._invalid = true;
  35053. return;
  35054. }
  35055. this._d.push(round4(val));
  35056. }
  35057. };
  35058. SVGPathRebuilder.prototype.generateStr = function () {
  35059. this._str = this._invalid ? '' : this._d.join(' ');
  35060. this._d = [];
  35061. };
  35062. SVGPathRebuilder.prototype.getStr = function () {
  35063. return this._str;
  35064. };
  35065. return SVGPathRebuilder;
  35066. }());
  35067. var svgPath = {
  35068. brush: function (el) {
  35069. var style = el.style;
  35070. var svgEl = el.__svgEl;
  35071. if (!svgEl) {
  35072. svgEl = createElement('path');
  35073. el.__svgEl = svgEl;
  35074. }
  35075. if (!el.path) {
  35076. el.createPathProxy();
  35077. }
  35078. var path = el.path;
  35079. if (el.shapeChanged()) {
  35080. path.beginPath();
  35081. el.buildPath(path, el.shape);
  35082. el.pathUpdated();
  35083. }
  35084. var pathVersion = path.getVersion();
  35085. var elExt = el;
  35086. var svgPathBuilder = elExt.__svgPathBuilder;
  35087. if (elExt.__svgPathVersion !== pathVersion || !svgPathBuilder || el.style.strokePercent < 1) {
  35088. if (!svgPathBuilder) {
  35089. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  35090. }
  35091. svgPathBuilder.reset();
  35092. path.rebuildPath(svgPathBuilder, el.style.strokePercent);
  35093. svgPathBuilder.generateStr();
  35094. elExt.__svgPathVersion = pathVersion;
  35095. }
  35096. attr(svgEl, 'd', svgPathBuilder.getStr());
  35097. bindStyle(svgEl, style, el);
  35098. setTransform(svgEl, el.transform);
  35099. }
  35100. };
  35101. var svgImage = {
  35102. brush: function (el) {
  35103. var style = el.style;
  35104. var image = style.image;
  35105. if (image instanceof HTMLImageElement) {
  35106. image = image.src;
  35107. }
  35108. else if (image instanceof HTMLCanvasElement) {
  35109. image = image.toDataURL();
  35110. }
  35111. if (!image) {
  35112. return;
  35113. }
  35114. var x = style.x || 0;
  35115. var y = style.y || 0;
  35116. var dw = style.width;
  35117. var dh = style.height;
  35118. var svgEl = el.__svgEl;
  35119. if (!svgEl) {
  35120. svgEl = createElement('image');
  35121. el.__svgEl = svgEl;
  35122. }
  35123. if (image !== el.__imageSrc) {
  35124. attrXLink(svgEl, 'href', image);
  35125. el.__imageSrc = image;
  35126. }
  35127. attr(svgEl, 'width', dw + '');
  35128. attr(svgEl, 'height', dh + '');
  35129. attr(svgEl, 'x', x + '');
  35130. attr(svgEl, 'y', y + '');
  35131. bindStyle(svgEl, style, el);
  35132. setTransform(svgEl, el.transform);
  35133. }
  35134. };
  35135. var TEXT_ALIGN_TO_ANCHOR = {
  35136. left: 'start',
  35137. right: 'end',
  35138. center: 'middle',
  35139. middle: 'middle'
  35140. };
  35141. function adjustTextY$1(y, lineHeight, textBaseline) {
  35142. if (textBaseline === 'top') {
  35143. y += lineHeight / 2;
  35144. }
  35145. else if (textBaseline === 'bottom') {
  35146. y -= lineHeight / 2;
  35147. }
  35148. return y;
  35149. }
  35150. var svgText = {
  35151. brush: function (el) {
  35152. var style = el.style;
  35153. var text = style.text;
  35154. text != null && (text += '');
  35155. if (!text || isNaN(style.x) || isNaN(style.y)) {
  35156. return;
  35157. }
  35158. var textSvgEl = el.__svgEl;
  35159. if (!textSvgEl) {
  35160. textSvgEl = createElement('text');
  35161. attrXML(textSvgEl, 'xml:space', 'preserve');
  35162. el.__svgEl = textSvgEl;
  35163. }
  35164. var font = style.font || DEFAULT_FONT;
  35165. var textSvgElStyle = textSvgEl.style;
  35166. textSvgElStyle.font = font;
  35167. textSvgEl.textContent = text;
  35168. bindStyle(textSvgEl, style, el);
  35169. setTransform(textSvgEl, el.transform);
  35170. var x = style.x || 0;
  35171. var y = adjustTextY$1(style.y || 0, getLineHeight(font), style.textBaseline);
  35172. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  35173. || style.textAlign;
  35174. attr(textSvgEl, 'dominant-baseline', 'central');
  35175. attr(textSvgEl, 'text-anchor', textAlign);
  35176. attr(textSvgEl, 'x', x + '');
  35177. attr(textSvgEl, 'y', y + '');
  35178. }
  35179. };
  35180. var MARK_UNUSED = '0';
  35181. var MARK_USED = '1';
  35182. var Definable = (function () {
  35183. function Definable(zrId, svgRoot, tagNames, markLabel, domName) {
  35184. this.nextId = 0;
  35185. this._domName = '_dom';
  35186. this.createElement = createElement;
  35187. this._zrId = zrId;
  35188. this._svgRoot = svgRoot;
  35189. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  35190. this._markLabel = markLabel;
  35191. if (domName) {
  35192. this._domName = domName;
  35193. }
  35194. }
  35195. Definable.prototype.getDefs = function (isForceCreating) {
  35196. var svgRoot = this._svgRoot;
  35197. var defs = this._svgRoot.getElementsByTagName('defs');
  35198. if (defs.length === 0) {
  35199. if (isForceCreating) {
  35200. var defs_1 = svgRoot.insertBefore(this.createElement('defs'), svgRoot.firstChild);
  35201. if (!defs_1.contains) {
  35202. defs_1.contains = function (el) {
  35203. var children = defs_1.children;
  35204. if (!children) {
  35205. return false;
  35206. }
  35207. for (var i = children.length - 1; i >= 0; --i) {
  35208. if (children[i] === el) {
  35209. return true;
  35210. }
  35211. }
  35212. return false;
  35213. };
  35214. }
  35215. return defs_1;
  35216. }
  35217. else {
  35218. return null;
  35219. }
  35220. }
  35221. else {
  35222. return defs[0];
  35223. }
  35224. };
  35225. Definable.prototype.doUpdate = function (target, onUpdate) {
  35226. if (!target) {
  35227. return;
  35228. }
  35229. var defs = this.getDefs(false);
  35230. if (target[this._domName] && defs.contains(target[this._domName])) {
  35231. if (typeof onUpdate === 'function') {
  35232. onUpdate(target);
  35233. }
  35234. }
  35235. else {
  35236. var dom = this.add(target);
  35237. if (dom) {
  35238. target[this._domName] = dom;
  35239. }
  35240. }
  35241. };
  35242. Definable.prototype.add = function (target) {
  35243. return null;
  35244. };
  35245. Definable.prototype.addDom = function (dom) {
  35246. var defs = this.getDefs(true);
  35247. if (dom.parentNode !== defs) {
  35248. defs.appendChild(dom);
  35249. }
  35250. };
  35251. Definable.prototype.removeDom = function (target) {
  35252. var defs = this.getDefs(false);
  35253. if (defs && target[this._domName]) {
  35254. defs.removeChild(target[this._domName]);
  35255. target[this._domName] = null;
  35256. }
  35257. };
  35258. Definable.prototype.getDoms = function () {
  35259. var defs = this.getDefs(false);
  35260. if (!defs) {
  35261. return [];
  35262. }
  35263. var doms = [];
  35264. each(this._tagNames, function (tagName) {
  35265. var tags = defs.getElementsByTagName(tagName);
  35266. for (var i = 0; i < tags.length; i++) {
  35267. doms.push(tags[i]);
  35268. }
  35269. });
  35270. return doms;
  35271. };
  35272. Definable.prototype.markAllUnused = function () {
  35273. var doms = this.getDoms();
  35274. var that = this;
  35275. each(doms, function (dom) {
  35276. dom[that._markLabel] = MARK_UNUSED;
  35277. });
  35278. };
  35279. Definable.prototype.markDomUsed = function (dom) {
  35280. dom && (dom[this._markLabel] = MARK_USED);
  35281. };
  35282. Definable.prototype.markDomUnused = function (dom) {
  35283. dom && (dom[this._markLabel] = MARK_UNUSED);
  35284. };
  35285. Definable.prototype.isDomUnused = function (dom) {
  35286. return dom && dom[this._markLabel] !== MARK_USED;
  35287. };
  35288. Definable.prototype.removeUnused = function () {
  35289. var _this = this;
  35290. var defs = this.getDefs(false);
  35291. if (!defs) {
  35292. return;
  35293. }
  35294. var doms = this.getDoms();
  35295. each(doms, function (dom) {
  35296. if (_this.isDomUnused(dom)) {
  35297. defs.removeChild(dom);
  35298. }
  35299. });
  35300. };
  35301. Definable.prototype.getSvgProxy = function (displayable) {
  35302. if (displayable instanceof Path) {
  35303. return svgPath;
  35304. }
  35305. else if (displayable instanceof ZRImage) {
  35306. return svgImage;
  35307. }
  35308. else if (displayable instanceof TSpan) {
  35309. return svgText;
  35310. }
  35311. else {
  35312. return svgPath;
  35313. }
  35314. };
  35315. Definable.prototype.getSvgElement = function (displayable) {
  35316. return displayable.__svgEl;
  35317. };
  35318. return Definable;
  35319. }());
  35320. function isLinearGradient(value) {
  35321. return value.type === 'linear';
  35322. }
  35323. function isRadialGradient(value) {
  35324. return value.type === 'radial';
  35325. }
  35326. function isGradient(value) {
  35327. return value && (value.type === 'linear'
  35328. || value.type === 'radial');
  35329. }
  35330. var GradientManager = (function (_super) {
  35331. __extends(GradientManager, _super);
  35332. function GradientManager(zrId, svgRoot) {
  35333. return _super.call(this, zrId, svgRoot, ['linearGradient', 'radialGradient'], '__gradient_in_use__') || this;
  35334. }
  35335. GradientManager.prototype.addWithoutUpdate = function (svgElement, displayable) {
  35336. if (displayable && displayable.style) {
  35337. var that_1 = this;
  35338. each(['fill', 'stroke'], function (fillOrStroke) {
  35339. var value = displayable.style[fillOrStroke];
  35340. if (isGradient(value)) {
  35341. var gradient = value;
  35342. var defs = that_1.getDefs(true);
  35343. var dom = void 0;
  35344. if (gradient.__dom) {
  35345. dom = gradient.__dom;
  35346. if (!defs.contains(gradient.__dom)) {
  35347. that_1.addDom(dom);
  35348. }
  35349. }
  35350. else {
  35351. dom = that_1.add(gradient);
  35352. }
  35353. that_1.markUsed(displayable);
  35354. var id = dom.getAttribute('id');
  35355. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  35356. }
  35357. });
  35358. }
  35359. };
  35360. GradientManager.prototype.add = function (gradient) {
  35361. var dom;
  35362. if (isLinearGradient(gradient)) {
  35363. dom = this.createElement('linearGradient');
  35364. }
  35365. else if (isRadialGradient(gradient)) {
  35366. dom = this.createElement('radialGradient');
  35367. }
  35368. else {
  35369. logError('Illegal gradient type.');
  35370. return null;
  35371. }
  35372. gradient.id = gradient.id || this.nextId++;
  35373. dom.setAttribute('id', 'zr' + this._zrId
  35374. + '-gradient-' + gradient.id);
  35375. this.updateDom(gradient, dom);
  35376. this.addDom(dom);
  35377. return dom;
  35378. };
  35379. GradientManager.prototype.update = function (gradient) {
  35380. if (!isGradient(gradient)) {
  35381. return;
  35382. }
  35383. var that = this;
  35384. this.doUpdate(gradient, function () {
  35385. var dom = gradient.__dom;
  35386. if (!dom) {
  35387. return;
  35388. }
  35389. var tagName = dom.tagName;
  35390. var type = gradient.type;
  35391. if (type === 'linear' && tagName === 'linearGradient'
  35392. || type === 'radial' && tagName === 'radialGradient') {
  35393. that.updateDom(gradient, gradient.__dom);
  35394. }
  35395. else {
  35396. that.removeDom(gradient);
  35397. that.add(gradient);
  35398. }
  35399. });
  35400. };
  35401. GradientManager.prototype.updateDom = function (gradient, dom) {
  35402. if (isLinearGradient(gradient)) {
  35403. dom.setAttribute('x1', gradient.x + '');
  35404. dom.setAttribute('y1', gradient.y + '');
  35405. dom.setAttribute('x2', gradient.x2 + '');
  35406. dom.setAttribute('y2', gradient.y2 + '');
  35407. }
  35408. else if (isRadialGradient(gradient)) {
  35409. dom.setAttribute('cx', gradient.x + '');
  35410. dom.setAttribute('cy', gradient.y + '');
  35411. dom.setAttribute('r', gradient.r + '');
  35412. }
  35413. else {
  35414. logError('Illegal gradient type.');
  35415. return;
  35416. }
  35417. if (gradient.global) {
  35418. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  35419. }
  35420. else {
  35421. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  35422. }
  35423. dom.innerHTML = '';
  35424. var colors = gradient.colorStops;
  35425. for (var i = 0, len = colors.length; i < len; ++i) {
  35426. var stop_1 = this.createElement('stop');
  35427. stop_1.setAttribute('offset', colors[i].offset * 100 + '%');
  35428. var color$1 = colors[i].color;
  35429. if (color$1.indexOf('rgba') > -1) {
  35430. var opacity = parse(color$1)[3];
  35431. var hex = toHex(color$1);
  35432. stop_1.setAttribute('stop-color', '#' + hex);
  35433. stop_1.setAttribute('stop-opacity', opacity + '');
  35434. }
  35435. else {
  35436. stop_1.setAttribute('stop-color', colors[i].color);
  35437. }
  35438. dom.appendChild(stop_1);
  35439. }
  35440. gradient.__dom = dom;
  35441. };
  35442. GradientManager.prototype.markUsed = function (displayable) {
  35443. if (displayable.style) {
  35444. var gradient = displayable.style.fill;
  35445. if (gradient && gradient.__dom) {
  35446. _super.prototype.markDomUsed.call(this, gradient.__dom);
  35447. }
  35448. gradient = displayable.style.stroke;
  35449. if (gradient && gradient.__dom) {
  35450. _super.prototype.markDomUsed.call(this, gradient.__dom);
  35451. }
  35452. }
  35453. };
  35454. return GradientManager;
  35455. }(Definable));
  35456. function isPattern(value) {
  35457. return value && (!!value.image || !!value.svgElement);
  35458. }
  35459. var patternDomMap = new WeakMap();
  35460. var PatternManager = (function (_super) {
  35461. __extends(PatternManager, _super);
  35462. function PatternManager(zrId, svgRoot) {
  35463. return _super.call(this, zrId, svgRoot, ['pattern'], '__pattern_in_use__') || this;
  35464. }
  35465. PatternManager.prototype.addWithoutUpdate = function (svgElement, displayable) {
  35466. if (displayable && displayable.style) {
  35467. var that_1 = this;
  35468. each(['fill', 'stroke'], function (fillOrStroke) {
  35469. var pattern = displayable.style[fillOrStroke];
  35470. if (isPattern(pattern)) {
  35471. var defs = that_1.getDefs(true);
  35472. var dom = patternDomMap.get(pattern);
  35473. if (dom) {
  35474. if (!defs.contains(dom)) {
  35475. that_1.addDom(dom);
  35476. }
  35477. }
  35478. else {
  35479. dom = that_1.add(pattern);
  35480. }
  35481. that_1.markUsed(displayable);
  35482. var id = dom.getAttribute('id');
  35483. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  35484. }
  35485. });
  35486. }
  35487. };
  35488. PatternManager.prototype.add = function (pattern) {
  35489. if (!isPattern(pattern)) {
  35490. return;
  35491. }
  35492. var dom = this.createElement('pattern');
  35493. pattern.id = pattern.id == null ? this.nextId++ : pattern.id;
  35494. dom.setAttribute('id', 'zr' + this._zrId
  35495. + '-pattern-' + pattern.id);
  35496. dom.setAttribute('x', '0');
  35497. dom.setAttribute('y', '0');
  35498. dom.setAttribute('patternUnits', 'userSpaceOnUse');
  35499. this.updateDom(pattern, dom);
  35500. this.addDom(dom);
  35501. return dom;
  35502. };
  35503. PatternManager.prototype.update = function (pattern) {
  35504. if (!isPattern(pattern)) {
  35505. return;
  35506. }
  35507. var that = this;
  35508. this.doUpdate(pattern, function () {
  35509. var dom = patternDomMap.get(pattern);
  35510. that.updateDom(pattern, dom);
  35511. });
  35512. };
  35513. PatternManager.prototype.updateDom = function (pattern, patternDom) {
  35514. var svgElement = pattern.svgElement;
  35515. if (svgElement instanceof SVGElement) {
  35516. if (svgElement.parentNode !== patternDom) {
  35517. patternDom.innerHTML = '';
  35518. patternDom.appendChild(svgElement);
  35519. patternDom.setAttribute('width', pattern.svgWidth + '');
  35520. patternDom.setAttribute('height', pattern.svgHeight + '');
  35521. }
  35522. }
  35523. else {
  35524. var img = void 0;
  35525. var prevImage = patternDom.getElementsByTagName('image');
  35526. if (prevImage.length) {
  35527. if (pattern.image) {
  35528. img = prevImage[0];
  35529. }
  35530. else {
  35531. patternDom.removeChild(prevImage[0]);
  35532. return;
  35533. }
  35534. }
  35535. else if (pattern.image) {
  35536. img = this.createElement('image');
  35537. }
  35538. if (img) {
  35539. var imageSrc = void 0;
  35540. var patternImage = pattern.image;
  35541. if (typeof patternImage === 'string') {
  35542. imageSrc = patternImage;
  35543. }
  35544. else if (patternImage instanceof HTMLImageElement) {
  35545. imageSrc = patternImage.src;
  35546. }
  35547. else if (patternImage instanceof HTMLCanvasElement) {
  35548. imageSrc = patternImage.toDataURL();
  35549. }
  35550. if (imageSrc) {
  35551. img.setAttribute('href', imageSrc);
  35552. img.setAttribute('x', '0');
  35553. img.setAttribute('y', '0');
  35554. var hostEl = {
  35555. dirty: function () { }
  35556. };
  35557. var createdImage = createOrUpdateImage(imageSrc, img, hostEl, function (img) {
  35558. patternDom.setAttribute('width', img.width + '');
  35559. patternDom.setAttribute('height', img.height + '');
  35560. });
  35561. if (createdImage && createdImage.width && createdImage.height) {
  35562. patternDom.setAttribute('width', createdImage.width + '');
  35563. patternDom.setAttribute('height', createdImage.height + '');
  35564. }
  35565. patternDom.appendChild(img);
  35566. }
  35567. }
  35568. }
  35569. var x = pattern.x || 0;
  35570. var y = pattern.y || 0;
  35571. var rotation = (pattern.rotation || 0) / Math.PI * 180;
  35572. var scaleX = pattern.scaleX || 1;
  35573. var scaleY = pattern.scaleY || 1;
  35574. var transform = "translate(" + x + ", " + y + ") rotate(" + rotation + ") scale(" + scaleX + ", " + scaleY + ")";
  35575. patternDom.setAttribute('patternTransform', transform);
  35576. patternDomMap.set(pattern, patternDom);
  35577. };
  35578. PatternManager.prototype.markUsed = function (displayable) {
  35579. if (displayable.style) {
  35580. if (isPattern(displayable.style.fill)) {
  35581. _super.prototype.markDomUsed.call(this, patternDomMap.get(displayable.style.fill));
  35582. }
  35583. if (isPattern(displayable.style.stroke)) {
  35584. _super.prototype.markDomUsed.call(this, patternDomMap.get(displayable.style.stroke));
  35585. }
  35586. }
  35587. };
  35588. return PatternManager;
  35589. }(Definable));
  35590. function generateClipPathsKey(clipPaths) {
  35591. var key = [];
  35592. if (clipPaths) {
  35593. for (var i = 0; i < clipPaths.length; i++) {
  35594. var clipPath = clipPaths[i];
  35595. key.push(clipPath.id);
  35596. }
  35597. }
  35598. return key.join(',');
  35599. }
  35600. function hasClipPath(displayable) {
  35601. var clipPaths = displayable.__clipPaths;
  35602. return clipPaths && clipPaths.length > 0;
  35603. }
  35604. var ClippathManager = (function (_super) {
  35605. __extends(ClippathManager, _super);
  35606. function ClippathManager(zrId, svgRoot) {
  35607. var _this = _super.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__') || this;
  35608. _this._refGroups = {};
  35609. _this._keyDuplicateCount = {};
  35610. return _this;
  35611. }
  35612. ClippathManager.prototype.markAllUnused = function () {
  35613. _super.prototype.markAllUnused.call(this);
  35614. var refGroups = this._refGroups;
  35615. for (var key in refGroups) {
  35616. if (refGroups.hasOwnProperty(key)) {
  35617. this.markDomUnused(refGroups[key]);
  35618. }
  35619. }
  35620. this._keyDuplicateCount = {};
  35621. };
  35622. ClippathManager.prototype._getClipPathGroup = function (displayable, prevDisplayable) {
  35623. if (!hasClipPath(displayable)) {
  35624. return;
  35625. }
  35626. var clipPaths = displayable.__clipPaths;
  35627. var keyDuplicateCount = this._keyDuplicateCount;
  35628. var clipPathKey = generateClipPathsKey(clipPaths);
  35629. if (isClipPathChanged(clipPaths, prevDisplayable && prevDisplayable.__clipPaths)) {
  35630. keyDuplicateCount[clipPathKey] = keyDuplicateCount[clipPathKey] || 0;
  35631. keyDuplicateCount[clipPathKey] && (clipPathKey += '-' + keyDuplicateCount[clipPathKey]);
  35632. keyDuplicateCount[clipPathKey]++;
  35633. }
  35634. return this._refGroups[clipPathKey]
  35635. || (this._refGroups[clipPathKey] = this.createElement('g'));
  35636. };
  35637. ClippathManager.prototype.update = function (displayable, prevDisplayable) {
  35638. var clipGroup = this._getClipPathGroup(displayable, prevDisplayable);
  35639. if (clipGroup) {
  35640. this.markDomUsed(clipGroup);
  35641. this.updateDom(clipGroup, displayable.__clipPaths);
  35642. }
  35643. return clipGroup;
  35644. };
  35645. ClippathManager.prototype.updateDom = function (parentEl, clipPaths) {
  35646. if (clipPaths && clipPaths.length > 0) {
  35647. var defs = this.getDefs(true);
  35648. var clipPath = clipPaths[0];
  35649. var clipPathEl = void 0;
  35650. var id = void 0;
  35651. if (clipPath._dom) {
  35652. id = clipPath._dom.getAttribute('id');
  35653. clipPathEl = clipPath._dom;
  35654. if (!defs.contains(clipPathEl)) {
  35655. defs.appendChild(clipPathEl);
  35656. }
  35657. }
  35658. else {
  35659. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  35660. ++this.nextId;
  35661. clipPathEl = this.createElement('clipPath');
  35662. clipPathEl.setAttribute('id', id);
  35663. defs.appendChild(clipPathEl);
  35664. clipPath._dom = clipPathEl;
  35665. }
  35666. var svgProxy = this.getSvgProxy(clipPath);
  35667. svgProxy.brush(clipPath);
  35668. var pathEl = this.getSvgElement(clipPath);
  35669. clipPathEl.innerHTML = '';
  35670. clipPathEl.appendChild(pathEl);
  35671. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  35672. if (clipPaths.length > 1) {
  35673. this.updateDom(clipPathEl, clipPaths.slice(1));
  35674. }
  35675. }
  35676. else {
  35677. if (parentEl) {
  35678. parentEl.setAttribute('clip-path', 'none');
  35679. }
  35680. }
  35681. };
  35682. ClippathManager.prototype.markUsed = function (displayable) {
  35683. var _this = this;
  35684. if (displayable.__clipPaths) {
  35685. each(displayable.__clipPaths, function (clipPath) {
  35686. if (clipPath._dom) {
  35687. _super.prototype.markDomUsed.call(_this, clipPath._dom);
  35688. }
  35689. });
  35690. }
  35691. };
  35692. ClippathManager.prototype.removeUnused = function () {
  35693. _super.prototype.removeUnused.call(this);
  35694. var newRefGroupsMap = {};
  35695. var refGroups = this._refGroups;
  35696. for (var key in refGroups) {
  35697. if (refGroups.hasOwnProperty(key)) {
  35698. var group = refGroups[key];
  35699. if (!this.isDomUnused(group)) {
  35700. newRefGroupsMap[key] = group;
  35701. }
  35702. else if (group.parentNode) {
  35703. group.parentNode.removeChild(group);
  35704. }
  35705. }
  35706. }
  35707. this._refGroups = newRefGroupsMap;
  35708. };
  35709. return ClippathManager;
  35710. }(Definable));
  35711. var ShadowManager = (function (_super) {
  35712. __extends(ShadowManager, _super);
  35713. function ShadowManager(zrId, svgRoot) {
  35714. var _this = _super.call(this, zrId, svgRoot, ['filter'], '__filter_in_use__', '_shadowDom') || this;
  35715. _this._shadowDomMap = {};
  35716. _this._shadowDomPool = [];
  35717. return _this;
  35718. }
  35719. ShadowManager.prototype._getFromPool = function () {
  35720. var shadowDom = this._shadowDomPool.pop();
  35721. if (!shadowDom) {
  35722. shadowDom = this.createElement('filter');
  35723. shadowDom.setAttribute('id', 'zr' + this._zrId + '-shadow-' + this.nextId++);
  35724. var domChild = this.createElement('feDropShadow');
  35725. shadowDom.appendChild(domChild);
  35726. this.addDom(shadowDom);
  35727. }
  35728. return shadowDom;
  35729. };
  35730. ShadowManager.prototype.update = function (svgElement, displayable) {
  35731. var style = displayable.style;
  35732. if (hasShadow(style)) {
  35733. var shadowKey = getShadowKey(displayable);
  35734. var shadowDom = displayable._shadowDom = this._shadowDomMap[shadowKey];
  35735. if (!shadowDom) {
  35736. shadowDom = this._getFromPool();
  35737. this._shadowDomMap[shadowKey] = shadowDom;
  35738. }
  35739. this.updateDom(svgElement, displayable, shadowDom);
  35740. }
  35741. else {
  35742. this.remove(svgElement, displayable);
  35743. }
  35744. };
  35745. ShadowManager.prototype.remove = function (svgElement, displayable) {
  35746. if (displayable._shadowDom != null) {
  35747. displayable._shadowDom = null;
  35748. svgElement.style.filter = '';
  35749. }
  35750. };
  35751. ShadowManager.prototype.updateDom = function (svgElement, displayable, shadowDom) {
  35752. var domChild = shadowDom.children[0];
  35753. var style = displayable.style;
  35754. var globalScale = displayable.getGlobalScale();
  35755. var scaleX = globalScale[0];
  35756. var scaleY = globalScale[1];
  35757. if (!scaleX || !scaleY) {
  35758. return;
  35759. }
  35760. var offsetX = style.shadowOffsetX || 0;
  35761. var offsetY = style.shadowOffsetY || 0;
  35762. var blur = style.shadowBlur;
  35763. var normalizedColor = normalizeColor(style.shadowColor);
  35764. domChild.setAttribute('dx', offsetX / scaleX + '');
  35765. domChild.setAttribute('dy', offsetY / scaleY + '');
  35766. domChild.setAttribute('flood-color', normalizedColor.color);
  35767. domChild.setAttribute('flood-opacity', normalizedColor.opacity + '');
  35768. var stdDx = blur / 2 / scaleX;
  35769. var stdDy = blur / 2 / scaleY;
  35770. var stdDeviation = stdDx + ' ' + stdDy;
  35771. domChild.setAttribute('stdDeviation', stdDeviation);
  35772. shadowDom.setAttribute('x', '-100%');
  35773. shadowDom.setAttribute('y', '-100%');
  35774. shadowDom.setAttribute('width', '300%');
  35775. shadowDom.setAttribute('height', '300%');
  35776. displayable._shadowDom = shadowDom;
  35777. var id = shadowDom.getAttribute('id');
  35778. svgElement.style.filter = 'url(#' + id + ')';
  35779. };
  35780. ShadowManager.prototype.removeUnused = function () {
  35781. var defs = this.getDefs(false);
  35782. if (!defs) {
  35783. return;
  35784. }
  35785. var shadowDomsPool = this._shadowDomPool;
  35786. var shadowDomMap = this._shadowDomMap;
  35787. for (var key in shadowDomMap) {
  35788. if (shadowDomMap.hasOwnProperty(key)) {
  35789. shadowDomsPool.push(shadowDomMap[key]);
  35790. }
  35791. }
  35792. this._shadowDomMap = {};
  35793. };
  35794. return ShadowManager;
  35795. }(Definable));
  35796. function hasShadow(style) {
  35797. return style
  35798. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  35799. }
  35800. function getShadowKey(displayable) {
  35801. var style = displayable.style;
  35802. var globalScale = displayable.getGlobalScale();
  35803. return [
  35804. style.shadowColor,
  35805. (style.shadowBlur || 0).toFixed(2),
  35806. (style.shadowOffsetX || 0).toFixed(2),
  35807. (style.shadowOffsetY || 0).toFixed(2),
  35808. globalScale[0],
  35809. globalScale[1]
  35810. ].join(',');
  35811. }
  35812. function parseInt10(val) {
  35813. return parseInt(val, 10);
  35814. }
  35815. function getSvgProxy(el) {
  35816. if (el instanceof Path) {
  35817. return svgPath;
  35818. }
  35819. else if (el instanceof ZRImage) {
  35820. return svgImage;
  35821. }
  35822. else if (el instanceof TSpan) {
  35823. return svgText;
  35824. }
  35825. else {
  35826. return svgPath;
  35827. }
  35828. }
  35829. function checkParentAvailable(parent, child) {
  35830. return child && parent && child.parentNode !== parent;
  35831. }
  35832. function insertAfter(parent, child, prevSibling) {
  35833. if (checkParentAvailable(parent, child) && prevSibling) {
  35834. var nextSibling = prevSibling.nextSibling;
  35835. nextSibling ? parent.insertBefore(child, nextSibling)
  35836. : parent.appendChild(child);
  35837. }
  35838. }
  35839. function prepend(parent, child) {
  35840. if (checkParentAvailable(parent, child)) {
  35841. var firstChild = parent.firstChild;
  35842. firstChild ? parent.insertBefore(child, firstChild)
  35843. : parent.appendChild(child);
  35844. }
  35845. }
  35846. function remove(parent, child) {
  35847. if (child && parent && child.parentNode === parent) {
  35848. parent.removeChild(child);
  35849. }
  35850. }
  35851. function removeFromMyParent(child) {
  35852. if (child && child.parentNode) {
  35853. child.parentNode.removeChild(child);
  35854. }
  35855. }
  35856. function getSvgElement(displayable) {
  35857. return displayable.__svgEl;
  35858. }
  35859. var SVGPainter = (function () {
  35860. function SVGPainter(root, storage, opts, zrId) {
  35861. this.type = 'svg';
  35862. this.refreshHover = createMethodNotSupport('refreshHover');
  35863. this.pathToImage = createMethodNotSupport('pathToImage');
  35864. this.configLayer = createMethodNotSupport('configLayer');
  35865. this.root = root;
  35866. this.storage = storage;
  35867. this._opts = opts = extend({}, opts || {});
  35868. var svgDom = createElement('svg');
  35869. svgDom.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', 'http://www.w3.org/2000/svg');
  35870. svgDom.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');
  35871. svgDom.setAttribute('version', '1.1');
  35872. svgDom.setAttribute('baseProfile', 'full');
  35873. svgDom.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  35874. var bgRoot = createElement('g');
  35875. svgDom.appendChild(bgRoot);
  35876. var svgRoot = createElement('g');
  35877. svgDom.appendChild(svgRoot);
  35878. this._gradientManager = new GradientManager(zrId, svgRoot);
  35879. this._patternManager = new PatternManager(zrId, svgRoot);
  35880. this._clipPathManager = new ClippathManager(zrId, svgRoot);
  35881. this._shadowManager = new ShadowManager(zrId, svgRoot);
  35882. var viewport = document.createElement('div');
  35883. viewport.style.cssText = 'overflow:hidden;position:relative';
  35884. this._svgDom = svgDom;
  35885. this._svgRoot = svgRoot;
  35886. this._backgroundRoot = bgRoot;
  35887. this._viewport = viewport;
  35888. root.appendChild(viewport);
  35889. viewport.appendChild(svgDom);
  35890. this.resize(opts.width, opts.height);
  35891. this._visibleList = [];
  35892. }
  35893. SVGPainter.prototype.getType = function () {
  35894. return 'svg';
  35895. };
  35896. SVGPainter.prototype.getViewportRoot = function () {
  35897. return this._viewport;
  35898. };
  35899. SVGPainter.prototype.getSvgDom = function () {
  35900. return this._svgDom;
  35901. };
  35902. SVGPainter.prototype.getSvgRoot = function () {
  35903. return this._svgRoot;
  35904. };
  35905. SVGPainter.prototype.getViewportRootOffset = function () {
  35906. var viewportRoot = this.getViewportRoot();
  35907. if (viewportRoot) {
  35908. return {
  35909. offsetLeft: viewportRoot.offsetLeft || 0,
  35910. offsetTop: viewportRoot.offsetTop || 0
  35911. };
  35912. }
  35913. };
  35914. SVGPainter.prototype.refresh = function () {
  35915. var list = this.storage.getDisplayList(true);
  35916. this._paintList(list);
  35917. };
  35918. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  35919. if (this._backgroundRoot && this._backgroundNode) {
  35920. this._backgroundRoot.removeChild(this._backgroundNode);
  35921. }
  35922. var bgNode = createElement('rect');
  35923. bgNode.setAttribute('width', this.getWidth());
  35924. bgNode.setAttribute('height', this.getHeight());
  35925. bgNode.setAttribute('x', 0);
  35926. bgNode.setAttribute('y', 0);
  35927. bgNode.setAttribute('id', 0);
  35928. var _a = normalizeColor(backgroundColor), color = _a.color, opacity = _a.opacity;
  35929. bgNode.setAttribute('fill', color);
  35930. bgNode.setAttribute('fill-opacity', opacity);
  35931. this._backgroundRoot.appendChild(bgNode);
  35932. this._backgroundNode = bgNode;
  35933. };
  35934. SVGPainter.prototype.createSVGElement = function (tag) {
  35935. return createElement(tag);
  35936. };
  35937. SVGPainter.prototype.paintOne = function (el) {
  35938. var svgProxy = getSvgProxy(el);
  35939. svgProxy && svgProxy.brush(el);
  35940. return getSvgElement(el);
  35941. };
  35942. SVGPainter.prototype._paintList = function (list) {
  35943. var gradientManager = this._gradientManager;
  35944. var patternManager = this._patternManager;
  35945. var clipPathManager = this._clipPathManager;
  35946. var shadowManager = this._shadowManager;
  35947. gradientManager.markAllUnused();
  35948. patternManager.markAllUnused();
  35949. clipPathManager.markAllUnused();
  35950. shadowManager.markAllUnused();
  35951. var svgRoot = this._svgRoot;
  35952. var visibleList = this._visibleList;
  35953. var listLen = list.length;
  35954. var newVisibleList = [];
  35955. for (var i = 0; i < listLen; i++) {
  35956. var displayable = list[i];
  35957. var svgProxy = getSvgProxy(displayable);
  35958. var svgElement = getSvgElement(displayable);
  35959. if (!displayable.invisible) {
  35960. if (displayable.__dirty || !svgElement) {
  35961. svgProxy && svgProxy.brush(displayable);
  35962. svgElement = getSvgElement(displayable);
  35963. if (svgElement && displayable.style) {
  35964. gradientManager.update(displayable.style.fill);
  35965. gradientManager.update(displayable.style.stroke);
  35966. patternManager.update(displayable.style.fill);
  35967. patternManager.update(displayable.style.stroke);
  35968. shadowManager.update(svgElement, displayable);
  35969. }
  35970. displayable.__dirty = 0;
  35971. }
  35972. if (svgElement) {
  35973. newVisibleList.push(displayable);
  35974. }
  35975. }
  35976. }
  35977. var diff = arrayDiff(visibleList, newVisibleList);
  35978. var prevSvgElement;
  35979. var topPrevSvgElement;
  35980. for (var i = 0; i < diff.length; i++) {
  35981. var item = diff[i];
  35982. if (item.removed) {
  35983. for (var k = 0; k < item.count; k++) {
  35984. var displayable = visibleList[item.indices[k]];
  35985. var svgElement = getSvgElement(displayable);
  35986. hasClipPath(displayable) ? removeFromMyParent(svgElement)
  35987. : remove(svgRoot, svgElement);
  35988. }
  35989. }
  35990. }
  35991. var prevDisplayable;
  35992. var currentClipGroup;
  35993. for (var i = 0; i < diff.length; i++) {
  35994. var item = diff[i];
  35995. if (item.removed) {
  35996. continue;
  35997. }
  35998. for (var k = 0; k < item.count; k++) {
  35999. var displayable = newVisibleList[item.indices[k]];
  36000. var clipGroup = clipPathManager.update(displayable, prevDisplayable);
  36001. if (clipGroup !== currentClipGroup) {
  36002. prevSvgElement = topPrevSvgElement;
  36003. if (clipGroup) {
  36004. prevSvgElement ? insertAfter(svgRoot, clipGroup, prevSvgElement)
  36005. : prepend(svgRoot, clipGroup);
  36006. topPrevSvgElement = clipGroup;
  36007. prevSvgElement = null;
  36008. }
  36009. currentClipGroup = clipGroup;
  36010. }
  36011. var svgElement = getSvgElement(displayable);
  36012. prevSvgElement
  36013. ? insertAfter(currentClipGroup || svgRoot, svgElement, prevSvgElement)
  36014. : prepend(currentClipGroup || svgRoot, svgElement);
  36015. prevSvgElement = svgElement || prevSvgElement;
  36016. if (!currentClipGroup) {
  36017. topPrevSvgElement = prevSvgElement;
  36018. }
  36019. gradientManager.markUsed(displayable);
  36020. gradientManager.addWithoutUpdate(svgElement, displayable);
  36021. patternManager.markUsed(displayable);
  36022. patternManager.addWithoutUpdate(svgElement, displayable);
  36023. clipPathManager.markUsed(displayable);
  36024. prevDisplayable = displayable;
  36025. }
  36026. }
  36027. gradientManager.removeUnused();
  36028. patternManager.removeUnused();
  36029. clipPathManager.removeUnused();
  36030. shadowManager.removeUnused();
  36031. this._visibleList = newVisibleList;
  36032. };
  36033. SVGPainter.prototype.resize = function (width, height) {
  36034. var viewport = this._viewport;
  36035. viewport.style.display = 'none';
  36036. var opts = this._opts;
  36037. width != null && (opts.width = width);
  36038. height != null && (opts.height = height);
  36039. width = this._getSize(0);
  36040. height = this._getSize(1);
  36041. viewport.style.display = '';
  36042. if (this._width !== width || this._height !== height) {
  36043. this._width = width;
  36044. this._height = height;
  36045. var viewportStyle = viewport.style;
  36046. viewportStyle.width = width + 'px';
  36047. viewportStyle.height = height + 'px';
  36048. var svgRoot = this._svgDom;
  36049. svgRoot.setAttribute('width', width + '');
  36050. svgRoot.setAttribute('height', height + '');
  36051. }
  36052. if (this._backgroundNode) {
  36053. this._backgroundNode.setAttribute('width', width);
  36054. this._backgroundNode.setAttribute('height', height);
  36055. }
  36056. };
  36057. SVGPainter.prototype.getWidth = function () {
  36058. return this._width;
  36059. };
  36060. SVGPainter.prototype.getHeight = function () {
  36061. return this._height;
  36062. };
  36063. SVGPainter.prototype._getSize = function (whIdx) {
  36064. var opts = this._opts;
  36065. var wh = ['width', 'height'][whIdx];
  36066. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  36067. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  36068. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  36069. if (opts[wh] != null && opts[wh] !== 'auto') {
  36070. return parseFloat(opts[wh]);
  36071. }
  36072. var root = this.root;
  36073. var stl = document.defaultView.getComputedStyle(root);
  36074. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  36075. - (parseInt10(stl[plt]) || 0)
  36076. - (parseInt10(stl[prb]) || 0)) | 0;
  36077. };
  36078. SVGPainter.prototype.dispose = function () {
  36079. this.root.innerHTML = '';
  36080. this._svgRoot =
  36081. this._backgroundRoot =
  36082. this._svgDom =
  36083. this._backgroundNode =
  36084. this._viewport = this.storage = null;
  36085. };
  36086. SVGPainter.prototype.clear = function () {
  36087. var viewportNode = this._viewport;
  36088. if (viewportNode && viewportNode.parentNode) {
  36089. viewportNode.parentNode.removeChild(viewportNode);
  36090. }
  36091. };
  36092. SVGPainter.prototype.toDataURL = function () {
  36093. this.refresh();
  36094. var svgDom = this._svgDom;
  36095. var outerHTML = svgDom.outerHTML
  36096. || (svgDom.parentNode && svgDom.parentNode).innerHTML;
  36097. var html = encodeURIComponent(outerHTML.replace(/></g, '>\n\r<'));
  36098. return 'data:image/svg+xml;charset=UTF-8,' + html;
  36099. };
  36100. return SVGPainter;
  36101. }());
  36102. function createMethodNotSupport(method) {
  36103. return function () {
  36104. logError('In SVG mode painter not support method "' + method + '"');
  36105. };
  36106. }
  36107. function install(registers) {
  36108. registers.registerPainter('svg', SVGPainter);
  36109. }
  36110. function returnFalse() {
  36111. return false;
  36112. }
  36113. function createDom(id, painter, dpr) {
  36114. var newDom = createCanvas();
  36115. var width = painter.getWidth();
  36116. var height = painter.getHeight();
  36117. var newDomStyle = newDom.style;
  36118. if (newDomStyle) {
  36119. newDomStyle.position = 'absolute';
  36120. newDomStyle.left = '0';
  36121. newDomStyle.top = '0';
  36122. newDomStyle.width = width + 'px';
  36123. newDomStyle.height = height + 'px';
  36124. newDom.setAttribute('data-zr-dom-id', id);
  36125. }
  36126. newDom.width = width * dpr;
  36127. newDom.height = height * dpr;
  36128. return newDom;
  36129. }
  36130. var Layer = (function (_super) {
  36131. __extends(Layer, _super);
  36132. function Layer(id, painter, dpr) {
  36133. var _this = _super.call(this) || this;
  36134. _this.motionBlur = false;
  36135. _this.lastFrameAlpha = 0.7;
  36136. _this.dpr = 1;
  36137. _this.virtual = false;
  36138. _this.config = {};
  36139. _this.incremental = false;
  36140. _this.zlevel = 0;
  36141. _this.maxRepaintRectCount = 5;
  36142. _this.__dirty = true;
  36143. _this.__firstTimePaint = true;
  36144. _this.__used = false;
  36145. _this.__drawIndex = 0;
  36146. _this.__startIndex = 0;
  36147. _this.__endIndex = 0;
  36148. _this.__prevStartIndex = null;
  36149. _this.__prevEndIndex = null;
  36150. var dom;
  36151. dpr = dpr || devicePixelRatio;
  36152. if (typeof id === 'string') {
  36153. dom = createDom(id, painter, dpr);
  36154. }
  36155. else if (isObject(id)) {
  36156. dom = id;
  36157. id = dom.id;
  36158. }
  36159. _this.id = id;
  36160. _this.dom = dom;
  36161. var domStyle = dom.style;
  36162. if (domStyle) {
  36163. dom.onselectstart = returnFalse;
  36164. domStyle.webkitUserSelect = 'none';
  36165. domStyle.userSelect = 'none';
  36166. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  36167. domStyle['-webkit-touch-callout'] = 'none';
  36168. domStyle.padding = '0';
  36169. domStyle.margin = '0';
  36170. domStyle.borderWidth = '0';
  36171. }
  36172. _this.domBack = null;
  36173. _this.ctxBack = null;
  36174. _this.painter = painter;
  36175. _this.config = null;
  36176. _this.dpr = dpr;
  36177. return _this;
  36178. }
  36179. Layer.prototype.getElementCount = function () {
  36180. return this.__endIndex - this.__startIndex;
  36181. };
  36182. Layer.prototype.afterBrush = function () {
  36183. this.__prevStartIndex = this.__startIndex;
  36184. this.__prevEndIndex = this.__endIndex;
  36185. };
  36186. Layer.prototype.initContext = function () {
  36187. this.ctx = this.dom.getContext('2d');
  36188. this.ctx.dpr = this.dpr;
  36189. };
  36190. Layer.prototype.setUnpainted = function () {
  36191. this.__firstTimePaint = true;
  36192. };
  36193. Layer.prototype.createBackBuffer = function () {
  36194. var dpr = this.dpr;
  36195. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  36196. this.ctxBack = this.domBack.getContext('2d');
  36197. if (dpr !== 1) {
  36198. this.ctxBack.scale(dpr, dpr);
  36199. }
  36200. };
  36201. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  36202. if (this.__firstTimePaint) {
  36203. this.__firstTimePaint = false;
  36204. return null;
  36205. }
  36206. var mergedRepaintRects = [];
  36207. var maxRepaintRectCount = this.maxRepaintRectCount;
  36208. var full = false;
  36209. var pendingRect = new BoundingRect(0, 0, 0, 0);
  36210. function addRectToMergePool(rect) {
  36211. if (!rect.isFinite() || rect.isZero()) {
  36212. return;
  36213. }
  36214. if (mergedRepaintRects.length === 0) {
  36215. var boundingRect = new BoundingRect(0, 0, 0, 0);
  36216. boundingRect.copy(rect);
  36217. mergedRepaintRects.push(boundingRect);
  36218. }
  36219. else {
  36220. var isMerged = false;
  36221. var minDeltaArea = Infinity;
  36222. var bestRectToMergeIdx = 0;
  36223. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  36224. var mergedRect = mergedRepaintRects[i];
  36225. if (mergedRect.intersect(rect)) {
  36226. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  36227. pendingRect_1.copy(mergedRect);
  36228. pendingRect_1.union(rect);
  36229. mergedRepaintRects[i] = pendingRect_1;
  36230. isMerged = true;
  36231. break;
  36232. }
  36233. else if (full) {
  36234. pendingRect.copy(rect);
  36235. pendingRect.union(mergedRect);
  36236. var aArea = rect.width * rect.height;
  36237. var bArea = mergedRect.width * mergedRect.height;
  36238. var pendingArea = pendingRect.width * pendingRect.height;
  36239. var deltaArea = pendingArea - aArea - bArea;
  36240. if (deltaArea < minDeltaArea) {
  36241. minDeltaArea = deltaArea;
  36242. bestRectToMergeIdx = i;
  36243. }
  36244. }
  36245. }
  36246. if (full) {
  36247. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  36248. isMerged = true;
  36249. }
  36250. if (!isMerged) {
  36251. var boundingRect = new BoundingRect(0, 0, 0, 0);
  36252. boundingRect.copy(rect);
  36253. mergedRepaintRects.push(boundingRect);
  36254. }
  36255. if (!full) {
  36256. full = mergedRepaintRects.length >= maxRepaintRectCount;
  36257. }
  36258. }
  36259. }
  36260. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  36261. var el = displayList[i];
  36262. if (el) {
  36263. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  36264. var prevRect = el.__isRendered && ((el.__dirty & REDARAW_BIT) || !shouldPaint)
  36265. ? el.getPrevPaintRect()
  36266. : null;
  36267. if (prevRect) {
  36268. addRectToMergePool(prevRect);
  36269. }
  36270. var curRect = shouldPaint && ((el.__dirty & REDARAW_BIT) || !el.__isRendered)
  36271. ? el.getPaintRect()
  36272. : null;
  36273. if (curRect) {
  36274. addRectToMergePool(curRect);
  36275. }
  36276. }
  36277. }
  36278. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  36279. var el = prevList[i];
  36280. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  36281. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  36282. var prevRect = el.getPrevPaintRect();
  36283. if (prevRect) {
  36284. addRectToMergePool(prevRect);
  36285. }
  36286. }
  36287. }
  36288. var hasIntersections;
  36289. do {
  36290. hasIntersections = false;
  36291. for (var i = 0; i < mergedRepaintRects.length;) {
  36292. if (mergedRepaintRects[i].isZero()) {
  36293. mergedRepaintRects.splice(i, 1);
  36294. continue;
  36295. }
  36296. for (var j = i + 1; j < mergedRepaintRects.length;) {
  36297. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  36298. hasIntersections = true;
  36299. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  36300. mergedRepaintRects.splice(j, 1);
  36301. }
  36302. else {
  36303. j++;
  36304. }
  36305. }
  36306. i++;
  36307. }
  36308. } while (hasIntersections);
  36309. this._paintRects = mergedRepaintRects;
  36310. return mergedRepaintRects;
  36311. };
  36312. Layer.prototype.debugGetPaintRects = function () {
  36313. return (this._paintRects || []).slice();
  36314. };
  36315. Layer.prototype.resize = function (width, height) {
  36316. var dpr = this.dpr;
  36317. var dom = this.dom;
  36318. var domStyle = dom.style;
  36319. var domBack = this.domBack;
  36320. if (domStyle) {
  36321. domStyle.width = width + 'px';
  36322. domStyle.height = height + 'px';
  36323. }
  36324. dom.width = width * dpr;
  36325. dom.height = height * dpr;
  36326. if (domBack) {
  36327. domBack.width = width * dpr;
  36328. domBack.height = height * dpr;
  36329. if (dpr !== 1) {
  36330. this.ctxBack.scale(dpr, dpr);
  36331. }
  36332. }
  36333. };
  36334. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  36335. var dom = this.dom;
  36336. var ctx = this.ctx;
  36337. var width = dom.width;
  36338. var height = dom.height;
  36339. clearColor = clearColor || this.clearColor;
  36340. var haveMotionBLur = this.motionBlur && !clearAll;
  36341. var lastFrameAlpha = this.lastFrameAlpha;
  36342. var dpr = this.dpr;
  36343. var self = this;
  36344. if (haveMotionBLur) {
  36345. if (!this.domBack) {
  36346. this.createBackBuffer();
  36347. }
  36348. this.ctxBack.globalCompositeOperation = 'copy';
  36349. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  36350. }
  36351. var domBack = this.domBack;
  36352. function doClear(x, y, width, height) {
  36353. ctx.clearRect(x, y, width, height);
  36354. if (clearColor && clearColor !== 'transparent') {
  36355. var clearColorGradientOrPattern = void 0;
  36356. if (isGradientObject(clearColor)) {
  36357. clearColorGradientOrPattern = clearColor.__canvasGradient
  36358. || getCanvasGradient(ctx, clearColor, {
  36359. x: 0,
  36360. y: 0,
  36361. width: width,
  36362. height: height
  36363. });
  36364. clearColor.__canvasGradient = clearColorGradientOrPattern;
  36365. }
  36366. else if (isImagePatternObject(clearColor)) {
  36367. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  36368. dirty: function () {
  36369. self.setUnpainted();
  36370. self.__painter.refresh();
  36371. }
  36372. });
  36373. }
  36374. ctx.save();
  36375. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  36376. ctx.fillRect(x, y, width, height);
  36377. ctx.restore();
  36378. }
  36379. if (haveMotionBLur) {
  36380. ctx.save();
  36381. ctx.globalAlpha = lastFrameAlpha;
  36382. ctx.drawImage(domBack, x, y, width, height);
  36383. ctx.restore();
  36384. }
  36385. }
  36386. if (!repaintRects || haveMotionBLur) {
  36387. doClear(0, 0, width, height);
  36388. }
  36389. else if (repaintRects.length) {
  36390. each(repaintRects, function (rect) {
  36391. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  36392. });
  36393. }
  36394. };
  36395. return Layer;
  36396. }(Eventful));
  36397. var HOVER_LAYER_ZLEVEL = 1e5;
  36398. var CANVAS_ZLEVEL = 314159;
  36399. var EL_AFTER_INCREMENTAL_INC = 0.01;
  36400. var INCREMENTAL_INC = 0.001;
  36401. function parseInt10$1(val) {
  36402. return parseInt(val, 10);
  36403. }
  36404. function isLayerValid(layer) {
  36405. if (!layer) {
  36406. return false;
  36407. }
  36408. if (layer.__builtin__) {
  36409. return true;
  36410. }
  36411. if (typeof (layer.resize) !== 'function'
  36412. || typeof (layer.refresh) !== 'function') {
  36413. return false;
  36414. }
  36415. return true;
  36416. }
  36417. function createRoot(width, height) {
  36418. var domRoot = document.createElement('div');
  36419. domRoot.style.cssText = [
  36420. 'position:relative',
  36421. 'width:' + width + 'px',
  36422. 'height:' + height + 'px',
  36423. 'padding:0',
  36424. 'margin:0',
  36425. 'border-width:0'
  36426. ].join(';') + ';';
  36427. return domRoot;
  36428. }
  36429. var CanvasPainter = (function () {
  36430. function CanvasPainter(root, storage, opts, id) {
  36431. this.type = 'canvas';
  36432. this._zlevelList = [];
  36433. this._prevDisplayList = [];
  36434. this._layers = {};
  36435. this._layerConfig = {};
  36436. this._needsManuallyCompositing = false;
  36437. this.type = 'canvas';
  36438. var singleCanvas = !root.nodeName
  36439. || root.nodeName.toUpperCase() === 'CANVAS';
  36440. this._opts = opts = extend({}, opts || {});
  36441. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  36442. this._singleCanvas = singleCanvas;
  36443. this.root = root;
  36444. var rootStyle = root.style;
  36445. if (rootStyle) {
  36446. rootStyle.webkitTapHighlightColor = 'transparent';
  36447. rootStyle.webkitUserSelect = 'none';
  36448. rootStyle.userSelect = 'none';
  36449. rootStyle['-webkit-touch-callout'] = 'none';
  36450. root.innerHTML = '';
  36451. }
  36452. this.storage = storage;
  36453. var zlevelList = this._zlevelList;
  36454. this._prevDisplayList = [];
  36455. var layers = this._layers;
  36456. if (!singleCanvas) {
  36457. this._width = this._getSize(0);
  36458. this._height = this._getSize(1);
  36459. var domRoot = this._domRoot = createRoot(this._width, this._height);
  36460. root.appendChild(domRoot);
  36461. }
  36462. else {
  36463. var rootCanvas = root;
  36464. var width = rootCanvas.width;
  36465. var height = rootCanvas.height;
  36466. if (opts.width != null) {
  36467. width = opts.width;
  36468. }
  36469. if (opts.height != null) {
  36470. height = opts.height;
  36471. }
  36472. this.dpr = opts.devicePixelRatio || 1;
  36473. rootCanvas.width = width * this.dpr;
  36474. rootCanvas.height = height * this.dpr;
  36475. this._width = width;
  36476. this._height = height;
  36477. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  36478. mainLayer.__builtin__ = true;
  36479. mainLayer.initContext();
  36480. layers[CANVAS_ZLEVEL] = mainLayer;
  36481. mainLayer.zlevel = CANVAS_ZLEVEL;
  36482. zlevelList.push(CANVAS_ZLEVEL);
  36483. this._domRoot = root;
  36484. }
  36485. }
  36486. CanvasPainter.prototype.getType = function () {
  36487. return 'canvas';
  36488. };
  36489. CanvasPainter.prototype.isSingleCanvas = function () {
  36490. return this._singleCanvas;
  36491. };
  36492. CanvasPainter.prototype.getViewportRoot = function () {
  36493. return this._domRoot;
  36494. };
  36495. CanvasPainter.prototype.getViewportRootOffset = function () {
  36496. var viewportRoot = this.getViewportRoot();
  36497. if (viewportRoot) {
  36498. return {
  36499. offsetLeft: viewportRoot.offsetLeft || 0,
  36500. offsetTop: viewportRoot.offsetTop || 0
  36501. };
  36502. }
  36503. };
  36504. CanvasPainter.prototype.refresh = function (paintAll) {
  36505. var list = this.storage.getDisplayList(true);
  36506. var prevList = this._prevDisplayList;
  36507. var zlevelList = this._zlevelList;
  36508. this._redrawId = Math.random();
  36509. this._paintList(list, prevList, paintAll, this._redrawId);
  36510. for (var i = 0; i < zlevelList.length; i++) {
  36511. var z = zlevelList[i];
  36512. var layer = this._layers[z];
  36513. if (!layer.__builtin__ && layer.refresh) {
  36514. var clearColor = i === 0 ? this._backgroundColor : null;
  36515. layer.refresh(clearColor);
  36516. }
  36517. }
  36518. if (this._opts.useDirtyRect) {
  36519. this._prevDisplayList = list.slice();
  36520. }
  36521. return this;
  36522. };
  36523. CanvasPainter.prototype.refreshHover = function () {
  36524. this._paintHoverList(this.storage.getDisplayList(false));
  36525. };
  36526. CanvasPainter.prototype._paintHoverList = function (list) {
  36527. var len = list.length;
  36528. var hoverLayer = this._hoverlayer;
  36529. hoverLayer && hoverLayer.clear();
  36530. if (!len) {
  36531. return;
  36532. }
  36533. var scope = {
  36534. inHover: true,
  36535. viewWidth: this._width,
  36536. viewHeight: this._height
  36537. };
  36538. var ctx;
  36539. for (var i = 0; i < len; i++) {
  36540. var el = list[i];
  36541. if (el.__inHover) {
  36542. if (!hoverLayer) {
  36543. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  36544. }
  36545. if (!ctx) {
  36546. ctx = hoverLayer.ctx;
  36547. ctx.save();
  36548. }
  36549. brush(ctx, el, scope, i === len - 1);
  36550. }
  36551. }
  36552. if (ctx) {
  36553. ctx.restore();
  36554. }
  36555. };
  36556. CanvasPainter.prototype.getHoverLayer = function () {
  36557. return this.getLayer(HOVER_LAYER_ZLEVEL);
  36558. };
  36559. CanvasPainter.prototype.paintOne = function (ctx, el) {
  36560. brushSingle(ctx, el);
  36561. };
  36562. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  36563. if (this._redrawId !== redrawId) {
  36564. return;
  36565. }
  36566. paintAll = paintAll || false;
  36567. this._updateLayerStatus(list);
  36568. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  36569. if (this._needsManuallyCompositing) {
  36570. this._compositeManually();
  36571. }
  36572. if (needsRefreshHover) {
  36573. this._paintHoverList(list);
  36574. }
  36575. if (!finished) {
  36576. var self_1 = this;
  36577. requestAnimationFrame$1(function () {
  36578. self_1._paintList(list, prevList, paintAll, redrawId);
  36579. });
  36580. }
  36581. else {
  36582. this.eachLayer(function (layer) {
  36583. layer.afterBrush && layer.afterBrush();
  36584. });
  36585. }
  36586. };
  36587. CanvasPainter.prototype._compositeManually = function () {
  36588. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  36589. var width = this._domRoot.width;
  36590. var height = this._domRoot.height;
  36591. ctx.clearRect(0, 0, width, height);
  36592. this.eachBuiltinLayer(function (layer) {
  36593. if (layer.virtual) {
  36594. ctx.drawImage(layer.dom, 0, 0, width, height);
  36595. }
  36596. });
  36597. };
  36598. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  36599. var _this = this;
  36600. var layerList = [];
  36601. var useDirtyRect = this._opts.useDirtyRect;
  36602. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  36603. var zlevel = this._zlevelList[zi];
  36604. var layer = this._layers[zlevel];
  36605. if (layer.__builtin__
  36606. && layer !== this._hoverlayer
  36607. && (layer.__dirty || paintAll)) {
  36608. layerList.push(layer);
  36609. }
  36610. }
  36611. var finished = true;
  36612. var needsRefreshHover = false;
  36613. var _loop_1 = function (k) {
  36614. var layer = layerList[k];
  36615. var ctx = layer.ctx;
  36616. var repaintRects = useDirtyRect
  36617. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  36618. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  36619. var useTimer = !paintAll && layer.incremental && Date.now;
  36620. var startTime = useTimer && Date.now();
  36621. var clearColor = layer.zlevel === this_1._zlevelList[0]
  36622. ? this_1._backgroundColor : null;
  36623. if (layer.__startIndex === layer.__endIndex) {
  36624. layer.clear(false, clearColor, repaintRects);
  36625. }
  36626. else if (start === layer.__startIndex) {
  36627. var firstEl = list[start];
  36628. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  36629. layer.clear(false, clearColor, repaintRects);
  36630. }
  36631. }
  36632. if (start === -1) {
  36633. console.error('For some unknown reason. drawIndex is -1');
  36634. start = layer.__startIndex;
  36635. }
  36636. var i;
  36637. var repaint = function (repaintRect) {
  36638. var scope = {
  36639. inHover: false,
  36640. allClipped: false,
  36641. prevEl: null,
  36642. viewWidth: _this._width,
  36643. viewHeight: _this._height
  36644. };
  36645. for (i = start; i < layer.__endIndex; i++) {
  36646. var el = list[i];
  36647. if (el.__inHover) {
  36648. needsRefreshHover = true;
  36649. }
  36650. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  36651. if (useTimer) {
  36652. var dTime = Date.now() - startTime;
  36653. if (dTime > 15) {
  36654. break;
  36655. }
  36656. }
  36657. }
  36658. if (scope.prevElClipPaths) {
  36659. ctx.restore();
  36660. }
  36661. };
  36662. if (repaintRects) {
  36663. if (repaintRects.length === 0) {
  36664. i = layer.__endIndex;
  36665. }
  36666. else {
  36667. var dpr = this_1.dpr;
  36668. for (var r = 0; r < repaintRects.length; ++r) {
  36669. var rect = repaintRects[r];
  36670. ctx.save();
  36671. ctx.beginPath();
  36672. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  36673. ctx.clip();
  36674. repaint(rect);
  36675. ctx.restore();
  36676. }
  36677. }
  36678. }
  36679. else {
  36680. ctx.save();
  36681. repaint();
  36682. ctx.restore();
  36683. }
  36684. layer.__drawIndex = i;
  36685. if (layer.__drawIndex < layer.__endIndex) {
  36686. finished = false;
  36687. }
  36688. };
  36689. var this_1 = this;
  36690. for (var k = 0; k < layerList.length; k++) {
  36691. _loop_1(k);
  36692. }
  36693. if (env.wxa) {
  36694. each(this._layers, function (layer) {
  36695. if (layer && layer.ctx && layer.ctx.draw) {
  36696. layer.ctx.draw();
  36697. }
  36698. });
  36699. }
  36700. return {
  36701. finished: finished,
  36702. needsRefreshHover: needsRefreshHover
  36703. };
  36704. };
  36705. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  36706. var ctx = currentLayer.ctx;
  36707. if (useDirtyRect) {
  36708. var paintRect = el.getPaintRect();
  36709. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  36710. brush(ctx, el, scope, isLast);
  36711. el.setPrevPaintRect(paintRect);
  36712. }
  36713. }
  36714. else {
  36715. brush(ctx, el, scope, isLast);
  36716. }
  36717. };
  36718. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  36719. if (this._singleCanvas && !this._needsManuallyCompositing) {
  36720. zlevel = CANVAS_ZLEVEL;
  36721. }
  36722. var layer = this._layers[zlevel];
  36723. if (!layer) {
  36724. layer = new Layer('zr_' + zlevel, this, this.dpr);
  36725. layer.zlevel = zlevel;
  36726. layer.__builtin__ = true;
  36727. if (this._layerConfig[zlevel]) {
  36728. merge(layer, this._layerConfig[zlevel], true);
  36729. }
  36730. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  36731. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  36732. }
  36733. if (virtual) {
  36734. layer.virtual = virtual;
  36735. }
  36736. this.insertLayer(zlevel, layer);
  36737. layer.initContext();
  36738. }
  36739. return layer;
  36740. };
  36741. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  36742. var layersMap = this._layers;
  36743. var zlevelList = this._zlevelList;
  36744. var len = zlevelList.length;
  36745. var domRoot = this._domRoot;
  36746. var prevLayer = null;
  36747. var i = -1;
  36748. if (layersMap[zlevel]) {
  36749. logError('ZLevel ' + zlevel + ' has been used already');
  36750. return;
  36751. }
  36752. if (!isLayerValid(layer)) {
  36753. logError('Layer of zlevel ' + zlevel + ' is not valid');
  36754. return;
  36755. }
  36756. if (len > 0 && zlevel > zlevelList[0]) {
  36757. for (i = 0; i < len - 1; i++) {
  36758. if (zlevelList[i] < zlevel
  36759. && zlevelList[i + 1] > zlevel) {
  36760. break;
  36761. }
  36762. }
  36763. prevLayer = layersMap[zlevelList[i]];
  36764. }
  36765. zlevelList.splice(i + 1, 0, zlevel);
  36766. layersMap[zlevel] = layer;
  36767. if (!layer.virtual) {
  36768. if (prevLayer) {
  36769. var prevDom = prevLayer.dom;
  36770. if (prevDom.nextSibling) {
  36771. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  36772. }
  36773. else {
  36774. domRoot.appendChild(layer.dom);
  36775. }
  36776. }
  36777. else {
  36778. if (domRoot.firstChild) {
  36779. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  36780. }
  36781. else {
  36782. domRoot.appendChild(layer.dom);
  36783. }
  36784. }
  36785. }
  36786. layer.__painter = this;
  36787. };
  36788. CanvasPainter.prototype.eachLayer = function (cb, context) {
  36789. var zlevelList = this._zlevelList;
  36790. for (var i = 0; i < zlevelList.length; i++) {
  36791. var z = zlevelList[i];
  36792. cb.call(context, this._layers[z], z);
  36793. }
  36794. };
  36795. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  36796. var zlevelList = this._zlevelList;
  36797. for (var i = 0; i < zlevelList.length; i++) {
  36798. var z = zlevelList[i];
  36799. var layer = this._layers[z];
  36800. if (layer.__builtin__) {
  36801. cb.call(context, layer, z);
  36802. }
  36803. }
  36804. };
  36805. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  36806. var zlevelList = this._zlevelList;
  36807. for (var i = 0; i < zlevelList.length; i++) {
  36808. var z = zlevelList[i];
  36809. var layer = this._layers[z];
  36810. if (!layer.__builtin__) {
  36811. cb.call(context, layer, z);
  36812. }
  36813. }
  36814. };
  36815. CanvasPainter.prototype.getLayers = function () {
  36816. return this._layers;
  36817. };
  36818. CanvasPainter.prototype._updateLayerStatus = function (list) {
  36819. this.eachBuiltinLayer(function (layer, z) {
  36820. layer.__dirty = layer.__used = false;
  36821. });
  36822. function updatePrevLayer(idx) {
  36823. if (prevLayer) {
  36824. if (prevLayer.__endIndex !== idx) {
  36825. prevLayer.__dirty = true;
  36826. }
  36827. prevLayer.__endIndex = idx;
  36828. }
  36829. }
  36830. if (this._singleCanvas) {
  36831. for (var i_1 = 1; i_1 < list.length; i_1++) {
  36832. var el = list[i_1];
  36833. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  36834. this._needsManuallyCompositing = true;
  36835. break;
  36836. }
  36837. }
  36838. }
  36839. var prevLayer = null;
  36840. var incrementalLayerCount = 0;
  36841. var prevZlevel;
  36842. var i;
  36843. for (i = 0; i < list.length; i++) {
  36844. var el = list[i];
  36845. var zlevel = el.zlevel;
  36846. var layer = void 0;
  36847. if (prevZlevel !== zlevel) {
  36848. prevZlevel = zlevel;
  36849. incrementalLayerCount = 0;
  36850. }
  36851. if (el.incremental) {
  36852. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  36853. layer.incremental = true;
  36854. incrementalLayerCount = 1;
  36855. }
  36856. else {
  36857. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  36858. }
  36859. if (!layer.__builtin__) {
  36860. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  36861. }
  36862. if (layer !== prevLayer) {
  36863. layer.__used = true;
  36864. if (layer.__startIndex !== i) {
  36865. layer.__dirty = true;
  36866. }
  36867. layer.__startIndex = i;
  36868. if (!layer.incremental) {
  36869. layer.__drawIndex = i;
  36870. }
  36871. else {
  36872. layer.__drawIndex = -1;
  36873. }
  36874. updatePrevLayer(i);
  36875. prevLayer = layer;
  36876. }
  36877. if ((el.__dirty & REDARAW_BIT) && !el.__inHover) {
  36878. layer.__dirty = true;
  36879. if (layer.incremental && layer.__drawIndex < 0) {
  36880. layer.__drawIndex = i;
  36881. }
  36882. }
  36883. }
  36884. updatePrevLayer(i);
  36885. this.eachBuiltinLayer(function (layer, z) {
  36886. if (!layer.__used && layer.getElementCount() > 0) {
  36887. layer.__dirty = true;
  36888. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  36889. }
  36890. if (layer.__dirty && layer.__drawIndex < 0) {
  36891. layer.__drawIndex = layer.__startIndex;
  36892. }
  36893. });
  36894. };
  36895. CanvasPainter.prototype.clear = function () {
  36896. this.eachBuiltinLayer(this._clearLayer);
  36897. return this;
  36898. };
  36899. CanvasPainter.prototype._clearLayer = function (layer) {
  36900. layer.clear();
  36901. };
  36902. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  36903. this._backgroundColor = backgroundColor;
  36904. each(this._layers, function (layer) {
  36905. layer.setUnpainted();
  36906. });
  36907. };
  36908. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  36909. if (config) {
  36910. var layerConfig = this._layerConfig;
  36911. if (!layerConfig[zlevel]) {
  36912. layerConfig[zlevel] = config;
  36913. }
  36914. else {
  36915. merge(layerConfig[zlevel], config, true);
  36916. }
  36917. for (var i = 0; i < this._zlevelList.length; i++) {
  36918. var _zlevel = this._zlevelList[i];
  36919. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  36920. var layer = this._layers[_zlevel];
  36921. merge(layer, layerConfig[zlevel], true);
  36922. }
  36923. }
  36924. }
  36925. };
  36926. CanvasPainter.prototype.delLayer = function (zlevel) {
  36927. var layers = this._layers;
  36928. var zlevelList = this._zlevelList;
  36929. var layer = layers[zlevel];
  36930. if (!layer) {
  36931. return;
  36932. }
  36933. layer.dom.parentNode.removeChild(layer.dom);
  36934. delete layers[zlevel];
  36935. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  36936. };
  36937. CanvasPainter.prototype.resize = function (width, height) {
  36938. if (!this._domRoot.style) {
  36939. if (width == null || height == null) {
  36940. return;
  36941. }
  36942. this._width = width;
  36943. this._height = height;
  36944. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  36945. }
  36946. else {
  36947. var domRoot = this._domRoot;
  36948. domRoot.style.display = 'none';
  36949. var opts = this._opts;
  36950. width != null && (opts.width = width);
  36951. height != null && (opts.height = height);
  36952. width = this._getSize(0);
  36953. height = this._getSize(1);
  36954. domRoot.style.display = '';
  36955. if (this._width !== width || height !== this._height) {
  36956. domRoot.style.width = width + 'px';
  36957. domRoot.style.height = height + 'px';
  36958. for (var id in this._layers) {
  36959. if (this._layers.hasOwnProperty(id)) {
  36960. this._layers[id].resize(width, height);
  36961. }
  36962. }
  36963. this.refresh(true);
  36964. }
  36965. this._width = width;
  36966. this._height = height;
  36967. }
  36968. return this;
  36969. };
  36970. CanvasPainter.prototype.clearLayer = function (zlevel) {
  36971. var layer = this._layers[zlevel];
  36972. if (layer) {
  36973. layer.clear();
  36974. }
  36975. };
  36976. CanvasPainter.prototype.dispose = function () {
  36977. this.root.innerHTML = '';
  36978. this.root =
  36979. this.storage =
  36980. this._domRoot =
  36981. this._layers = null;
  36982. };
  36983. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  36984. opts = opts || {};
  36985. if (this._singleCanvas && !this._compositeManually) {
  36986. return this._layers[CANVAS_ZLEVEL].dom;
  36987. }
  36988. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  36989. imageLayer.initContext();
  36990. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  36991. var ctx = imageLayer.ctx;
  36992. if (opts.pixelRatio <= this.dpr) {
  36993. this.refresh();
  36994. var width_1 = imageLayer.dom.width;
  36995. var height_1 = imageLayer.dom.height;
  36996. this.eachLayer(function (layer) {
  36997. if (layer.__builtin__) {
  36998. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  36999. }
  37000. else if (layer.renderToCanvas) {
  37001. ctx.save();
  37002. layer.renderToCanvas(ctx);
  37003. ctx.restore();
  37004. }
  37005. });
  37006. }
  37007. else {
  37008. var scope = {
  37009. inHover: false,
  37010. viewWidth: this._width,
  37011. viewHeight: this._height
  37012. };
  37013. var displayList = this.storage.getDisplayList(true);
  37014. for (var i = 0, len = displayList.length; i < len; i++) {
  37015. var el = displayList[i];
  37016. brush(ctx, el, scope, i === len - 1);
  37017. }
  37018. }
  37019. return imageLayer.dom;
  37020. };
  37021. CanvasPainter.prototype.getWidth = function () {
  37022. return this._width;
  37023. };
  37024. CanvasPainter.prototype.getHeight = function () {
  37025. return this._height;
  37026. };
  37027. CanvasPainter.prototype._getSize = function (whIdx) {
  37028. var opts = this._opts;
  37029. var wh = ['width', 'height'][whIdx];
  37030. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  37031. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  37032. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  37033. if (opts[wh] != null && opts[wh] !== 'auto') {
  37034. return parseFloat(opts[wh]);
  37035. }
  37036. var root = this.root;
  37037. var stl = document.defaultView.getComputedStyle(root);
  37038. return ((root[cwh] || parseInt10$1(stl[wh]) || parseInt10$1(root.style[wh]))
  37039. - (parseInt10$1(stl[plt]) || 0)
  37040. - (parseInt10$1(stl[prb]) || 0)) | 0;
  37041. };
  37042. CanvasPainter.prototype.pathToImage = function (path, dpr) {
  37043. dpr = dpr || this.dpr;
  37044. var canvas = document.createElement('canvas');
  37045. var ctx = canvas.getContext('2d');
  37046. var rect = path.getBoundingRect();
  37047. var style = path.style;
  37048. var shadowBlurSize = style.shadowBlur * dpr;
  37049. var shadowOffsetX = style.shadowOffsetX * dpr;
  37050. var shadowOffsetY = style.shadowOffsetY * dpr;
  37051. var lineWidth = path.hasStroke() ? style.lineWidth : 0;
  37052. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  37053. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  37054. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  37055. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  37056. var width = rect.width + leftMargin + rightMargin;
  37057. var height = rect.height + topMargin + bottomMargin;
  37058. canvas.width = width * dpr;
  37059. canvas.height = height * dpr;
  37060. ctx.scale(dpr, dpr);
  37061. ctx.clearRect(0, 0, width, height);
  37062. ctx.dpr = dpr;
  37063. var pathTransform = {
  37064. x: path.x,
  37065. y: path.y,
  37066. scaleX: path.scaleX,
  37067. scaleY: path.scaleY,
  37068. rotation: path.rotation,
  37069. originX: path.originX,
  37070. originY: path.originY
  37071. };
  37072. path.x = leftMargin - rect.x;
  37073. path.y = topMargin - rect.y;
  37074. path.rotation = 0;
  37075. path.scaleX = 1;
  37076. path.scaleY = 1;
  37077. path.updateTransform();
  37078. if (path) {
  37079. brush(ctx, path, {
  37080. inHover: false,
  37081. viewWidth: this._width,
  37082. viewHeight: this._height
  37083. }, true);
  37084. }
  37085. var imgShape = new ZRImage({
  37086. style: {
  37087. x: 0,
  37088. y: 0,
  37089. image: canvas
  37090. }
  37091. });
  37092. extend(path, pathTransform);
  37093. return imgShape;
  37094. };
  37095. return CanvasPainter;
  37096. }());
  37097. function install$1(registers) {
  37098. registers.registerPainter('canvas', CanvasPainter);
  37099. }
  37100. var LineSeriesModel =
  37101. /** @class */
  37102. function (_super) {
  37103. __extends(LineSeriesModel, _super);
  37104. function LineSeriesModel() {
  37105. var _this = _super !== null && _super.apply(this, arguments) || this;
  37106. _this.type = LineSeriesModel.type;
  37107. _this.hasSymbolVisual = true;
  37108. return _this;
  37109. }
  37110. LineSeriesModel.prototype.getInitialData = function (option) {
  37111. if ("development" !== 'production') {
  37112. var coordSys = option.coordinateSystem;
  37113. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  37114. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  37115. }
  37116. }
  37117. return createSeriesData(null, this, {
  37118. useEncodeDefaulter: true
  37119. });
  37120. };
  37121. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  37122. var group = new Group();
  37123. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  37124. group.add(line);
  37125. line.setStyle(opt.lineStyle);
  37126. var visualType = this.getData().getVisual('symbol');
  37127. var visualRotate = this.getData().getVisual('symbolRotate');
  37128. var symbolType = visualType === 'none' ? 'circle' : visualType; // Symbol size is 80% when there is a line
  37129. var size = opt.itemHeight * 0.8;
  37130. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  37131. group.add(symbol);
  37132. symbol.setStyle(opt.itemStyle);
  37133. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  37134. symbol.rotation = symbolRotate * Math.PI / 180;
  37135. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  37136. if (symbolType.indexOf('empty') > -1) {
  37137. symbol.style.stroke = symbol.style.fill;
  37138. symbol.style.fill = '#fff';
  37139. symbol.style.lineWidth = 2;
  37140. }
  37141. return group;
  37142. };
  37143. LineSeriesModel.type = 'series.line';
  37144. LineSeriesModel.dependencies = ['grid', 'polar'];
  37145. LineSeriesModel.defaultOption = {
  37146. zlevel: 0,
  37147. z: 3,
  37148. coordinateSystem: 'cartesian2d',
  37149. legendHoverLink: true,
  37150. clip: true,
  37151. label: {
  37152. position: 'top'
  37153. },
  37154. // itemStyle: {
  37155. // },
  37156. endLabel: {
  37157. show: false,
  37158. valueAnimation: true,
  37159. distance: 8
  37160. },
  37161. lineStyle: {
  37162. width: 2,
  37163. type: 'solid'
  37164. },
  37165. emphasis: {
  37166. scale: true,
  37167. lineStyle: {
  37168. width: 'bolder'
  37169. }
  37170. },
  37171. // areaStyle: {
  37172. // origin of areaStyle. Valid values:
  37173. // `'auto'/null/undefined`: from axisLine to data
  37174. // `'start'`: from min to data
  37175. // `'end'`: from data to max
  37176. // origin: 'auto'
  37177. // },
  37178. // false, 'start', 'end', 'middle'
  37179. step: false,
  37180. // Disabled if step is true
  37181. smooth: false,
  37182. smoothMonotone: null,
  37183. symbol: 'emptyCircle',
  37184. symbolSize: 4,
  37185. symbolRotate: null,
  37186. showSymbol: true,
  37187. // `false`: follow the label interval strategy.
  37188. // `true`: show all symbols.
  37189. // `'auto'`: If possible, show all symbols, otherwise
  37190. // follow the label interval strategy.
  37191. showAllSymbol: 'auto',
  37192. // Whether to connect break point.
  37193. connectNulls: false,
  37194. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  37195. sampling: 'none',
  37196. animationEasing: 'linear',
  37197. // Disable progressive
  37198. progressive: 0,
  37199. hoverLayerThreshold: Infinity,
  37200. universalTransition: {
  37201. divideShape: 'clone'
  37202. }
  37203. };
  37204. return LineSeriesModel;
  37205. }(SeriesModel);
  37206. /**
  37207. * @return label string. Not null/undefined
  37208. */
  37209. function getDefaultLabel(data, dataIndex) {
  37210. var labelDims = data.mapDimensionsAll('defaultedLabel');
  37211. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  37212. if (len === 1) {
  37213. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  37214. return rawVal != null ? rawVal + '' : null;
  37215. } else if (len) {
  37216. var vals = [];
  37217. for (var i = 0; i < labelDims.length; i++) {
  37218. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  37219. }
  37220. return vals.join(' ');
  37221. }
  37222. }
  37223. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  37224. var labelDims = data.mapDimensionsAll('defaultedLabel');
  37225. if (!isArray(interpolatedValue)) {
  37226. return interpolatedValue + '';
  37227. }
  37228. var vals = [];
  37229. for (var i = 0; i < labelDims.length; i++) {
  37230. var dimIndex = data.getDimensionIndex(labelDims[i]);
  37231. if (dimIndex >= 0) {
  37232. vals.push(interpolatedValue[dimIndex]);
  37233. }
  37234. }
  37235. return vals.join(' ');
  37236. }
  37237. var Symbol =
  37238. /** @class */
  37239. function (_super) {
  37240. __extends(Symbol, _super);
  37241. function Symbol(data, idx, seriesScope, opts) {
  37242. var _this = _super.call(this) || this;
  37243. _this.updateData(data, idx, seriesScope, opts);
  37244. return _this;
  37245. }
  37246. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  37247. // Remove paths created before
  37248. this.removeAll(); // let symbolPath = createSymbol(
  37249. // symbolType, -0.5, -0.5, 1, 1, color
  37250. // );
  37251. // If width/height are set too small (e.g., set to 1) on ios10
  37252. // and macOS Sierra, a circle stroke become a rect, no matter what
  37253. // the scale is set. So we set width/height as 2. See #4150.
  37254. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  37255. symbolPath.attr({
  37256. z2: 100,
  37257. culling: true,
  37258. scaleX: symbolSize[0] / 2,
  37259. scaleY: symbolSize[1] / 2
  37260. }); // Rewrite drift method
  37261. symbolPath.drift = driftSymbol;
  37262. this._symbolType = symbolType;
  37263. this.add(symbolPath);
  37264. };
  37265. /**
  37266. * Stop animation
  37267. * @param {boolean} toLastFrame
  37268. */
  37269. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  37270. this.childAt(0).stopAnimation(null, toLastFrame);
  37271. };
  37272. Symbol.prototype.getSymbolType = function () {
  37273. return this._symbolType;
  37274. };
  37275. /**
  37276. * FIXME:
  37277. * Caution: This method breaks the encapsulation of this module,
  37278. * but it indeed brings convenience. So do not use the method
  37279. * unless you detailedly know all the implements of `Symbol`,
  37280. * especially animation.
  37281. *
  37282. * Get symbol path element.
  37283. */
  37284. Symbol.prototype.getSymbolPath = function () {
  37285. return this.childAt(0);
  37286. };
  37287. /**
  37288. * Highlight symbol
  37289. */
  37290. Symbol.prototype.highlight = function () {
  37291. enterEmphasis(this.childAt(0));
  37292. };
  37293. /**
  37294. * Downplay symbol
  37295. */
  37296. Symbol.prototype.downplay = function () {
  37297. leaveEmphasis(this.childAt(0));
  37298. };
  37299. /**
  37300. * @param {number} zlevel
  37301. * @param {number} z
  37302. */
  37303. Symbol.prototype.setZ = function (zlevel, z) {
  37304. var symbolPath = this.childAt(0);
  37305. symbolPath.zlevel = zlevel;
  37306. symbolPath.z = z;
  37307. };
  37308. Symbol.prototype.setDraggable = function (draggable) {
  37309. var symbolPath = this.childAt(0);
  37310. symbolPath.draggable = draggable;
  37311. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  37312. };
  37313. /**
  37314. * Update symbol properties
  37315. */
  37316. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  37317. this.silent = false;
  37318. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  37319. var seriesModel = data.hostModel;
  37320. var symbolSize = Symbol.getSymbolSize(data, idx);
  37321. var isInit = symbolType !== this._symbolType;
  37322. var disableAnimation = opts && opts.disableAnimation;
  37323. if (isInit) {
  37324. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  37325. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  37326. } else {
  37327. var symbolPath = this.childAt(0);
  37328. symbolPath.silent = false;
  37329. var target = {
  37330. scaleX: symbolSize[0] / 2,
  37331. scaleY: symbolSize[1] / 2
  37332. };
  37333. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  37334. saveOldStyle(symbolPath);
  37335. }
  37336. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  37337. if (isInit) {
  37338. var symbolPath = this.childAt(0);
  37339. if (!disableAnimation) {
  37340. var target = {
  37341. scaleX: this._sizeX,
  37342. scaleY: this._sizeY,
  37343. style: {
  37344. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  37345. opacity: symbolPath.style.opacity
  37346. }
  37347. };
  37348. symbolPath.scaleX = symbolPath.scaleY = 0;
  37349. symbolPath.style.opacity = 0;
  37350. initProps(symbolPath, target, seriesModel, idx);
  37351. }
  37352. }
  37353. if (disableAnimation) {
  37354. // Must stop remove animation manually if don't call initProps or updateProps.
  37355. this.childAt(0).stopAnimation('remove');
  37356. }
  37357. this._seriesModel = seriesModel;
  37358. };
  37359. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  37360. var symbolPath = this.childAt(0);
  37361. var seriesModel = data.hostModel;
  37362. var emphasisItemStyle;
  37363. var blurItemStyle;
  37364. var selectItemStyle;
  37365. var focus;
  37366. var blurScope;
  37367. var labelStatesModels;
  37368. var hoverScale;
  37369. var cursorStyle;
  37370. if (seriesScope) {
  37371. emphasisItemStyle = seriesScope.emphasisItemStyle;
  37372. blurItemStyle = seriesScope.blurItemStyle;
  37373. selectItemStyle = seriesScope.selectItemStyle;
  37374. focus = seriesScope.focus;
  37375. blurScope = seriesScope.blurScope;
  37376. labelStatesModels = seriesScope.labelStatesModels;
  37377. hoverScale = seriesScope.hoverScale;
  37378. cursorStyle = seriesScope.cursorStyle;
  37379. }
  37380. if (!seriesScope || data.hasItemOption) {
  37381. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  37382. var emphasisModel = itemModel.getModel('emphasis');
  37383. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  37384. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  37385. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  37386. focus = emphasisModel.get('focus');
  37387. blurScope = emphasisModel.get('blurScope');
  37388. labelStatesModels = getLabelStatesModels(itemModel);
  37389. hoverScale = emphasisModel.getShallow('scale');
  37390. cursorStyle = itemModel.getShallow('cursor');
  37391. }
  37392. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  37393. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  37394. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  37395. if (symbolOffset) {
  37396. symbolPath.x = symbolOffset[0];
  37397. symbolPath.y = symbolOffset[1];
  37398. }
  37399. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  37400. var symbolStyle = data.getItemVisual(idx, 'style');
  37401. var visualColor = symbolStyle.fill;
  37402. if (symbolPath instanceof ZRImage) {
  37403. var pathStyle = symbolPath.style;
  37404. symbolPath.useStyle(extend({
  37405. // TODO other properties like x, y ?
  37406. image: pathStyle.image,
  37407. x: pathStyle.x,
  37408. y: pathStyle.y,
  37409. width: pathStyle.width,
  37410. height: pathStyle.height
  37411. }, symbolStyle));
  37412. } else {
  37413. if (symbolPath.__isEmptyBrush) {
  37414. // fill and stroke will be swapped if it's empty.
  37415. // So we cloned a new style to avoid it affecting the original style in visual storage.
  37416. // TODO Better implementation. No empty logic!
  37417. symbolPath.useStyle(extend({}, symbolStyle));
  37418. } else {
  37419. symbolPath.useStyle(symbolStyle);
  37420. } // Disable decal because symbol scale will been applied on the decal.
  37421. symbolPath.style.decal = null;
  37422. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  37423. symbolPath.style.strokeNoScale = true;
  37424. }
  37425. var liftZ = data.getItemVisual(idx, 'liftZ');
  37426. var z2Origin = this._z2;
  37427. if (liftZ != null) {
  37428. if (z2Origin == null) {
  37429. this._z2 = symbolPath.z2;
  37430. symbolPath.z2 += liftZ;
  37431. }
  37432. } else if (z2Origin != null) {
  37433. symbolPath.z2 = z2Origin;
  37434. this._z2 = null;
  37435. }
  37436. var useNameLabel = opts && opts.useNameLabel;
  37437. setLabelStyle(symbolPath, labelStatesModels, {
  37438. labelFetcher: seriesModel,
  37439. labelDataIndex: idx,
  37440. defaultText: getLabelDefaultText,
  37441. inheritColor: visualColor,
  37442. defaultOpacity: symbolStyle.opacity
  37443. }); // Do not execute util needed.
  37444. function getLabelDefaultText(idx) {
  37445. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  37446. }
  37447. this._sizeX = symbolSize[0] / 2;
  37448. this._sizeY = symbolSize[1] / 2;
  37449. var emphasisState = symbolPath.ensureState('emphasis');
  37450. emphasisState.style = emphasisItemStyle;
  37451. symbolPath.ensureState('select').style = selectItemStyle;
  37452. symbolPath.ensureState('blur').style = blurItemStyle;
  37453. if (hoverScale) {
  37454. var scaleRatio = Math.max(1.1, 3 / this._sizeY);
  37455. emphasisState.scaleX = this._sizeX * scaleRatio;
  37456. emphasisState.scaleY = this._sizeY * scaleRatio;
  37457. }
  37458. this.setSymbolScale(1);
  37459. enableHoverEmphasis(this, focus, blurScope);
  37460. };
  37461. Symbol.prototype.setSymbolScale = function (scale) {
  37462. this.scaleX = this.scaleY = scale;
  37463. };
  37464. Symbol.prototype.fadeOut = function (cb, opt) {
  37465. var symbolPath = this.childAt(0);
  37466. var seriesModel = this._seriesModel;
  37467. var dataIndex = getECData(this).dataIndex;
  37468. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  37469. this.silent = symbolPath.silent = true; // Not show text when animating
  37470. if (opt && opt.fadeLabel) {
  37471. var textContent = symbolPath.getTextContent();
  37472. if (textContent) {
  37473. removeElement(textContent, {
  37474. style: {
  37475. opacity: 0
  37476. }
  37477. }, seriesModel, {
  37478. dataIndex: dataIndex,
  37479. removeOpt: animationOpt,
  37480. cb: function () {
  37481. symbolPath.removeTextContent();
  37482. }
  37483. });
  37484. }
  37485. } else {
  37486. symbolPath.removeTextContent();
  37487. }
  37488. removeElement(symbolPath, {
  37489. style: {
  37490. opacity: 0
  37491. },
  37492. scaleX: 0,
  37493. scaleY: 0
  37494. }, seriesModel, {
  37495. dataIndex: dataIndex,
  37496. cb: cb,
  37497. removeOpt: animationOpt
  37498. });
  37499. };
  37500. Symbol.getSymbolSize = function (data, idx) {
  37501. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  37502. };
  37503. return Symbol;
  37504. }(Group);
  37505. function driftSymbol(dx, dy) {
  37506. this.parent.drift(dx, dy);
  37507. }
  37508. function symbolNeedsDraw(data, point, idx, opt) {
  37509. 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
  37510. // the symbol element shape. We use the same clip shape here as
  37511. // the line clip.
  37512. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  37513. }
  37514. function normalizeUpdateOpt(opt) {
  37515. if (opt != null && !isObject(opt)) {
  37516. opt = {
  37517. isIgnore: opt
  37518. };
  37519. }
  37520. return opt || {};
  37521. }
  37522. function makeSeriesScope(data) {
  37523. var seriesModel = data.hostModel;
  37524. var emphasisModel = seriesModel.getModel('emphasis');
  37525. return {
  37526. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  37527. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  37528. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  37529. focus: emphasisModel.get('focus'),
  37530. blurScope: emphasisModel.get('blurScope'),
  37531. hoverScale: emphasisModel.get('scale'),
  37532. labelStatesModels: getLabelStatesModels(seriesModel),
  37533. cursorStyle: seriesModel.get('cursor')
  37534. };
  37535. }
  37536. var SymbolDraw =
  37537. /** @class */
  37538. function () {
  37539. function SymbolDraw(SymbolCtor) {
  37540. this.group = new Group();
  37541. this._SymbolCtor = SymbolCtor || Symbol;
  37542. }
  37543. /**
  37544. * Update symbols draw by new data
  37545. */
  37546. SymbolDraw.prototype.updateData = function (data, opt) {
  37547. opt = normalizeUpdateOpt(opt);
  37548. var group = this.group;
  37549. var seriesModel = data.hostModel;
  37550. var oldData = this._data;
  37551. var SymbolCtor = this._SymbolCtor;
  37552. var disableAnimation = opt.disableAnimation;
  37553. var seriesScope = makeSeriesScope(data);
  37554. var symbolUpdateOpt = {
  37555. disableAnimation: disableAnimation
  37556. };
  37557. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  37558. return data.getItemLayout(idx);
  37559. }; // There is no oldLineData only when first rendering or switching from
  37560. // stream mode to normal mode, where previous elements should be removed.
  37561. if (!oldData) {
  37562. group.removeAll();
  37563. }
  37564. data.diff(oldData).add(function (newIdx) {
  37565. var point = getSymbolPoint(newIdx);
  37566. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  37567. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  37568. symbolEl.setPosition(point);
  37569. data.setItemGraphicEl(newIdx, symbolEl);
  37570. group.add(symbolEl);
  37571. }
  37572. }).update(function (newIdx, oldIdx) {
  37573. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  37574. var point = getSymbolPoint(newIdx);
  37575. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  37576. group.remove(symbolEl);
  37577. return;
  37578. }
  37579. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  37580. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  37581. if (!symbolEl // Create a new if symbol type changed.
  37582. || oldSymbolType && oldSymbolType !== newSymbolType) {
  37583. group.remove(symbolEl);
  37584. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  37585. symbolEl.setPosition(point);
  37586. } else {
  37587. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  37588. var target = {
  37589. x: point[0],
  37590. y: point[1]
  37591. };
  37592. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  37593. } // Add back
  37594. group.add(symbolEl);
  37595. data.setItemGraphicEl(newIdx, symbolEl);
  37596. }).remove(function (oldIdx) {
  37597. var el = oldData.getItemGraphicEl(oldIdx);
  37598. el && el.fadeOut(function () {
  37599. group.remove(el);
  37600. });
  37601. }).execute();
  37602. this._getSymbolPoint = getSymbolPoint;
  37603. this._data = data;
  37604. };
  37605. SymbolDraw.prototype.isPersistent = function () {
  37606. return true;
  37607. };
  37608. SymbolDraw.prototype.updateLayout = function () {
  37609. var _this = this;
  37610. var data = this._data;
  37611. if (data) {
  37612. // Not use animation
  37613. data.eachItemGraphicEl(function (el, idx) {
  37614. var point = _this._getSymbolPoint(idx);
  37615. el.setPosition(point);
  37616. el.markRedraw();
  37617. });
  37618. }
  37619. };
  37620. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  37621. this._seriesScope = makeSeriesScope(data);
  37622. this._data = null;
  37623. this.group.removeAll();
  37624. };
  37625. /**
  37626. * Update symbols draw by new data
  37627. */
  37628. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  37629. opt = normalizeUpdateOpt(opt);
  37630. function updateIncrementalAndHover(el) {
  37631. if (!el.isGroup) {
  37632. el.incremental = true;
  37633. el.ensureState('emphasis').hoverLayer = true;
  37634. }
  37635. }
  37636. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  37637. var point = data.getItemLayout(idx);
  37638. if (symbolNeedsDraw(data, point, idx, opt)) {
  37639. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  37640. el.traverse(updateIncrementalAndHover);
  37641. el.setPosition(point);
  37642. this.group.add(el);
  37643. data.setItemGraphicEl(idx, el);
  37644. }
  37645. }
  37646. };
  37647. SymbolDraw.prototype.remove = function (enableAnimation) {
  37648. var group = this.group;
  37649. var data = this._data; // Incremental model do not have this._data.
  37650. if (data && enableAnimation) {
  37651. data.eachItemGraphicEl(function (el) {
  37652. el.fadeOut(function () {
  37653. group.remove(el);
  37654. });
  37655. });
  37656. } else {
  37657. group.removeAll();
  37658. }
  37659. };
  37660. return SymbolDraw;
  37661. }();
  37662. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  37663. var baseAxis = coordSys.getBaseAxis();
  37664. var valueAxis = coordSys.getOtherAxis(baseAxis);
  37665. var valueStart = getValueStart(valueAxis, valueOrigin);
  37666. var baseAxisDim = baseAxis.dim;
  37667. var valueAxisDim = valueAxis.dim;
  37668. var valueDim = data.mapDimension(valueAxisDim);
  37669. var baseDim = data.mapDimension(baseAxisDim);
  37670. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  37671. var dims = map(coordSys.dimensions, function (coordDim) {
  37672. return data.mapDimension(coordDim);
  37673. });
  37674. var stacked = false;
  37675. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  37676. if (isDimensionStacked(data, dims[0]
  37677. /*, dims[1]*/
  37678. )) {
  37679. // jshint ignore:line
  37680. stacked = true;
  37681. dims[0] = stackResultDim;
  37682. }
  37683. if (isDimensionStacked(data, dims[1]
  37684. /*, dims[0]*/
  37685. )) {
  37686. // jshint ignore:line
  37687. stacked = true;
  37688. dims[1] = stackResultDim;
  37689. }
  37690. return {
  37691. dataDimsForPoint: dims,
  37692. valueStart: valueStart,
  37693. valueAxisDim: valueAxisDim,
  37694. baseAxisDim: baseAxisDim,
  37695. stacked: !!stacked,
  37696. valueDim: valueDim,
  37697. baseDim: baseDim,
  37698. baseDataOffset: baseDataOffset,
  37699. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  37700. };
  37701. }
  37702. function getValueStart(valueAxis, valueOrigin) {
  37703. var valueStart = 0;
  37704. var extent = valueAxis.scale.getExtent();
  37705. if (valueOrigin === 'start') {
  37706. valueStart = extent[0];
  37707. } else if (valueOrigin === 'end') {
  37708. valueStart = extent[1];
  37709. } // auto
  37710. else {
  37711. // Both positive
  37712. if (extent[0] > 0) {
  37713. valueStart = extent[0];
  37714. } // Both negative
  37715. else if (extent[1] < 0) {
  37716. valueStart = extent[1];
  37717. } // If is one positive, and one negative, onZero shall be true
  37718. }
  37719. return valueStart;
  37720. }
  37721. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  37722. var value = NaN;
  37723. if (dataCoordInfo.stacked) {
  37724. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  37725. }
  37726. if (isNaN(value)) {
  37727. value = dataCoordInfo.valueStart;
  37728. }
  37729. var baseDataOffset = dataCoordInfo.baseDataOffset;
  37730. var stackedData = [];
  37731. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  37732. stackedData[1 - baseDataOffset] = value;
  37733. return coordSys.dataToPoint(stackedData);
  37734. }
  37735. /* global Float32Array */
  37736. var supportFloat32Array = typeof Float32Array !== 'undefined';
  37737. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  37738. function createFloat32Array(arg) {
  37739. if (isArray(arg)) {
  37740. // Return self directly if don't support TypedArray.
  37741. return supportFloat32Array ? new Float32Array(arg) : arg;
  37742. } // Else is number
  37743. return new Float32ArrayCtor(arg);
  37744. }
  37745. function diffData(oldData, newData) {
  37746. var diffResult = [];
  37747. newData.diff(oldData).add(function (idx) {
  37748. diffResult.push({
  37749. cmd: '+',
  37750. idx: idx
  37751. });
  37752. }).update(function (newIdx, oldIdx) {
  37753. diffResult.push({
  37754. cmd: '=',
  37755. idx: oldIdx,
  37756. idx1: newIdx
  37757. });
  37758. }).remove(function (idx) {
  37759. diffResult.push({
  37760. cmd: '-',
  37761. idx: idx
  37762. });
  37763. }).execute();
  37764. return diffResult;
  37765. }
  37766. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  37767. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  37768. // let oldIdList = oldData.mapArray(oldData.getId);
  37769. // convertToIntId(newIdList, oldIdList);
  37770. // // FIXME One data ?
  37771. // diff = arrayDiff(oldIdList, newIdList);
  37772. var currPoints = [];
  37773. var nextPoints = []; // Points for stacking base line
  37774. var currStackedPoints = [];
  37775. var nextStackedPoints = [];
  37776. var status = [];
  37777. var sortedIndices = [];
  37778. var rawIndices = [];
  37779. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin); // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  37780. var oldPoints = oldData.getLayout('points') || [];
  37781. var newPoints = newData.getLayout('points') || [];
  37782. for (var i = 0; i < diff.length; i++) {
  37783. var diffItem = diff[i];
  37784. var pointAdded = true;
  37785. var oldIdx2 = void 0;
  37786. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  37787. // Which is in case remvoing or add more than one data in the tail or head
  37788. switch (diffItem.cmd) {
  37789. case '=':
  37790. oldIdx2 = diffItem.idx * 2;
  37791. newIdx2 = diffItem.idx1 * 2;
  37792. var currentX = oldPoints[oldIdx2];
  37793. var currentY = oldPoints[oldIdx2 + 1];
  37794. var nextX = newPoints[newIdx2];
  37795. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  37796. if (isNaN(currentX) || isNaN(currentY)) {
  37797. currentX = nextX;
  37798. currentY = nextY;
  37799. }
  37800. currPoints.push(currentX, currentY);
  37801. nextPoints.push(nextX, nextY);
  37802. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  37803. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37804. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  37805. break;
  37806. case '+':
  37807. var newIdx = diffItem.idx;
  37808. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  37809. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  37810. newIdx2 = newIdx * 2;
  37811. currPoints.push(oldPt[0], oldPt[1]);
  37812. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  37813. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  37814. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  37815. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37816. rawIndices.push(newData.getRawIndex(newIdx));
  37817. break;
  37818. case '-':
  37819. pointAdded = false;
  37820. } // Original indices
  37821. if (pointAdded) {
  37822. status.push(diffItem);
  37823. sortedIndices.push(sortedIndices.length);
  37824. }
  37825. } // Diff result may be crossed if all items are changed
  37826. // Sort by data index
  37827. sortedIndices.sort(function (a, b) {
  37828. return rawIndices[a] - rawIndices[b];
  37829. });
  37830. var len = currPoints.length;
  37831. var sortedCurrPoints = createFloat32Array(len);
  37832. var sortedNextPoints = createFloat32Array(len);
  37833. var sortedCurrStackedPoints = createFloat32Array(len);
  37834. var sortedNextStackedPoints = createFloat32Array(len);
  37835. var sortedStatus = [];
  37836. for (var i = 0; i < sortedIndices.length; i++) {
  37837. var idx = sortedIndices[i];
  37838. var i2 = i * 2;
  37839. var idx2 = idx * 2;
  37840. sortedCurrPoints[i2] = currPoints[idx2];
  37841. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  37842. sortedNextPoints[i2] = nextPoints[idx2];
  37843. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  37844. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  37845. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  37846. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  37847. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  37848. sortedStatus[i] = status[idx];
  37849. }
  37850. return {
  37851. current: sortedCurrPoints,
  37852. next: sortedNextPoints,
  37853. stackedOnCurrent: sortedCurrStackedPoints,
  37854. stackedOnNext: sortedNextStackedPoints,
  37855. status: sortedStatus
  37856. };
  37857. }
  37858. var mathMin$5 = Math.min;
  37859. var mathMax$5 = Math.max;
  37860. function isPointNull(x, y) {
  37861. return isNaN(x) || isNaN(y);
  37862. }
  37863. /**
  37864. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  37865. * situations. This should be used when points are non-monotone neither in x or
  37866. * y dimension.
  37867. */
  37868. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  37869. var prevX;
  37870. var prevY;
  37871. var cpx0;
  37872. var cpy0;
  37873. var cpx1;
  37874. var cpy1;
  37875. var idx = start;
  37876. var k = 0;
  37877. for (; k < segLen; k++) {
  37878. var x = points[idx * 2];
  37879. var y = points[idx * 2 + 1];
  37880. if (idx >= allLen || idx < 0) {
  37881. break;
  37882. }
  37883. if (isPointNull(x, y)) {
  37884. if (connectNulls) {
  37885. idx += dir;
  37886. continue;
  37887. }
  37888. break;
  37889. }
  37890. if (idx === start) {
  37891. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  37892. cpx0 = x;
  37893. cpy0 = y;
  37894. } else {
  37895. var dx = x - prevX;
  37896. var dy = y - prevY; // Ignore tiny segment.
  37897. if (dx * dx + dy * dy < 0.5) {
  37898. idx += dir;
  37899. continue;
  37900. }
  37901. if (smooth > 0) {
  37902. var nextIdx = idx + dir;
  37903. var nextX = points[nextIdx * 2];
  37904. var nextY = points[nextIdx * 2 + 1];
  37905. var tmpK = k + 1;
  37906. if (connectNulls) {
  37907. // Find next point not null
  37908. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  37909. tmpK++;
  37910. nextIdx += dir;
  37911. nextX = points[nextIdx * 2];
  37912. nextY = points[nextIdx * 2 + 1];
  37913. }
  37914. }
  37915. var ratioNextSeg = 0.5;
  37916. var vx = 0;
  37917. var vy = 0;
  37918. var nextCpx0 = void 0;
  37919. var nextCpy0 = void 0; // Is last point
  37920. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  37921. cpx1 = x;
  37922. cpy1 = y;
  37923. } else {
  37924. vx = nextX - prevX;
  37925. vy = nextY - prevY;
  37926. var dx0 = x - prevX;
  37927. var dx1 = nextX - x;
  37928. var dy0 = y - prevY;
  37929. var dy1 = nextY - y;
  37930. var lenPrevSeg = void 0;
  37931. var lenNextSeg = void 0;
  37932. if (smoothMonotone === 'x') {
  37933. lenPrevSeg = Math.abs(dx0);
  37934. lenNextSeg = Math.abs(dx1);
  37935. cpx1 = x - lenPrevSeg * smooth;
  37936. cpy1 = y;
  37937. nextCpx0 = x + lenPrevSeg * smooth;
  37938. nextCpy0 = y;
  37939. } else if (smoothMonotone === 'y') {
  37940. lenPrevSeg = Math.abs(dy0);
  37941. lenNextSeg = Math.abs(dy1);
  37942. cpx1 = x;
  37943. cpy1 = y - lenPrevSeg * smooth;
  37944. nextCpx0 = x;
  37945. nextCpy0 = y + lenPrevSeg * smooth;
  37946. } else {
  37947. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  37948. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  37949. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  37950. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  37951. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  37952. nextCpx0 = x + vx * smooth * ratioNextSeg;
  37953. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  37954. // Avoid exceeding extreme after smoothing.
  37955. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  37956. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  37957. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  37958. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  37959. vx = nextCpx0 - x;
  37960. vy = nextCpy0 - y;
  37961. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  37962. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  37963. // Avoid exceeding extreme after smoothing.
  37964. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  37965. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  37966. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  37967. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  37968. vx = x - cpx1;
  37969. vy = y - cpy1;
  37970. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  37971. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  37972. }
  37973. }
  37974. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  37975. cpx0 = nextCpx0;
  37976. cpy0 = nextCpy0;
  37977. } else {
  37978. ctx.lineTo(x, y);
  37979. }
  37980. }
  37981. prevX = x;
  37982. prevY = y;
  37983. idx += dir;
  37984. }
  37985. return k;
  37986. }
  37987. var ECPolylineShape =
  37988. /** @class */
  37989. function () {
  37990. function ECPolylineShape() {
  37991. this.smooth = 0;
  37992. this.smoothConstraint = true;
  37993. }
  37994. return ECPolylineShape;
  37995. }();
  37996. var ECPolyline =
  37997. /** @class */
  37998. function (_super) {
  37999. __extends(ECPolyline, _super);
  38000. function ECPolyline(opts) {
  38001. var _this = _super.call(this, opts) || this;
  38002. _this.type = 'ec-polyline';
  38003. return _this;
  38004. }
  38005. ECPolyline.prototype.getDefaultStyle = function () {
  38006. return {
  38007. stroke: '#000',
  38008. fill: null
  38009. };
  38010. };
  38011. ECPolyline.prototype.getDefaultShape = function () {
  38012. return new ECPolylineShape();
  38013. };
  38014. ECPolyline.prototype.buildPath = function (ctx, shape) {
  38015. var points = shape.points;
  38016. var i = 0;
  38017. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  38018. if (shape.connectNulls) {
  38019. // Must remove first and last null values avoid draw error in polygon
  38020. for (; len > 0; len--) {
  38021. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  38022. break;
  38023. }
  38024. }
  38025. for (; i < len; i++) {
  38026. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  38027. break;
  38028. }
  38029. }
  38030. }
  38031. while (i < len) {
  38032. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  38033. }
  38034. };
  38035. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  38036. if (!this.path) {
  38037. this.createPathProxy();
  38038. this.buildPath(this.path, this.shape);
  38039. }
  38040. var path = this.path;
  38041. var data = path.data;
  38042. var CMD = PathProxy.CMD;
  38043. var x0;
  38044. var y0;
  38045. var isDimX = dim === 'x';
  38046. var roots = [];
  38047. for (var i = 0; i < data.length;) {
  38048. var cmd = data[i++];
  38049. var x = void 0;
  38050. var y = void 0;
  38051. var x2 = void 0;
  38052. var y2 = void 0;
  38053. var x3 = void 0;
  38054. var y3 = void 0;
  38055. var t = void 0;
  38056. switch (cmd) {
  38057. case CMD.M:
  38058. x0 = data[i++];
  38059. y0 = data[i++];
  38060. break;
  38061. case CMD.L:
  38062. x = data[i++];
  38063. y = data[i++];
  38064. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  38065. if (t <= 1 && t >= 0) {
  38066. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  38067. return isDimX ? [xOrY, val] : [val, xOrY];
  38068. }
  38069. x0 = x;
  38070. y0 = y;
  38071. break;
  38072. case CMD.C:
  38073. x = data[i++];
  38074. y = data[i++];
  38075. x2 = data[i++];
  38076. y2 = data[i++];
  38077. x3 = data[i++];
  38078. y3 = data[i++];
  38079. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  38080. if (nRoot > 0) {
  38081. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  38082. var t_1 = roots[i_1];
  38083. if (t_1 <= 1 && t_1 >= 0) {
  38084. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  38085. return isDimX ? [xOrY, val] : [val, xOrY];
  38086. }
  38087. }
  38088. }
  38089. x0 = x3;
  38090. y0 = y3;
  38091. break;
  38092. }
  38093. }
  38094. };
  38095. return ECPolyline;
  38096. }(Path);
  38097. var ECPolygonShape =
  38098. /** @class */
  38099. function (_super) {
  38100. __extends(ECPolygonShape, _super);
  38101. function ECPolygonShape() {
  38102. return _super !== null && _super.apply(this, arguments) || this;
  38103. }
  38104. return ECPolygonShape;
  38105. }(ECPolylineShape);
  38106. var ECPolygon =
  38107. /** @class */
  38108. function (_super) {
  38109. __extends(ECPolygon, _super);
  38110. function ECPolygon(opts) {
  38111. var _this = _super.call(this, opts) || this;
  38112. _this.type = 'ec-polygon';
  38113. return _this;
  38114. }
  38115. ECPolygon.prototype.getDefaultShape = function () {
  38116. return new ECPolygonShape();
  38117. };
  38118. ECPolygon.prototype.buildPath = function (ctx, shape) {
  38119. var points = shape.points;
  38120. var stackedOnPoints = shape.stackedOnPoints;
  38121. var i = 0;
  38122. var len = points.length / 2;
  38123. var smoothMonotone = shape.smoothMonotone;
  38124. if (shape.connectNulls) {
  38125. // Must remove first and last null values avoid draw error in polygon
  38126. for (; len > 0; len--) {
  38127. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  38128. break;
  38129. }
  38130. }
  38131. for (; i < len; i++) {
  38132. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  38133. break;
  38134. }
  38135. }
  38136. }
  38137. while (i < len) {
  38138. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  38139. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  38140. i += k + 1;
  38141. ctx.closePath();
  38142. }
  38143. };
  38144. return ECPolygon;
  38145. }(Path);
  38146. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  38147. var rect = cartesian.getArea();
  38148. var x = rect.x;
  38149. var y = rect.y;
  38150. var width = rect.width;
  38151. var height = rect.height;
  38152. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  38153. x -= lineWidth / 2;
  38154. y -= lineWidth / 2;
  38155. width += lineWidth;
  38156. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  38157. x = Math.floor(x);
  38158. width = Math.round(width);
  38159. var clipPath = new Rect({
  38160. shape: {
  38161. x: x,
  38162. y: y,
  38163. width: width,
  38164. height: height
  38165. }
  38166. });
  38167. if (hasAnimation) {
  38168. var baseAxis = cartesian.getBaseAxis();
  38169. var isHorizontal = baseAxis.isHorizontal();
  38170. var isAxisInversed = baseAxis.inverse;
  38171. if (isHorizontal) {
  38172. if (isAxisInversed) {
  38173. clipPath.shape.x += width;
  38174. }
  38175. clipPath.shape.width = 0;
  38176. } else {
  38177. if (!isAxisInversed) {
  38178. clipPath.shape.y += height;
  38179. }
  38180. clipPath.shape.height = 0;
  38181. }
  38182. var duringCb = typeof during === 'function' ? function (percent) {
  38183. during(percent, clipPath);
  38184. } : null;
  38185. initProps(clipPath, {
  38186. shape: {
  38187. width: width,
  38188. height: height,
  38189. x: x,
  38190. y: y
  38191. }
  38192. }, seriesModel, null, done, duringCb);
  38193. }
  38194. return clipPath;
  38195. }
  38196. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  38197. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  38198. var r0 = round(sectorArea.r0, 1);
  38199. var r = round(sectorArea.r, 1);
  38200. var clipPath = new Sector({
  38201. shape: {
  38202. cx: round(polar.cx, 1),
  38203. cy: round(polar.cy, 1),
  38204. r0: r0,
  38205. r: r,
  38206. startAngle: sectorArea.startAngle,
  38207. endAngle: sectorArea.endAngle,
  38208. clockwise: sectorArea.clockwise
  38209. }
  38210. });
  38211. if (hasAnimation) {
  38212. var isRadial = polar.getBaseAxis().dim === 'angle';
  38213. if (isRadial) {
  38214. clipPath.shape.endAngle = sectorArea.startAngle;
  38215. } else {
  38216. clipPath.shape.r = r0;
  38217. }
  38218. initProps(clipPath, {
  38219. shape: {
  38220. endAngle: sectorArea.endAngle,
  38221. r: r
  38222. }
  38223. }, seriesModel);
  38224. }
  38225. return clipPath;
  38226. }
  38227. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  38228. if (!coordSys) {
  38229. return null;
  38230. } else if (coordSys.type === 'polar') {
  38231. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  38232. } else if (coordSys.type === 'cartesian2d') {
  38233. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  38234. }
  38235. return null;
  38236. }
  38237. /*
  38238. * Licensed to the Apache Software Foundation (ASF) under one
  38239. * or more contributor license agreements. See the NOTICE file
  38240. * distributed with this work for additional information
  38241. * regarding copyright ownership. The ASF licenses this file
  38242. * to you under the Apache License, Version 2.0 (the
  38243. * "License"); you may not use this file except in compliance
  38244. * with the License. You may obtain a copy of the License at
  38245. *
  38246. * http://www.apache.org/licenses/LICENSE-2.0
  38247. *
  38248. * Unless required by applicable law or agreed to in writing,
  38249. * software distributed under the License is distributed on an
  38250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38251. * KIND, either express or implied. See the License for the
  38252. * specific language governing permissions and limitations
  38253. * under the License.
  38254. */
  38255. /**
  38256. * AUTO-GENERATED FILE. DO NOT MODIFY.
  38257. */
  38258. /*
  38259. * Licensed to the Apache Software Foundation (ASF) under one
  38260. * or more contributor license agreements. See the NOTICE file
  38261. * distributed with this work for additional information
  38262. * regarding copyright ownership. The ASF licenses this file
  38263. * to you under the Apache License, Version 2.0 (the
  38264. * "License"); you may not use this file except in compliance
  38265. * with the License. You may obtain a copy of the License at
  38266. *
  38267. * http://www.apache.org/licenses/LICENSE-2.0
  38268. *
  38269. * Unless required by applicable law or agreed to in writing,
  38270. * software distributed under the License is distributed on an
  38271. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38272. * KIND, either express or implied. See the License for the
  38273. * specific language governing permissions and limitations
  38274. * under the License.
  38275. */
  38276. function isCoordinateSystemType(coordSys, type) {
  38277. return coordSys.type === type;
  38278. }
  38279. function isPointsSame(points1, points2) {
  38280. if (points1.length !== points2.length) {
  38281. return;
  38282. }
  38283. for (var i = 0; i < points1.length; i++) {
  38284. if (points1[i] !== points2[i]) {
  38285. return;
  38286. }
  38287. }
  38288. return true;
  38289. }
  38290. function bboxFromPoints(points) {
  38291. var minX = Infinity;
  38292. var minY = Infinity;
  38293. var maxX = -Infinity;
  38294. var maxY = -Infinity;
  38295. for (var i = 0; i < points.length;) {
  38296. var x = points[i++];
  38297. var y = points[i++];
  38298. if (!isNaN(x)) {
  38299. minX = Math.min(x, minX);
  38300. maxX = Math.max(x, maxX);
  38301. }
  38302. if (!isNaN(y)) {
  38303. minY = Math.min(y, minY);
  38304. maxY = Math.max(y, maxY);
  38305. }
  38306. }
  38307. return [[minX, minY], [maxX, maxY]];
  38308. }
  38309. function getBoundingDiff(points1, points2) {
  38310. var _a = bboxFromPoints(points1),
  38311. min1 = _a[0],
  38312. max1 = _a[1];
  38313. var _b = bboxFromPoints(points2),
  38314. min2 = _b[0],
  38315. max2 = _b[1]; // Get a max value from each corner of two boundings.
  38316. 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]));
  38317. }
  38318. function getSmooth(smooth) {
  38319. return typeof smooth === 'number' ? smooth : smooth ? 0.5 : 0;
  38320. }
  38321. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  38322. if (!dataCoordInfo.valueDim) {
  38323. return [];
  38324. }
  38325. var len = data.count();
  38326. var points = createFloat32Array(len * 2);
  38327. for (var idx = 0; idx < len; idx++) {
  38328. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  38329. points[idx * 2] = pt[0];
  38330. points[idx * 2 + 1] = pt[1];
  38331. }
  38332. return points;
  38333. }
  38334. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  38335. var baseAxis = coordSys.getBaseAxis();
  38336. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  38337. var stepPoints = [];
  38338. var i = 0;
  38339. var stepPt = [];
  38340. var pt = [];
  38341. var nextPt = [];
  38342. for (; i < points.length - 2; i += 2) {
  38343. nextPt[0] = points[i + 2];
  38344. nextPt[1] = points[i + 3];
  38345. pt[0] = points[i];
  38346. pt[1] = points[i + 1];
  38347. stepPoints.push(pt[0], pt[1]);
  38348. switch (stepTurnAt) {
  38349. case 'end':
  38350. stepPt[baseIndex] = nextPt[baseIndex];
  38351. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  38352. stepPoints.push(stepPt[0], stepPt[1]);
  38353. break;
  38354. case 'middle':
  38355. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  38356. var stepPt2 = [];
  38357. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  38358. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  38359. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  38360. stepPoints.push(stepPt[0], stepPt[1]);
  38361. stepPoints.push(stepPt2[0], stepPt2[1]);
  38362. break;
  38363. default:
  38364. // default is start
  38365. stepPt[baseIndex] = pt[baseIndex];
  38366. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  38367. stepPoints.push(stepPt[0], stepPt[1]);
  38368. }
  38369. } // Last points
  38370. stepPoints.push(points[i++], points[i++]);
  38371. return stepPoints;
  38372. }
  38373. function getVisualGradient(data, coordSys) {
  38374. var visualMetaList = data.getVisual('visualMeta');
  38375. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  38376. // When data.count() is 0, gradient range can not be calculated.
  38377. return;
  38378. }
  38379. if (coordSys.type !== 'cartesian2d') {
  38380. if ("development" !== 'production') {
  38381. console.warn('Visual map on line style is only supported on cartesian2d.');
  38382. }
  38383. return;
  38384. }
  38385. var coordDim;
  38386. var visualMeta;
  38387. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  38388. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  38389. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  38390. if (coordDim === 'x' || coordDim === 'y') {
  38391. visualMeta = visualMetaList[i];
  38392. break;
  38393. }
  38394. }
  38395. if (!visualMeta) {
  38396. if ("development" !== 'production') {
  38397. console.warn('Visual map on line style only support x or y dimension.');
  38398. }
  38399. return;
  38400. } // If the area to be rendered is bigger than area defined by LinearGradient,
  38401. // the canvas spec prescribes that the color of the first stop and the last
  38402. // stop should be used. But if two stops are added at offset 0, in effect
  38403. // browsers use the color of the second stop to render area outside
  38404. // LinearGradient. So we can only infinitesimally extend area defined in
  38405. // LinearGradient to render `outerColors`.
  38406. var axis = coordSys.getAxis(coordDim);
  38407. var axisScaleExtent = axis.scale.getExtent(); // dataToCoord mapping may not be linear, but must be monotonic.
  38408. var colorStops = map(visualMeta.stops, function (stop) {
  38409. var coord = axis.toGlobalCoord(axis.dataToCoord(stop.value)); // normalize the infinite value
  38410. isNaN(coord) || isFinite(coord) || (coord = axis.toGlobalCoord(axis.dataToCoord(axisScaleExtent[+(coord < 0)])));
  38411. return {
  38412. offset: 0,
  38413. coord: coord,
  38414. color: stop.color
  38415. };
  38416. });
  38417. var stopLen = colorStops.length;
  38418. var outerColors = visualMeta.outerColors.slice();
  38419. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  38420. colorStops.reverse();
  38421. outerColors.reverse();
  38422. }
  38423. var tinyExtent = 10; // Arbitrary value: 10px
  38424. var minCoord = colorStops[0].coord - tinyExtent;
  38425. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  38426. var coordSpan = maxCoord - minCoord;
  38427. if (coordSpan < 1e-3) {
  38428. return 'transparent';
  38429. }
  38430. each(colorStops, function (stop) {
  38431. stop.offset = (stop.coord - minCoord) / coordSpan;
  38432. });
  38433. colorStops.push({
  38434. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  38435. color: outerColors[1] || 'transparent'
  38436. });
  38437. colorStops.unshift({
  38438. offset: stopLen ? colorStops[0].offset : 0.5,
  38439. color: outerColors[0] || 'transparent'
  38440. }); // zrUtil.each(colorStops, function (colorStop) {
  38441. // // Make sure each offset has rounded px to avoid not sharp edge
  38442. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  38443. // });
  38444. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  38445. gradient[coordDim] = minCoord;
  38446. gradient[coordDim + '2'] = maxCoord;
  38447. return gradient;
  38448. }
  38449. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  38450. var showAllSymbol = seriesModel.get('showAllSymbol');
  38451. var isAuto = showAllSymbol === 'auto';
  38452. if (showAllSymbol && !isAuto) {
  38453. return;
  38454. }
  38455. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  38456. if (!categoryAxis) {
  38457. return;
  38458. } // Note that category label interval strategy might bring some weird effect
  38459. // in some scenario: users may wonder why some of the symbols are not
  38460. // displayed. So we show all symbols as possible as we can.
  38461. if (isAuto // Simplify the logic, do not determine label overlap here.
  38462. && canShowAllSymbolForCategory(categoryAxis, data)) {
  38463. return;
  38464. } // Otherwise follow the label interval strategy on category axis.
  38465. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  38466. var labelMap = {};
  38467. each(categoryAxis.getViewLabels(), function (labelItem) {
  38468. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  38469. labelMap[ordinalNumber] = 1;
  38470. });
  38471. return function (dataIndex) {
  38472. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  38473. };
  38474. }
  38475. function canShowAllSymbolForCategory(categoryAxis, data) {
  38476. // In mose cases, line is monotonous on category axis, and the label size
  38477. // is close with each other. So we check the symbol size and some of the
  38478. // label size alone with the category axis to estimate whether all symbol
  38479. // can be shown without overlap.
  38480. var axisExtent = categoryAxis.getExtent();
  38481. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  38482. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  38483. // Sampling some points, max 5.
  38484. var dataLen = data.count();
  38485. var step = Math.max(1, Math.round(dataLen / 5));
  38486. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  38487. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  38488. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  38489. * 1.5 > availSize) {
  38490. return false;
  38491. }
  38492. }
  38493. return true;
  38494. }
  38495. function isPointNull$1(x, y) {
  38496. return isNaN(x) || isNaN(y);
  38497. }
  38498. function getLastIndexNotNull(points) {
  38499. var len = points.length / 2;
  38500. for (; len > 0; len--) {
  38501. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  38502. break;
  38503. }
  38504. }
  38505. return len - 1;
  38506. }
  38507. function getPointAtIndex(points, idx) {
  38508. return [points[idx * 2], points[idx * 2 + 1]];
  38509. }
  38510. function getIndexRange(points, xOrY, dim) {
  38511. var len = points.length / 2;
  38512. var dimIdx = dim === 'x' ? 0 : 1;
  38513. var a;
  38514. var b;
  38515. var prevIndex = 0;
  38516. var nextIndex = -1;
  38517. for (var i = 0; i < len; i++) {
  38518. b = points[i * 2 + dimIdx];
  38519. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  38520. continue;
  38521. }
  38522. if (i === 0) {
  38523. a = b;
  38524. continue;
  38525. }
  38526. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  38527. nextIndex = i;
  38528. break;
  38529. }
  38530. prevIndex = i;
  38531. a = b;
  38532. }
  38533. return {
  38534. range: [prevIndex, nextIndex],
  38535. t: (xOrY - a) / (b - a)
  38536. };
  38537. }
  38538. function anyStateShowEndLabel(seriesModel) {
  38539. if (seriesModel.get(['endLabel', 'show'])) {
  38540. return true;
  38541. }
  38542. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  38543. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  38544. return true;
  38545. }
  38546. }
  38547. return false;
  38548. }
  38549. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  38550. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  38551. var endLabelModel_1 = seriesModel.getModel('endLabel');
  38552. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  38553. var data_1 = seriesModel.getData();
  38554. var labelAnimationRecord_1 = {
  38555. lastFrameIndex: 0
  38556. };
  38557. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  38558. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  38559. } : null;
  38560. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  38561. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  38562. var endLabel = lineView._endLabel;
  38563. if (endLabel && hasAnimation) {
  38564. if (labelAnimationRecord_1.originalX != null) {
  38565. endLabel.attr({
  38566. x: labelAnimationRecord_1.originalX,
  38567. y: labelAnimationRecord_1.originalY
  38568. });
  38569. }
  38570. }
  38571. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  38572. if (!seriesModel.get('clip', true)) {
  38573. var rectShape = clipPath.shape;
  38574. var expandSize = Math.max(rectShape.width, rectShape.height);
  38575. if (isHorizontal) {
  38576. rectShape.y -= expandSize;
  38577. rectShape.height += expandSize * 2;
  38578. } else {
  38579. rectShape.x -= expandSize;
  38580. rectShape.width += expandSize * 2;
  38581. }
  38582. } // Set to the final frame. To make sure label layout is right.
  38583. if (during) {
  38584. during(1, clipPath);
  38585. }
  38586. return clipPath;
  38587. } else {
  38588. if ("development" !== 'production') {
  38589. if (seriesModel.get(['endLabel', 'show'])) {
  38590. console.warn('endLabel is not supported for lines in polar systems.');
  38591. }
  38592. }
  38593. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  38594. }
  38595. }
  38596. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  38597. var baseAxis = coordSys.getBaseAxis();
  38598. var isHorizontal = baseAxis.isHorizontal();
  38599. var isBaseInversed = baseAxis.inverse;
  38600. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  38601. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  38602. return {
  38603. normal: {
  38604. align: endLabelModel.get('align') || align,
  38605. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  38606. }
  38607. };
  38608. }
  38609. var LineView =
  38610. /** @class */
  38611. function (_super) {
  38612. __extends(LineView, _super);
  38613. function LineView() {
  38614. return _super !== null && _super.apply(this, arguments) || this;
  38615. }
  38616. LineView.prototype.init = function () {
  38617. var lineGroup = new Group();
  38618. var symbolDraw = new SymbolDraw();
  38619. this.group.add(symbolDraw.group);
  38620. this._symbolDraw = symbolDraw;
  38621. this._lineGroup = lineGroup;
  38622. };
  38623. LineView.prototype.render = function (seriesModel, ecModel, api) {
  38624. var _this = this;
  38625. var coordSys = seriesModel.coordinateSystem;
  38626. var group = this.group;
  38627. var data = seriesModel.getData();
  38628. var lineStyleModel = seriesModel.getModel('lineStyle');
  38629. var areaStyleModel = seriesModel.getModel('areaStyle');
  38630. var points = data.getLayout('points') || [];
  38631. var isCoordSysPolar = coordSys.type === 'polar';
  38632. var prevCoordSys = this._coordSys;
  38633. var symbolDraw = this._symbolDraw;
  38634. var polyline = this._polyline;
  38635. var polygon = this._polygon;
  38636. var lineGroup = this._lineGroup;
  38637. var hasAnimation = seriesModel.get('animation');
  38638. var isAreaChart = !areaStyleModel.isEmpty();
  38639. var valueOrigin = areaStyleModel.get('origin');
  38640. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  38641. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  38642. var showSymbol = seriesModel.get('showSymbol');
  38643. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  38644. var oldData = this._data;
  38645. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38646. if (el.__temp) {
  38647. group.remove(el);
  38648. oldData.setItemGraphicEl(idx, null);
  38649. }
  38650. }); // Remove previous created symbols if showSymbol changed to false
  38651. if (!showSymbol) {
  38652. symbolDraw.remove();
  38653. }
  38654. group.add(lineGroup); // FIXME step not support polar
  38655. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  38656. var clipShapeForSymbol;
  38657. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  38658. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  38659. // See #7913 and `test/dataZoom-clip.html`.
  38660. if (clipShapeForSymbol.width != null) {
  38661. clipShapeForSymbol.x -= 0.1;
  38662. clipShapeForSymbol.y -= 0.1;
  38663. clipShapeForSymbol.width += 0.2;
  38664. clipShapeForSymbol.height += 0.2;
  38665. } else if (clipShapeForSymbol.r0) {
  38666. clipShapeForSymbol.r0 -= 0.5;
  38667. clipShapeForSymbol.r += 0.5;
  38668. }
  38669. }
  38670. this._clipShapeForSymbol = clipShapeForSymbol;
  38671. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  38672. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  38673. showSymbol && symbolDraw.updateData(data, {
  38674. isIgnore: isIgnoreFunc,
  38675. clipShape: clipShapeForSymbol,
  38676. disableAnimation: true,
  38677. getSymbolPoint: function (idx) {
  38678. return [points[idx * 2], points[idx * 2 + 1]];
  38679. }
  38680. });
  38681. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  38682. if (step) {
  38683. // TODO If stacked series is not step
  38684. points = turnPointsIntoStep(points, coordSys, step);
  38685. if (stackedOnPoints) {
  38686. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  38687. }
  38688. }
  38689. polyline = this._newPolyline(points);
  38690. if (isAreaChart) {
  38691. polygon = this._newPolygon(points, stackedOnPoints);
  38692. } // NOTE: Must update _endLabel before setClipPath.
  38693. if (!isCoordSysPolar) {
  38694. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38695. }
  38696. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38697. } else {
  38698. if (isAreaChart && !polygon) {
  38699. // If areaStyle is added
  38700. polygon = this._newPolygon(points, stackedOnPoints);
  38701. } else if (polygon && !isAreaChart) {
  38702. // If areaStyle is removed
  38703. lineGroup.remove(polygon);
  38704. polygon = this._polygon = null;
  38705. } // NOTE: Must update _endLabel before setClipPath.
  38706. if (!isCoordSysPolar) {
  38707. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38708. } // Update clipPath
  38709. lineGroup.setClipPath(createLineClipPath(this, coordSys, false, seriesModel)); // Always update, or it is wrong in the case turning on legend
  38710. // because points are not changed
  38711. showSymbol && symbolDraw.updateData(data, {
  38712. isIgnore: isIgnoreFunc,
  38713. clipShape: clipShapeForSymbol,
  38714. disableAnimation: true,
  38715. getSymbolPoint: function (idx) {
  38716. return [points[idx * 2], points[idx * 2 + 1]];
  38717. }
  38718. }); // In the case data zoom triggerred refreshing frequently
  38719. // Data may not change if line has a category axis. So it should animate nothing
  38720. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  38721. if (hasAnimation) {
  38722. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin);
  38723. } else {
  38724. // Not do it in update with animation
  38725. if (step) {
  38726. // TODO If stacked series is not step
  38727. points = turnPointsIntoStep(points, coordSys, step);
  38728. if (stackedOnPoints) {
  38729. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  38730. }
  38731. }
  38732. polyline.setShape({
  38733. points: points
  38734. });
  38735. polygon && polygon.setShape({
  38736. points: points,
  38737. stackedOnPoints: stackedOnPoints
  38738. });
  38739. }
  38740. }
  38741. }
  38742. var focus = seriesModel.get(['emphasis', 'focus']);
  38743. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  38744. polyline.useStyle(defaults( // Use color in lineStyle first
  38745. lineStyleModel.getLineStyle(), {
  38746. fill: 'none',
  38747. stroke: visualColor,
  38748. lineJoin: 'bevel'
  38749. }));
  38750. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  38751. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  38752. var emphasisLineStyle = polyline.getState('emphasis').style;
  38753. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  38754. } // Needs seriesIndex for focus
  38755. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  38756. enableHoverEmphasis(polyline, focus, blurScope);
  38757. var smooth = getSmooth(seriesModel.get('smooth'));
  38758. var smoothMonotone = seriesModel.get('smoothMonotone');
  38759. var connectNulls = seriesModel.get('connectNulls');
  38760. polyline.setShape({
  38761. smooth: smooth,
  38762. smoothMonotone: smoothMonotone,
  38763. connectNulls: connectNulls
  38764. });
  38765. if (polygon) {
  38766. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  38767. var stackedOnSmooth = 0;
  38768. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  38769. fill: visualColor,
  38770. opacity: 0.7,
  38771. lineJoin: 'bevel',
  38772. decal: data.getVisual('style').decal
  38773. }));
  38774. if (stackedOnSeries) {
  38775. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  38776. }
  38777. polygon.setShape({
  38778. smooth: smooth,
  38779. stackedOnSmooth: stackedOnSmooth,
  38780. smoothMonotone: smoothMonotone,
  38781. connectNulls: connectNulls
  38782. });
  38783. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  38784. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  38785. enableHoverEmphasis(polygon, focus, blurScope);
  38786. }
  38787. var changePolyState = function (toState) {
  38788. _this._changePolyState(toState);
  38789. };
  38790. data.eachItemGraphicEl(function (el) {
  38791. // Switch polyline / polygon state if element changed its state.
  38792. el && (el.onHoverStateChange = changePolyState);
  38793. });
  38794. this._polyline.onHoverStateChange = changePolyState;
  38795. this._data = data; // Save the coordinate system for transition animation when data changed
  38796. this._coordSys = coordSys;
  38797. this._stackedOnPoints = stackedOnPoints;
  38798. this._points = points;
  38799. this._step = step;
  38800. this._valueOrigin = valueOrigin;
  38801. };
  38802. LineView.prototype.dispose = function () {};
  38803. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  38804. var data = seriesModel.getData();
  38805. var dataIndex = queryDataIndex(data, payload);
  38806. this._changePolyState('emphasis');
  38807. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  38808. var points = data.getLayout('points');
  38809. var symbol = data.getItemGraphicEl(dataIndex);
  38810. if (!symbol) {
  38811. // Create a temporary symbol if it is not exists
  38812. var x = points[dataIndex * 2];
  38813. var y = points[dataIndex * 2 + 1];
  38814. if (isNaN(x) || isNaN(y)) {
  38815. // Null data
  38816. return;
  38817. } // fix #11360: should't draw symbol outside clipShapeForSymbol
  38818. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  38819. return;
  38820. }
  38821. var zlevel = seriesModel.get('zlevel');
  38822. var z = seriesModel.get('z');
  38823. symbol = new Symbol(data, dataIndex);
  38824. symbol.x = x;
  38825. symbol.y = y;
  38826. symbol.setZ(zlevel, z); // ensure label text of the temporary symbol is in front of line and area polygon
  38827. var symbolLabel = symbol.getSymbolPath().getTextContent();
  38828. if (symbolLabel) {
  38829. symbolLabel.zlevel = zlevel;
  38830. symbolLabel.z = z;
  38831. symbolLabel.z2 = this._polyline.z2 + 1;
  38832. }
  38833. symbol.__temp = true;
  38834. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  38835. symbol.stopSymbolAnimation(true);
  38836. this.group.add(symbol);
  38837. }
  38838. symbol.highlight();
  38839. } else {
  38840. // Highlight whole series
  38841. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  38842. }
  38843. };
  38844. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  38845. var data = seriesModel.getData();
  38846. var dataIndex = queryDataIndex(data, payload);
  38847. this._changePolyState('normal');
  38848. if (dataIndex != null && dataIndex >= 0) {
  38849. var symbol = data.getItemGraphicEl(dataIndex);
  38850. if (symbol) {
  38851. if (symbol.__temp) {
  38852. data.setItemGraphicEl(dataIndex, null);
  38853. this.group.remove(symbol);
  38854. } else {
  38855. symbol.downplay();
  38856. }
  38857. }
  38858. } else {
  38859. // FIXME
  38860. // can not downplay completely.
  38861. // Downplay whole series
  38862. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  38863. }
  38864. };
  38865. LineView.prototype._changePolyState = function (toState) {
  38866. var polygon = this._polygon;
  38867. setStatesFlag(this._polyline, toState);
  38868. polygon && setStatesFlag(polygon, toState);
  38869. };
  38870. LineView.prototype._newPolyline = function (points) {
  38871. var polyline = this._polyline; // Remove previous created polyline
  38872. if (polyline) {
  38873. this._lineGroup.remove(polyline);
  38874. }
  38875. polyline = new ECPolyline({
  38876. shape: {
  38877. points: points
  38878. },
  38879. segmentIgnoreThreshold: 2,
  38880. z2: 10
  38881. });
  38882. this._lineGroup.add(polyline);
  38883. this._polyline = polyline;
  38884. return polyline;
  38885. };
  38886. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  38887. var polygon = this._polygon; // Remove previous created polygon
  38888. if (polygon) {
  38889. this._lineGroup.remove(polygon);
  38890. }
  38891. polygon = new ECPolygon({
  38892. shape: {
  38893. points: points,
  38894. stackedOnPoints: stackedOnPoints
  38895. },
  38896. segmentIgnoreThreshold: 2
  38897. });
  38898. this._lineGroup.add(polygon);
  38899. this._polygon = polygon;
  38900. return polygon;
  38901. };
  38902. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  38903. var isHorizontalOrRadial;
  38904. var isCoordSysPolar;
  38905. var baseAxis = coordSys.getBaseAxis();
  38906. var isAxisInverse = baseAxis.inverse;
  38907. if (coordSys.type === 'cartesian2d') {
  38908. isHorizontalOrRadial = baseAxis.isHorizontal();
  38909. isCoordSysPolar = false;
  38910. } else if (coordSys.type === 'polar') {
  38911. isHorizontalOrRadial = baseAxis.dim === 'angle';
  38912. isCoordSysPolar = true;
  38913. }
  38914. var seriesModel = data.hostModel;
  38915. var seriesDuration = seriesModel.get('animationDuration');
  38916. if (typeof seriesDuration === 'function') {
  38917. seriesDuration = seriesDuration(null);
  38918. }
  38919. var seriesDalay = seriesModel.get('animationDelay') || 0;
  38920. var seriesDalayValue = typeof seriesDalay === 'function' ? seriesDalay(null) : seriesDalay;
  38921. data.eachItemGraphicEl(function (symbol, idx) {
  38922. var el = symbol;
  38923. if (el) {
  38924. var point = [symbol.x, symbol.y];
  38925. var start = void 0;
  38926. var end = void 0;
  38927. var current = void 0;
  38928. if (clipShape) {
  38929. if (isCoordSysPolar) {
  38930. var polarClip = clipShape;
  38931. var coord = coordSys.pointToCoord(point);
  38932. if (isHorizontalOrRadial) {
  38933. start = polarClip.startAngle;
  38934. end = polarClip.endAngle;
  38935. current = -coord[1] / 180 * Math.PI;
  38936. } else {
  38937. start = polarClip.r0;
  38938. end = polarClip.r;
  38939. current = coord[0];
  38940. }
  38941. } else {
  38942. var gridClip = clipShape;
  38943. if (isHorizontalOrRadial) {
  38944. start = gridClip.x;
  38945. end = gridClip.x + gridClip.width;
  38946. current = symbol.x;
  38947. } else {
  38948. start = gridClip.y + gridClip.height;
  38949. end = gridClip.y;
  38950. current = symbol.y;
  38951. }
  38952. }
  38953. }
  38954. var ratio = end === start ? 0 : (current - start) / (end - start);
  38955. if (isAxisInverse) {
  38956. ratio = 1 - ratio;
  38957. }
  38958. var delay = typeof seriesDalay === 'function' ? seriesDalay(idx) : seriesDuration * ratio + seriesDalayValue;
  38959. var symbolPath = el.getSymbolPath();
  38960. var text = symbolPath.getTextContent();
  38961. el.attr({
  38962. scaleX: 0,
  38963. scaleY: 0
  38964. });
  38965. el.animateTo({
  38966. scaleX: 1,
  38967. scaleY: 1
  38968. }, {
  38969. duration: 200,
  38970. setToFinal: true,
  38971. delay: delay
  38972. });
  38973. if (text) {
  38974. text.animateFrom({
  38975. style: {
  38976. opacity: 0
  38977. }
  38978. }, {
  38979. duration: 300,
  38980. delay: delay
  38981. });
  38982. }
  38983. symbolPath.disableLabelAnimation = true;
  38984. }
  38985. });
  38986. };
  38987. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  38988. var endLabelModel = seriesModel.getModel('endLabel');
  38989. if (anyStateShowEndLabel(seriesModel)) {
  38990. var data_2 = seriesModel.getData();
  38991. var polyline = this._polyline;
  38992. var endLabel = this._endLabel;
  38993. if (!endLabel) {
  38994. endLabel = this._endLabel = new ZRText({
  38995. z2: 200 // should be higher than item symbol
  38996. });
  38997. endLabel.ignoreClip = true;
  38998. polyline.setTextContent(this._endLabel);
  38999. polyline.disableLabelAnimation = true;
  39000. } // Find last non-NaN data to display data
  39001. var dataIndex = getLastIndexNotNull(data_2.getLayout('points'));
  39002. if (dataIndex >= 0) {
  39003. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  39004. inheritColor: inheritColor,
  39005. labelFetcher: seriesModel,
  39006. labelDataIndex: dataIndex,
  39007. defaultText: function (dataIndex, opt, interpolatedValue) {
  39008. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  39009. },
  39010. enableTextSetter: true
  39011. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  39012. polyline.textConfig.position = null;
  39013. }
  39014. } else if (this._endLabel) {
  39015. this._polyline.removeTextContent();
  39016. this._endLabel = null;
  39017. }
  39018. };
  39019. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  39020. var endLabel = this._endLabel;
  39021. var polyline = this._polyline;
  39022. if (endLabel) {
  39023. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  39024. // The label is not prepared at this time.
  39025. if (percent < 1 && animationRecord.originalX == null) {
  39026. animationRecord.originalX = endLabel.x;
  39027. animationRecord.originalY = endLabel.y;
  39028. }
  39029. var points = data.getLayout('points');
  39030. var seriesModel = data.hostModel;
  39031. var connectNulls = seriesModel.get('connectNulls');
  39032. var precision = endLabelModel.get('precision');
  39033. var distance = endLabelModel.get('distance') || 0;
  39034. var baseAxis = coordSys.getBaseAxis();
  39035. var isHorizontal = baseAxis.isHorizontal();
  39036. var isBaseInversed = baseAxis.inverse;
  39037. var clipShape = clipRect.shape;
  39038. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  39039. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  39040. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  39041. var dim = isHorizontal ? 'x' : 'y';
  39042. var dataIndexRange = getIndexRange(points, xOrY, dim);
  39043. var indices = dataIndexRange.range;
  39044. var diff = indices[1] - indices[0];
  39045. var value = void 0;
  39046. if (diff >= 1) {
  39047. // diff > 1 && connectNulls, which is on the null data.
  39048. if (diff > 1 && !connectNulls) {
  39049. var pt = getPointAtIndex(points, indices[0]);
  39050. endLabel.attr({
  39051. x: pt[0] + distanceX,
  39052. y: pt[1] + distanceY
  39053. });
  39054. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  39055. } else {
  39056. var pt = polyline.getPointOn(xOrY, dim);
  39057. pt && endLabel.attr({
  39058. x: pt[0] + distanceX,
  39059. y: pt[1] + distanceY
  39060. });
  39061. var startValue = seriesModel.getRawValue(indices[0]);
  39062. var endValue = seriesModel.getRawValue(indices[1]);
  39063. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  39064. }
  39065. animationRecord.lastFrameIndex = indices[0];
  39066. } else {
  39067. // If diff <= 0, which is the range is not found(Include NaN)
  39068. // Choose the first point or last point.
  39069. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  39070. var pt = getPointAtIndex(points, idx);
  39071. valueAnimation && (value = seriesModel.getRawValue(idx));
  39072. endLabel.attr({
  39073. x: pt[0] + distanceX,
  39074. y: pt[1] + distanceY
  39075. });
  39076. }
  39077. if (valueAnimation) {
  39078. labelInner(endLabel).setLabelText(value);
  39079. }
  39080. }
  39081. };
  39082. /**
  39083. * @private
  39084. */
  39085. // FIXME Two value axis
  39086. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  39087. var polyline = this._polyline;
  39088. var polygon = this._polygon;
  39089. var seriesModel = data.hostModel;
  39090. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  39091. var current = diff.current;
  39092. var stackedOnCurrent = diff.stackedOnCurrent;
  39093. var next = diff.next;
  39094. var stackedOnNext = diff.stackedOnNext;
  39095. if (step) {
  39096. // TODO If stacked series is not step
  39097. current = turnPointsIntoStep(diff.current, coordSys, step);
  39098. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  39099. next = turnPointsIntoStep(diff.next, coordSys, step);
  39100. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  39101. } // Don't apply animation if diff is large.
  39102. // For better result and avoid memory explosion problems like
  39103. // https://github.com/apache/incubator-echarts/issues/12229
  39104. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  39105. polyline.setShape({
  39106. points: next
  39107. });
  39108. if (polygon) {
  39109. polygon.setShape({
  39110. points: next,
  39111. stackedOnPoints: stackedOnNext
  39112. });
  39113. }
  39114. return;
  39115. }
  39116. polyline.shape.__points = diff.current;
  39117. polyline.shape.points = current;
  39118. var target = {
  39119. shape: {
  39120. points: next
  39121. }
  39122. }; // Also animate the original points.
  39123. // If points reference is changed when turning into step line.
  39124. if (diff.current !== current) {
  39125. target.shape.__points = diff.next;
  39126. } // Stop previous animation.
  39127. polyline.stopAnimation();
  39128. updateProps(polyline, target, seriesModel);
  39129. if (polygon) {
  39130. polygon.setShape({
  39131. // Reuse the points with polyline.
  39132. points: current,
  39133. stackedOnPoints: stackedOnCurrent
  39134. });
  39135. polygon.stopAnimation();
  39136. updateProps(polygon, {
  39137. shape: {
  39138. stackedOnPoints: stackedOnNext
  39139. }
  39140. }, seriesModel); // If use attr directly in updateProps.
  39141. if (polyline.shape.points !== polygon.shape.points) {
  39142. polygon.shape.points = polyline.shape.points;
  39143. }
  39144. }
  39145. var updatedDataInfo = [];
  39146. var diffStatus = diff.status;
  39147. for (var i = 0; i < diffStatus.length; i++) {
  39148. var cmd = diffStatus[i].cmd;
  39149. if (cmd === '=') {
  39150. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  39151. if (el) {
  39152. updatedDataInfo.push({
  39153. el: el,
  39154. ptIdx: i // Index of points
  39155. });
  39156. }
  39157. }
  39158. }
  39159. if (polyline.animators && polyline.animators.length) {
  39160. polyline.animators[0].during(function () {
  39161. polygon && polygon.dirtyShape();
  39162. var points = polyline.shape.__points;
  39163. for (var i = 0; i < updatedDataInfo.length; i++) {
  39164. var el = updatedDataInfo[i].el;
  39165. var offset = updatedDataInfo[i].ptIdx * 2;
  39166. el.x = points[offset];
  39167. el.y = points[offset + 1];
  39168. el.markRedraw();
  39169. }
  39170. });
  39171. }
  39172. };
  39173. LineView.prototype.remove = function (ecModel) {
  39174. var group = this.group;
  39175. var oldData = this._data;
  39176. this._lineGroup.removeAll();
  39177. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  39178. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  39179. if (el.__temp) {
  39180. group.remove(el);
  39181. oldData.setItemGraphicEl(idx, null);
  39182. }
  39183. });
  39184. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  39185. };
  39186. LineView.type = 'line';
  39187. return LineView;
  39188. }(ChartView);
  39189. function pointsLayout(seriesType, forceStoreInTypedArray) {
  39190. return {
  39191. seriesType: seriesType,
  39192. plan: createRenderPlanner(),
  39193. reset: function (seriesModel) {
  39194. var data = seriesModel.getData();
  39195. var coordSys = seriesModel.coordinateSystem;
  39196. var pipelineContext = seriesModel.pipelineContext;
  39197. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  39198. if (!coordSys) {
  39199. return;
  39200. }
  39201. var dims = map(coordSys.dimensions, function (dim) {
  39202. return data.mapDimension(dim);
  39203. }).slice(0, 2);
  39204. var dimLen = dims.length;
  39205. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  39206. if (isDimensionStacked(data, dims[0]
  39207. /*, dims[1]*/
  39208. )) {
  39209. dims[0] = stackResultDim;
  39210. }
  39211. if (isDimensionStacked(data, dims[1]
  39212. /*, dims[0]*/
  39213. )) {
  39214. dims[1] = stackResultDim;
  39215. }
  39216. var store = data.getStore();
  39217. var dimIdx0 = data.getDimensionIndex(dims[0]);
  39218. var dimIdx1 = data.getDimensionIndex(dims[1]);
  39219. return dimLen && {
  39220. progress: function (params, data) {
  39221. var segCount = params.end - params.start;
  39222. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  39223. var tmpIn = [];
  39224. var tmpOut = [];
  39225. for (var i = params.start, offset = 0; i < params.end; i++) {
  39226. var point = void 0;
  39227. if (dimLen === 1) {
  39228. var x = store.get(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  39229. point = coordSys.dataToPoint(x, null, tmpOut);
  39230. } else {
  39231. tmpIn[0] = store.get(dimIdx0, i);
  39232. tmpIn[1] = store.get(dimIdx1, i); // Let coordinate system to handle the NaN data.
  39233. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  39234. }
  39235. if (useTypedArray) {
  39236. points[offset++] = point[0];
  39237. points[offset++] = point[1];
  39238. } else {
  39239. data.setItemLayout(i, point.slice());
  39240. }
  39241. }
  39242. useTypedArray && data.setLayout('points', points);
  39243. }
  39244. };
  39245. }
  39246. };
  39247. }
  39248. /*
  39249. * Licensed to the Apache Software Foundation (ASF) under one
  39250. * or more contributor license agreements. See the NOTICE file
  39251. * distributed with this work for additional information
  39252. * regarding copyright ownership. The ASF licenses this file
  39253. * to you under the Apache License, Version 2.0 (the
  39254. * "License"); you may not use this file except in compliance
  39255. * with the License. You may obtain a copy of the License at
  39256. *
  39257. * http://www.apache.org/licenses/LICENSE-2.0
  39258. *
  39259. * Unless required by applicable law or agreed to in writing,
  39260. * software distributed under the License is distributed on an
  39261. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39262. * KIND, either express or implied. See the License for the
  39263. * specific language governing permissions and limitations
  39264. * under the License.
  39265. */
  39266. /**
  39267. * AUTO-GENERATED FILE. DO NOT MODIFY.
  39268. */
  39269. /*
  39270. * Licensed to the Apache Software Foundation (ASF) under one
  39271. * or more contributor license agreements. See the NOTICE file
  39272. * distributed with this work for additional information
  39273. * regarding copyright ownership. The ASF licenses this file
  39274. * to you under the Apache License, Version 2.0 (the
  39275. * "License"); you may not use this file except in compliance
  39276. * with the License. You may obtain a copy of the License at
  39277. *
  39278. * http://www.apache.org/licenses/LICENSE-2.0
  39279. *
  39280. * Unless required by applicable law or agreed to in writing,
  39281. * software distributed under the License is distributed on an
  39282. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39283. * KIND, either express or implied. See the License for the
  39284. * specific language governing permissions and limitations
  39285. * under the License.
  39286. */
  39287. var samplers = {
  39288. average: function (frame) {
  39289. var sum = 0;
  39290. var count = 0;
  39291. for (var i = 0; i < frame.length; i++) {
  39292. if (!isNaN(frame[i])) {
  39293. sum += frame[i];
  39294. count++;
  39295. }
  39296. } // Return NaN if count is 0
  39297. return count === 0 ? NaN : sum / count;
  39298. },
  39299. sum: function (frame) {
  39300. var sum = 0;
  39301. for (var i = 0; i < frame.length; i++) {
  39302. // Ignore NaN
  39303. sum += frame[i] || 0;
  39304. }
  39305. return sum;
  39306. },
  39307. max: function (frame) {
  39308. var max = -Infinity;
  39309. for (var i = 0; i < frame.length; i++) {
  39310. frame[i] > max && (max = frame[i]);
  39311. } // NaN will cause illegal axis extent.
  39312. return isFinite(max) ? max : NaN;
  39313. },
  39314. min: function (frame) {
  39315. var min = Infinity;
  39316. for (var i = 0; i < frame.length; i++) {
  39317. frame[i] < min && (min = frame[i]);
  39318. } // NaN will cause illegal axis extent.
  39319. return isFinite(min) ? min : NaN;
  39320. },
  39321. // TODO
  39322. // Median
  39323. nearest: function (frame) {
  39324. return frame[0];
  39325. }
  39326. };
  39327. var indexSampler = function (frame) {
  39328. return Math.round(frame.length / 2);
  39329. };
  39330. function dataSample(seriesType) {
  39331. return {
  39332. seriesType: seriesType,
  39333. // FIXME:TS never used, so comment it
  39334. // modifyOutputEnd: true,
  39335. reset: function (seriesModel, ecModel, api) {
  39336. var data = seriesModel.getData();
  39337. var sampling = seriesModel.get('sampling');
  39338. var coordSys = seriesModel.coordinateSystem;
  39339. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  39340. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  39341. var baseAxis = coordSys.getBaseAxis();
  39342. var valueAxis = coordSys.getOtherAxis(baseAxis);
  39343. var extent = baseAxis.getExtent();
  39344. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  39345. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  39346. var rate = Math.round(count / size);
  39347. if (rate > 1) {
  39348. if (sampling === 'lttb') {
  39349. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  39350. }
  39351. var sampler = void 0;
  39352. if (typeof sampling === 'string') {
  39353. sampler = samplers[sampling];
  39354. } else if (typeof sampling === 'function') {
  39355. sampler = sampling;
  39356. }
  39357. if (sampler) {
  39358. // Only support sample the first dim mapped from value axis.
  39359. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  39360. }
  39361. }
  39362. }
  39363. }
  39364. };
  39365. }
  39366. function install$2(registers) {
  39367. registers.registerChartView(LineView);
  39368. registers.registerSeriesModel(LineSeriesModel);
  39369. registers.registerLayout(pointsLayout('line', true));
  39370. registers.registerVisual({
  39371. seriesType: 'line',
  39372. reset: function (seriesModel) {
  39373. var data = seriesModel.getData(); // Visual coding for legend
  39374. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  39375. if (lineStyle && !lineStyle.stroke) {
  39376. // Fill in visual should be palette color if
  39377. // has color callback
  39378. lineStyle.stroke = data.getVisual('style').fill;
  39379. }
  39380. data.setVisual('legendLineStyle', lineStyle);
  39381. }
  39382. }); // Down sample after filter
  39383. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  39384. }
  39385. var BaseBarSeriesModel =
  39386. /** @class */
  39387. function (_super) {
  39388. __extends(BaseBarSeriesModel, _super);
  39389. function BaseBarSeriesModel() {
  39390. var _this = _super !== null && _super.apply(this, arguments) || this;
  39391. _this.type = BaseBarSeriesModel.type;
  39392. return _this;
  39393. }
  39394. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  39395. return createSeriesData(null, this, {
  39396. useEncodeDefaulter: true
  39397. });
  39398. };
  39399. BaseBarSeriesModel.prototype.getMarkerPosition = function (value) {
  39400. var coordSys = this.coordinateSystem;
  39401. if (coordSys && coordSys.clampData) {
  39402. // PENDING if clamp ?
  39403. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  39404. var data = this.getData();
  39405. var offset = data.getLayout('offset');
  39406. var size = data.getLayout('size');
  39407. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  39408. pt[offsetIndex] += offset + size / 2;
  39409. return pt;
  39410. }
  39411. return [NaN, NaN];
  39412. };
  39413. BaseBarSeriesModel.type = 'series.__base_bar__';
  39414. BaseBarSeriesModel.defaultOption = {
  39415. zlevel: 0,
  39416. z: 2,
  39417. coordinateSystem: 'cartesian2d',
  39418. legendHoverLink: true,
  39419. // stack: null
  39420. // Cartesian coordinate system
  39421. // xAxisIndex: 0,
  39422. // yAxisIndex: 0,
  39423. barMinHeight: 0,
  39424. barMinAngle: 0,
  39425. // cursor: null,
  39426. large: false,
  39427. largeThreshold: 400,
  39428. progressive: 3e3,
  39429. progressiveChunkMode: 'mod'
  39430. };
  39431. return BaseBarSeriesModel;
  39432. }(SeriesModel);
  39433. SeriesModel.registerClass(BaseBarSeriesModel);
  39434. var BarSeriesModel =
  39435. /** @class */
  39436. function (_super) {
  39437. __extends(BarSeriesModel, _super);
  39438. function BarSeriesModel() {
  39439. var _this = _super !== null && _super.apply(this, arguments) || this;
  39440. _this.type = BarSeriesModel.type;
  39441. return _this;
  39442. }
  39443. BarSeriesModel.prototype.getInitialData = function () {
  39444. return createSeriesData(null, this, {
  39445. useEncodeDefaulter: true,
  39446. createInvertedIndices: !!this.get('realtimeSort', true) || null
  39447. });
  39448. };
  39449. /**
  39450. * @override
  39451. */
  39452. BarSeriesModel.prototype.getProgressive = function () {
  39453. // Do not support progressive in normal mode.
  39454. return this.get('large') ? this.get('progressive') : false;
  39455. };
  39456. /**
  39457. * @override
  39458. */
  39459. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  39460. // Do not support progressive in normal mode.
  39461. var progressiveThreshold = this.get('progressiveThreshold');
  39462. var largeThreshold = this.get('largeThreshold');
  39463. if (largeThreshold > progressiveThreshold) {
  39464. progressiveThreshold = largeThreshold;
  39465. }
  39466. return progressiveThreshold;
  39467. };
  39468. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  39469. return selectors.rect(data.getItemLayout(dataIndex));
  39470. };
  39471. BarSeriesModel.type = 'series.bar';
  39472. BarSeriesModel.dependencies = ['grid', 'polar'];
  39473. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  39474. // If clipped
  39475. // Only available on cartesian2d
  39476. clip: true,
  39477. roundCap: false,
  39478. showBackground: false,
  39479. backgroundStyle: {
  39480. color: 'rgba(180, 180, 180, 0.2)',
  39481. borderColor: null,
  39482. borderWidth: 0,
  39483. borderType: 'solid',
  39484. borderRadius: 0,
  39485. shadowBlur: 0,
  39486. shadowColor: null,
  39487. shadowOffsetX: 0,
  39488. shadowOffsetY: 0,
  39489. opacity: 1
  39490. },
  39491. select: {
  39492. itemStyle: {
  39493. borderColor: '#212121'
  39494. }
  39495. },
  39496. realtimeSort: false
  39497. });
  39498. return BarSeriesModel;
  39499. }(BaseBarSeriesModel);
  39500. /**
  39501. * Sausage: similar to sector, but have half circle on both sides
  39502. */
  39503. var SausageShape =
  39504. /** @class */
  39505. function () {
  39506. function SausageShape() {
  39507. this.cx = 0;
  39508. this.cy = 0;
  39509. this.r0 = 0;
  39510. this.r = 0;
  39511. this.startAngle = 0;
  39512. this.endAngle = Math.PI * 2;
  39513. this.clockwise = true;
  39514. }
  39515. return SausageShape;
  39516. }();
  39517. var SausagePath =
  39518. /** @class */
  39519. function (_super) {
  39520. __extends(SausagePath, _super);
  39521. function SausagePath(opts) {
  39522. var _this = _super.call(this, opts) || this;
  39523. _this.type = 'sausage';
  39524. return _this;
  39525. }
  39526. SausagePath.prototype.getDefaultShape = function () {
  39527. return new SausageShape();
  39528. };
  39529. SausagePath.prototype.buildPath = function (ctx, shape) {
  39530. var x = shape.cx;
  39531. var y = shape.cy;
  39532. var r0 = Math.max(shape.r0 || 0, 0);
  39533. var r = Math.max(shape.r, 0);
  39534. var dr = (r - r0) * 0.5;
  39535. var rCenter = r0 + dr;
  39536. var startAngle = shape.startAngle;
  39537. var endAngle = shape.endAngle;
  39538. var clockwise = shape.clockwise;
  39539. var unitStartX = Math.cos(startAngle);
  39540. var unitStartY = Math.sin(startAngle);
  39541. var unitEndX = Math.cos(endAngle);
  39542. var unitEndY = Math.sin(endAngle);
  39543. var lessThanCircle = clockwise ? endAngle - startAngle < Math.PI * 2 : startAngle - endAngle < Math.PI * 2;
  39544. if (lessThanCircle) {
  39545. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  39546. ctx.arc(unitStartX * rCenter + x, unitStartY * rCenter + y, dr, -Math.PI + startAngle, startAngle, !clockwise);
  39547. }
  39548. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  39549. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  39550. ctx.arc(unitEndX * rCenter + x, unitEndY * rCenter + y, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  39551. if (r0 !== 0) {
  39552. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  39553. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  39554. }
  39555. ctx.closePath();
  39556. };
  39557. return SausagePath;
  39558. }(Path);
  39559. function createSectorCalculateTextPosition(positionMapping, opts) {
  39560. opts = opts || {};
  39561. var isRoundCap = opts.isRoundCap;
  39562. return function (out, opts, boundingRect) {
  39563. var textPosition = opts.position;
  39564. if (!textPosition || textPosition instanceof Array) {
  39565. return calculateTextPosition(out, opts, boundingRect);
  39566. }
  39567. var mappedSectorPosition = positionMapping(textPosition);
  39568. var distance = opts.distance != null ? opts.distance : 5;
  39569. var sector = this.shape;
  39570. var cx = sector.cx;
  39571. var cy = sector.cy;
  39572. var r = sector.r;
  39573. var r0 = sector.r0;
  39574. var middleR = (r + r0) / 2;
  39575. var startAngle = sector.startAngle;
  39576. var endAngle = sector.endAngle;
  39577. var middleAngle = (startAngle + endAngle) / 2;
  39578. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  39579. var mathCos = Math.cos;
  39580. var mathSin = Math.sin; // base position: top-left
  39581. var x = cx + r * mathCos(startAngle);
  39582. var y = cy + r * mathSin(startAngle);
  39583. var textAlign = 'left';
  39584. var textVerticalAlign = 'top';
  39585. switch (mappedSectorPosition) {
  39586. case 'startArc':
  39587. x = cx + (r0 - distance) * mathCos(middleAngle);
  39588. y = cy + (r0 - distance) * mathSin(middleAngle);
  39589. textAlign = 'center';
  39590. textVerticalAlign = 'top';
  39591. break;
  39592. case 'insideStartArc':
  39593. x = cx + (r0 + distance) * mathCos(middleAngle);
  39594. y = cy + (r0 + distance) * mathSin(middleAngle);
  39595. textAlign = 'center';
  39596. textVerticalAlign = 'bottom';
  39597. break;
  39598. case 'startAngle':
  39599. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  39600. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  39601. textAlign = 'right';
  39602. textVerticalAlign = 'middle';
  39603. break;
  39604. case 'insideStartAngle':
  39605. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  39606. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  39607. textAlign = 'left';
  39608. textVerticalAlign = 'middle';
  39609. break;
  39610. case 'middle':
  39611. x = cx + middleR * mathCos(middleAngle);
  39612. y = cy + middleR * mathSin(middleAngle);
  39613. textAlign = 'center';
  39614. textVerticalAlign = 'middle';
  39615. break;
  39616. case 'endArc':
  39617. x = cx + (r + distance) * mathCos(middleAngle);
  39618. y = cy + (r + distance) * mathSin(middleAngle);
  39619. textAlign = 'center';
  39620. textVerticalAlign = 'bottom';
  39621. break;
  39622. case 'insideEndArc':
  39623. x = cx + (r - distance) * mathCos(middleAngle);
  39624. y = cy + (r - distance) * mathSin(middleAngle);
  39625. textAlign = 'center';
  39626. textVerticalAlign = 'top';
  39627. break;
  39628. case 'endAngle':
  39629. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  39630. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  39631. textAlign = 'left';
  39632. textVerticalAlign = 'middle';
  39633. break;
  39634. case 'insideEndAngle':
  39635. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  39636. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  39637. textAlign = 'right';
  39638. textVerticalAlign = 'middle';
  39639. break;
  39640. default:
  39641. return calculateTextPosition(out, opts, boundingRect);
  39642. }
  39643. out = out || {};
  39644. out.x = x;
  39645. out.y = y;
  39646. out.align = textAlign;
  39647. out.verticalAlign = textVerticalAlign;
  39648. return out;
  39649. };
  39650. }
  39651. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  39652. if (typeof rotateType === 'number') {
  39653. // user-set rotation
  39654. sector.setTextConfig({
  39655. rotation: rotateType
  39656. });
  39657. return;
  39658. } else if (isArray(textPosition)) {
  39659. // user-set position, use 0 as auto rotation
  39660. sector.setTextConfig({
  39661. rotation: 0
  39662. });
  39663. return;
  39664. }
  39665. var shape = sector.shape;
  39666. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  39667. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  39668. var middleAngle = (startAngle + endAngle) / 2;
  39669. var anchorAngle;
  39670. var mappedSectorPosition = positionMapping(textPosition);
  39671. switch (mappedSectorPosition) {
  39672. case 'startArc':
  39673. case 'insideStartArc':
  39674. case 'middle':
  39675. case 'insideEndArc':
  39676. case 'endArc':
  39677. anchorAngle = middleAngle;
  39678. break;
  39679. case 'startAngle':
  39680. case 'insideStartAngle':
  39681. anchorAngle = startAngle;
  39682. break;
  39683. case 'endAngle':
  39684. case 'insideEndAngle':
  39685. anchorAngle = endAngle;
  39686. break;
  39687. default:
  39688. sector.setTextConfig({
  39689. rotation: 0
  39690. });
  39691. return;
  39692. }
  39693. var rotate = Math.PI * 1.5 - anchorAngle;
  39694. /**
  39695. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  39696. * half round flipped to increase readability. However, only middle
  39697. * position supports this for now, because in other positions, the
  39698. * anchor point is not at the center of the text, so the positions
  39699. * after rotating is not as expected.
  39700. */
  39701. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  39702. rotate -= Math.PI;
  39703. }
  39704. sector.setTextConfig({
  39705. rotation: rotate
  39706. });
  39707. }
  39708. function adjustAngleDistanceX(angle, distance, isEnd) {
  39709. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  39710. }
  39711. function adjustAngleDistanceY(angle, distance, isEnd) {
  39712. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  39713. }
  39714. var _eventPos = [0, 0];
  39715. var mathMax$6 = Math.max;
  39716. var mathMin$6 = Math.min;
  39717. function getClipArea(coord, data) {
  39718. var coordSysClipArea = coord.getArea && coord.getArea();
  39719. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39720. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  39721. // We should not clip this part.
  39722. // See test/bar2.html
  39723. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  39724. var expandWidth = data.getLayout('bandWidth');
  39725. if (baseAxis.isHorizontal()) {
  39726. coordSysClipArea.x -= expandWidth;
  39727. coordSysClipArea.width += expandWidth * 2;
  39728. } else {
  39729. coordSysClipArea.y -= expandWidth;
  39730. coordSysClipArea.height += expandWidth * 2;
  39731. }
  39732. }
  39733. }
  39734. return coordSysClipArea;
  39735. }
  39736. var BarView =
  39737. /** @class */
  39738. function (_super) {
  39739. __extends(BarView, _super);
  39740. function BarView() {
  39741. var _this = _super.call(this) || this;
  39742. _this.type = BarView.type;
  39743. _this._isFirstFrame = true;
  39744. return _this;
  39745. }
  39746. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  39747. this._model = seriesModel;
  39748. this._removeOnRenderedListener(api);
  39749. this._updateDrawMode(seriesModel);
  39750. var coordinateSystemType = seriesModel.get('coordinateSystem');
  39751. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  39752. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  39753. } else if ("development" !== 'production') {
  39754. warn('Only cartesian2d and polar supported for bar.');
  39755. }
  39756. };
  39757. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  39758. this._clear();
  39759. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  39760. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  39761. this._updateLargeClip(seriesModel);
  39762. };
  39763. BarView.prototype.incrementalRender = function (params, seriesModel) {
  39764. // Do not support progressive in normal mode.
  39765. this._incrementalRenderLarge(params, seriesModel);
  39766. };
  39767. BarView.prototype._updateDrawMode = function (seriesModel) {
  39768. var isLargeDraw = seriesModel.pipelineContext.large;
  39769. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  39770. this._isLargeDraw = isLargeDraw;
  39771. this._clear();
  39772. }
  39773. };
  39774. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  39775. var group = this.group;
  39776. var data = seriesModel.getData();
  39777. var oldData = this._data;
  39778. var coord = seriesModel.coordinateSystem;
  39779. var baseAxis = coord.getBaseAxis();
  39780. var isHorizontalOrRadial;
  39781. if (coord.type === 'cartesian2d') {
  39782. isHorizontalOrRadial = baseAxis.isHorizontal();
  39783. } else if (coord.type === 'polar') {
  39784. isHorizontalOrRadial = baseAxis.dim === 'angle';
  39785. }
  39786. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  39787. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  39788. if (realtimeSortCfg) {
  39789. this._enableRealtimeSort(realtimeSortCfg, data, api);
  39790. }
  39791. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  39792. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  39793. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  39794. // And don't want the label are clipped.
  39795. var roundCap = seriesModel.get('roundCap', true);
  39796. var drawBackground = seriesModel.get('showBackground', true);
  39797. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39798. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  39799. var bgEls = [];
  39800. var oldBgEls = this._backgroundEls;
  39801. var isInitSort = payload && payload.isInitSort;
  39802. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  39803. function createBackground(dataIndex) {
  39804. var bgLayout = getLayout[coord.type](data, dataIndex);
  39805. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  39806. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  39807. if (coord.type === 'cartesian2d') {
  39808. bgEl.setShape('r', barBorderRadius);
  39809. }
  39810. bgEls[dataIndex] = bgEl;
  39811. return bgEl;
  39812. }
  39813. data.diff(oldData).add(function (dataIndex) {
  39814. var itemModel = data.getItemModel(dataIndex);
  39815. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  39816. if (drawBackground) {
  39817. createBackground(dataIndex);
  39818. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  39819. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  39820. return;
  39821. }
  39822. var isClipped = false;
  39823. if (needsClip) {
  39824. // Clip will modify the layout params.
  39825. // And return a boolean to determine if the shape are fully clipped.
  39826. isClipped = clip[coord.type](coordSysClipArea, layout);
  39827. }
  39828. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  39829. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39830. if (isInitSort) {
  39831. el.attr({
  39832. shape: layout
  39833. });
  39834. } else if (realtimeSortCfg) {
  39835. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  39836. } else {
  39837. initProps(el, {
  39838. shape: layout
  39839. }, seriesModel, dataIndex);
  39840. }
  39841. data.setItemGraphicEl(dataIndex, el);
  39842. group.add(el);
  39843. el.ignore = isClipped;
  39844. }).update(function (newIndex, oldIndex) {
  39845. var itemModel = data.getItemModel(newIndex);
  39846. var layout = getLayout[coord.type](data, newIndex, itemModel);
  39847. if (drawBackground) {
  39848. var bgEl = void 0;
  39849. if (oldBgEls.length === 0) {
  39850. bgEl = createBackground(oldIndex);
  39851. } else {
  39852. bgEl = oldBgEls[oldIndex];
  39853. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  39854. if (coord.type === 'cartesian2d') {
  39855. bgEl.setShape('r', barBorderRadius);
  39856. }
  39857. bgEls[newIndex] = bgEl;
  39858. }
  39859. var bgLayout = getLayout[coord.type](data, newIndex);
  39860. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  39861. updateProps(bgEl, {
  39862. shape: shape
  39863. }, animationModel, newIndex);
  39864. }
  39865. var el = oldData.getItemGraphicEl(oldIndex);
  39866. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  39867. group.remove(el);
  39868. return;
  39869. }
  39870. var isClipped = false;
  39871. if (needsClip) {
  39872. isClipped = clip[coord.type](coordSysClipArea, layout);
  39873. if (isClipped) {
  39874. group.remove(el);
  39875. }
  39876. }
  39877. if (!el) {
  39878. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  39879. } else {
  39880. saveOldStyle(el);
  39881. } // Not change anything if only order changed.
  39882. // Especially not change label.
  39883. if (!isChangeOrder) {
  39884. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39885. }
  39886. if (isInitSort) {
  39887. el.attr({
  39888. shape: layout
  39889. });
  39890. } else if (realtimeSortCfg) {
  39891. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  39892. } else {
  39893. updateProps(el, {
  39894. shape: layout
  39895. }, seriesModel, newIndex, null);
  39896. }
  39897. data.setItemGraphicEl(newIndex, el);
  39898. el.ignore = isClipped;
  39899. group.add(el);
  39900. }).remove(function (dataIndex) {
  39901. var el = oldData.getItemGraphicEl(dataIndex);
  39902. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  39903. }).execute();
  39904. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  39905. bgGroup.removeAll();
  39906. for (var i = 0; i < bgEls.length; ++i) {
  39907. bgGroup.add(bgEls[i]);
  39908. }
  39909. group.add(bgGroup);
  39910. this._backgroundEls = bgEls;
  39911. this._data = data;
  39912. };
  39913. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  39914. this._clear();
  39915. createLarge(seriesModel, this.group);
  39916. this._updateLargeClip(seriesModel);
  39917. };
  39918. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  39919. this._removeBackground();
  39920. createLarge(seriesModel, this.group, true);
  39921. };
  39922. BarView.prototype._updateLargeClip = function (seriesModel) {
  39923. // Use clipPath in large mode.
  39924. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  39925. if (clipPath) {
  39926. this.group.setClipPath(clipPath);
  39927. } else {
  39928. this.group.removeClipPath();
  39929. }
  39930. };
  39931. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  39932. var _this = this; // If no data in the first frame, wait for data to initSort
  39933. if (!data.count()) {
  39934. return;
  39935. }
  39936. var baseAxis = realtimeSortCfg.baseAxis;
  39937. if (this._isFirstFrame) {
  39938. this._dispatchInitSort(data, realtimeSortCfg, api);
  39939. this._isFirstFrame = false;
  39940. } else {
  39941. var orderMapping_1 = function (idx) {
  39942. var el = data.getItemGraphicEl(idx);
  39943. if (el) {
  39944. var shape = el.shape; // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  39945. return (baseAxis.isHorizontal() // The result should be consistent with the initial sort by data value.
  39946. // Do not support the case that both positive and negative exist.
  39947. ? Math.abs(shape.height) : Math.abs(shape.width)) || 0;
  39948. } else {
  39949. return 0;
  39950. }
  39951. };
  39952. this._onRendered = function () {
  39953. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  39954. };
  39955. api.getZr().on('rendered', this._onRendered);
  39956. }
  39957. };
  39958. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  39959. var info = [];
  39960. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  39961. var mappedValue = orderMapping(dataIdx);
  39962. mappedValue = mappedValue == null ? NaN : mappedValue;
  39963. info.push({
  39964. dataIndex: dataIdx,
  39965. mappedValue: mappedValue,
  39966. ordinalNumber: ordinalNumber
  39967. });
  39968. });
  39969. info.sort(function (a, b) {
  39970. // If NaN, it will be treated as min val.
  39971. return b.mappedValue - a.mappedValue;
  39972. });
  39973. return {
  39974. ordinalNumbers: map(info, function (item) {
  39975. return item.ordinalNumber;
  39976. })
  39977. };
  39978. };
  39979. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  39980. var scale = baseAxis.scale;
  39981. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  39982. var lastValue = Number.MAX_VALUE;
  39983. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  39984. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  39985. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  39986. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  39987. : orderMapping(data.indexOfRawIndex(rawIdx));
  39988. if (value > lastValue) {
  39989. return true;
  39990. }
  39991. lastValue = value;
  39992. }
  39993. return false;
  39994. };
  39995. /*
  39996. * Consider the case when A and B changed order, whose representing
  39997. * bars are both out of sight, we don't wish to trigger reorder action
  39998. * as long as the order in the view doesn't change.
  39999. */
  40000. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  40001. var scale = baseAxis.scale;
  40002. var extent = scale.getExtent();
  40003. var tickNum = Math.max(0, extent[0]);
  40004. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  40005. for (; tickNum <= tickMax; ++tickNum) {
  40006. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  40007. return true;
  40008. }
  40009. }
  40010. };
  40011. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  40012. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  40013. return;
  40014. }
  40015. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  40016. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  40017. this._removeOnRenderedListener(api);
  40018. api.dispatchAction({
  40019. type: 'changeAxisOrder',
  40020. componentType: baseAxis.dim + 'Axis',
  40021. axisId: baseAxis.index,
  40022. sortInfo: sortInfo
  40023. });
  40024. }
  40025. };
  40026. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  40027. var baseAxis = realtimeSortCfg.baseAxis;
  40028. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  40029. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  40030. });
  40031. api.dispatchAction({
  40032. type: 'changeAxisOrder',
  40033. componentType: baseAxis.dim + 'Axis',
  40034. isInitSort: true,
  40035. axisId: baseAxis.index,
  40036. sortInfo: sortResult
  40037. });
  40038. };
  40039. BarView.prototype.remove = function (ecModel, api) {
  40040. this._clear(this._model);
  40041. this._removeOnRenderedListener(api);
  40042. };
  40043. BarView.prototype.dispose = function (ecModel, api) {
  40044. this._removeOnRenderedListener(api);
  40045. };
  40046. BarView.prototype._removeOnRenderedListener = function (api) {
  40047. if (this._onRendered) {
  40048. api.getZr().off('rendered', this._onRendered);
  40049. this._onRendered = null;
  40050. }
  40051. };
  40052. BarView.prototype._clear = function (model) {
  40053. var group = this.group;
  40054. var data = this._data;
  40055. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  40056. this._removeBackground();
  40057. this._backgroundEls = [];
  40058. data.eachItemGraphicEl(function (el) {
  40059. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  40060. });
  40061. } else {
  40062. group.removeAll();
  40063. }
  40064. this._data = null;
  40065. this._isFirstFrame = true;
  40066. };
  40067. BarView.prototype._removeBackground = function () {
  40068. this.group.remove(this._backgroundGroup);
  40069. this._backgroundGroup = null;
  40070. };
  40071. BarView.type = 'bar';
  40072. return BarView;
  40073. }(ChartView);
  40074. var clip = {
  40075. cartesian2d: function (coordSysBoundingRect, layout) {
  40076. var signWidth = layout.width < 0 ? -1 : 1;
  40077. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  40078. if (signWidth < 0) {
  40079. layout.x += layout.width;
  40080. layout.width = -layout.width;
  40081. }
  40082. if (signHeight < 0) {
  40083. layout.y += layout.height;
  40084. layout.height = -layout.height;
  40085. }
  40086. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  40087. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  40088. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  40089. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  40090. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  40091. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  40092. var xClipped = x2 < x;
  40093. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  40094. // But we should also place the element at the edge of the coord sys bounding rect.
  40095. // Beause if data changed and the bar show again, its transition animaiton
  40096. // will begin at this place.
  40097. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  40098. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  40099. layout.width = xClipped ? 0 : x2 - x;
  40100. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  40101. if (signWidth < 0) {
  40102. layout.x += layout.width;
  40103. layout.width = -layout.width;
  40104. }
  40105. if (signHeight < 0) {
  40106. layout.y += layout.height;
  40107. layout.height = -layout.height;
  40108. }
  40109. return xClipped || yClipped;
  40110. },
  40111. polar: function (coordSysClipArea, layout) {
  40112. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  40113. if (signR < 0) {
  40114. var tmp = layout.r;
  40115. layout.r = layout.r0;
  40116. layout.r0 = tmp;
  40117. }
  40118. var r = mathMin$6(layout.r, coordSysClipArea.r);
  40119. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  40120. layout.r = r;
  40121. layout.r0 = r0;
  40122. var clipped = r - r0 < 0; // Reverse back
  40123. if (signR < 0) {
  40124. var tmp = layout.r;
  40125. layout.r = layout.r0;
  40126. layout.r0 = tmp;
  40127. }
  40128. return clipped;
  40129. }
  40130. };
  40131. var elementCreator = {
  40132. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  40133. var rect = new Rect({
  40134. shape: extend({}, layout),
  40135. z2: 1
  40136. });
  40137. rect.__dataIndex = newIndex;
  40138. rect.name = 'item';
  40139. if (animationModel) {
  40140. var rectShape = rect.shape;
  40141. var animateProperty = isHorizontal ? 'height' : 'width';
  40142. rectShape[animateProperty] = 0;
  40143. }
  40144. return rect;
  40145. },
  40146. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  40147. // Keep the same logic with bar in catesion: use end value to control
  40148. // direction. Notice that if clockwise is true (by default), the sector
  40149. // will always draw clockwisely, no matter whether endAngle is greater
  40150. // or less than startAngle.
  40151. var clockwise = layout.startAngle < layout.endAngle;
  40152. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  40153. var sector = new ShapeClass({
  40154. shape: defaults({
  40155. clockwise: clockwise
  40156. }, layout),
  40157. z2: 1
  40158. });
  40159. sector.name = 'item';
  40160. var positionMap = createPolarPositionMapping(isRadial);
  40161. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  40162. isRoundCap: ShapeClass === SausagePath
  40163. }); // Animation
  40164. if (animationModel) {
  40165. var sectorShape = sector.shape;
  40166. var animateProperty = isRadial ? 'r' : 'endAngle';
  40167. var animateTarget = {};
  40168. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  40169. animateTarget[animateProperty] = layout[animateProperty];
  40170. (isUpdate ? updateProps : initProps)(sector, {
  40171. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  40172. }, animationModel);
  40173. }
  40174. return sector;
  40175. }
  40176. };
  40177. function shouldRealtimeSort(seriesModel, coordSys) {
  40178. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  40179. var baseAxis = coordSys.getBaseAxis();
  40180. if ("development" !== 'production') {
  40181. if (realtimeSortOption) {
  40182. if (baseAxis.type !== 'category') {
  40183. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  40184. }
  40185. if (coordSys.type !== 'cartesian2d') {
  40186. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  40187. }
  40188. }
  40189. }
  40190. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  40191. return {
  40192. baseAxis: baseAxis,
  40193. otherAxis: coordSys.getOtherAxis(baseAxis)
  40194. };
  40195. }
  40196. }
  40197. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  40198. var seriesTarget;
  40199. var axisTarget;
  40200. if (isHorizontal) {
  40201. axisTarget = {
  40202. x: layout.x,
  40203. width: layout.width
  40204. };
  40205. seriesTarget = {
  40206. y: layout.y,
  40207. height: layout.height
  40208. };
  40209. } else {
  40210. axisTarget = {
  40211. y: layout.y,
  40212. height: layout.height
  40213. };
  40214. seriesTarget = {
  40215. x: layout.x,
  40216. width: layout.width
  40217. };
  40218. }
  40219. if (!isChangeOrder) {
  40220. // Keep the original growth animation if only axis order changed.
  40221. // Not start a new animation.
  40222. (isUpdate ? updateProps : initProps)(el, {
  40223. shape: seriesTarget
  40224. }, seriesAnimationModel, newIndex, null);
  40225. }
  40226. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  40227. (isUpdate ? updateProps : initProps)(el, {
  40228. shape: axisTarget
  40229. }, axisAnimationModel, newIndex);
  40230. }
  40231. function checkPropertiesNotValid(obj, props) {
  40232. for (var i = 0; i < props.length; i++) {
  40233. if (!isFinite(obj[props[i]])) {
  40234. return true;
  40235. }
  40236. }
  40237. return false;
  40238. }
  40239. var rectPropties = ['x', 'y', 'width', 'height'];
  40240. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  40241. var isValidLayout = {
  40242. cartesian2d: function (layout) {
  40243. return !checkPropertiesNotValid(layout, rectPropties);
  40244. },
  40245. polar: function (layout) {
  40246. return !checkPropertiesNotValid(layout, polarPropties);
  40247. }
  40248. };
  40249. var getLayout = {
  40250. // itemModel is only used to get borderWidth, which is not needed
  40251. // when calculating bar background layout.
  40252. cartesian2d: function (data, dataIndex, itemModel) {
  40253. var layout = data.getItemLayout(dataIndex);
  40254. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  40255. var signX = layout.width > 0 ? 1 : -1;
  40256. var signY = layout.height > 0 ? 1 : -1;
  40257. return {
  40258. x: layout.x + signX * fixedLineWidth / 2,
  40259. y: layout.y + signY * fixedLineWidth / 2,
  40260. width: layout.width - signX * fixedLineWidth,
  40261. height: layout.height - signY * fixedLineWidth
  40262. };
  40263. },
  40264. polar: function (data, dataIndex, itemModel) {
  40265. var layout = data.getItemLayout(dataIndex);
  40266. return {
  40267. cx: layout.cx,
  40268. cy: layout.cy,
  40269. r0: layout.r0,
  40270. r: layout.r,
  40271. startAngle: layout.startAngle,
  40272. endAngle: layout.endAngle
  40273. };
  40274. }
  40275. };
  40276. function isZeroOnPolar(layout) {
  40277. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  40278. }
  40279. function createPolarPositionMapping(isRadial) {
  40280. return function (isRadial) {
  40281. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  40282. return function (position) {
  40283. switch (position) {
  40284. case 'start':
  40285. case 'insideStart':
  40286. case 'end':
  40287. case 'insideEnd':
  40288. return position + arcOrAngle;
  40289. default:
  40290. return position;
  40291. }
  40292. };
  40293. }(isRadial);
  40294. }
  40295. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  40296. var style = data.getItemVisual(dataIndex, 'style');
  40297. if (!isPolar) {
  40298. el.setShape('r', itemModel.get(['itemStyle', 'borderRadius']) || 0);
  40299. }
  40300. el.useStyle(style);
  40301. var cursorStyle = itemModel.getShallow('cursor');
  40302. cursorStyle && el.attr('cursor', cursorStyle);
  40303. 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';
  40304. var labelStatesModels = getLabelStatesModels(itemModel);
  40305. setLabelStyle(el, labelStatesModels, {
  40306. labelFetcher: seriesModel,
  40307. labelDataIndex: dataIndex,
  40308. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  40309. inheritColor: style.fill,
  40310. defaultOpacity: style.opacity,
  40311. defaultOutsidePosition: labelPositionOutside
  40312. });
  40313. var label = el.getTextContent();
  40314. if (isPolar && label) {
  40315. var position = itemModel.get(['label', 'position']);
  40316. el.textConfig.inside = position === 'middle' ? true : null;
  40317. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  40318. }
  40319. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  40320. return getDefaultInterpolatedLabel(data, value);
  40321. });
  40322. var emphasisModel = itemModel.getModel(['emphasis']);
  40323. enableHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  40324. setStatesStylesFromModel(el, itemModel);
  40325. if (isZeroOnPolar(layout)) {
  40326. el.style.fill = 'none';
  40327. el.style.stroke = 'none';
  40328. each(el.states, function (state) {
  40329. if (state.style) {
  40330. state.style.fill = state.style.stroke = 'none';
  40331. }
  40332. });
  40333. }
  40334. } // In case width or height are too small.
  40335. function getLineWidth(itemModel, rawLayout) {
  40336. // Has no border.
  40337. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  40338. if (!borderColor || borderColor === 'none') {
  40339. return 0;
  40340. }
  40341. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0; // width or height may be NaN for empty data
  40342. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  40343. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  40344. return Math.min(lineWidth, width, height);
  40345. }
  40346. var LagePathShape =
  40347. /** @class */
  40348. function () {
  40349. function LagePathShape() {}
  40350. return LagePathShape;
  40351. }();
  40352. var LargePath =
  40353. /** @class */
  40354. function (_super) {
  40355. __extends(LargePath, _super);
  40356. function LargePath(opts) {
  40357. var _this = _super.call(this, opts) || this;
  40358. _this.type = 'largeBar';
  40359. return _this;
  40360. }
  40361. LargePath.prototype.getDefaultShape = function () {
  40362. return new LagePathShape();
  40363. };
  40364. LargePath.prototype.buildPath = function (ctx, shape) {
  40365. // Drawing lines is more efficient than drawing
  40366. // a whole line or drawing rects.
  40367. var points = shape.points;
  40368. var startPoint = this.__startPoint;
  40369. var baseDimIdx = this.__baseDimIdx;
  40370. for (var i = 0; i < points.length; i += 2) {
  40371. startPoint[baseDimIdx] = points[i + baseDimIdx];
  40372. ctx.moveTo(startPoint[0], startPoint[1]);
  40373. ctx.lineTo(points[i], points[i + 1]);
  40374. }
  40375. };
  40376. return LargePath;
  40377. }(Path);
  40378. function createLarge(seriesModel, group, incremental) {
  40379. // TODO support polar
  40380. var data = seriesModel.getData();
  40381. var startPoint = [];
  40382. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  40383. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  40384. var largeDataIndices = data.getLayout('largeDataIndices');
  40385. var barWidth = data.getLayout('barWidth');
  40386. var backgroundModel = seriesModel.getModel('backgroundStyle');
  40387. var drawBackground = seriesModel.get('showBackground', true);
  40388. if (drawBackground) {
  40389. var points = data.getLayout('largeBackgroundPoints');
  40390. var backgroundStartPoint = [];
  40391. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  40392. var bgEl = new LargePath({
  40393. shape: {
  40394. points: points
  40395. },
  40396. incremental: !!incremental,
  40397. silent: true,
  40398. z2: 0
  40399. });
  40400. bgEl.__startPoint = backgroundStartPoint;
  40401. bgEl.__baseDimIdx = baseDimIdx;
  40402. bgEl.__largeDataIndices = largeDataIndices;
  40403. bgEl.__barWidth = barWidth;
  40404. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  40405. group.add(bgEl);
  40406. }
  40407. var el = new LargePath({
  40408. shape: {
  40409. points: data.getLayout('largePoints')
  40410. },
  40411. incremental: !!incremental
  40412. });
  40413. el.__startPoint = startPoint;
  40414. el.__baseDimIdx = baseDimIdx;
  40415. el.__largeDataIndices = largeDataIndices;
  40416. el.__barWidth = barWidth;
  40417. group.add(el);
  40418. setLargeStyle(el, seriesModel, data); // Enable tooltip and user mouse/touch event handlers.
  40419. getECData(el).seriesIndex = seriesModel.seriesIndex;
  40420. if (!seriesModel.get('silent')) {
  40421. el.on('mousedown', largePathUpdateDataIndex);
  40422. el.on('mousemove', largePathUpdateDataIndex);
  40423. }
  40424. } // Use throttle to avoid frequently traverse to find dataIndex.
  40425. var largePathUpdateDataIndex = throttle(function (event) {
  40426. var largePath = this;
  40427. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  40428. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  40429. }, 30, false);
  40430. function largePathFindDataIndex(largePath, x, y) {
  40431. var baseDimIdx = largePath.__baseDimIdx;
  40432. var valueDimIdx = 1 - baseDimIdx;
  40433. var points = largePath.shape.points;
  40434. var largeDataIndices = largePath.__largeDataIndices;
  40435. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  40436. var startValueVal = largePath.__startPoint[valueDimIdx];
  40437. _eventPos[0] = x;
  40438. _eventPos[1] = y;
  40439. var pointerBaseVal = _eventPos[baseDimIdx];
  40440. var pointerValueVal = _eventPos[1 - baseDimIdx];
  40441. var baseLowerBound = pointerBaseVal - barWidthHalf;
  40442. var baseUpperBound = pointerBaseVal + barWidthHalf;
  40443. for (var i = 0, len = points.length / 2; i < len; i++) {
  40444. var ii = i * 2;
  40445. var barBaseVal = points[ii + baseDimIdx];
  40446. var barValueVal = points[ii + valueDimIdx];
  40447. if (barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound && (startValueVal <= barValueVal ? pointerValueVal >= startValueVal && pointerValueVal <= barValueVal : pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)) {
  40448. return largeDataIndices[i];
  40449. }
  40450. }
  40451. return -1;
  40452. }
  40453. function setLargeStyle(el, seriesModel, data) {
  40454. var globalStyle = data.getVisual('style');
  40455. el.useStyle(extend({}, globalStyle)); // Use stroke instead of fill.
  40456. el.style.fill = null;
  40457. el.style.stroke = globalStyle.fill;
  40458. el.style.lineWidth = data.getLayout('barWidth');
  40459. }
  40460. function setLargeBackgroundStyle(el, backgroundModel, data) {
  40461. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  40462. var itemStyle = backgroundModel.getItemStyle();
  40463. el.useStyle(itemStyle);
  40464. el.style.fill = null;
  40465. el.style.stroke = borderColor;
  40466. el.style.lineWidth = data.getLayout('barWidth');
  40467. }
  40468. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  40469. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  40470. var rectShape = layout;
  40471. var coordLayout = coord.getArea();
  40472. return {
  40473. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  40474. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  40475. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  40476. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  40477. };
  40478. } else {
  40479. var coordLayout = coord.getArea();
  40480. var sectorShape = layout;
  40481. return {
  40482. cx: coordLayout.cx,
  40483. cy: coordLayout.cy,
  40484. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  40485. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  40486. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  40487. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  40488. };
  40489. }
  40490. }
  40491. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  40492. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  40493. return new ElementClz({
  40494. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  40495. silent: true,
  40496. z2: 0
  40497. });
  40498. }
  40499. function install$3(registers) {
  40500. registers.registerChartView(BarView);
  40501. registers.registerSeriesModel(BarSeriesModel);
  40502. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Use higher prority to avoid to be blocked by other overall layout, which do not
  40503. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  40504. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout); // Down sample after filter
  40505. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  40506. /**
  40507. * @payload
  40508. * @property {string} [componentType=series]
  40509. * @property {number} [dx]
  40510. * @property {number} [dy]
  40511. * @property {number} [zoom]
  40512. * @property {number} [originX]
  40513. * @property {number} [originY]
  40514. */
  40515. registers.registerAction({
  40516. type: 'changeAxisOrder',
  40517. event: 'changeAxisOrder',
  40518. update: 'update'
  40519. }, function (payload, ecModel) {
  40520. var componentType = payload.componentType || 'series';
  40521. ecModel.eachComponent({
  40522. mainType: componentType,
  40523. query: payload
  40524. }, function (componentModel) {
  40525. if (payload.sortInfo) {
  40526. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  40527. }
  40528. });
  40529. });
  40530. }
  40531. var PI2$8 = Math.PI * 2;
  40532. var RADIAN = Math.PI / 180;
  40533. function getViewRect(seriesModel, api) {
  40534. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  40535. width: api.getWidth(),
  40536. height: api.getHeight()
  40537. });
  40538. }
  40539. function getBasicPieLayout(seriesModel, api) {
  40540. var viewRect = getViewRect(seriesModel, api);
  40541. var center = seriesModel.get('center');
  40542. var radius = seriesModel.get('radius');
  40543. if (!isArray(radius)) {
  40544. radius = [0, radius];
  40545. }
  40546. if (!isArray(center)) {
  40547. center = [center, center];
  40548. }
  40549. var width = parsePercent$1(viewRect.width, api.getWidth());
  40550. var height = parsePercent$1(viewRect.height, api.getHeight());
  40551. var size = Math.min(width, height);
  40552. var cx = parsePercent$1(center[0], width) + viewRect.x;
  40553. var cy = parsePercent$1(center[1], height) + viewRect.y;
  40554. var r0 = parsePercent$1(radius[0], size / 2);
  40555. var r = parsePercent$1(radius[1], size / 2);
  40556. return {
  40557. cx: cx,
  40558. cy: cy,
  40559. r0: r0,
  40560. r: r
  40561. };
  40562. }
  40563. function pieLayout(seriesType, ecModel, api) {
  40564. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  40565. var data = seriesModel.getData();
  40566. var valueDim = data.mapDimension('value');
  40567. var viewRect = getViewRect(seriesModel, api);
  40568. var _a = getBasicPieLayout(seriesModel, api),
  40569. cx = _a.cx,
  40570. cy = _a.cy,
  40571. r = _a.r,
  40572. r0 = _a.r0;
  40573. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  40574. var minAngle = seriesModel.get('minAngle') * RADIAN;
  40575. var validDataCount = 0;
  40576. data.each(valueDim, function (value) {
  40577. !isNaN(value) && validDataCount++;
  40578. });
  40579. var sum = data.getSum(valueDim); // Sum may be 0
  40580. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  40581. var clockwise = seriesModel.get('clockwise');
  40582. var roseType = seriesModel.get('roseType');
  40583. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  40584. var extent = data.getDataExtent(valueDim);
  40585. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  40586. var restAngle = PI2$8;
  40587. var valueSumLargerThanMinAngle = 0;
  40588. var currentAngle = startAngle;
  40589. var dir = clockwise ? 1 : -1;
  40590. data.setLayout({
  40591. viewRect: viewRect,
  40592. r: r
  40593. });
  40594. data.each(valueDim, function (value, idx) {
  40595. var angle;
  40596. if (isNaN(value)) {
  40597. data.setItemLayout(idx, {
  40598. angle: NaN,
  40599. startAngle: NaN,
  40600. endAngle: NaN,
  40601. clockwise: clockwise,
  40602. cx: cx,
  40603. cy: cy,
  40604. r0: r0,
  40605. r: roseType ? NaN : r
  40606. });
  40607. return;
  40608. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  40609. if (roseType !== 'area') {
  40610. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  40611. } else {
  40612. angle = PI2$8 / validDataCount;
  40613. }
  40614. if (angle < minAngle) {
  40615. angle = minAngle;
  40616. restAngle -= minAngle;
  40617. } else {
  40618. valueSumLargerThanMinAngle += value;
  40619. }
  40620. var endAngle = currentAngle + dir * angle;
  40621. data.setItemLayout(idx, {
  40622. angle: angle,
  40623. startAngle: currentAngle,
  40624. endAngle: endAngle,
  40625. clockwise: clockwise,
  40626. cx: cx,
  40627. cy: cy,
  40628. r0: r0,
  40629. r: roseType ? linearMap(value, extent, [r0, r]) : r
  40630. });
  40631. currentAngle = endAngle;
  40632. }); // Some sector is constrained by minAngle
  40633. // Rest sectors needs recalculate angle
  40634. if (restAngle < PI2$8 && validDataCount) {
  40635. // Average the angle if rest angle is not enough after all angles is
  40636. // Constrained by minAngle
  40637. if (restAngle <= 1e-3) {
  40638. var angle_1 = PI2$8 / validDataCount;
  40639. data.each(valueDim, function (value, idx) {
  40640. if (!isNaN(value)) {
  40641. var layout_1 = data.getItemLayout(idx);
  40642. layout_1.angle = angle_1;
  40643. layout_1.startAngle = startAngle + dir * idx * angle_1;
  40644. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  40645. }
  40646. });
  40647. } else {
  40648. unitRadian = restAngle / valueSumLargerThanMinAngle;
  40649. currentAngle = startAngle;
  40650. data.each(valueDim, function (value, idx) {
  40651. if (!isNaN(value)) {
  40652. var layout_2 = data.getItemLayout(idx);
  40653. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  40654. layout_2.startAngle = currentAngle;
  40655. layout_2.endAngle = currentAngle + dir * angle;
  40656. currentAngle += dir * angle;
  40657. }
  40658. });
  40659. }
  40660. }
  40661. });
  40662. }
  40663. /*
  40664. * Licensed to the Apache Software Foundation (ASF) under one
  40665. * or more contributor license agreements. See the NOTICE file
  40666. * distributed with this work for additional information
  40667. * regarding copyright ownership. The ASF licenses this file
  40668. * to you under the Apache License, Version 2.0 (the
  40669. * "License"); you may not use this file except in compliance
  40670. * with the License. You may obtain a copy of the License at
  40671. *
  40672. * http://www.apache.org/licenses/LICENSE-2.0
  40673. *
  40674. * Unless required by applicable law or agreed to in writing,
  40675. * software distributed under the License is distributed on an
  40676. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40677. * KIND, either express or implied. See the License for the
  40678. * specific language governing permissions and limitations
  40679. * under the License.
  40680. */
  40681. /**
  40682. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40683. */
  40684. /*
  40685. * Licensed to the Apache Software Foundation (ASF) under one
  40686. * or more contributor license agreements. See the NOTICE file
  40687. * distributed with this work for additional information
  40688. * regarding copyright ownership. The ASF licenses this file
  40689. * to you under the Apache License, Version 2.0 (the
  40690. * "License"); you may not use this file except in compliance
  40691. * with the License. You may obtain a copy of the License at
  40692. *
  40693. * http://www.apache.org/licenses/LICENSE-2.0
  40694. *
  40695. * Unless required by applicable law or agreed to in writing,
  40696. * software distributed under the License is distributed on an
  40697. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40698. * KIND, either express or implied. See the License for the
  40699. * specific language governing permissions and limitations
  40700. * under the License.
  40701. */
  40702. function dataFilter(seriesType) {
  40703. return {
  40704. seriesType: seriesType,
  40705. reset: function (seriesModel, ecModel) {
  40706. var legendModels = ecModel.findComponents({
  40707. mainType: 'legend'
  40708. });
  40709. if (!legendModels || !legendModels.length) {
  40710. return;
  40711. }
  40712. var data = seriesModel.getData();
  40713. data.filterSelf(function (idx) {
  40714. var name = data.getName(idx); // If in any legend component the status is not selected.
  40715. for (var i = 0; i < legendModels.length; i++) {
  40716. // @ts-ignore FIXME: LegendModel
  40717. if (!legendModels[i].isSelected(name)) {
  40718. return false;
  40719. }
  40720. }
  40721. return true;
  40722. });
  40723. }
  40724. };
  40725. }
  40726. var RADIAN$1 = Math.PI / 180;
  40727. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  40728. if (list.length < 2) {
  40729. return;
  40730. }
  40731. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  40732. var rB = semi.rB;
  40733. var rB2 = rB * rB;
  40734. for (var i = 0; i < semi.list.length; i++) {
  40735. var item = semi.list[i];
  40736. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  40737. var rA = r + item.len;
  40738. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  40739. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  40740. item.label.x = cx + (dx + item.len2) * dir;
  40741. }
  40742. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  40743. function recalculateX(items) {
  40744. // Extremes of
  40745. var topSemi = {
  40746. list: [],
  40747. maxY: 0
  40748. };
  40749. var bottomSemi = {
  40750. list: [],
  40751. maxY: 0
  40752. };
  40753. for (var i = 0; i < items.length; i++) {
  40754. if (items[i].labelAlignTo !== 'none') {
  40755. continue;
  40756. }
  40757. var item = items[i];
  40758. var semi = item.label.y > cy ? bottomSemi : topSemi;
  40759. var dy = Math.abs(item.label.y - cy);
  40760. if (dy > semi.maxY) {
  40761. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  40762. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  40763. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  40764. semi.rB = rB;
  40765. semi.maxY = dy;
  40766. }
  40767. semi.list.push(item);
  40768. }
  40769. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  40770. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  40771. }
  40772. var len = list.length;
  40773. for (var i = 0; i < len; i++) {
  40774. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  40775. var dx = list[i].label.x - farthestX;
  40776. list[i].linePoints[1][0] += dx;
  40777. list[i].label.x = farthestX;
  40778. }
  40779. }
  40780. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  40781. recalculateX(list);
  40782. }
  40783. }
  40784. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  40785. var leftList = [];
  40786. var rightList = [];
  40787. var leftmostX = Number.MAX_VALUE;
  40788. var rightmostX = -Number.MAX_VALUE;
  40789. for (var i = 0; i < labelLayoutList.length; i++) {
  40790. var label = labelLayoutList[i].label;
  40791. if (isPositionCenter(labelLayoutList[i])) {
  40792. continue;
  40793. }
  40794. if (label.x < cx) {
  40795. leftmostX = Math.min(leftmostX, label.x);
  40796. leftList.push(labelLayoutList[i]);
  40797. } else {
  40798. rightmostX = Math.max(rightmostX, label.x);
  40799. rightList.push(labelLayoutList[i]);
  40800. }
  40801. }
  40802. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  40803. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  40804. for (var i = 0; i < labelLayoutList.length; i++) {
  40805. var layout = labelLayoutList[i];
  40806. var label = layout.label;
  40807. if (isPositionCenter(layout)) {
  40808. continue;
  40809. }
  40810. var linePoints = layout.linePoints;
  40811. if (linePoints) {
  40812. var isAlignToEdge = layout.labelAlignTo === 'edge';
  40813. var realTextWidth = layout.rect.width;
  40814. var targetTextWidth = void 0;
  40815. if (isAlignToEdge) {
  40816. if (label.x < cx) {
  40817. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  40818. } else {
  40819. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  40820. }
  40821. } else {
  40822. if (label.x < cx) {
  40823. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  40824. } else {
  40825. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  40826. }
  40827. }
  40828. if (targetTextWidth < layout.rect.width) {
  40829. // TODOTODO
  40830. // layout.text = textContain.truncateText(layout.text, targetTextWidth, layout.font);
  40831. layout.label.style.width = targetTextWidth;
  40832. if (layout.labelAlignTo === 'edge') {
  40833. realTextWidth = targetTextWidth; // realTextWidth = textContain.getWidth(layout.text, layout.font);
  40834. }
  40835. }
  40836. var dist = linePoints[1][0] - linePoints[2][0];
  40837. if (isAlignToEdge) {
  40838. if (label.x < cx) {
  40839. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  40840. } else {
  40841. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  40842. }
  40843. } else {
  40844. if (label.x < cx) {
  40845. linePoints[2][0] = label.x + layout.labelDistance;
  40846. } else {
  40847. linePoints[2][0] = label.x - layout.labelDistance;
  40848. }
  40849. linePoints[1][0] = linePoints[2][0] + dist;
  40850. }
  40851. linePoints[1][1] = linePoints[2][1] = label.y;
  40852. }
  40853. }
  40854. }
  40855. function isPositionCenter(sectorShape) {
  40856. // Not change x for center label
  40857. return sectorShape.position === 'center';
  40858. }
  40859. function pieLabelLayout(seriesModel) {
  40860. var data = seriesModel.getData();
  40861. var labelLayoutList = [];
  40862. var cx;
  40863. var cy;
  40864. var hasLabelRotate = false;
  40865. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  40866. var viewRect = data.getLayout('viewRect');
  40867. var r = data.getLayout('r');
  40868. var viewWidth = viewRect.width;
  40869. var viewLeft = viewRect.x;
  40870. var viewTop = viewRect.y;
  40871. var viewHeight = viewRect.height;
  40872. function setNotShow(el) {
  40873. el.ignore = true;
  40874. }
  40875. function isLabelShown(label) {
  40876. if (!label.ignore) {
  40877. return true;
  40878. }
  40879. for (var key in label.states) {
  40880. if (label.states[key].ignore === false) {
  40881. return true;
  40882. }
  40883. }
  40884. return false;
  40885. }
  40886. data.each(function (idx) {
  40887. var sector = data.getItemGraphicEl(idx);
  40888. var sectorShape = sector.shape;
  40889. var label = sector.getTextContent();
  40890. var labelLine = sector.getTextGuideLine();
  40891. var itemModel = data.getItemModel(idx);
  40892. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  40893. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  40894. var labelDistance = labelModel.get('distanceToLabelLine');
  40895. var labelAlignTo = labelModel.get('alignTo');
  40896. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  40897. var bleedMargin = labelModel.get('bleedMargin');
  40898. var labelLineModel = itemModel.getModel('labelLine');
  40899. var labelLineLen = labelLineModel.get('length');
  40900. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  40901. var labelLineLen2 = labelLineModel.get('length2');
  40902. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  40903. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  40904. each(label.states, setNotShow);
  40905. label.ignore = true;
  40906. return;
  40907. }
  40908. if (!isLabelShown(label)) {
  40909. return;
  40910. }
  40911. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  40912. var nx = Math.cos(midAngle);
  40913. var ny = Math.sin(midAngle);
  40914. var textX;
  40915. var textY;
  40916. var linePoints;
  40917. var textAlign;
  40918. cx = sectorShape.cx;
  40919. cy = sectorShape.cy;
  40920. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  40921. if (labelPosition === 'center') {
  40922. textX = sectorShape.cx;
  40923. textY = sectorShape.cy;
  40924. textAlign = 'center';
  40925. } else {
  40926. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  40927. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  40928. textX = x1 + nx * 3;
  40929. textY = y1 + ny * 3;
  40930. if (!isLabelInside) {
  40931. // For roseType
  40932. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  40933. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  40934. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  40935. var y3 = y2;
  40936. if (labelAlignTo === 'edge') {
  40937. // Adjust textX because text align of edge is opposite
  40938. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  40939. } else {
  40940. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  40941. }
  40942. textY = y3;
  40943. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  40944. }
  40945. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  40946. }
  40947. var labelRotate;
  40948. var rotate = labelModel.get('rotate');
  40949. if (typeof rotate === 'number') {
  40950. labelRotate = rotate * (Math.PI / 180);
  40951. } else if (labelPosition === 'center') {
  40952. labelRotate = 0;
  40953. } else {
  40954. var radialAngle = nx < 0 ? -midAngle + Math.PI : -midAngle;
  40955. if (rotate === 'radial' || rotate === true) {
  40956. labelRotate = radialAngle;
  40957. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  40958. labelRotate = radialAngle + Math.PI / 2;
  40959. if (labelRotate > Math.PI / 2) {
  40960. labelRotate -= Math.PI;
  40961. }
  40962. } else {
  40963. labelRotate = 0;
  40964. }
  40965. }
  40966. hasLabelRotate = !!labelRotate;
  40967. label.x = textX;
  40968. label.y = textY;
  40969. label.rotation = labelRotate;
  40970. label.setStyle({
  40971. verticalAlign: 'middle'
  40972. }); // Not sectorShape the inside label
  40973. if (!isLabelInside) {
  40974. var textRect = label.getBoundingRect().clone();
  40975. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  40976. var margin = (label.style.margin || 0) + 2.1;
  40977. textRect.y -= margin / 2;
  40978. textRect.height += margin;
  40979. labelLayoutList.push({
  40980. label: label,
  40981. labelLine: labelLine,
  40982. position: labelPosition,
  40983. len: labelLineLen,
  40984. len2: labelLineLen2,
  40985. minTurnAngle: labelLineModel.get('minTurnAngle'),
  40986. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  40987. surfaceNormal: new Point(nx, ny),
  40988. linePoints: linePoints,
  40989. textAlign: textAlign,
  40990. labelDistance: labelDistance,
  40991. labelAlignTo: labelAlignTo,
  40992. edgeDistance: edgeDistance,
  40993. bleedMargin: bleedMargin,
  40994. rect: textRect
  40995. });
  40996. } else {
  40997. label.setStyle({
  40998. align: textAlign
  40999. });
  41000. var selectState = label.states.select;
  41001. if (selectState) {
  41002. selectState.x += label.x;
  41003. selectState.y += label.y;
  41004. }
  41005. }
  41006. sector.setTextConfig({
  41007. inside: isLabelInside
  41008. });
  41009. });
  41010. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  41011. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  41012. }
  41013. for (var i = 0; i < labelLayoutList.length; i++) {
  41014. var layout = labelLayoutList[i];
  41015. var label = layout.label;
  41016. var labelLine = layout.labelLine;
  41017. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  41018. if (label) {
  41019. label.setStyle({
  41020. align: layout.textAlign
  41021. });
  41022. if (notShowLabel) {
  41023. each(label.states, setNotShow);
  41024. label.ignore = true;
  41025. }
  41026. var selectState = label.states.select;
  41027. if (selectState) {
  41028. selectState.x += label.x;
  41029. selectState.y += label.y;
  41030. }
  41031. }
  41032. if (labelLine) {
  41033. var linePoints = layout.linePoints;
  41034. if (notShowLabel || !linePoints) {
  41035. each(labelLine.states, setNotShow);
  41036. labelLine.ignore = true;
  41037. } else {
  41038. limitTurnAngle(linePoints, layout.minTurnAngle);
  41039. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  41040. labelLine.setShape({
  41041. points: linePoints
  41042. }); // Set the anchor to the midpoint of sector
  41043. label.__hostTarget.textGuideLineConfig = {
  41044. anchor: new Point(linePoints[0][0], linePoints[0][1])
  41045. };
  41046. }
  41047. }
  41048. }
  41049. }
  41050. function getSectorCornerRadius(model, shape, zeroIfNull) {
  41051. var cornerRadius = model.get('borderRadius');
  41052. if (cornerRadius == null) {
  41053. return zeroIfNull ? {
  41054. innerCornerRadius: 0,
  41055. cornerRadius: 0
  41056. } : null;
  41057. }
  41058. if (!isArray(cornerRadius)) {
  41059. cornerRadius = [cornerRadius, cornerRadius];
  41060. }
  41061. return {
  41062. innerCornerRadius: parsePercent(cornerRadius[0], shape.r0),
  41063. cornerRadius: parsePercent(cornerRadius[1], shape.r)
  41064. };
  41065. }
  41066. /**
  41067. * Piece of pie including Sector, Label, LabelLine
  41068. */
  41069. var PiePiece =
  41070. /** @class */
  41071. function (_super) {
  41072. __extends(PiePiece, _super);
  41073. function PiePiece(data, idx, startAngle) {
  41074. var _this = _super.call(this) || this;
  41075. _this.z2 = 2;
  41076. var text = new ZRText();
  41077. _this.setTextContent(text);
  41078. _this.updateData(data, idx, startAngle, true);
  41079. return _this;
  41080. }
  41081. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  41082. var sector = this;
  41083. var seriesModel = data.hostModel;
  41084. var itemModel = data.getItemModel(idx);
  41085. var emphasisModel = itemModel.getModel('emphasis');
  41086. var layout = data.getItemLayout(idx); // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  41087. // see `setItemLayout` in `pieLayout.ts`.
  41088. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout); // Ignore NaN data.
  41089. if (isNaN(sectorShape.startAngle)) {
  41090. // Use NaN shape to avoid drawing shape.
  41091. sector.setShape(sectorShape);
  41092. return;
  41093. }
  41094. if (firstCreate) {
  41095. sector.setShape(sectorShape);
  41096. var animationType = seriesModel.getShallow('animationType');
  41097. if (animationType === 'scale') {
  41098. sector.shape.r = layout.r0;
  41099. initProps(sector, {
  41100. shape: {
  41101. r: layout.r
  41102. }
  41103. }, seriesModel, idx);
  41104. } // Expansion
  41105. else {
  41106. if (startAngle != null) {
  41107. sector.setShape({
  41108. startAngle: startAngle,
  41109. endAngle: startAngle
  41110. });
  41111. initProps(sector, {
  41112. shape: {
  41113. startAngle: layout.startAngle,
  41114. endAngle: layout.endAngle
  41115. }
  41116. }, seriesModel, idx);
  41117. } else {
  41118. sector.shape.endAngle = layout.startAngle;
  41119. updateProps(sector, {
  41120. shape: {
  41121. endAngle: layout.endAngle
  41122. }
  41123. }, seriesModel, idx);
  41124. }
  41125. }
  41126. } else {
  41127. saveOldStyle(sector); // Transition animation from the old shape
  41128. updateProps(sector, {
  41129. shape: sectorShape
  41130. }, seriesModel, idx);
  41131. }
  41132. sector.useStyle(data.getItemVisual(idx, 'style'));
  41133. setStatesStylesFromModel(sector, itemModel);
  41134. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  41135. var offset = seriesModel.get('selectedOffset');
  41136. var dx = Math.cos(midAngle) * offset;
  41137. var dy = Math.sin(midAngle) * offset;
  41138. var cursorStyle = itemModel.getShallow('cursor');
  41139. cursorStyle && sector.attr('cursor', cursorStyle);
  41140. this._updateLabel(seriesModel, data, idx);
  41141. sector.ensureState('emphasis').shape = __assign({
  41142. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  41143. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  41144. extend(sector.ensureState('select'), {
  41145. x: dx,
  41146. y: dy,
  41147. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  41148. });
  41149. extend(sector.ensureState('blur'), {
  41150. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  41151. });
  41152. var labelLine = sector.getTextGuideLine();
  41153. var labelText = sector.getTextContent();
  41154. labelLine && extend(labelLine.ensureState('select'), {
  41155. x: dx,
  41156. y: dy
  41157. }); // TODO: needs dx, dy in zrender?
  41158. extend(labelText.ensureState('select'), {
  41159. x: dx,
  41160. y: dy
  41161. });
  41162. enableHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  41163. };
  41164. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  41165. var sector = this;
  41166. var itemModel = data.getItemModel(idx);
  41167. var labelLineModel = itemModel.getModel('labelLine');
  41168. var style = data.getItemVisual(idx, 'style');
  41169. var visualColor = style && style.fill;
  41170. var visualOpacity = style && style.opacity;
  41171. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  41172. labelFetcher: data.hostModel,
  41173. labelDataIndex: idx,
  41174. inheritColor: visualColor,
  41175. defaultOpacity: visualOpacity,
  41176. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  41177. });
  41178. var labelText = sector.getTextContent(); // Set textConfig on sector.
  41179. sector.setTextConfig({
  41180. // reset position, rotation
  41181. position: null,
  41182. rotation: null
  41183. }); // Make sure update style on labelText after setLabelStyle.
  41184. // Because setLabelStyle will replace a new style on it.
  41185. labelText.attr({
  41186. z2: 10
  41187. });
  41188. var labelPosition = seriesModel.get(['label', 'position']);
  41189. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  41190. sector.removeTextGuideLine();
  41191. } else {
  41192. var polyline = this.getTextGuideLine();
  41193. if (!polyline) {
  41194. polyline = new Polyline();
  41195. this.setTextGuideLine(polyline);
  41196. } // Default use item visual color
  41197. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  41198. stroke: visualColor,
  41199. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  41200. });
  41201. }
  41202. };
  41203. return PiePiece;
  41204. }(Sector); // Pie view
  41205. var PieView =
  41206. /** @class */
  41207. function (_super) {
  41208. __extends(PieView, _super);
  41209. function PieView() {
  41210. var _this = _super !== null && _super.apply(this, arguments) || this;
  41211. _this.ignoreLabelLineUpdate = true;
  41212. return _this;
  41213. }
  41214. PieView.prototype.init = function () {
  41215. var sectorGroup = new Group();
  41216. this._sectorGroup = sectorGroup;
  41217. };
  41218. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  41219. var data = seriesModel.getData();
  41220. var oldData = this._data;
  41221. var group = this.group;
  41222. var startAngle; // First render
  41223. if (!oldData && data.count() > 0) {
  41224. var shape = data.getItemLayout(0);
  41225. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  41226. shape = data.getItemLayout(s);
  41227. }
  41228. if (shape) {
  41229. startAngle = shape.startAngle;
  41230. }
  41231. } // remove empty-circle if it exists
  41232. if (this._emptyCircleSector) {
  41233. group.remove(this._emptyCircleSector);
  41234. } // when all data are filtered, show lightgray empty circle
  41235. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  41236. var sector = new Sector({
  41237. shape: getBasicPieLayout(seriesModel, api)
  41238. });
  41239. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  41240. this._emptyCircleSector = sector;
  41241. group.add(sector);
  41242. }
  41243. data.diff(oldData).add(function (idx) {
  41244. var piePiece = new PiePiece(data, idx, startAngle);
  41245. data.setItemGraphicEl(idx, piePiece);
  41246. group.add(piePiece);
  41247. }).update(function (newIdx, oldIdx) {
  41248. var piePiece = oldData.getItemGraphicEl(oldIdx);
  41249. piePiece.updateData(data, newIdx, startAngle);
  41250. piePiece.off('click');
  41251. group.add(piePiece);
  41252. data.setItemGraphicEl(newIdx, piePiece);
  41253. }).remove(function (idx) {
  41254. var piePiece = oldData.getItemGraphicEl(idx);
  41255. removeElementWithFadeOut(piePiece, seriesModel, idx);
  41256. }).execute();
  41257. pieLabelLayout(seriesModel); // Always use initial animation.
  41258. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  41259. this._data = data;
  41260. }
  41261. };
  41262. PieView.prototype.dispose = function () {};
  41263. PieView.prototype.containPoint = function (point, seriesModel) {
  41264. var data = seriesModel.getData();
  41265. var itemLayout = data.getItemLayout(0);
  41266. if (itemLayout) {
  41267. var dx = point[0] - itemLayout.cx;
  41268. var dy = point[1] - itemLayout.cy;
  41269. var radius = Math.sqrt(dx * dx + dy * dy);
  41270. return radius <= itemLayout.r && radius >= itemLayout.r0;
  41271. }
  41272. };
  41273. PieView.type = 'pie';
  41274. return PieView;
  41275. }(ChartView);
  41276. /**
  41277. * [Usage]:
  41278. * (1)
  41279. * createListSimply(seriesModel, ['value']);
  41280. * (2)
  41281. * createListSimply(seriesModel, {
  41282. * coordDimensions: ['value'],
  41283. * dimensionsCount: 5
  41284. * });
  41285. */
  41286. function createSeriesDataSimply(seriesModel, opt, nameList) {
  41287. opt = isArray(opt) && {
  41288. coordDimensions: opt
  41289. } || extend({
  41290. encodeDefine: seriesModel.getEncode()
  41291. }, opt);
  41292. var source = seriesModel.getSource();
  41293. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  41294. var list = new SeriesData(dimensions, seriesModel);
  41295. list.initData(source, nameList);
  41296. return list;
  41297. }
  41298. /*
  41299. * Licensed to the Apache Software Foundation (ASF) under one
  41300. * or more contributor license agreements. See the NOTICE file
  41301. * distributed with this work for additional information
  41302. * regarding copyright ownership. The ASF licenses this file
  41303. * to you under the Apache License, Version 2.0 (the
  41304. * "License"); you may not use this file except in compliance
  41305. * with the License. You may obtain a copy of the License at
  41306. *
  41307. * http://www.apache.org/licenses/LICENSE-2.0
  41308. *
  41309. * Unless required by applicable law or agreed to in writing,
  41310. * software distributed under the License is distributed on an
  41311. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41312. * KIND, either express or implied. See the License for the
  41313. * specific language governing permissions and limitations
  41314. * under the License.
  41315. */
  41316. /**
  41317. * AUTO-GENERATED FILE. DO NOT MODIFY.
  41318. */
  41319. /*
  41320. * Licensed to the Apache Software Foundation (ASF) under one
  41321. * or more contributor license agreements. See the NOTICE file
  41322. * distributed with this work for additional information
  41323. * regarding copyright ownership. The ASF licenses this file
  41324. * to you under the Apache License, Version 2.0 (the
  41325. * "License"); you may not use this file except in compliance
  41326. * with the License. You may obtain a copy of the License at
  41327. *
  41328. * http://www.apache.org/licenses/LICENSE-2.0
  41329. *
  41330. * Unless required by applicable law or agreed to in writing,
  41331. * software distributed under the License is distributed on an
  41332. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41333. * KIND, either express or implied. See the License for the
  41334. * specific language governing permissions and limitations
  41335. * under the License.
  41336. */
  41337. /**
  41338. * LegendVisualProvider is an bridge that pick encoded color from data and
  41339. * provide to the legend component.
  41340. */
  41341. var LegendVisualProvider =
  41342. /** @class */
  41343. function () {
  41344. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  41345. getDataWithEncodedVisual, // Function to get raw data before filtered.
  41346. getRawData) {
  41347. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  41348. this._getRawData = getRawData;
  41349. }
  41350. LegendVisualProvider.prototype.getAllNames = function () {
  41351. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  41352. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  41353. return rawData.mapArray(rawData.getName);
  41354. };
  41355. LegendVisualProvider.prototype.containName = function (name) {
  41356. var rawData = this._getRawData();
  41357. return rawData.indexOfName(name) >= 0;
  41358. };
  41359. LegendVisualProvider.prototype.indexOfName = function (name) {
  41360. // Only get data when necessary.
  41361. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  41362. // Invoking Series#getData immediately will throw an error.
  41363. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  41364. return dataWithEncodedVisual.indexOfName(name);
  41365. };
  41366. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  41367. // Get encoded visual properties from final filtered data.
  41368. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  41369. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  41370. };
  41371. return LegendVisualProvider;
  41372. }();
  41373. var PieSeriesModel =
  41374. /** @class */
  41375. function (_super) {
  41376. __extends(PieSeriesModel, _super);
  41377. function PieSeriesModel() {
  41378. return _super !== null && _super.apply(this, arguments) || this;
  41379. }
  41380. /**
  41381. * @overwrite
  41382. */
  41383. PieSeriesModel.prototype.init = function (option) {
  41384. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  41385. // Use a function instead of direct access because data reference may changed
  41386. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  41387. this._defaultLabelLine(option);
  41388. };
  41389. /**
  41390. * @overwrite
  41391. */
  41392. PieSeriesModel.prototype.mergeOption = function () {
  41393. _super.prototype.mergeOption.apply(this, arguments);
  41394. };
  41395. /**
  41396. * @overwrite
  41397. */
  41398. PieSeriesModel.prototype.getInitialData = function () {
  41399. return createSeriesDataSimply(this, {
  41400. coordDimensions: ['value'],
  41401. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  41402. });
  41403. };
  41404. /**
  41405. * @overwrite
  41406. */
  41407. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  41408. var data = this.getData();
  41409. var params = _super.prototype.getDataParams.call(this, dataIndex); // FIXME toFixed?
  41410. var valueList = [];
  41411. data.each(data.mapDimension('value'), function (value) {
  41412. valueList.push(value);
  41413. });
  41414. params.percent = getPercentWithPrecision(valueList, dataIndex, data.hostModel.get('percentPrecision'));
  41415. params.$vars.push('percent');
  41416. return params;
  41417. };
  41418. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  41419. // Extend labelLine emphasis
  41420. defaultEmphasis(option, 'labelLine', ['show']);
  41421. var labelLineNormalOpt = option.labelLine;
  41422. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  41423. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  41424. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  41425. };
  41426. PieSeriesModel.type = 'series.pie';
  41427. PieSeriesModel.defaultOption = {
  41428. zlevel: 0,
  41429. z: 2,
  41430. legendHoverLink: true,
  41431. colorBy: 'data',
  41432. // 默认全局居中
  41433. center: ['50%', '50%'],
  41434. radius: [0, '75%'],
  41435. // 默认顺时针
  41436. clockwise: true,
  41437. startAngle: 90,
  41438. // 最小角度改为0
  41439. minAngle: 0,
  41440. // If the angle of a sector less than `minShowLabelAngle`,
  41441. // the label will not be displayed.
  41442. minShowLabelAngle: 0,
  41443. // 选中时扇区偏移量
  41444. selectedOffset: 10,
  41445. // 选择模式,默认关闭,可选single,multiple
  41446. // selectedMode: false,
  41447. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  41448. // roseType: null,
  41449. percentPrecision: 2,
  41450. // If still show when all data zero.
  41451. stillShowZeroSum: true,
  41452. // cursor: null,
  41453. left: 0,
  41454. top: 0,
  41455. right: 0,
  41456. bottom: 0,
  41457. width: null,
  41458. height: null,
  41459. label: {
  41460. // color: 'inherit',
  41461. // If rotate around circle
  41462. rotate: 0,
  41463. show: true,
  41464. overflow: 'truncate',
  41465. // 'outer', 'inside', 'center'
  41466. position: 'outer',
  41467. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  41468. alignTo: 'none',
  41469. // Closest distance between label and chart edge.
  41470. // Works only position is 'outer' and alignTo is 'edge'.
  41471. edgeDistance: '25%',
  41472. // Works only position is 'outer' and alignTo is not 'edge'.
  41473. bleedMargin: 10,
  41474. // Distance between text and label line.
  41475. distanceToLabelLine: 5 // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  41476. // 默认使用全局文本样式,详见TEXTSTYLE
  41477. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  41478. },
  41479. // Enabled when label.normal.position is 'outer'
  41480. labelLine: {
  41481. show: true,
  41482. // 引导线两段中的第一段长度
  41483. length: 15,
  41484. // 引导线两段中的第二段长度
  41485. length2: 15,
  41486. smooth: false,
  41487. minTurnAngle: 90,
  41488. maxSurfaceAngle: 90,
  41489. lineStyle: {
  41490. // color: 各异,
  41491. width: 1,
  41492. type: 'solid'
  41493. }
  41494. },
  41495. itemStyle: {
  41496. borderWidth: 1,
  41497. borderJoin: 'round'
  41498. },
  41499. showEmptyCircle: true,
  41500. emptyCircleStyle: {
  41501. color: 'lightgray',
  41502. opacity: 1
  41503. },
  41504. labelLayout: {
  41505. // Hide the overlapped label.
  41506. hideOverlap: true
  41507. },
  41508. emphasis: {
  41509. scale: true,
  41510. scaleSize: 5
  41511. },
  41512. // If use strategy to avoid label overlapping
  41513. avoidLabelOverlap: true,
  41514. // Animation type. Valid values: expansion, scale
  41515. animationType: 'expansion',
  41516. animationDuration: 1000,
  41517. // Animation type when update. Valid values: transition, expansion
  41518. animationTypeUpdate: 'transition',
  41519. animationEasingUpdate: 'cubicInOut',
  41520. animationDurationUpdate: 500,
  41521. animationEasing: 'cubicInOut'
  41522. };
  41523. return PieSeriesModel;
  41524. }(SeriesModel);
  41525. /*
  41526. * Licensed to the Apache Software Foundation (ASF) under one
  41527. * or more contributor license agreements. See the NOTICE file
  41528. * distributed with this work for additional information
  41529. * regarding copyright ownership. The ASF licenses this file
  41530. * to you under the Apache License, Version 2.0 (the
  41531. * "License"); you may not use this file except in compliance
  41532. * with the License. You may obtain a copy of the License at
  41533. *
  41534. * http://www.apache.org/licenses/LICENSE-2.0
  41535. *
  41536. * Unless required by applicable law or agreed to in writing,
  41537. * software distributed under the License is distributed on an
  41538. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41539. * KIND, either express or implied. See the License for the
  41540. * specific language governing permissions and limitations
  41541. * under the License.
  41542. */
  41543. /**
  41544. * AUTO-GENERATED FILE. DO NOT MODIFY.
  41545. */
  41546. /*
  41547. * Licensed to the Apache Software Foundation (ASF) under one
  41548. * or more contributor license agreements. See the NOTICE file
  41549. * distributed with this work for additional information
  41550. * regarding copyright ownership. The ASF licenses this file
  41551. * to you under the Apache License, Version 2.0 (the
  41552. * "License"); you may not use this file except in compliance
  41553. * with the License. You may obtain a copy of the License at
  41554. *
  41555. * http://www.apache.org/licenses/LICENSE-2.0
  41556. *
  41557. * Unless required by applicable law or agreed to in writing,
  41558. * software distributed under the License is distributed on an
  41559. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41560. * KIND, either express or implied. See the License for the
  41561. * specific language governing permissions and limitations
  41562. * under the License.
  41563. */
  41564. function negativeDataFilter(seriesType) {
  41565. return {
  41566. seriesType: seriesType,
  41567. reset: function (seriesModel, ecModel) {
  41568. var data = seriesModel.getData();
  41569. data.filterSelf(function (idx) {
  41570. // handle negative value condition
  41571. var valueDim = data.mapDimension('value');
  41572. var curValue = data.get(valueDim, idx);
  41573. if (typeof curValue === 'number' && !isNaN(curValue) && curValue < 0) {
  41574. return false;
  41575. }
  41576. return true;
  41577. });
  41578. }
  41579. };
  41580. }
  41581. function install$4(registers) {
  41582. registers.registerChartView(PieView);
  41583. registers.registerSeriesModel(PieSeriesModel);
  41584. createLegacyDataSelectAction('pie', registers.registerAction);
  41585. registers.registerLayout(curry(pieLayout, 'pie'));
  41586. registers.registerProcessor(dataFilter('pie'));
  41587. registers.registerProcessor(negativeDataFilter('pie'));
  41588. }
  41589. var ScatterSeriesModel =
  41590. /** @class */
  41591. function (_super) {
  41592. __extends(ScatterSeriesModel, _super);
  41593. function ScatterSeriesModel() {
  41594. var _this = _super !== null && _super.apply(this, arguments) || this;
  41595. _this.type = ScatterSeriesModel.type;
  41596. _this.hasSymbolVisual = true;
  41597. return _this;
  41598. }
  41599. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  41600. return createSeriesData(null, this, {
  41601. useEncodeDefaulter: true
  41602. });
  41603. };
  41604. ScatterSeriesModel.prototype.getProgressive = function () {
  41605. var progressive = this.option.progressive;
  41606. if (progressive == null) {
  41607. // PENDING
  41608. return this.option.large ? 5e3 : this.get('progressive');
  41609. }
  41610. return progressive;
  41611. };
  41612. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  41613. var progressiveThreshold = this.option.progressiveThreshold;
  41614. if (progressiveThreshold == null) {
  41615. // PENDING
  41616. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  41617. }
  41618. return progressiveThreshold;
  41619. };
  41620. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  41621. return selectors.point(data.getItemLayout(dataIndex));
  41622. };
  41623. ScatterSeriesModel.type = 'series.scatter';
  41624. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  41625. ScatterSeriesModel.defaultOption = {
  41626. coordinateSystem: 'cartesian2d',
  41627. zlevel: 0,
  41628. z: 2,
  41629. legendHoverLink: true,
  41630. symbolSize: 10,
  41631. // symbolRotate: null, // 图形旋转控制
  41632. large: false,
  41633. // Available when large is true
  41634. largeThreshold: 2000,
  41635. // cursor: null,
  41636. itemStyle: {
  41637. opacity: 0.8 // color: 各异
  41638. },
  41639. emphasis: {
  41640. scale: true
  41641. },
  41642. // If clip the overflow graphics
  41643. // Works on cartesian / polar series
  41644. clip: true,
  41645. select: {
  41646. itemStyle: {
  41647. borderColor: '#212121'
  41648. }
  41649. },
  41650. universalTransition: {
  41651. divideShape: 'clone'
  41652. } // progressive: null
  41653. };
  41654. return ScatterSeriesModel;
  41655. }(SeriesModel);
  41656. var BOOST_SIZE_THRESHOLD = 4;
  41657. var LargeSymbolPathShape =
  41658. /** @class */
  41659. function () {
  41660. function LargeSymbolPathShape() {}
  41661. return LargeSymbolPathShape;
  41662. }();
  41663. var LargeSymbolPath =
  41664. /** @class */
  41665. function (_super) {
  41666. __extends(LargeSymbolPath, _super);
  41667. function LargeSymbolPath(opts) {
  41668. return _super.call(this, opts) || this;
  41669. }
  41670. LargeSymbolPath.prototype.getDefaultShape = function () {
  41671. return new LargeSymbolPathShape();
  41672. };
  41673. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  41674. var points = shape.points;
  41675. var size = shape.size;
  41676. var symbolProxy = this.symbolProxy;
  41677. var symbolProxyShape = symbolProxy.shape;
  41678. var ctx = path.getContext ? path.getContext() : path;
  41679. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD; // Do draw in afterBrush.
  41680. if (canBoost) {
  41681. this._ctx = ctx;
  41682. return;
  41683. }
  41684. this._ctx = null;
  41685. for (var i = 0; i < points.length;) {
  41686. var x = points[i++];
  41687. var y = points[i++];
  41688. if (isNaN(x) || isNaN(y)) {
  41689. continue;
  41690. }
  41691. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  41692. continue;
  41693. }
  41694. symbolProxyShape.x = x - size[0] / 2;
  41695. symbolProxyShape.y = y - size[1] / 2;
  41696. symbolProxyShape.width = size[0];
  41697. symbolProxyShape.height = size[1];
  41698. symbolProxy.buildPath(path, symbolProxyShape, true);
  41699. }
  41700. };
  41701. LargeSymbolPath.prototype.afterBrush = function () {
  41702. var shape = this.shape;
  41703. var points = shape.points;
  41704. var size = shape.size;
  41705. var ctx = this._ctx;
  41706. if (!ctx) {
  41707. return;
  41708. } // PENDING If style or other canvas status changed?
  41709. for (var i = 0; i < points.length;) {
  41710. var x = points[i++];
  41711. var y = points[i++];
  41712. if (isNaN(x) || isNaN(y)) {
  41713. continue;
  41714. }
  41715. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  41716. continue;
  41717. } // fillRect is faster than building a rect path and draw.
  41718. // And it support light globalCompositeOperation.
  41719. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  41720. }
  41721. };
  41722. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  41723. // TODO ???
  41724. // Consider transform
  41725. var shape = this.shape;
  41726. var points = shape.points;
  41727. var size = shape.size;
  41728. var w = Math.max(size[0], 4);
  41729. var h = Math.max(size[1], 4); // Not consider transform
  41730. // Treat each element as a rect
  41731. // top down traverse
  41732. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  41733. var i = idx * 2;
  41734. var x0 = points[i] - w / 2;
  41735. var y0 = points[i + 1] - h / 2;
  41736. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  41737. return idx;
  41738. }
  41739. }
  41740. return -1;
  41741. };
  41742. return LargeSymbolPath;
  41743. }(Path);
  41744. var LargeSymbolDraw =
  41745. /** @class */
  41746. function () {
  41747. function LargeSymbolDraw() {
  41748. this.group = new Group();
  41749. }
  41750. LargeSymbolDraw.prototype.isPersistent = function () {
  41751. return !this._incremental;
  41752. };
  41753. /**
  41754. * Update symbols draw by new data
  41755. */
  41756. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  41757. this.group.removeAll();
  41758. var symbolEl = new LargeSymbolPath({
  41759. rectHover: true,
  41760. cursor: 'default'
  41761. });
  41762. symbolEl.setShape({
  41763. points: data.getLayout('points')
  41764. });
  41765. this._setCommon(symbolEl, data, false, opt);
  41766. this.group.add(symbolEl);
  41767. this._incremental = null;
  41768. };
  41769. LargeSymbolDraw.prototype.updateLayout = function (data) {
  41770. if (this._incremental) {
  41771. return;
  41772. }
  41773. var points = data.getLayout('points');
  41774. this.group.eachChild(function (child) {
  41775. if (child.startIndex != null) {
  41776. var len = (child.endIndex - child.startIndex) * 2;
  41777. var byteOffset = child.startIndex * 4 * 2;
  41778. points = new Float32Array(points.buffer, byteOffset, len);
  41779. }
  41780. child.setShape('points', points);
  41781. });
  41782. };
  41783. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  41784. this.group.removeAll();
  41785. this._clearIncremental(); // Only use incremental displayables when data amount is larger than 2 million.
  41786. // PENDING Incremental data?
  41787. if (data.count() > 2e6) {
  41788. if (!this._incremental) {
  41789. this._incremental = new IncrementalDisplayable({
  41790. silent: true
  41791. });
  41792. }
  41793. this.group.add(this._incremental);
  41794. } else {
  41795. this._incremental = null;
  41796. }
  41797. };
  41798. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  41799. var symbolEl;
  41800. if (this._incremental) {
  41801. symbolEl = new LargeSymbolPath();
  41802. this._incremental.addDisplayable(symbolEl, true);
  41803. } else {
  41804. symbolEl = new LargeSymbolPath({
  41805. rectHover: true,
  41806. cursor: 'default',
  41807. startIndex: taskParams.start,
  41808. endIndex: taskParams.end
  41809. });
  41810. symbolEl.incremental = true;
  41811. this.group.add(symbolEl);
  41812. }
  41813. symbolEl.setShape({
  41814. points: data.getLayout('points')
  41815. });
  41816. this._setCommon(symbolEl, data, !!this._incremental, opt);
  41817. };
  41818. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, isIncremental, opt) {
  41819. var hostModel = data.hostModel;
  41820. opt = opt || {};
  41821. var size = data.getVisual('symbolSize');
  41822. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  41823. symbolEl.softClipShape = opt.clipShape || null; // Create symbolProxy to build path for each data
  41824. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0); // Use symbolProxy setColor method
  41825. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  41826. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  41827. symbolEl.useStyle( // Draw shadow when doing fillRect is extremely slow.
  41828. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  41829. var globalStyle = data.getVisual('style');
  41830. var visualColor = globalStyle && globalStyle.fill;
  41831. if (visualColor) {
  41832. symbolEl.setColor(visualColor);
  41833. }
  41834. if (!isIncremental) {
  41835. var ecData_1 = getECData(symbolEl); // Enable tooltip
  41836. // PENDING May have performance issue when path is extremely large
  41837. ecData_1.seriesIndex = hostModel.seriesIndex;
  41838. symbolEl.on('mousemove', function (e) {
  41839. ecData_1.dataIndex = null;
  41840. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  41841. if (dataIndex >= 0) {
  41842. // Provide dataIndex for tooltip
  41843. ecData_1.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  41844. }
  41845. });
  41846. }
  41847. };
  41848. LargeSymbolDraw.prototype.remove = function () {
  41849. this._clearIncremental();
  41850. this._incremental = null;
  41851. this.group.removeAll();
  41852. };
  41853. LargeSymbolDraw.prototype._clearIncremental = function () {
  41854. var incremental = this._incremental;
  41855. if (incremental) {
  41856. incremental.clearDisplaybles();
  41857. }
  41858. };
  41859. return LargeSymbolDraw;
  41860. }();
  41861. var ScatterView =
  41862. /** @class */
  41863. function (_super) {
  41864. __extends(ScatterView, _super);
  41865. function ScatterView() {
  41866. var _this = _super !== null && _super.apply(this, arguments) || this;
  41867. _this.type = ScatterView.type;
  41868. return _this;
  41869. }
  41870. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  41871. var data = seriesModel.getData();
  41872. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41873. symbolDraw.updateData(data, {
  41874. // TODO
  41875. // If this parameter should be a shape or a bounding volume
  41876. // shape will be more general.
  41877. // But bounding volume like bounding rect will be much faster in the contain calculation
  41878. clipShape: this._getClipShape(seriesModel)
  41879. });
  41880. this._finished = true;
  41881. };
  41882. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  41883. var data = seriesModel.getData();
  41884. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41885. symbolDraw.incrementalPrepareUpdate(data);
  41886. this._finished = false;
  41887. };
  41888. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  41889. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  41890. clipShape: this._getClipShape(seriesModel)
  41891. });
  41892. this._finished = taskParams.end === seriesModel.getData().count();
  41893. };
  41894. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  41895. var data = seriesModel.getData(); // Must mark group dirty and make sure the incremental layer will be cleared
  41896. // PENDING
  41897. this.group.dirty();
  41898. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  41899. return {
  41900. update: true
  41901. };
  41902. } else {
  41903. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  41904. if (res.progress) {
  41905. res.progress({
  41906. start: 0,
  41907. end: data.count(),
  41908. count: data.count()
  41909. }, data);
  41910. }
  41911. this._symbolDraw.updateLayout(data);
  41912. }
  41913. };
  41914. ScatterView.prototype._getClipShape = function (seriesModel) {
  41915. var coordSys = seriesModel.coordinateSystem;
  41916. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  41917. return seriesModel.get('clip', true) ? clipArea : null;
  41918. };
  41919. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  41920. var symbolDraw = this._symbolDraw;
  41921. var pipelineContext = seriesModel.pipelineContext;
  41922. var isLargeDraw = pipelineContext.large;
  41923. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  41924. symbolDraw && symbolDraw.remove();
  41925. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  41926. this._isLargeDraw = isLargeDraw;
  41927. this.group.removeAll();
  41928. }
  41929. this.group.add(symbolDraw.group);
  41930. return symbolDraw;
  41931. };
  41932. ScatterView.prototype.remove = function (ecModel, api) {
  41933. this._symbolDraw && this._symbolDraw.remove(true);
  41934. this._symbolDraw = null;
  41935. };
  41936. ScatterView.prototype.dispose = function () {};
  41937. ScatterView.type = 'scatter';
  41938. return ScatterView;
  41939. }(ChartView);
  41940. var GridModel =
  41941. /** @class */
  41942. function (_super) {
  41943. __extends(GridModel, _super);
  41944. function GridModel() {
  41945. return _super !== null && _super.apply(this, arguments) || this;
  41946. }
  41947. GridModel.type = 'grid';
  41948. GridModel.dependencies = ['xAxis', 'yAxis'];
  41949. GridModel.layoutMode = 'box';
  41950. GridModel.defaultOption = {
  41951. show: false,
  41952. zlevel: 0,
  41953. z: 0,
  41954. left: '10%',
  41955. top: 60,
  41956. right: '10%',
  41957. bottom: 70,
  41958. // If grid size contain label
  41959. containLabel: false,
  41960. // width: {totalWidth} - left - right,
  41961. // height: {totalHeight} - top - bottom,
  41962. backgroundColor: 'rgba(0,0,0,0)',
  41963. borderWidth: 1,
  41964. borderColor: '#ccc'
  41965. };
  41966. return GridModel;
  41967. }(ComponentModel);
  41968. var CartesianAxisModel =
  41969. /** @class */
  41970. function (_super) {
  41971. __extends(CartesianAxisModel, _super);
  41972. function CartesianAxisModel() {
  41973. return _super !== null && _super.apply(this, arguments) || this;
  41974. }
  41975. CartesianAxisModel.prototype.getCoordSysModel = function () {
  41976. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  41977. };
  41978. CartesianAxisModel.type = 'cartesian2dAxis';
  41979. return CartesianAxisModel;
  41980. }(ComponentModel);
  41981. mixin(CartesianAxisModel, AxisModelCommonMixin);
  41982. var defaultOption = {
  41983. show: true,
  41984. zlevel: 0,
  41985. z: 0,
  41986. // Inverse the axis.
  41987. inverse: false,
  41988. // Axis name displayed.
  41989. name: '',
  41990. // 'start' | 'middle' | 'end'
  41991. nameLocation: 'end',
  41992. // By degree. By default auto rotate by nameLocation.
  41993. nameRotate: null,
  41994. nameTruncate: {
  41995. maxWidth: null,
  41996. ellipsis: '...',
  41997. placeholder: '.'
  41998. },
  41999. // Use global text style by default.
  42000. nameTextStyle: {},
  42001. // The gap between axisName and axisLine.
  42002. nameGap: 15,
  42003. // Default `false` to support tooltip.
  42004. silent: false,
  42005. // Default `false` to avoid legacy user event listener fail.
  42006. triggerEvent: false,
  42007. tooltip: {
  42008. show: false
  42009. },
  42010. axisPointer: {},
  42011. axisLine: {
  42012. show: true,
  42013. onZero: true,
  42014. onZeroAxisIndex: null,
  42015. lineStyle: {
  42016. color: '#6E7079',
  42017. width: 1,
  42018. type: 'solid'
  42019. },
  42020. // The arrow at both ends the the axis.
  42021. symbol: ['none', 'none'],
  42022. symbolSize: [10, 15]
  42023. },
  42024. axisTick: {
  42025. show: true,
  42026. // Whether axisTick is inside the grid or outside the grid.
  42027. inside: false,
  42028. // The length of axisTick.
  42029. length: 5,
  42030. lineStyle: {
  42031. width: 1
  42032. }
  42033. },
  42034. axisLabel: {
  42035. show: true,
  42036. // Whether axisLabel is inside the grid or outside the grid.
  42037. inside: false,
  42038. rotate: 0,
  42039. // true | false | null/undefined (auto)
  42040. showMinLabel: null,
  42041. // true | false | null/undefined (auto)
  42042. showMaxLabel: null,
  42043. margin: 8,
  42044. // formatter: null,
  42045. fontSize: 12
  42046. },
  42047. splitLine: {
  42048. show: true,
  42049. lineStyle: {
  42050. color: ['#E0E6F1'],
  42051. width: 1,
  42052. type: 'solid'
  42053. }
  42054. },
  42055. splitArea: {
  42056. show: false,
  42057. areaStyle: {
  42058. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  42059. }
  42060. }
  42061. };
  42062. var categoryAxis = merge({
  42063. // The gap at both ends of the axis. For categoryAxis, boolean.
  42064. boundaryGap: true,
  42065. // Set false to faster category collection.
  42066. deduplication: null,
  42067. // splitArea: {
  42068. // show: false
  42069. // },
  42070. splitLine: {
  42071. show: false
  42072. },
  42073. axisTick: {
  42074. // If tick is align with label when boundaryGap is true
  42075. alignWithLabel: false,
  42076. interval: 'auto'
  42077. },
  42078. axisLabel: {
  42079. interval: 'auto'
  42080. }
  42081. }, defaultOption);
  42082. var valueAxis = merge({
  42083. boundaryGap: [0, 0],
  42084. axisLine: {
  42085. // Not shown when other axis is categoryAxis in cartesian
  42086. show: 'auto'
  42087. },
  42088. axisTick: {
  42089. // Not shown when other axis is categoryAxis in cartesian
  42090. show: 'auto'
  42091. },
  42092. // TODO
  42093. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  42094. splitNumber: 5,
  42095. minorTick: {
  42096. // Minor tick, not available for cateogry axis.
  42097. show: false,
  42098. // Split number of minor ticks. The value should be in range of (0, 100)
  42099. splitNumber: 5,
  42100. // Lenght of minor tick
  42101. length: 3,
  42102. // Line style
  42103. lineStyle: {// Default to be same with axisTick
  42104. }
  42105. },
  42106. minorSplitLine: {
  42107. show: false,
  42108. lineStyle: {
  42109. color: '#F4F7FD',
  42110. width: 1
  42111. }
  42112. }
  42113. }, defaultOption);
  42114. var timeAxis = merge({
  42115. scale: true,
  42116. splitNumber: 6,
  42117. axisLabel: {
  42118. // To eliminate labels that are not nice
  42119. showMinLabel: false,
  42120. showMaxLabel: false,
  42121. rich: {
  42122. primary: {
  42123. fontWeight: 'bold'
  42124. }
  42125. }
  42126. },
  42127. splitLine: {
  42128. show: false
  42129. }
  42130. }, valueAxis);
  42131. var logAxis = defaults({
  42132. scale: true,
  42133. logBase: 10
  42134. }, valueAxis);
  42135. var axisDefault = {
  42136. category: categoryAxis,
  42137. value: valueAxis,
  42138. time: timeAxis,
  42139. log: logAxis
  42140. };
  42141. /*
  42142. * Licensed to the Apache Software Foundation (ASF) under one
  42143. * or more contributor license agreements. See the NOTICE file
  42144. * distributed with this work for additional information
  42145. * regarding copyright ownership. The ASF licenses this file
  42146. * to you under the Apache License, Version 2.0 (the
  42147. * "License"); you may not use this file except in compliance
  42148. * with the License. You may obtain a copy of the License at
  42149. *
  42150. * http://www.apache.org/licenses/LICENSE-2.0
  42151. *
  42152. * Unless required by applicable law or agreed to in writing,
  42153. * software distributed under the License is distributed on an
  42154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42155. * KIND, either express or implied. See the License for the
  42156. * specific language governing permissions and limitations
  42157. * under the License.
  42158. */
  42159. /**
  42160. * AUTO-GENERATED FILE. DO NOT MODIFY.
  42161. */
  42162. /*
  42163. * Licensed to the Apache Software Foundation (ASF) under one
  42164. * or more contributor license agreements. See the NOTICE file
  42165. * distributed with this work for additional information
  42166. * regarding copyright ownership. The ASF licenses this file
  42167. * to you under the Apache License, Version 2.0 (the
  42168. * "License"); you may not use this file except in compliance
  42169. * with the License. You may obtain a copy of the License at
  42170. *
  42171. * http://www.apache.org/licenses/LICENSE-2.0
  42172. *
  42173. * Unless required by applicable law or agreed to in writing,
  42174. * software distributed under the License is distributed on an
  42175. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42176. * KIND, either express or implied. See the License for the
  42177. * specific language governing permissions and limitations
  42178. * under the License.
  42179. */
  42180. var AXIS_TYPES = {
  42181. value: 1,
  42182. category: 1,
  42183. time: 1,
  42184. log: 1
  42185. };
  42186. /**
  42187. * Generate sub axis model class
  42188. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  42189. */
  42190. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  42191. each(AXIS_TYPES, function (v, axisType) {
  42192. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  42193. var AxisModel =
  42194. /** @class */
  42195. function (_super) {
  42196. __extends(AxisModel, _super);
  42197. function AxisModel() {
  42198. var _this = _super !== null && _super.apply(this, arguments) || this;
  42199. _this.type = axisName + 'Axis.' + axisType;
  42200. return _this;
  42201. }
  42202. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  42203. var layoutMode = fetchLayoutMode(this);
  42204. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  42205. var themeModel = ecModel.getTheme();
  42206. merge(option, themeModel.get(axisType + 'Axis'));
  42207. merge(option, this.getDefaultOption());
  42208. option.type = getAxisType(option);
  42209. if (layoutMode) {
  42210. mergeLayoutParam(option, inputPositionParams, layoutMode);
  42211. }
  42212. };
  42213. AxisModel.prototype.optionUpdated = function () {
  42214. var thisOption = this.option;
  42215. if (thisOption.type === 'category') {
  42216. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  42217. }
  42218. };
  42219. /**
  42220. * Should not be called before all of 'getInitailData' finished.
  42221. * Because categories are collected during initializing data.
  42222. */
  42223. AxisModel.prototype.getCategories = function (rawData) {
  42224. var option = this.option; // FIXME
  42225. // warning if called before all of 'getInitailData' finished.
  42226. if (option.type === 'category') {
  42227. if (rawData) {
  42228. return option.data;
  42229. }
  42230. return this.__ordinalMeta.categories;
  42231. }
  42232. };
  42233. AxisModel.prototype.getOrdinalMeta = function () {
  42234. return this.__ordinalMeta;
  42235. };
  42236. AxisModel.type = axisName + 'Axis.' + axisType;
  42237. AxisModel.defaultOption = defaultOption;
  42238. return AxisModel;
  42239. }(BaseAxisModelClass);
  42240. registers.registerComponentModel(AxisModel);
  42241. });
  42242. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  42243. }
  42244. function getAxisType(option) {
  42245. // Default axis with data is category axis
  42246. return option.type || (option.data ? 'category' : 'value');
  42247. }
  42248. var Cartesian =
  42249. /** @class */
  42250. function () {
  42251. function Cartesian(name) {
  42252. this.type = 'cartesian';
  42253. this._dimList = [];
  42254. this._axes = {};
  42255. this.name = name || '';
  42256. }
  42257. Cartesian.prototype.getAxis = function (dim) {
  42258. return this._axes[dim];
  42259. };
  42260. Cartesian.prototype.getAxes = function () {
  42261. return map(this._dimList, function (dim) {
  42262. return this._axes[dim];
  42263. }, this);
  42264. };
  42265. Cartesian.prototype.getAxesByScale = function (scaleType) {
  42266. scaleType = scaleType.toLowerCase();
  42267. return filter(this.getAxes(), function (axis) {
  42268. return axis.scale.type === scaleType;
  42269. });
  42270. };
  42271. Cartesian.prototype.addAxis = function (axis) {
  42272. var dim = axis.dim;
  42273. this._axes[dim] = axis;
  42274. this._dimList.push(dim);
  42275. };
  42276. return Cartesian;
  42277. }();
  42278. var cartesian2DDimensions = ['x', 'y'];
  42279. function canCalculateAffineTransform(scale) {
  42280. return scale.type === 'interval' || scale.type === 'time';
  42281. }
  42282. var Cartesian2D =
  42283. /** @class */
  42284. function (_super) {
  42285. __extends(Cartesian2D, _super);
  42286. function Cartesian2D() {
  42287. var _this = _super !== null && _super.apply(this, arguments) || this;
  42288. _this.type = 'cartesian2d';
  42289. _this.dimensions = cartesian2DDimensions;
  42290. return _this;
  42291. }
  42292. /**
  42293. * Calculate an affine transform matrix if two axes are time or value.
  42294. * It's mainly for accelartion on the large time series data.
  42295. */
  42296. Cartesian2D.prototype.calcAffineTransform = function () {
  42297. this._transform = this._invTransform = null;
  42298. var xAxisScale = this.getAxis('x').scale;
  42299. var yAxisScale = this.getAxis('y').scale;
  42300. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  42301. return;
  42302. }
  42303. var xScaleExtent = xAxisScale.getExtent();
  42304. var yScaleExtent = yAxisScale.getExtent();
  42305. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  42306. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  42307. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  42308. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  42309. if (!xScaleSpan || !yScaleSpan) {
  42310. return;
  42311. } // Accelerate data to point calculation on the special large time series data.
  42312. var scaleX = (end[0] - start[0]) / xScaleSpan;
  42313. var scaleY = (end[1] - start[1]) / yScaleSpan;
  42314. var translateX = start[0] - xScaleExtent[0] * scaleX;
  42315. var translateY = start[1] - yScaleExtent[0] * scaleY;
  42316. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  42317. this._invTransform = invert([], m);
  42318. };
  42319. /**
  42320. * Base axis will be used on stacking.
  42321. */
  42322. Cartesian2D.prototype.getBaseAxis = function () {
  42323. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  42324. };
  42325. Cartesian2D.prototype.containPoint = function (point) {
  42326. var axisX = this.getAxis('x');
  42327. var axisY = this.getAxis('y');
  42328. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  42329. };
  42330. Cartesian2D.prototype.containData = function (data) {
  42331. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  42332. };
  42333. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  42334. out = out || [];
  42335. var xVal = data[0];
  42336. var yVal = data[1]; // Fast path
  42337. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  42338. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  42339. return applyTransform(out, data, this._transform);
  42340. }
  42341. var xAxis = this.getAxis('x');
  42342. var yAxis = this.getAxis('y');
  42343. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  42344. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  42345. return out;
  42346. };
  42347. Cartesian2D.prototype.clampData = function (data, out) {
  42348. var xScale = this.getAxis('x').scale;
  42349. var yScale = this.getAxis('y').scale;
  42350. var xAxisExtent = xScale.getExtent();
  42351. var yAxisExtent = yScale.getExtent();
  42352. var x = xScale.parse(data[0]);
  42353. var y = yScale.parse(data[1]);
  42354. out = out || [];
  42355. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  42356. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  42357. return out;
  42358. };
  42359. Cartesian2D.prototype.pointToData = function (point, clamp) {
  42360. var out = [];
  42361. if (this._invTransform) {
  42362. return applyTransform(out, point, this._invTransform);
  42363. }
  42364. var xAxis = this.getAxis('x');
  42365. var yAxis = this.getAxis('y');
  42366. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  42367. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  42368. return out;
  42369. };
  42370. Cartesian2D.prototype.getOtherAxis = function (axis) {
  42371. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  42372. };
  42373. /**
  42374. * Get rect area of cartesian.
  42375. * Area will have a contain function to determine if a point is in the coordinate system.
  42376. */
  42377. Cartesian2D.prototype.getArea = function () {
  42378. var xExtent = this.getAxis('x').getGlobalExtent();
  42379. var yExtent = this.getAxis('y').getGlobalExtent();
  42380. var x = Math.min(xExtent[0], xExtent[1]);
  42381. var y = Math.min(yExtent[0], yExtent[1]);
  42382. var width = Math.max(xExtent[0], xExtent[1]) - x;
  42383. var height = Math.max(yExtent[0], yExtent[1]) - y;
  42384. return new BoundingRect(x, y, width, height);
  42385. };
  42386. return Cartesian2D;
  42387. }(Cartesian);
  42388. var Axis2D =
  42389. /** @class */
  42390. function (_super) {
  42391. __extends(Axis2D, _super);
  42392. function Axis2D(dim, scale, coordExtent, axisType, position) {
  42393. var _this = _super.call(this, dim, scale, coordExtent) || this;
  42394. /**
  42395. * Index of axis, can be used as key
  42396. * Injected outside.
  42397. */
  42398. _this.index = 0;
  42399. _this.type = axisType || 'value';
  42400. _this.position = position || 'bottom';
  42401. return _this;
  42402. }
  42403. Axis2D.prototype.isHorizontal = function () {
  42404. var position = this.position;
  42405. return position === 'top' || position === 'bottom';
  42406. };
  42407. /**
  42408. * Each item cooresponds to this.getExtent(), which
  42409. * means globalExtent[0] may greater than globalExtent[1],
  42410. * unless `asc` is input.
  42411. *
  42412. * @param {boolean} [asc]
  42413. * @return {Array.<number>}
  42414. */
  42415. Axis2D.prototype.getGlobalExtent = function (asc) {
  42416. var ret = this.getExtent();
  42417. ret[0] = this.toGlobalCoord(ret[0]);
  42418. ret[1] = this.toGlobalCoord(ret[1]);
  42419. asc && ret[0] > ret[1] && ret.reverse();
  42420. return ret;
  42421. };
  42422. Axis2D.prototype.pointToData = function (point, clamp) {
  42423. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  42424. };
  42425. /**
  42426. * Set ordinalSortInfo
  42427. * @param info new OrdinalSortInfo
  42428. */
  42429. Axis2D.prototype.setCategorySortInfo = function (info) {
  42430. if (this.type !== 'category') {
  42431. return false;
  42432. }
  42433. this.model.option.categorySortInfo = info;
  42434. this.scale.setSortInfo(info);
  42435. };
  42436. return Axis2D;
  42437. }(Axis);
  42438. /**
  42439. * Can only be called after coordinate system creation stage.
  42440. * (Can be called before coordinate system update stage).
  42441. */
  42442. function layout$1(gridModel, axisModel, opt) {
  42443. opt = opt || {};
  42444. var grid = gridModel.coordinateSystem;
  42445. var axis = axisModel.axis;
  42446. var layout = {};
  42447. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  42448. var rawAxisPosition = axis.position;
  42449. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  42450. var axisDim = axis.dim;
  42451. var rect = grid.getRect();
  42452. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  42453. var idx = {
  42454. left: 0,
  42455. right: 1,
  42456. top: 0,
  42457. bottom: 1,
  42458. onZero: 2
  42459. };
  42460. var axisOffset = axisModel.get('offset') || 0;
  42461. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  42462. if (otherAxisOnZeroOf) {
  42463. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  42464. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  42465. } // Axis position
  42466. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  42467. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  42468. var dirMap = {
  42469. top: -1,
  42470. bottom: 1,
  42471. left: -1,
  42472. right: 1
  42473. };
  42474. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  42475. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  42476. if (axisModel.get(['axisTick', 'inside'])) {
  42477. layout.tickDirection = -layout.tickDirection;
  42478. }
  42479. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  42480. layout.labelDirection = -layout.labelDirection;
  42481. } // Special label rotation
  42482. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  42483. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  42484. layout.z2 = 1;
  42485. return layout;
  42486. }
  42487. function isCartesian2DSeries(seriesModel) {
  42488. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  42489. }
  42490. function findAxisModels(seriesModel) {
  42491. var axisModelMap = {
  42492. xAxisModel: null,
  42493. yAxisModel: null
  42494. };
  42495. each(axisModelMap, function (v, key) {
  42496. var axisType = key.replace(/Model$/, '');
  42497. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  42498. if ("development" !== 'production') {
  42499. if (!axisModel) {
  42500. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  42501. }
  42502. }
  42503. axisModelMap[key] = axisModel;
  42504. });
  42505. return axisModelMap;
  42506. }
  42507. var Grid =
  42508. /** @class */
  42509. function () {
  42510. function Grid(gridModel, ecModel, api) {
  42511. // FIXME:TS where used (different from registered type 'cartesian2d')?
  42512. this.type = 'grid';
  42513. this._coordsMap = {};
  42514. this._coordsList = [];
  42515. this._axesMap = {};
  42516. this._axesList = [];
  42517. this.axisPointerEnabled = true;
  42518. this.dimensions = cartesian2DDimensions;
  42519. this._initCartesian(gridModel, ecModel, api);
  42520. this.model = gridModel;
  42521. }
  42522. Grid.prototype.getRect = function () {
  42523. return this._rect;
  42524. };
  42525. Grid.prototype.update = function (ecModel, api) {
  42526. var axesMap = this._axesMap;
  42527. this._updateScale(ecModel, this.model);
  42528. each(axesMap.x, function (xAxis) {
  42529. niceScaleExtent(xAxis.scale, xAxis.model);
  42530. });
  42531. each(axesMap.y, function (yAxis) {
  42532. niceScaleExtent(yAxis.scale, yAxis.model);
  42533. }); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  42534. var onZeroRecords = {};
  42535. each(axesMap.x, function (xAxis) {
  42536. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  42537. });
  42538. each(axesMap.y, function (yAxis) {
  42539. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  42540. }); // Resize again if containLabel is enabled
  42541. // FIXME It may cause getting wrong grid size in data processing stage
  42542. this.resize(this.model, api);
  42543. };
  42544. /**
  42545. * Resize the grid
  42546. */
  42547. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  42548. var boxLayoutParams = gridModel.getBoxLayoutParams();
  42549. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  42550. var gridRect = getLayoutRect(boxLayoutParams, {
  42551. width: api.getWidth(),
  42552. height: api.getHeight()
  42553. });
  42554. this._rect = gridRect;
  42555. var axesList = this._axesList;
  42556. adjustAxes(); // Minus label size
  42557. if (isContainLabel) {
  42558. each(axesList, function (axis) {
  42559. if (!axis.model.get(['axisLabel', 'inside'])) {
  42560. var labelUnionRect = estimateLabelUnionRect(axis);
  42561. if (labelUnionRect) {
  42562. var dim = axis.isHorizontal() ? 'height' : 'width';
  42563. var margin = axis.model.get(['axisLabel', 'margin']);
  42564. gridRect[dim] -= labelUnionRect[dim] + margin;
  42565. if (axis.position === 'top') {
  42566. gridRect.y += labelUnionRect.height + margin;
  42567. } else if (axis.position === 'left') {
  42568. gridRect.x += labelUnionRect.width + margin;
  42569. }
  42570. }
  42571. }
  42572. });
  42573. adjustAxes();
  42574. }
  42575. each(this._coordsList, function (coord) {
  42576. // Calculate affine matrix to accelerate the data to point transform.
  42577. // If all the axes scales are time or value.
  42578. coord.calcAffineTransform();
  42579. });
  42580. function adjustAxes() {
  42581. each(axesList, function (axis) {
  42582. var isHorizontal = axis.isHorizontal();
  42583. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  42584. var idx = axis.inverse ? 1 : 0;
  42585. axis.setExtent(extent[idx], extent[1 - idx]);
  42586. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  42587. });
  42588. }
  42589. };
  42590. Grid.prototype.getAxis = function (dim, axisIndex) {
  42591. var axesMapOnDim = this._axesMap[dim];
  42592. if (axesMapOnDim != null) {
  42593. return axesMapOnDim[axisIndex || 0]; // if (axisIndex == null) {
  42594. // Find first axis
  42595. // for (let name in axesMapOnDim) {
  42596. // if (axesMapOnDim.hasOwnProperty(name)) {
  42597. // return axesMapOnDim[name];
  42598. // }
  42599. // }
  42600. // }
  42601. // return axesMapOnDim[axisIndex];
  42602. }
  42603. };
  42604. Grid.prototype.getAxes = function () {
  42605. return this._axesList.slice();
  42606. };
  42607. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  42608. if (xAxisIndex != null && yAxisIndex != null) {
  42609. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42610. return this._coordsMap[key];
  42611. }
  42612. if (isObject(xAxisIndex)) {
  42613. yAxisIndex = xAxisIndex.yAxisIndex;
  42614. xAxisIndex = xAxisIndex.xAxisIndex;
  42615. }
  42616. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  42617. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  42618. return coordList[i];
  42619. }
  42620. }
  42621. };
  42622. Grid.prototype.getCartesians = function () {
  42623. return this._coordsList.slice();
  42624. };
  42625. /**
  42626. * @implements
  42627. */
  42628. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  42629. var target = this._findConvertTarget(finder);
  42630. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  42631. };
  42632. /**
  42633. * @implements
  42634. */
  42635. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  42636. var target = this._findConvertTarget(finder);
  42637. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  42638. };
  42639. Grid.prototype._findConvertTarget = function (finder) {
  42640. var seriesModel = finder.seriesModel;
  42641. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  42642. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  42643. var gridModel = finder.gridModel;
  42644. var coordsList = this._coordsList;
  42645. var cartesian;
  42646. var axis;
  42647. if (seriesModel) {
  42648. cartesian = seriesModel.coordinateSystem;
  42649. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  42650. } else if (xAxisModel && yAxisModel) {
  42651. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42652. } else if (xAxisModel) {
  42653. axis = this.getAxis('x', xAxisModel.componentIndex);
  42654. } else if (yAxisModel) {
  42655. axis = this.getAxis('y', yAxisModel.componentIndex);
  42656. } // Lowest priority.
  42657. else if (gridModel) {
  42658. var grid = gridModel.coordinateSystem;
  42659. if (grid === this) {
  42660. cartesian = this._coordsList[0];
  42661. }
  42662. }
  42663. return {
  42664. cartesian: cartesian,
  42665. axis: axis
  42666. };
  42667. };
  42668. /**
  42669. * @implements
  42670. */
  42671. Grid.prototype.containPoint = function (point) {
  42672. var coord = this._coordsList[0];
  42673. if (coord) {
  42674. return coord.containPoint(point);
  42675. }
  42676. };
  42677. /**
  42678. * Initialize cartesian coordinate systems
  42679. */
  42680. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  42681. var _this = this;
  42682. var grid = this;
  42683. var axisPositionUsed = {
  42684. left: false,
  42685. right: false,
  42686. top: false,
  42687. bottom: false
  42688. };
  42689. var axesMap = {
  42690. x: {},
  42691. y: {}
  42692. };
  42693. var axesCount = {
  42694. x: 0,
  42695. y: 0
  42696. }; /// Create axis
  42697. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  42698. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  42699. if (!axesCount.x || !axesCount.y) {
  42700. // Roll back when there no either x or y axis
  42701. this._axesMap = {};
  42702. this._axesList = [];
  42703. return;
  42704. }
  42705. this._axesMap = axesMap; /// Create cartesian2d
  42706. each(axesMap.x, function (xAxis, xAxisIndex) {
  42707. each(axesMap.y, function (yAxis, yAxisIndex) {
  42708. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42709. var cartesian = new Cartesian2D(key);
  42710. cartesian.master = _this;
  42711. cartesian.model = gridModel;
  42712. _this._coordsMap[key] = cartesian;
  42713. _this._coordsList.push(cartesian);
  42714. cartesian.addAxis(xAxis);
  42715. cartesian.addAxis(yAxis);
  42716. });
  42717. });
  42718. function createAxisCreator(dimName) {
  42719. return function (axisModel, idx) {
  42720. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  42721. return;
  42722. }
  42723. var axisPosition = axisModel.get('position');
  42724. if (dimName === 'x') {
  42725. // Fix position
  42726. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  42727. // Default bottom of X
  42728. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  42729. }
  42730. } else {
  42731. // Fix position
  42732. if (axisPosition !== 'left' && axisPosition !== 'right') {
  42733. // Default left of Y
  42734. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  42735. }
  42736. }
  42737. axisPositionUsed[axisPosition] = true;
  42738. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  42739. var isCategory = axis.type === 'category';
  42740. axis.onBand = isCategory && axisModel.get('boundaryGap');
  42741. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  42742. axisModel.axis = axis; // Inject axisModel into axis
  42743. axis.model = axisModel; // Inject grid info axis
  42744. axis.grid = grid; // Index of axis, can be used as key
  42745. axis.index = idx;
  42746. grid._axesList.push(axis);
  42747. axesMap[dimName][idx] = axis;
  42748. axesCount[dimName]++;
  42749. };
  42750. }
  42751. };
  42752. /**
  42753. * Update cartesian properties from series.
  42754. */
  42755. Grid.prototype._updateScale = function (ecModel, gridModel) {
  42756. // Reset scale
  42757. each(this._axesList, function (axis) {
  42758. axis.scale.setExtent(Infinity, -Infinity);
  42759. if (axis.type === 'category') {
  42760. var categorySortInfo = axis.model.get('categorySortInfo');
  42761. axis.scale.setSortInfo(categorySortInfo);
  42762. }
  42763. });
  42764. ecModel.eachSeries(function (seriesModel) {
  42765. if (isCartesian2DSeries(seriesModel)) {
  42766. var axesModelMap = findAxisModels(seriesModel);
  42767. var xAxisModel = axesModelMap.xAxisModel;
  42768. var yAxisModel = axesModelMap.yAxisModel;
  42769. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  42770. return;
  42771. }
  42772. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42773. var data = seriesModel.getData();
  42774. var xAxis = cartesian.getAxis('x');
  42775. var yAxis = cartesian.getAxis('y');
  42776. if (data.type === 'list') {
  42777. unionExtent(data, xAxis);
  42778. unionExtent(data, yAxis);
  42779. }
  42780. }
  42781. }, this);
  42782. function unionExtent(data, axis) {
  42783. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  42784. axis.scale.unionExtentFromData(data, dim);
  42785. });
  42786. }
  42787. };
  42788. /**
  42789. * @param dim 'x' or 'y' or 'auto' or null/undefined
  42790. */
  42791. Grid.prototype.getTooltipAxes = function (dim) {
  42792. var baseAxes = [];
  42793. var otherAxes = [];
  42794. each(this.getCartesians(), function (cartesian) {
  42795. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  42796. var otherAxis = cartesian.getOtherAxis(baseAxis);
  42797. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  42798. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  42799. });
  42800. return {
  42801. baseAxes: baseAxes,
  42802. otherAxes: otherAxes
  42803. };
  42804. };
  42805. Grid.create = function (ecModel, api) {
  42806. var grids = [];
  42807. ecModel.eachComponent('grid', function (gridModel, idx) {
  42808. var grid = new Grid(gridModel, ecModel, api);
  42809. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  42810. // should be performed in create stage.
  42811. grid.resize(gridModel, api, true);
  42812. gridModel.coordinateSystem = grid;
  42813. grids.push(grid);
  42814. }); // Inject the coordinateSystems into seriesModel
  42815. ecModel.eachSeries(function (seriesModel) {
  42816. if (!isCartesian2DSeries(seriesModel)) {
  42817. return;
  42818. }
  42819. var axesModelMap = findAxisModels(seriesModel);
  42820. var xAxisModel = axesModelMap.xAxisModel;
  42821. var yAxisModel = axesModelMap.yAxisModel;
  42822. var gridModel = xAxisModel.getCoordSysModel();
  42823. if ("development" !== 'production') {
  42824. if (!gridModel) {
  42825. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  42826. }
  42827. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  42828. throw new Error('xAxis and yAxis must use the same grid');
  42829. }
  42830. }
  42831. var grid = gridModel.coordinateSystem;
  42832. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42833. });
  42834. return grids;
  42835. }; // For deciding which dimensions to use when creating list data
  42836. Grid.dimensions = cartesian2DDimensions;
  42837. return Grid;
  42838. }();
  42839. /**
  42840. * Check if the axis is used in the specified grid.
  42841. */
  42842. function isAxisUsedInTheGrid(axisModel, gridModel) {
  42843. return axisModel.getCoordSysModel() === gridModel;
  42844. }
  42845. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  42846. onZeroRecords) {
  42847. axis.getAxesOnZeroOf = function () {
  42848. // TODO: onZero of multiple axes.
  42849. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  42850. }; // onZero can not be enabled in these two situations:
  42851. // 1. When any other axis is a category axis.
  42852. // 2. When no axis is cross 0 point.
  42853. var otherAxes = axesMap[otherAxisDim];
  42854. var otherAxisOnZeroOf;
  42855. var axisModel = axis.model;
  42856. var onZero = axisModel.get(['axisLine', 'onZero']);
  42857. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  42858. if (!onZero) {
  42859. return;
  42860. } // If target axis is specified.
  42861. if (onZeroAxisIndex != null) {
  42862. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  42863. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  42864. }
  42865. } else {
  42866. // Find the first available other axis.
  42867. for (var idx in otherAxes) {
  42868. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  42869. // if both onZero, the two Y axes overlap.
  42870. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  42871. otherAxisOnZeroOf = otherAxes[idx];
  42872. break;
  42873. }
  42874. }
  42875. }
  42876. if (otherAxisOnZeroOf) {
  42877. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  42878. }
  42879. function getOnZeroRecordKey(axis) {
  42880. return axis.dim + '_' + axis.index;
  42881. }
  42882. }
  42883. function canOnZeroToAxis(axis) {
  42884. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  42885. }
  42886. function updateAxisTransform(axis, coordBase) {
  42887. var axisExtent = axis.getExtent();
  42888. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  42889. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  42890. return coord + coordBase;
  42891. } : function (coord) {
  42892. return axisExtentSum - coord + coordBase;
  42893. };
  42894. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  42895. return coord - coordBase;
  42896. } : function (coord) {
  42897. return axisExtentSum - coord + coordBase;
  42898. };
  42899. }
  42900. var PI$5 = Math.PI;
  42901. /**
  42902. * A final axis is translated and rotated from a "standard axis".
  42903. * So opt.position and opt.rotation is required.
  42904. *
  42905. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  42906. * for example: (0, 0) ------------> (0, 50)
  42907. *
  42908. * nameDirection or tickDirection or labelDirection is 1 means tick
  42909. * or label is below the standard axis, whereas is -1 means above
  42910. * the standard axis. labelOffset means offset between label and axis,
  42911. * which is useful when 'onZero', where axisLabel is in the grid and
  42912. * label in outside grid.
  42913. *
  42914. * Tips: like always,
  42915. * positive rotation represents anticlockwise, and negative rotation
  42916. * represents clockwise.
  42917. * The direction of position coordinate is the same as the direction
  42918. * of screen coordinate.
  42919. *
  42920. * Do not need to consider axis 'inverse', which is auto processed by
  42921. * axis extent.
  42922. */
  42923. var AxisBuilder =
  42924. /** @class */
  42925. function () {
  42926. function AxisBuilder(axisModel, opt) {
  42927. this.group = new Group();
  42928. this.opt = opt;
  42929. this.axisModel = axisModel; // Default value
  42930. defaults(opt, {
  42931. labelOffset: 0,
  42932. nameDirection: 1,
  42933. tickDirection: 1,
  42934. labelDirection: 1,
  42935. silent: true,
  42936. handleAutoShown: function () {
  42937. return true;
  42938. }
  42939. }); // FIXME Not use a seperate text group?
  42940. var transformGroup = new Group({
  42941. x: opt.position[0],
  42942. y: opt.position[1],
  42943. rotation: opt.rotation
  42944. }); // this.group.add(transformGroup);
  42945. // this._transformGroup = transformGroup;
  42946. transformGroup.updateTransform();
  42947. this._transformGroup = transformGroup;
  42948. }
  42949. AxisBuilder.prototype.hasBuilder = function (name) {
  42950. return !!builders[name];
  42951. };
  42952. AxisBuilder.prototype.add = function (name) {
  42953. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  42954. };
  42955. AxisBuilder.prototype.getGroup = function () {
  42956. return this.group;
  42957. };
  42958. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  42959. var rotationDiff = remRadian(textRotation - axisRotation);
  42960. var textAlign;
  42961. var textVerticalAlign;
  42962. if (isRadianAroundZero(rotationDiff)) {
  42963. // Label is parallel with axis line.
  42964. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  42965. textAlign = 'center';
  42966. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  42967. // Label is inverse parallel with axis line.
  42968. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  42969. textAlign = 'center';
  42970. } else {
  42971. textVerticalAlign = 'middle';
  42972. if (rotationDiff > 0 && rotationDiff < PI$5) {
  42973. textAlign = direction > 0 ? 'right' : 'left';
  42974. } else {
  42975. textAlign = direction > 0 ? 'left' : 'right';
  42976. }
  42977. }
  42978. return {
  42979. rotation: rotationDiff,
  42980. textAlign: textAlign,
  42981. textVerticalAlign: textVerticalAlign
  42982. };
  42983. };
  42984. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  42985. var eventData = {
  42986. componentType: axisModel.mainType,
  42987. componentIndex: axisModel.componentIndex
  42988. };
  42989. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  42990. return eventData;
  42991. };
  42992. AxisBuilder.isLabelSilent = function (axisModel) {
  42993. var tooltipOpt = axisModel.get('tooltip');
  42994. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  42995. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  42996. };
  42997. return AxisBuilder;
  42998. }();
  42999. var builders = {
  43000. axisLine: function (opt, axisModel, group, transformGroup) {
  43001. var shown = axisModel.get(['axisLine', 'show']);
  43002. if (shown === 'auto' && opt.handleAutoShown) {
  43003. shown = opt.handleAutoShown('axisLine');
  43004. }
  43005. if (!shown) {
  43006. return;
  43007. }
  43008. var extent = axisModel.axis.getExtent();
  43009. var matrix = transformGroup.transform;
  43010. var pt1 = [extent[0], 0];
  43011. var pt2 = [extent[1], 0];
  43012. if (matrix) {
  43013. applyTransform(pt1, pt1, matrix);
  43014. applyTransform(pt2, pt2, matrix);
  43015. }
  43016. var lineStyle = extend({
  43017. lineCap: 'round'
  43018. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  43019. var line = new Line({
  43020. // Id for animation
  43021. subPixelOptimize: true,
  43022. shape: {
  43023. x1: pt1[0],
  43024. y1: pt1[1],
  43025. x2: pt2[0],
  43026. y2: pt2[1]
  43027. },
  43028. style: lineStyle,
  43029. strokeContainThreshold: opt.strokeContainThreshold || 5,
  43030. silent: true,
  43031. z2: 1
  43032. });
  43033. line.anid = 'line';
  43034. group.add(line);
  43035. var arrows = axisModel.get(['axisLine', 'symbol']);
  43036. if (arrows != null) {
  43037. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  43038. if (typeof arrows === 'string') {
  43039. // Use the same arrow for start and end point
  43040. arrows = [arrows, arrows];
  43041. }
  43042. if (typeof arrowSize === 'string' || typeof arrowSize === 'number') {
  43043. // Use the same size for width and height
  43044. arrowSize = [arrowSize, arrowSize];
  43045. }
  43046. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  43047. var symbolWidth_1 = arrowSize[0];
  43048. var symbolHeight_1 = arrowSize[1];
  43049. each([{
  43050. rotate: opt.rotation + Math.PI / 2,
  43051. offset: arrowOffset[0],
  43052. r: 0
  43053. }, {
  43054. rotate: opt.rotation - Math.PI / 2,
  43055. offset: arrowOffset[1],
  43056. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  43057. }], function (point, index) {
  43058. if (arrows[index] !== 'none' && arrows[index] != null) {
  43059. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  43060. var r = point.r + point.offset;
  43061. symbol.attr({
  43062. rotation: point.rotate,
  43063. x: pt1[0] + r * Math.cos(opt.rotation),
  43064. y: pt1[1] - r * Math.sin(opt.rotation),
  43065. silent: true,
  43066. z2: 11
  43067. });
  43068. group.add(symbol);
  43069. }
  43070. });
  43071. }
  43072. },
  43073. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  43074. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  43075. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  43076. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  43077. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection);
  43078. },
  43079. axisName: function (opt, axisModel, group, transformGroup) {
  43080. var name = retrieve(opt.axisName, axisModel.get('name'));
  43081. if (!name) {
  43082. return;
  43083. }
  43084. var nameLocation = axisModel.get('nameLocation');
  43085. var nameDirection = opt.nameDirection;
  43086. var textStyleModel = axisModel.getModel('nameTextStyle');
  43087. var gap = axisModel.get('nameGap') || 0;
  43088. var extent = axisModel.axis.getExtent();
  43089. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  43090. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  43091. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  43092. var labelLayout;
  43093. var nameRotation = axisModel.get('nameRotate');
  43094. if (nameRotation != null) {
  43095. nameRotation = nameRotation * PI$5 / 180; // To radian.
  43096. }
  43097. var axisNameAvailableWidth;
  43098. if (isNameLocationCenter(nameLocation)) {
  43099. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  43100. nameDirection);
  43101. } else {
  43102. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  43103. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  43104. if (axisNameAvailableWidth != null) {
  43105. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  43106. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  43107. }
  43108. }
  43109. var textFont = textStyleModel.getFont();
  43110. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  43111. var ellipsis = truncateOpt.ellipsis;
  43112. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  43113. var textEl = new ZRText({
  43114. x: pos[0],
  43115. y: pos[1],
  43116. rotation: labelLayout.rotation,
  43117. silent: AxisBuilder.isLabelSilent(axisModel),
  43118. style: createTextStyle(textStyleModel, {
  43119. text: name,
  43120. font: textFont,
  43121. overflow: 'truncate',
  43122. width: maxWidth,
  43123. ellipsis: ellipsis,
  43124. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  43125. align: textStyleModel.get('align') || labelLayout.textAlign,
  43126. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  43127. }),
  43128. z2: 1
  43129. });
  43130. setTooltipConfig({
  43131. el: textEl,
  43132. componentModel: axisModel,
  43133. itemName: name
  43134. });
  43135. textEl.__fullText = name; // Id for animation
  43136. textEl.anid = 'name';
  43137. if (axisModel.get('triggerEvent')) {
  43138. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  43139. eventData.targetType = 'axisName';
  43140. eventData.name = name;
  43141. getECData(textEl).eventData = eventData;
  43142. } // FIXME
  43143. transformGroup.add(textEl);
  43144. textEl.updateTransform();
  43145. group.add(textEl);
  43146. textEl.decomposeTransform();
  43147. }
  43148. };
  43149. function endTextLayout(rotation, textPosition, textRotate, extent) {
  43150. var rotationDiff = remRadian(textRotate - rotation);
  43151. var textAlign;
  43152. var textVerticalAlign;
  43153. var inverse = extent[0] > extent[1];
  43154. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  43155. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  43156. textVerticalAlign = onLeft ? 'bottom' : 'top';
  43157. textAlign = 'center';
  43158. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  43159. textVerticalAlign = onLeft ? 'top' : 'bottom';
  43160. textAlign = 'center';
  43161. } else {
  43162. textVerticalAlign = 'middle';
  43163. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  43164. textAlign = onLeft ? 'left' : 'right';
  43165. } else {
  43166. textAlign = onLeft ? 'right' : 'left';
  43167. }
  43168. }
  43169. return {
  43170. rotation: rotationDiff,
  43171. textAlign: textAlign,
  43172. textVerticalAlign: textVerticalAlign
  43173. };
  43174. }
  43175. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  43176. if (shouldShowAllLabels(axisModel.axis)) {
  43177. return;
  43178. } // If min or max are user set, we need to check
  43179. // If the tick on min(max) are overlap on their neighbour tick
  43180. // If they are overlapped, we need to hide the min(max) tick label
  43181. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  43182. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  43183. // Have not consider onBand yet, where tick els is more than label els.
  43184. labelEls = labelEls || [];
  43185. tickEls = tickEls || [];
  43186. var firstLabel = labelEls[0];
  43187. var nextLabel = labelEls[1];
  43188. var lastLabel = labelEls[labelEls.length - 1];
  43189. var prevLabel = labelEls[labelEls.length - 2];
  43190. var firstTick = tickEls[0];
  43191. var nextTick = tickEls[1];
  43192. var lastTick = tickEls[tickEls.length - 1];
  43193. var prevTick = tickEls[tickEls.length - 2];
  43194. if (showMinLabel === false) {
  43195. ignoreEl(firstLabel);
  43196. ignoreEl(firstTick);
  43197. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  43198. if (showMinLabel) {
  43199. ignoreEl(nextLabel);
  43200. ignoreEl(nextTick);
  43201. } else {
  43202. ignoreEl(firstLabel);
  43203. ignoreEl(firstTick);
  43204. }
  43205. }
  43206. if (showMaxLabel === false) {
  43207. ignoreEl(lastLabel);
  43208. ignoreEl(lastTick);
  43209. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  43210. if (showMaxLabel) {
  43211. ignoreEl(prevLabel);
  43212. ignoreEl(prevTick);
  43213. } else {
  43214. ignoreEl(lastLabel);
  43215. ignoreEl(lastTick);
  43216. }
  43217. }
  43218. }
  43219. function ignoreEl(el) {
  43220. el && (el.ignore = true);
  43221. }
  43222. function isTwoLabelOverlapped(current, next) {
  43223. // current and next has the same rotation.
  43224. var firstRect = current && current.getBoundingRect().clone();
  43225. var nextRect = next && next.getBoundingRect().clone();
  43226. if (!firstRect || !nextRect) {
  43227. return;
  43228. } // When checking intersect of two rotated labels, we use mRotationBack
  43229. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  43230. var mRotationBack = identity([]);
  43231. rotate(mRotationBack, mRotationBack, -current.rotation);
  43232. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  43233. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  43234. return firstRect.intersect(nextRect);
  43235. }
  43236. function isNameLocationCenter(nameLocation) {
  43237. return nameLocation === 'middle' || nameLocation === 'center';
  43238. }
  43239. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  43240. var tickEls = [];
  43241. var pt1 = [];
  43242. var pt2 = [];
  43243. for (var i = 0; i < ticksCoords.length; i++) {
  43244. var tickCoord = ticksCoords[i].coord;
  43245. pt1[0] = tickCoord;
  43246. pt1[1] = 0;
  43247. pt2[0] = tickCoord;
  43248. pt2[1] = tickEndCoord;
  43249. if (tickTransform) {
  43250. applyTransform(pt1, pt1, tickTransform);
  43251. applyTransform(pt2, pt2, tickTransform);
  43252. } // Tick line, Not use group transform to have better line draw
  43253. var tickEl = new Line({
  43254. subPixelOptimize: true,
  43255. shape: {
  43256. x1: pt1[0],
  43257. y1: pt1[1],
  43258. x2: pt2[0],
  43259. y2: pt2[1]
  43260. },
  43261. style: tickLineStyle,
  43262. z2: 2,
  43263. autoBatch: true,
  43264. silent: true
  43265. });
  43266. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  43267. tickEls.push(tickEl);
  43268. }
  43269. return tickEls;
  43270. }
  43271. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  43272. var axis = axisModel.axis;
  43273. var tickModel = axisModel.getModel('axisTick');
  43274. var shown = tickModel.get('show');
  43275. if (shown === 'auto' && opt.handleAutoShown) {
  43276. shown = opt.handleAutoShown('axisTick');
  43277. }
  43278. if (!shown || axis.scale.isBlank()) {
  43279. return;
  43280. }
  43281. var lineStyleModel = tickModel.getModel('lineStyle');
  43282. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  43283. var ticksCoords = axis.getTicksCoords();
  43284. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  43285. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43286. }), 'ticks');
  43287. for (var i = 0; i < ticksEls.length; i++) {
  43288. group.add(ticksEls[i]);
  43289. }
  43290. return ticksEls;
  43291. }
  43292. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  43293. var axis = axisModel.axis;
  43294. var minorTickModel = axisModel.getModel('minorTick');
  43295. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  43296. return;
  43297. }
  43298. var minorTicksCoords = axis.getMinorTicksCoords();
  43299. if (!minorTicksCoords.length) {
  43300. return;
  43301. }
  43302. var lineStyleModel = minorTickModel.getModel('lineStyle');
  43303. var tickEndCoord = tickDirection * minorTickModel.get('length');
  43304. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  43305. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43306. }));
  43307. for (var i = 0; i < minorTicksCoords.length; i++) {
  43308. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  43309. for (var k = 0; k < minorTicksEls.length; k++) {
  43310. group.add(minorTicksEls[k]);
  43311. }
  43312. }
  43313. }
  43314. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  43315. var axis = axisModel.axis;
  43316. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  43317. if (!show || axis.scale.isBlank()) {
  43318. return;
  43319. }
  43320. var labelModel = axisModel.getModel('axisLabel');
  43321. var labelMargin = labelModel.get('margin');
  43322. var labels = axis.getViewLabels(); // Special label rotate.
  43323. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  43324. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  43325. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  43326. var labelEls = [];
  43327. var silent = AxisBuilder.isLabelSilent(axisModel);
  43328. var triggerEvent = axisModel.get('triggerEvent');
  43329. each(labels, function (labelItem, index) {
  43330. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  43331. var formattedLabel = labelItem.formattedLabel;
  43332. var rawLabel = labelItem.rawLabel;
  43333. var itemLabelModel = labelModel;
  43334. if (rawCategoryData && rawCategoryData[tickValue]) {
  43335. var rawCategoryItem = rawCategoryData[tickValue];
  43336. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  43337. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  43338. }
  43339. }
  43340. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  43341. var tickCoord = axis.dataToCoord(tickValue);
  43342. var textEl = new ZRText({
  43343. x: tickCoord,
  43344. y: opt.labelOffset + opt.labelDirection * labelMargin,
  43345. rotation: labelLayout.rotation,
  43346. silent: silent,
  43347. z2: 10,
  43348. style: createTextStyle(itemLabelModel, {
  43349. text: formattedLabel,
  43350. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  43351. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  43352. fill: typeof textColor === 'function' ? textColor( // (1) In category axis with data zoom, tick is not the original
  43353. // index of axis.data. So tick should not be exposed to user
  43354. // in category axis.
  43355. // (2) Compatible with previous version, which always use formatted label as
  43356. // input. But in interval scale the formatted label is like '223,445', which
  43357. // maked user repalce ','. So we modify it to return original val but remain
  43358. // it as 'string' to avoid error in replacing.
  43359. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  43360. })
  43361. });
  43362. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  43363. if (triggerEvent) {
  43364. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  43365. eventData.targetType = 'axisLabel';
  43366. eventData.value = rawLabel;
  43367. getECData(textEl).eventData = eventData;
  43368. } // FIXME
  43369. transformGroup.add(textEl);
  43370. textEl.updateTransform();
  43371. labelEls.push(textEl);
  43372. group.add(textEl);
  43373. textEl.decomposeTransform();
  43374. });
  43375. return labelEls;
  43376. }
  43377. // allAxesInfo should be updated when setOption performed.
  43378. function collect(ecModel, api) {
  43379. var result = {
  43380. /**
  43381. * key: makeKey(axis.model)
  43382. * value: {
  43383. * axis,
  43384. * coordSys,
  43385. * axisPointerModel,
  43386. * triggerTooltip,
  43387. * involveSeries,
  43388. * snap,
  43389. * seriesModels,
  43390. * seriesDataCount
  43391. * }
  43392. */
  43393. axesInfo: {},
  43394. seriesInvolved: false,
  43395. /**
  43396. * key: makeKey(coordSys.model)
  43397. * value: Object: key makeKey(axis.model), value: axisInfo
  43398. */
  43399. coordSysAxesInfo: {},
  43400. coordSysMap: {}
  43401. };
  43402. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  43403. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  43404. return result;
  43405. }
  43406. function collectAxesInfo(result, ecModel, api) {
  43407. var globalTooltipModel = ecModel.getComponent('tooltip');
  43408. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  43409. var linksOption = globalAxisPointerModel.get('link', true) || [];
  43410. var linkGroups = []; // Collect axes info.
  43411. each(api.getCoordinateSystems(), function (coordSys) {
  43412. // Some coordinate system do not support axes, like geo.
  43413. if (!coordSys.axisPointerEnabled) {
  43414. return;
  43415. }
  43416. var coordSysKey = makeKey(coordSys.model);
  43417. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  43418. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convienent way to show axisPointer
  43419. // for user. So we enable seting tooltip on coordSys model.
  43420. var coordSysModel = coordSys.model;
  43421. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  43422. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  43423. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  43424. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  43425. // show but axisPointer will show as normal.
  43426. && baseTooltipModel.get('show')) {
  43427. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  43428. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  43429. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  43430. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  43431. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  43432. if (triggerAxis || cross) {
  43433. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  43434. }
  43435. if (cross) {
  43436. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  43437. }
  43438. } // fromTooltip: true | false | 'cross'
  43439. // triggerTooltip: true | false | null
  43440. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  43441. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  43442. var axisPointerShow = axisPointerModel.get('show');
  43443. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  43444. return;
  43445. }
  43446. if (triggerTooltip == null) {
  43447. triggerTooltip = axisPointerModel.get('triggerTooltip');
  43448. }
  43449. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  43450. var snap = axisPointerModel.get('snap');
  43451. var axisKey = makeKey(axis.model);
  43452. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  43453. var axisInfo = result.axesInfo[axisKey] = {
  43454. key: axisKey,
  43455. axis: axis,
  43456. coordSys: coordSys,
  43457. axisPointerModel: axisPointerModel,
  43458. triggerTooltip: triggerTooltip,
  43459. involveSeries: involveSeries,
  43460. snap: snap,
  43461. useHandle: isHandleTrigger(axisPointerModel),
  43462. seriesModels: [],
  43463. linkGroup: null
  43464. };
  43465. axesInfoInCoordSys[axisKey] = axisInfo;
  43466. result.seriesInvolved = result.seriesInvolved || involveSeries;
  43467. var groupIndex = getLinkGroupIndex(linksOption, axis);
  43468. if (groupIndex != null) {
  43469. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  43470. axesInfo: {}
  43471. });
  43472. linkGroup.axesInfo[axisKey] = axisInfo;
  43473. linkGroup.mapper = linksOption[groupIndex].mapper;
  43474. axisInfo.linkGroup = linkGroup;
  43475. }
  43476. }
  43477. });
  43478. }
  43479. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  43480. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  43481. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  43482. var volatileOption = {};
  43483. each(fields, function (field) {
  43484. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  43485. }); // category axis do not auto snap, otherwise some tick that do not
  43486. // has value can not be hovered. value/time/log axis default snap if
  43487. // triggered from tooltip and trigger tooltip.
  43488. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatibel with previous behavior, tooltip axis do not show label by default.
  43489. // Only these properties can be overrided from tooltip to axisPointer.
  43490. if (tooltipAxisPointerModel.get('type') === 'cross') {
  43491. volatileOption.type = 'line';
  43492. }
  43493. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  43494. labelOption.show == null && (labelOption.show = false);
  43495. if (fromTooltip === 'cross') {
  43496. // When 'cross', both axes show labels.
  43497. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  43498. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  43499. // (cross style is dashed by default)
  43500. if (!triggerTooltip) {
  43501. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  43502. crossStyle && defaults(labelOption, crossStyle.textStyle);
  43503. }
  43504. }
  43505. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  43506. }
  43507. function collectSeriesInfo(result, ecModel) {
  43508. // Prepare data for axis trigger
  43509. ecModel.eachSeries(function (seriesModel) {
  43510. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  43511. var coordSys = seriesModel.coordinateSystem;
  43512. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  43513. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  43514. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  43515. return;
  43516. }
  43517. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  43518. var axis = axisInfo.axis;
  43519. if (coordSys.getAxis(axis.dim) === axis) {
  43520. axisInfo.seriesModels.push(seriesModel);
  43521. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  43522. axisInfo.seriesDataCount += seriesModel.getData().count();
  43523. }
  43524. });
  43525. });
  43526. }
  43527. /**
  43528. * For example:
  43529. * {
  43530. * axisPointer: {
  43531. * links: [{
  43532. * xAxisIndex: [2, 4],
  43533. * yAxisIndex: 'all'
  43534. * }, {
  43535. * xAxisId: ['a5', 'a7'],
  43536. * xAxisName: 'xxx'
  43537. * }]
  43538. * }
  43539. * }
  43540. */
  43541. function getLinkGroupIndex(linksOption, axis) {
  43542. var axisModel = axis.model;
  43543. var dim = axis.dim;
  43544. for (var i = 0; i < linksOption.length; i++) {
  43545. var linkOption = linksOption[i] || {};
  43546. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  43547. return i;
  43548. }
  43549. }
  43550. }
  43551. function checkPropInLink(linkPropValue, axisPropValue) {
  43552. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  43553. }
  43554. function fixValue(axisModel) {
  43555. var axisInfo = getAxisInfo(axisModel);
  43556. if (!axisInfo) {
  43557. return;
  43558. }
  43559. var axisPointerModel = axisInfo.axisPointerModel;
  43560. var scale = axisInfo.axis.scale;
  43561. var option = axisPointerModel.option;
  43562. var status = axisPointerModel.get('status');
  43563. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  43564. if (value != null) {
  43565. value = scale.parse(value);
  43566. }
  43567. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  43568. // and status should be initialized.
  43569. if (status == null) {
  43570. option.status = useHandle ? 'show' : 'hide';
  43571. }
  43572. var extent = scale.getExtent().slice();
  43573. extent[0] > extent[1] && extent.reverse();
  43574. if ( // Pick a value on axis when initializing.
  43575. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  43576. // where we should re-pick a value to keep `handle` displaying normally.
  43577. || value > extent[1]) {
  43578. // Make handle displayed on the end of the axis when init, which looks better.
  43579. value = extent[1];
  43580. }
  43581. if (value < extent[0]) {
  43582. value = extent[0];
  43583. }
  43584. option.value = value;
  43585. if (useHandle) {
  43586. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  43587. }
  43588. }
  43589. function getAxisInfo(axisModel) {
  43590. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  43591. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  43592. }
  43593. function getAxisPointerModel(axisModel) {
  43594. var axisInfo = getAxisInfo(axisModel);
  43595. return axisInfo && axisInfo.axisPointerModel;
  43596. }
  43597. function isHandleTrigger(axisPointerModel) {
  43598. return !!axisPointerModel.get(['handle', 'show']);
  43599. }
  43600. /**
  43601. * @param {module:echarts/model/Model} model
  43602. * @return {string} unique key
  43603. */
  43604. function makeKey(model) {
  43605. return model.type + '||' + model.id;
  43606. }
  43607. var axisPointerClazz = {};
  43608. /**
  43609. * Base class of AxisView.
  43610. */
  43611. var AxisView =
  43612. /** @class */
  43613. function (_super) {
  43614. __extends(AxisView, _super);
  43615. function AxisView() {
  43616. var _this = _super !== null && _super.apply(this, arguments) || this;
  43617. _this.type = AxisView.type;
  43618. return _this;
  43619. }
  43620. /**
  43621. * @override
  43622. */
  43623. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43624. // FIXME
  43625. // This process should proformed after coordinate systems updated
  43626. // (axis scale updated), and should be performed each time update.
  43627. // So put it here temporarily, although it is not appropriate to
  43628. // put a model-writing procedure in `view`.
  43629. this.axisPointerClass && fixValue(axisModel);
  43630. _super.prototype.render.apply(this, arguments);
  43631. this._doUpdateAxisPointerClass(axisModel, api, true);
  43632. };
  43633. /**
  43634. * Action handler.
  43635. */
  43636. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  43637. this._doUpdateAxisPointerClass(axisModel, api, false);
  43638. };
  43639. /**
  43640. * @override
  43641. */
  43642. AxisView.prototype.remove = function (ecModel, api) {
  43643. var axisPointer = this._axisPointer;
  43644. axisPointer && axisPointer.remove(api);
  43645. };
  43646. /**
  43647. * @override
  43648. */
  43649. AxisView.prototype.dispose = function (ecModel, api) {
  43650. this._disposeAxisPointer(api);
  43651. _super.prototype.dispose.apply(this, arguments);
  43652. };
  43653. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  43654. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  43655. if (!Clazz) {
  43656. return;
  43657. }
  43658. var axisPointerModel = getAxisPointerModel(axisModel);
  43659. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  43660. };
  43661. AxisView.prototype._disposeAxisPointer = function (api) {
  43662. this._axisPointer && this._axisPointer.dispose(api);
  43663. this._axisPointer = null;
  43664. };
  43665. AxisView.registerAxisPointerClass = function (type, clazz) {
  43666. if ("development" !== 'production') {
  43667. if (axisPointerClazz[type]) {
  43668. throw new Error('axisPointer ' + type + ' exists');
  43669. }
  43670. }
  43671. axisPointerClazz[type] = clazz;
  43672. };
  43673. AxisView.getAxisPointerClass = function (type) {
  43674. return type && axisPointerClazz[type];
  43675. };
  43676. AxisView.type = 'axis';
  43677. return AxisView;
  43678. }(ComponentView);
  43679. var inner$6 = makeInner();
  43680. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  43681. var axis = axisModel.axis;
  43682. if (axis.scale.isBlank()) {
  43683. return;
  43684. } // TODO: TYPE
  43685. var splitAreaModel = axisModel.getModel('splitArea');
  43686. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  43687. var areaColors = areaStyleModel.get('color');
  43688. var gridRect = gridModel.coordinateSystem.getRect();
  43689. var ticksCoords = axis.getTicksCoords({
  43690. tickModel: splitAreaModel,
  43691. clamp: true
  43692. });
  43693. if (!ticksCoords.length) {
  43694. return;
  43695. } // For Making appropriate splitArea animation, the color and anid
  43696. // should be corresponding to previous one if possible.
  43697. var areaColorsLen = areaColors.length;
  43698. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  43699. var newSplitAreaColors = createHashMap();
  43700. var colorIndex = 0;
  43701. if (lastSplitAreaColors) {
  43702. for (var i = 0; i < ticksCoords.length; i++) {
  43703. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  43704. if (cIndex != null) {
  43705. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  43706. break;
  43707. }
  43708. }
  43709. }
  43710. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  43711. var areaStyle = areaStyleModel.getAreaStyle();
  43712. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  43713. for (var i = 1; i < ticksCoords.length; i++) {
  43714. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43715. var x = void 0;
  43716. var y = void 0;
  43717. var width = void 0;
  43718. var height = void 0;
  43719. if (axis.isHorizontal()) {
  43720. x = prev;
  43721. y = gridRect.y;
  43722. width = tickCoord - x;
  43723. height = gridRect.height;
  43724. prev = x + width;
  43725. } else {
  43726. x = gridRect.x;
  43727. y = prev;
  43728. width = gridRect.width;
  43729. height = tickCoord - y;
  43730. prev = y + height;
  43731. }
  43732. var tickValue = ticksCoords[i - 1].tickValue;
  43733. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  43734. axisGroup.add(new Rect({
  43735. anid: tickValue != null ? 'area_' + tickValue : null,
  43736. shape: {
  43737. x: x,
  43738. y: y,
  43739. width: width,
  43740. height: height
  43741. },
  43742. style: defaults({
  43743. fill: areaColors[colorIndex]
  43744. }, areaStyle),
  43745. autoBatch: true,
  43746. silent: true
  43747. }));
  43748. colorIndex = (colorIndex + 1) % areaColorsLen;
  43749. }
  43750. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  43751. }
  43752. function rectCoordAxisHandleRemove(axisView) {
  43753. inner$6(axisView).splitAreaColors = null;
  43754. }
  43755. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  43756. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  43757. var CartesianAxisView =
  43758. /** @class */
  43759. function (_super) {
  43760. __extends(CartesianAxisView, _super);
  43761. function CartesianAxisView() {
  43762. var _this = _super !== null && _super.apply(this, arguments) || this;
  43763. _this.type = CartesianAxisView.type;
  43764. _this.axisPointerClass = 'CartesianAxisPointer';
  43765. return _this;
  43766. }
  43767. /**
  43768. * @override
  43769. */
  43770. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43771. this.group.removeAll();
  43772. var oldAxisGroup = this._axisGroup;
  43773. this._axisGroup = new Group();
  43774. this.group.add(this._axisGroup);
  43775. if (!axisModel.get('show')) {
  43776. return;
  43777. }
  43778. var gridModel = axisModel.getCoordSysModel();
  43779. var layout = layout$1(gridModel, axisModel);
  43780. var axisBuilder = new AxisBuilder(axisModel, extend({
  43781. handleAutoShown: function (elementType) {
  43782. var cartesians = gridModel.coordinateSystem.getCartesians();
  43783. for (var i = 0; i < cartesians.length; i++) {
  43784. var otherAxisType = cartesians[i].getOtherAxis(axisModel.axis).type;
  43785. if (otherAxisType === 'value' || otherAxisType === 'log') {
  43786. // Still show axis tick or axisLine if other axis is value / log
  43787. return true;
  43788. }
  43789. } // Not show axisTick or axisLine if other axis is category / time
  43790. return false;
  43791. }
  43792. }, layout));
  43793. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  43794. this._axisGroup.add(axisBuilder.getGroup());
  43795. each(selfBuilderAttrs, function (name) {
  43796. if (axisModel.get([name, 'show'])) {
  43797. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  43798. }
  43799. }, this); // THIS is a special case for bar racing chart.
  43800. // Update the axis label from the natural initial layout to
  43801. // sorted layout should has no animation.
  43802. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  43803. if (!isInitialSortFromBarRacing) {
  43804. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  43805. }
  43806. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  43807. };
  43808. CartesianAxisView.prototype.remove = function () {
  43809. rectCoordAxisHandleRemove(this);
  43810. };
  43811. CartesianAxisView.type = 'cartesianAxis';
  43812. return CartesianAxisView;
  43813. }(AxisView);
  43814. var axisElementBuilders = {
  43815. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43816. var axis = axisModel.axis;
  43817. if (axis.scale.isBlank()) {
  43818. return;
  43819. }
  43820. var splitLineModel = axisModel.getModel('splitLine');
  43821. var lineStyleModel = splitLineModel.getModel('lineStyle');
  43822. var lineColors = lineStyleModel.get('color');
  43823. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  43824. var gridRect = gridModel.coordinateSystem.getRect();
  43825. var isHorizontal = axis.isHorizontal();
  43826. var lineCount = 0;
  43827. var ticksCoords = axis.getTicksCoords({
  43828. tickModel: splitLineModel
  43829. });
  43830. var p1 = [];
  43831. var p2 = [];
  43832. var lineStyle = lineStyleModel.getLineStyle();
  43833. for (var i = 0; i < ticksCoords.length; i++) {
  43834. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43835. if (isHorizontal) {
  43836. p1[0] = tickCoord;
  43837. p1[1] = gridRect.y;
  43838. p2[0] = tickCoord;
  43839. p2[1] = gridRect.y + gridRect.height;
  43840. } else {
  43841. p1[0] = gridRect.x;
  43842. p1[1] = tickCoord;
  43843. p2[0] = gridRect.x + gridRect.width;
  43844. p2[1] = tickCoord;
  43845. }
  43846. var colorIndex = lineCount++ % lineColors.length;
  43847. var tickValue = ticksCoords[i].tickValue;
  43848. axisGroup.add(new Line({
  43849. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  43850. subPixelOptimize: true,
  43851. autoBatch: true,
  43852. shape: {
  43853. x1: p1[0],
  43854. y1: p1[1],
  43855. x2: p2[0],
  43856. y2: p2[1]
  43857. },
  43858. style: defaults({
  43859. stroke: lineColors[colorIndex]
  43860. }, lineStyle),
  43861. silent: true
  43862. }));
  43863. }
  43864. },
  43865. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43866. var axis = axisModel.axis;
  43867. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  43868. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  43869. var gridRect = gridModel.coordinateSystem.getRect();
  43870. var isHorizontal = axis.isHorizontal();
  43871. var minorTicksCoords = axis.getMinorTicksCoords();
  43872. if (!minorTicksCoords.length) {
  43873. return;
  43874. }
  43875. var p1 = [];
  43876. var p2 = [];
  43877. var lineStyle = lineStyleModel.getLineStyle();
  43878. for (var i = 0; i < minorTicksCoords.length; i++) {
  43879. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  43880. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  43881. if (isHorizontal) {
  43882. p1[0] = tickCoord;
  43883. p1[1] = gridRect.y;
  43884. p2[0] = tickCoord;
  43885. p2[1] = gridRect.y + gridRect.height;
  43886. } else {
  43887. p1[0] = gridRect.x;
  43888. p1[1] = tickCoord;
  43889. p2[0] = gridRect.x + gridRect.width;
  43890. p2[1] = tickCoord;
  43891. }
  43892. axisGroup.add(new Line({
  43893. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  43894. subPixelOptimize: true,
  43895. autoBatch: true,
  43896. shape: {
  43897. x1: p1[0],
  43898. y1: p1[1],
  43899. x2: p2[0],
  43900. y2: p2[1]
  43901. },
  43902. style: lineStyle,
  43903. silent: true
  43904. }));
  43905. }
  43906. }
  43907. },
  43908. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  43909. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  43910. }
  43911. };
  43912. var CartesianXAxisView =
  43913. /** @class */
  43914. function (_super) {
  43915. __extends(CartesianXAxisView, _super);
  43916. function CartesianXAxisView() {
  43917. var _this = _super !== null && _super.apply(this, arguments) || this;
  43918. _this.type = CartesianXAxisView.type;
  43919. return _this;
  43920. }
  43921. CartesianXAxisView.type = 'xAxis';
  43922. return CartesianXAxisView;
  43923. }(CartesianAxisView);
  43924. var CartesianYAxisView =
  43925. /** @class */
  43926. function (_super) {
  43927. __extends(CartesianYAxisView, _super);
  43928. function CartesianYAxisView() {
  43929. var _this = _super !== null && _super.apply(this, arguments) || this;
  43930. _this.type = CartesianXAxisView.type;
  43931. return _this;
  43932. }
  43933. CartesianYAxisView.type = 'yAxis';
  43934. return CartesianYAxisView;
  43935. }(CartesianAxisView);
  43936. var GridView =
  43937. /** @class */
  43938. function (_super) {
  43939. __extends(GridView, _super);
  43940. function GridView() {
  43941. var _this = _super !== null && _super.apply(this, arguments) || this;
  43942. _this.type = 'grid';
  43943. return _this;
  43944. }
  43945. GridView.prototype.render = function (gridModel, ecModel) {
  43946. this.group.removeAll();
  43947. if (gridModel.get('show')) {
  43948. this.group.add(new Rect({
  43949. shape: gridModel.coordinateSystem.getRect(),
  43950. style: defaults({
  43951. fill: gridModel.get('backgroundColor')
  43952. }, gridModel.getItemStyle()),
  43953. silent: true,
  43954. z2: -1
  43955. }));
  43956. }
  43957. };
  43958. GridView.type = 'grid';
  43959. return GridView;
  43960. }(ComponentView);
  43961. var extraOption = {
  43962. // gridIndex: 0,
  43963. // gridId: '',
  43964. offset: 0
  43965. };
  43966. function install$5(registers) {
  43967. registers.registerComponentView(GridView);
  43968. registers.registerComponentModel(GridModel);
  43969. registers.registerCoordinateSystem('cartesian2d', Grid);
  43970. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  43971. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  43972. registers.registerComponentView(CartesianXAxisView);
  43973. registers.registerComponentView(CartesianYAxisView);
  43974. registers.registerPreprocessor(function (option) {
  43975. // Only create grid when need
  43976. if (option.xAxis && option.yAxis && !option.grid) {
  43977. option.grid = {};
  43978. }
  43979. });
  43980. }
  43981. function install$6(registers) {
  43982. // In case developer forget to include grid component
  43983. use(install$5);
  43984. registers.registerSeriesModel(ScatterSeriesModel);
  43985. registers.registerChartView(ScatterView);
  43986. registers.registerLayout(pointsLayout('scatter'));
  43987. }
  43988. function radarLayout(ecModel) {
  43989. ecModel.eachSeriesByType('radar', function (seriesModel) {
  43990. var data = seriesModel.getData();
  43991. var points = [];
  43992. var coordSys = seriesModel.coordinateSystem;
  43993. if (!coordSys) {
  43994. return;
  43995. }
  43996. var axes = coordSys.getIndicatorAxes();
  43997. each(axes, function (axis, axisIndex) {
  43998. data.each(data.mapDimension(axes[axisIndex].dim), function (val, dataIndex) {
  43999. points[dataIndex] = points[dataIndex] || [];
  44000. var point = coordSys.dataToPoint(val, axisIndex);
  44001. points[dataIndex][axisIndex] = isValidPoint(point) ? point : getValueMissingPoint(coordSys);
  44002. });
  44003. }); // Close polygon
  44004. data.each(function (idx) {
  44005. // TODO
  44006. // Is it appropriate to connect to the next data when some data is missing?
  44007. // Or, should trade it like `connectNull` in line chart?
  44008. var firstPoint = find(points[idx], function (point) {
  44009. return isValidPoint(point);
  44010. }) || getValueMissingPoint(coordSys); // Copy the first actual point to the end of the array
  44011. points[idx].push(firstPoint.slice());
  44012. data.setItemLayout(idx, points[idx]);
  44013. });
  44014. });
  44015. }
  44016. function isValidPoint(point) {
  44017. return !isNaN(point[0]) && !isNaN(point[1]);
  44018. }
  44019. function getValueMissingPoint(coordSys) {
  44020. // It is error-prone to input [NaN, NaN] into polygon, polygon.
  44021. // (probably cause problem when refreshing or animating)
  44022. return [coordSys.cx, coordSys.cy];
  44023. }
  44024. function radarBackwardCompat(option) {
  44025. var polarOptArr = option.polar;
  44026. if (polarOptArr) {
  44027. if (!isArray(polarOptArr)) {
  44028. polarOptArr = [polarOptArr];
  44029. }
  44030. var polarNotRadar_1 = [];
  44031. each(polarOptArr, function (polarOpt, idx) {
  44032. if (polarOpt.indicator) {
  44033. if (polarOpt.type && !polarOpt.shape) {
  44034. polarOpt.shape = polarOpt.type;
  44035. }
  44036. option.radar = option.radar || [];
  44037. if (!isArray(option.radar)) {
  44038. option.radar = [option.radar];
  44039. }
  44040. option.radar.push(polarOpt);
  44041. } else {
  44042. polarNotRadar_1.push(polarOpt);
  44043. }
  44044. });
  44045. option.polar = polarNotRadar_1;
  44046. }
  44047. each(option.series, function (seriesOpt) {
  44048. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  44049. seriesOpt.radarIndex = seriesOpt.polarIndex;
  44050. }
  44051. });
  44052. }
  44053. var RadarView =
  44054. /** @class */
  44055. function (_super) {
  44056. __extends(RadarView, _super);
  44057. function RadarView() {
  44058. var _this = _super !== null && _super.apply(this, arguments) || this;
  44059. _this.type = RadarView.type;
  44060. return _this;
  44061. }
  44062. RadarView.prototype.render = function (seriesModel, ecModel, api) {
  44063. var polar = seriesModel.coordinateSystem;
  44064. var group = this.group;
  44065. var data = seriesModel.getData();
  44066. var oldData = this._data;
  44067. function createSymbol$1(data, idx) {
  44068. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  44069. if (symbolType === 'none') {
  44070. return;
  44071. }
  44072. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  44073. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2);
  44074. var symbolRotate = data.getItemVisual(idx, 'symbolRotate') || 0;
  44075. symbolPath.attr({
  44076. style: {
  44077. strokeNoScale: true
  44078. },
  44079. z2: 100,
  44080. scaleX: symbolSize[0] / 2,
  44081. scaleY: symbolSize[1] / 2,
  44082. rotation: symbolRotate * Math.PI / 180 || 0
  44083. });
  44084. return symbolPath;
  44085. }
  44086. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  44087. // Simply rerender all
  44088. symbolGroup.removeAll();
  44089. for (var i = 0; i < newPoints.length - 1; i++) {
  44090. var symbolPath = createSymbol$1(data, idx);
  44091. if (symbolPath) {
  44092. symbolPath.__dimIdx = i;
  44093. if (oldPoints[i]) {
  44094. symbolPath.setPosition(oldPoints[i]);
  44095. graphic[isInit ? 'initProps' : 'updateProps'](symbolPath, {
  44096. x: newPoints[i][0],
  44097. y: newPoints[i][1]
  44098. }, seriesModel, idx);
  44099. } else {
  44100. symbolPath.setPosition(newPoints[i]);
  44101. }
  44102. symbolGroup.add(symbolPath);
  44103. }
  44104. }
  44105. }
  44106. function getInitialPoints(points) {
  44107. return map(points, function (pt) {
  44108. return [polar.cx, polar.cy];
  44109. });
  44110. }
  44111. data.diff(oldData).add(function (idx) {
  44112. var points = data.getItemLayout(idx);
  44113. if (!points) {
  44114. return;
  44115. }
  44116. var polygon = new Polygon();
  44117. var polyline = new Polyline();
  44118. var target = {
  44119. shape: {
  44120. points: points
  44121. }
  44122. };
  44123. polygon.shape.points = getInitialPoints(points);
  44124. polyline.shape.points = getInitialPoints(points);
  44125. initProps(polygon, target, seriesModel, idx);
  44126. initProps(polyline, target, seriesModel, idx);
  44127. var itemGroup = new Group();
  44128. var symbolGroup = new Group();
  44129. itemGroup.add(polyline);
  44130. itemGroup.add(polygon);
  44131. itemGroup.add(symbolGroup);
  44132. updateSymbols(polyline.shape.points, points, symbolGroup, data, idx, true);
  44133. data.setItemGraphicEl(idx, itemGroup);
  44134. }).update(function (newIdx, oldIdx) {
  44135. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  44136. var polyline = itemGroup.childAt(0);
  44137. var polygon = itemGroup.childAt(1);
  44138. var symbolGroup = itemGroup.childAt(2);
  44139. var target = {
  44140. shape: {
  44141. points: data.getItemLayout(newIdx)
  44142. }
  44143. };
  44144. if (!target.shape.points) {
  44145. return;
  44146. }
  44147. updateSymbols(polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false);
  44148. saveOldStyle(polygon);
  44149. saveOldStyle(polyline);
  44150. updateProps(polyline, target, seriesModel);
  44151. updateProps(polygon, target, seriesModel);
  44152. data.setItemGraphicEl(newIdx, itemGroup);
  44153. }).remove(function (idx) {
  44154. group.remove(oldData.getItemGraphicEl(idx));
  44155. }).execute();
  44156. data.eachItemGraphicEl(function (itemGroup, idx) {
  44157. var itemModel = data.getItemModel(idx);
  44158. var polyline = itemGroup.childAt(0);
  44159. var polygon = itemGroup.childAt(1);
  44160. var symbolGroup = itemGroup.childAt(2); // Radar uses the visual encoded from itemStyle.
  44161. var itemStyle = data.getItemVisual(idx, 'style');
  44162. var color = itemStyle.fill;
  44163. group.add(itemGroup);
  44164. polyline.useStyle(defaults(itemModel.getModel('lineStyle').getLineStyle(), {
  44165. fill: 'none',
  44166. stroke: color
  44167. }));
  44168. setStatesStylesFromModel(polyline, itemModel, 'lineStyle');
  44169. setStatesStylesFromModel(polygon, itemModel, 'areaStyle');
  44170. var areaStyleModel = itemModel.getModel('areaStyle');
  44171. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  44172. polygon.ignore = polygonIgnore;
  44173. each(['emphasis', 'select', 'blur'], function (stateName) {
  44174. var stateModel = itemModel.getModel([stateName, 'areaStyle']);
  44175. var stateIgnore = stateModel.isEmpty() && stateModel.parentModel.isEmpty(); // Won't be ignore if normal state is not ignore.
  44176. polygon.ensureState(stateName).ignore = stateIgnore && polygonIgnore;
  44177. });
  44178. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  44179. fill: color,
  44180. opacity: 0.7,
  44181. decal: itemStyle.decal
  44182. }));
  44183. var emphasisModel = itemModel.getModel('emphasis');
  44184. var itemHoverStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  44185. symbolGroup.eachChild(function (symbolPath) {
  44186. if (symbolPath instanceof ZRImage) {
  44187. var pathStyle = symbolPath.style;
  44188. symbolPath.useStyle(extend({
  44189. // TODO other properties like x, y ?
  44190. image: pathStyle.image,
  44191. x: pathStyle.x,
  44192. y: pathStyle.y,
  44193. width: pathStyle.width,
  44194. height: pathStyle.height
  44195. }, itemStyle));
  44196. } else {
  44197. symbolPath.useStyle(itemStyle);
  44198. symbolPath.setColor(color);
  44199. symbolPath.style.strokeNoScale = true;
  44200. }
  44201. var pathEmphasisState = symbolPath.ensureState('emphasis');
  44202. pathEmphasisState.style = clone(itemHoverStyle);
  44203. var defaultText = data.getStore().get(data.getDimensionIndex(symbolPath.__dimIdx), idx);
  44204. (defaultText == null || isNaN(defaultText)) && (defaultText = '');
  44205. setLabelStyle(symbolPath, getLabelStatesModels(itemModel), {
  44206. labelFetcher: data.hostModel,
  44207. labelDataIndex: idx,
  44208. labelDimIndex: symbolPath.__dimIdx,
  44209. defaultText: defaultText,
  44210. inheritColor: color,
  44211. defaultOpacity: itemStyle.opacity
  44212. });
  44213. });
  44214. enableHoverEmphasis(itemGroup, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  44215. });
  44216. this._data = data;
  44217. };
  44218. RadarView.prototype.remove = function () {
  44219. this.group.removeAll();
  44220. this._data = null;
  44221. };
  44222. RadarView.type = 'radar';
  44223. return RadarView;
  44224. }(ChartView);
  44225. var RadarSeriesModel =
  44226. /** @class */
  44227. function (_super) {
  44228. __extends(RadarSeriesModel, _super);
  44229. function RadarSeriesModel() {
  44230. var _this = _super !== null && _super.apply(this, arguments) || this;
  44231. _this.type = RadarSeriesModel.type;
  44232. _this.hasSymbolVisual = true;
  44233. return _this;
  44234. } // Overwrite
  44235. RadarSeriesModel.prototype.init = function (option) {
  44236. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  44237. // Use a function instead of direct access because data reference may changed
  44238. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  44239. };
  44240. RadarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  44241. return createSeriesDataSimply(this, {
  44242. generateCoord: 'indicator_',
  44243. generateCoordCount: Infinity
  44244. });
  44245. };
  44246. RadarSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  44247. var data = this.getData();
  44248. var coordSys = this.coordinateSystem;
  44249. var indicatorAxes = coordSys.getIndicatorAxes();
  44250. var name = this.getData().getName(dataIndex);
  44251. var nameToDisplay = name === '' ? this.name : name;
  44252. var markerColor = retrieveVisualColorForTooltipMarker(this, dataIndex);
  44253. return createTooltipMarkup('section', {
  44254. header: nameToDisplay,
  44255. sortBlocks: true,
  44256. blocks: map(indicatorAxes, function (axis) {
  44257. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  44258. return createTooltipMarkup('nameValue', {
  44259. markerType: 'subItem',
  44260. markerColor: markerColor,
  44261. name: axis.name,
  44262. value: val,
  44263. sortParam: val
  44264. });
  44265. })
  44266. });
  44267. };
  44268. RadarSeriesModel.prototype.getTooltipPosition = function (dataIndex) {
  44269. if (dataIndex != null) {
  44270. var data_1 = this.getData();
  44271. var coordSys = this.coordinateSystem;
  44272. var values = data_1.getValues(map(coordSys.dimensions, function (dim) {
  44273. return data_1.mapDimension(dim);
  44274. }), dataIndex);
  44275. for (var i = 0, len = values.length; i < len; i++) {
  44276. if (!isNaN(values[i])) {
  44277. var indicatorAxes = coordSys.getIndicatorAxes();
  44278. return coordSys.coordToPoint(indicatorAxes[i].dataToCoord(values[i]), i);
  44279. }
  44280. }
  44281. }
  44282. };
  44283. RadarSeriesModel.type = 'series.radar';
  44284. RadarSeriesModel.dependencies = ['radar'];
  44285. RadarSeriesModel.defaultOption = {
  44286. zlevel: 0,
  44287. z: 2,
  44288. colorBy: 'data',
  44289. coordinateSystem: 'radar',
  44290. legendHoverLink: true,
  44291. radarIndex: 0,
  44292. lineStyle: {
  44293. width: 2,
  44294. type: 'solid',
  44295. join: 'round'
  44296. },
  44297. label: {
  44298. position: 'top'
  44299. },
  44300. // areaStyle: {
  44301. // },
  44302. // itemStyle: {}
  44303. symbolSize: 8 // symbolRotate: null
  44304. };
  44305. return RadarSeriesModel;
  44306. }(SeriesModel);
  44307. var valueAxisDefault = axisDefault.value;
  44308. function defaultsShow(opt, show) {
  44309. return defaults({
  44310. show: show
  44311. }, opt);
  44312. }
  44313. var RadarModel =
  44314. /** @class */
  44315. function (_super) {
  44316. __extends(RadarModel, _super);
  44317. function RadarModel() {
  44318. var _this = _super !== null && _super.apply(this, arguments) || this;
  44319. _this.type = RadarModel.type;
  44320. return _this;
  44321. }
  44322. RadarModel.prototype.optionUpdated = function () {
  44323. var boundaryGap = this.get('boundaryGap');
  44324. var splitNumber = this.get('splitNumber');
  44325. var scale = this.get('scale');
  44326. var axisLine = this.get('axisLine');
  44327. var axisTick = this.get('axisTick'); // let axisType = this.get('axisType');
  44328. var axisLabel = this.get('axisLabel');
  44329. var nameTextStyle = this.get('axisName');
  44330. var showName = this.get(['axisName', 'show']);
  44331. var nameFormatter = this.get(['axisName', 'formatter']);
  44332. var nameGap = this.get('axisNameGap');
  44333. var triggerEvent = this.get('triggerEvent');
  44334. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  44335. // PENDING
  44336. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  44337. indicatorOpt.min = 0;
  44338. } else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  44339. indicatorOpt.max = 0;
  44340. }
  44341. var iNameTextStyle = nameTextStyle;
  44342. if (indicatorOpt.color != null) {
  44343. iNameTextStyle = defaults({
  44344. color: indicatorOpt.color
  44345. }, nameTextStyle);
  44346. } // Use same configuration
  44347. var innerIndicatorOpt = merge(clone(indicatorOpt), {
  44348. boundaryGap: boundaryGap,
  44349. splitNumber: splitNumber,
  44350. scale: scale,
  44351. axisLine: axisLine,
  44352. axisTick: axisTick,
  44353. // axisType: axisType,
  44354. axisLabel: axisLabel,
  44355. // Compatible with 2 and use text
  44356. name: indicatorOpt.text,
  44357. nameLocation: 'end',
  44358. nameGap: nameGap,
  44359. // min: 0,
  44360. nameTextStyle: iNameTextStyle,
  44361. triggerEvent: triggerEvent
  44362. }, false);
  44363. if (!showName) {
  44364. innerIndicatorOpt.name = '';
  44365. }
  44366. if (typeof nameFormatter === 'string') {
  44367. var indName = innerIndicatorOpt.name;
  44368. innerIndicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  44369. } else if (typeof nameFormatter === 'function') {
  44370. innerIndicatorOpt.name = nameFormatter(innerIndicatorOpt.name, innerIndicatorOpt);
  44371. }
  44372. var model = new Model(innerIndicatorOpt, null, this.ecModel);
  44373. mixin(model, AxisModelCommonMixin.prototype); // For triggerEvent.
  44374. model.mainType = 'radar';
  44375. model.componentIndex = this.componentIndex;
  44376. return model;
  44377. }, this);
  44378. this._indicatorModels = indicatorModels;
  44379. };
  44380. RadarModel.prototype.getIndicatorModels = function () {
  44381. return this._indicatorModels;
  44382. };
  44383. RadarModel.type = 'radar';
  44384. RadarModel.defaultOption = {
  44385. zlevel: 0,
  44386. z: 0,
  44387. center: ['50%', '50%'],
  44388. radius: '75%',
  44389. startAngle: 90,
  44390. axisName: {
  44391. show: true // formatter: null
  44392. // textStyle: {}
  44393. },
  44394. boundaryGap: [0, 0],
  44395. splitNumber: 5,
  44396. axisNameGap: 15,
  44397. scale: false,
  44398. // Polygon or circle
  44399. shape: 'polygon',
  44400. axisLine: merge({
  44401. lineStyle: {
  44402. color: '#bbb'
  44403. }
  44404. }, valueAxisDefault.axisLine),
  44405. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  44406. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  44407. // axisType: 'value',
  44408. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  44409. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  44410. // {text, min, max}
  44411. indicator: []
  44412. };
  44413. return RadarModel;
  44414. }(ComponentModel);
  44415. var axisBuilderAttrs$1 = ['axisLine', 'axisTickLabel', 'axisName'];
  44416. var RadarView$1 =
  44417. /** @class */
  44418. function (_super) {
  44419. __extends(RadarView, _super);
  44420. function RadarView() {
  44421. var _this = _super !== null && _super.apply(this, arguments) || this;
  44422. _this.type = RadarView.type;
  44423. return _this;
  44424. }
  44425. RadarView.prototype.render = function (radarModel, ecModel, api) {
  44426. var group = this.group;
  44427. group.removeAll();
  44428. this._buildAxes(radarModel);
  44429. this._buildSplitLineAndArea(radarModel);
  44430. };
  44431. RadarView.prototype._buildAxes = function (radarModel) {
  44432. var radar = radarModel.coordinateSystem;
  44433. var indicatorAxes = radar.getIndicatorAxes();
  44434. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  44435. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  44436. position: [radar.cx, radar.cy],
  44437. rotation: indicatorAxis.angle,
  44438. labelDirection: -1,
  44439. tickDirection: -1,
  44440. nameDirection: 1
  44441. });
  44442. return axisBuilder;
  44443. });
  44444. each(axisBuilders, function (axisBuilder) {
  44445. each(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  44446. this.group.add(axisBuilder.getGroup());
  44447. }, this);
  44448. };
  44449. RadarView.prototype._buildSplitLineAndArea = function (radarModel) {
  44450. var radar = radarModel.coordinateSystem;
  44451. var indicatorAxes = radar.getIndicatorAxes();
  44452. if (!indicatorAxes.length) {
  44453. return;
  44454. }
  44455. var shape = radarModel.get('shape');
  44456. var splitLineModel = radarModel.getModel('splitLine');
  44457. var splitAreaModel = radarModel.getModel('splitArea');
  44458. var lineStyleModel = splitLineModel.getModel('lineStyle');
  44459. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  44460. var showSplitLine = splitLineModel.get('show');
  44461. var showSplitArea = splitAreaModel.get('show');
  44462. var splitLineColors = lineStyleModel.get('color');
  44463. var splitAreaColors = areaStyleModel.get('color');
  44464. var splitLineColorsArr = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  44465. var splitAreaColorsArr = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  44466. var splitLines = [];
  44467. var splitAreas = [];
  44468. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  44469. var colorIndex = idx % areaOrLineColorList.length;
  44470. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  44471. return colorIndex;
  44472. }
  44473. if (shape === 'circle') {
  44474. var ticksRadius = indicatorAxes[0].getTicksCoords();
  44475. var cx = radar.cx;
  44476. var cy = radar.cy;
  44477. for (var i = 0; i < ticksRadius.length; i++) {
  44478. if (showSplitLine) {
  44479. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  44480. splitLines[colorIndex].push(new Circle({
  44481. shape: {
  44482. cx: cx,
  44483. cy: cy,
  44484. r: ticksRadius[i].coord
  44485. }
  44486. }));
  44487. }
  44488. if (showSplitArea && i < ticksRadius.length - 1) {
  44489. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i);
  44490. splitAreas[colorIndex].push(new Ring({
  44491. shape: {
  44492. cx: cx,
  44493. cy: cy,
  44494. r0: ticksRadius[i].coord,
  44495. r: ticksRadius[i + 1].coord
  44496. }
  44497. }));
  44498. }
  44499. }
  44500. } // Polyyon
  44501. else {
  44502. var realSplitNumber_1;
  44503. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  44504. var ticksCoords = indicatorAxis.getTicksCoords();
  44505. realSplitNumber_1 = realSplitNumber_1 == null ? ticksCoords.length - 1 : Math.min(ticksCoords.length - 1, realSplitNumber_1);
  44506. return map(ticksCoords, function (tickCoord) {
  44507. return radar.coordToPoint(tickCoord.coord, idx);
  44508. });
  44509. });
  44510. var prevPoints = [];
  44511. for (var i = 0; i <= realSplitNumber_1; i++) {
  44512. var points = [];
  44513. for (var j = 0; j < indicatorAxes.length; j++) {
  44514. points.push(axesTicksPoints[j][i]);
  44515. } // Close
  44516. if (points[0]) {
  44517. points.push(points[0].slice());
  44518. } else {
  44519. if ("development" !== 'production') {
  44520. console.error('Can\'t draw value axis ' + i);
  44521. }
  44522. }
  44523. if (showSplitLine) {
  44524. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  44525. splitLines[colorIndex].push(new Polyline({
  44526. shape: {
  44527. points: points
  44528. }
  44529. }));
  44530. }
  44531. if (showSplitArea && prevPoints) {
  44532. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i - 1);
  44533. splitAreas[colorIndex].push(new Polygon({
  44534. shape: {
  44535. points: points.concat(prevPoints)
  44536. }
  44537. }));
  44538. }
  44539. prevPoints = points.slice().reverse();
  44540. }
  44541. }
  44542. var lineStyle = lineStyleModel.getLineStyle();
  44543. var areaStyle = areaStyleModel.getAreaStyle(); // Add splitArea before splitLine
  44544. each(splitAreas, function (splitAreas, idx) {
  44545. this.group.add(mergePath$1(splitAreas, {
  44546. style: defaults({
  44547. stroke: 'none',
  44548. fill: splitAreaColorsArr[idx % splitAreaColorsArr.length]
  44549. }, areaStyle),
  44550. silent: true
  44551. }));
  44552. }, this);
  44553. each(splitLines, function (splitLines, idx) {
  44554. this.group.add(mergePath$1(splitLines, {
  44555. style: defaults({
  44556. fill: 'none',
  44557. stroke: splitLineColorsArr[idx % splitLineColorsArr.length]
  44558. }, lineStyle),
  44559. silent: true
  44560. }));
  44561. }, this);
  44562. };
  44563. RadarView.type = 'radar';
  44564. return RadarView;
  44565. }(ComponentView);
  44566. var IndicatorAxis =
  44567. /** @class */
  44568. function (_super) {
  44569. __extends(IndicatorAxis, _super);
  44570. function IndicatorAxis(dim, scale, radiusExtent) {
  44571. var _this = _super.call(this, dim, scale, radiusExtent) || this;
  44572. _this.type = 'value';
  44573. _this.angle = 0;
  44574. _this.name = '';
  44575. return _this;
  44576. }
  44577. return IndicatorAxis;
  44578. }(Axis);
  44579. var Radar =
  44580. /** @class */
  44581. function () {
  44582. function Radar(radarModel, ecModel, api) {
  44583. /**
  44584. *
  44585. * Radar dimensions
  44586. */
  44587. this.dimensions = [];
  44588. this._model = radarModel;
  44589. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  44590. var dim = 'indicator_' + idx;
  44591. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale() // (indicatorModel.get('axisType') === 'log') ? new LogScale() : new IntervalScale()
  44592. );
  44593. indicatorAxis.name = indicatorModel.get('name'); // Inject model and axis
  44594. indicatorAxis.model = indicatorModel;
  44595. indicatorModel.axis = indicatorAxis;
  44596. this.dimensions.push(dim);
  44597. return indicatorAxis;
  44598. }, this);
  44599. this.resize(radarModel, api);
  44600. }
  44601. Radar.prototype.getIndicatorAxes = function () {
  44602. return this._indicatorAxes;
  44603. };
  44604. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  44605. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  44606. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  44607. }; // TODO: API should be coordToPoint([coord, indicatorIndex])
  44608. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  44609. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  44610. var angle = indicatorAxis.angle;
  44611. var x = this.cx + coord * Math.cos(angle);
  44612. var y = this.cy - coord * Math.sin(angle);
  44613. return [x, y];
  44614. };
  44615. Radar.prototype.pointToData = function (pt) {
  44616. var dx = pt[0] - this.cx;
  44617. var dy = pt[1] - this.cy;
  44618. var radius = Math.sqrt(dx * dx + dy * dy);
  44619. dx /= radius;
  44620. dy /= radius;
  44621. var radian = Math.atan2(-dy, dx); // Find the closest angle
  44622. // FIXME index can calculated directly
  44623. var minRadianDiff = Infinity;
  44624. var closestAxis;
  44625. var closestAxisIdx = -1;
  44626. for (var i = 0; i < this._indicatorAxes.length; i++) {
  44627. var indicatorAxis = this._indicatorAxes[i];
  44628. var diff = Math.abs(radian - indicatorAxis.angle);
  44629. if (diff < minRadianDiff) {
  44630. closestAxis = indicatorAxis;
  44631. closestAxisIdx = i;
  44632. minRadianDiff = diff;
  44633. }
  44634. }
  44635. return [closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius))];
  44636. };
  44637. Radar.prototype.resize = function (radarModel, api) {
  44638. var center = radarModel.get('center');
  44639. var viewWidth = api.getWidth();
  44640. var viewHeight = api.getHeight();
  44641. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  44642. this.cx = parsePercent$1(center[0], viewWidth);
  44643. this.cy = parsePercent$1(center[1], viewHeight);
  44644. this.startAngle = radarModel.get('startAngle') * Math.PI / 180; // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  44645. var radius = radarModel.get('radius');
  44646. if (typeof radius === 'string' || typeof radius === 'number') {
  44647. radius = [0, radius];
  44648. }
  44649. this.r0 = parsePercent$1(radius[0], viewSize);
  44650. this.r = parsePercent$1(radius[1], viewSize);
  44651. each(this._indicatorAxes, function (indicatorAxis, idx) {
  44652. indicatorAxis.setExtent(this.r0, this.r);
  44653. var angle = this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length; // Normalize to [-PI, PI]
  44654. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  44655. indicatorAxis.angle = angle;
  44656. }, this);
  44657. };
  44658. Radar.prototype.update = function (ecModel, api) {
  44659. var indicatorAxes = this._indicatorAxes;
  44660. var radarModel = this._model;
  44661. each(indicatorAxes, function (indicatorAxis) {
  44662. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  44663. });
  44664. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  44665. if (radarSeries.get('coordinateSystem') !== 'radar' // @ts-ignore
  44666. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel) {
  44667. return;
  44668. }
  44669. var data = radarSeries.getData();
  44670. each(indicatorAxes, function (indicatorAxis) {
  44671. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  44672. });
  44673. }, this);
  44674. var splitNumber = radarModel.get('splitNumber');
  44675. function increaseInterval(interval) {
  44676. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10)); // Increase interval
  44677. var f = interval / exp10;
  44678. if (f === 2) {
  44679. f = 5;
  44680. } else {
  44681. // f is 2 or 5
  44682. f *= 2;
  44683. }
  44684. return f * exp10;
  44685. } // Force all the axis fixing the maxSplitNumber.
  44686. each(indicatorAxes, function (indicatorAxis, idx) {
  44687. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model).extent;
  44688. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  44689. var axisModel = indicatorAxis.model;
  44690. var scale = indicatorAxis.scale;
  44691. var fixedMin = parseAxisModelMinMax(scale, axisModel.get('min', true));
  44692. var fixedMax = parseAxisModelMinMax(scale, axisModel.get('max', true));
  44693. var interval = scale.getInterval();
  44694. if (fixedMin != null && fixedMax != null) {
  44695. // User set min, max, divide to get new interval
  44696. scale.setExtent(+fixedMin, +fixedMax);
  44697. scale.setInterval((fixedMax - fixedMin) / splitNumber);
  44698. } else if (fixedMin != null) {
  44699. var max = void 0; // User set min, expand extent on the other side
  44700. do {
  44701. max = fixedMin + interval * splitNumber;
  44702. scale.setExtent(+fixedMin, max); // Interval must been set after extent
  44703. // FIXME
  44704. scale.setInterval(interval);
  44705. interval = increaseInterval(interval);
  44706. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  44707. } else if (fixedMax != null) {
  44708. var min = void 0; // User set min, expand extent on the other side
  44709. do {
  44710. min = fixedMax - interval * splitNumber;
  44711. scale.setExtent(min, +fixedMax);
  44712. scale.setInterval(interval);
  44713. interval = increaseInterval(interval);
  44714. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  44715. } else {
  44716. var nicedSplitNumber = scale.getTicks().length - 1;
  44717. if (nicedSplitNumber > splitNumber) {
  44718. interval = increaseInterval(interval);
  44719. } // TODO
  44720. var max = Math.ceil(rawExtent[1] / interval) * interval;
  44721. var min = round(max - interval * splitNumber);
  44722. scale.setExtent(min, max);
  44723. scale.setInterval(interval);
  44724. }
  44725. });
  44726. };
  44727. Radar.prototype.convertToPixel = function (ecModel, finder, value) {
  44728. console.warn('Not implemented.');
  44729. return null;
  44730. };
  44731. Radar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  44732. console.warn('Not implemented.');
  44733. return null;
  44734. };
  44735. Radar.prototype.containPoint = function (point) {
  44736. console.warn('Not implemented.');
  44737. return false;
  44738. };
  44739. Radar.create = function (ecModel, api) {
  44740. var radarList = [];
  44741. ecModel.eachComponent('radar', function (radarModel) {
  44742. var radar = new Radar(radarModel, ecModel, api);
  44743. radarList.push(radar);
  44744. radarModel.coordinateSystem = radar;
  44745. });
  44746. ecModel.eachSeriesByType('radar', function (radarSeries) {
  44747. if (radarSeries.get('coordinateSystem') === 'radar') {
  44748. // Inject coordinate system
  44749. // @ts-ignore
  44750. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  44751. }
  44752. });
  44753. return radarList;
  44754. };
  44755. /**
  44756. * Radar dimensions is based on the data
  44757. */
  44758. Radar.dimensions = [];
  44759. return Radar;
  44760. }();
  44761. function install$7(registers) {
  44762. registers.registerCoordinateSystem('radar', Radar);
  44763. registers.registerComponentModel(RadarModel);
  44764. registers.registerComponentView(RadarView$1);
  44765. registers.registerVisual({
  44766. seriesType: 'radar',
  44767. reset: function (seriesModel) {
  44768. var data = seriesModel.getData(); // itemVisual symbol is for selected data
  44769. data.each(function (idx) {
  44770. data.setItemVisual(idx, 'legendIcon', 'roundRect');
  44771. }); // visual is for unselected data
  44772. data.setVisual('legendIcon', 'roundRect');
  44773. }
  44774. });
  44775. }
  44776. function install$8(registers) {
  44777. use(install$7);
  44778. registers.registerChartView(RadarView);
  44779. registers.registerSeriesModel(RadarSeriesModel);
  44780. registers.registerLayout(radarLayout);
  44781. registers.registerProcessor(dataFilter('radar'));
  44782. registers.registerPreprocessor(radarBackwardCompat);
  44783. }
  44784. var ATTR = '\0_ec_interaction_mutex';
  44785. function take(zr, resourceKey, userKey) {
  44786. var store = getStore(zr);
  44787. store[resourceKey] = userKey;
  44788. }
  44789. function release(zr, resourceKey, userKey) {
  44790. var store = getStore(zr);
  44791. var uKey = store[resourceKey];
  44792. if (uKey === userKey) {
  44793. store[resourceKey] = null;
  44794. }
  44795. }
  44796. function isTaken(zr, resourceKey) {
  44797. return !!getStore(zr)[resourceKey];
  44798. }
  44799. function getStore(zr) {
  44800. return zr[ATTR] || (zr[ATTR] = {});
  44801. }
  44802. /**
  44803. * payload: {
  44804. * type: 'takeGlobalCursor',
  44805. * key: 'dataZoomSelect', or 'brush', or ...,
  44806. * If no userKey, release global cursor.
  44807. * }
  44808. */
  44809. // TODO: SELF REGISTERED.
  44810. registerAction({
  44811. type: 'takeGlobalCursor',
  44812. event: 'globalCursorTaken',
  44813. update: 'update'
  44814. }, function () {});
  44815. var RoamController =
  44816. /** @class */
  44817. function (_super) {
  44818. __extends(RoamController, _super);
  44819. function RoamController(zr) {
  44820. var _this = _super.call(this) || this;
  44821. _this._zr = zr; // Avoid two roamController bind the same handler
  44822. var mousedownHandler = bind(_this._mousedownHandler, _this);
  44823. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  44824. var mouseupHandler = bind(_this._mouseupHandler, _this);
  44825. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  44826. var pinchHandler = bind(_this._pinchHandler, _this);
  44827. /**
  44828. * Notice: only enable needed types. For example, if 'zoom'
  44829. * is not needed, 'zoom' should not be enabled, otherwise
  44830. * default mousewheel behaviour (scroll page) will be disabled.
  44831. */
  44832. _this.enable = function (controlType, opt) {
  44833. // Disable previous first
  44834. this.disable();
  44835. this._opt = defaults(clone(opt) || {}, {
  44836. zoomOnMouseWheel: true,
  44837. moveOnMouseMove: true,
  44838. // By default, wheel do not trigger move.
  44839. moveOnMouseWheel: false,
  44840. preventDefaultMouseMove: true
  44841. });
  44842. if (controlType == null) {
  44843. controlType = true;
  44844. }
  44845. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  44846. zr.on('mousedown', mousedownHandler);
  44847. zr.on('mousemove', mousemoveHandler);
  44848. zr.on('mouseup', mouseupHandler);
  44849. }
  44850. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  44851. zr.on('mousewheel', mousewheelHandler);
  44852. zr.on('pinch', pinchHandler);
  44853. }
  44854. };
  44855. _this.disable = function () {
  44856. zr.off('mousedown', mousedownHandler);
  44857. zr.off('mousemove', mousemoveHandler);
  44858. zr.off('mouseup', mouseupHandler);
  44859. zr.off('mousewheel', mousewheelHandler);
  44860. zr.off('pinch', pinchHandler);
  44861. };
  44862. return _this;
  44863. }
  44864. RoamController.prototype.isDragging = function () {
  44865. return this._dragging;
  44866. };
  44867. RoamController.prototype.isPinching = function () {
  44868. return this._pinching;
  44869. };
  44870. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  44871. this.pointerChecker = pointerChecker;
  44872. };
  44873. RoamController.prototype.dispose = function () {
  44874. this.disable();
  44875. };
  44876. RoamController.prototype._mousedownHandler = function (e) {
  44877. if (isMiddleOrRightButtonOnMouseUpDown(e) || e.target && e.target.draggable) {
  44878. return;
  44879. }
  44880. var x = e.offsetX;
  44881. var y = e.offsetY; // Only check on mosedown, but not mousemove.
  44882. // Mouse can be out of target when mouse moving.
  44883. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  44884. this._x = x;
  44885. this._y = y;
  44886. this._dragging = true;
  44887. }
  44888. };
  44889. RoamController.prototype._mousemoveHandler = function (e) {
  44890. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  44891. return;
  44892. }
  44893. var x = e.offsetX;
  44894. var y = e.offsetY;
  44895. var oldX = this._x;
  44896. var oldY = this._y;
  44897. var dx = x - oldX;
  44898. var dy = y - oldY;
  44899. this._x = x;
  44900. this._y = y;
  44901. this._opt.preventDefaultMouseMove && stop(e.event);
  44902. trigger(this, 'pan', 'moveOnMouseMove', e, {
  44903. dx: dx,
  44904. dy: dy,
  44905. oldX: oldX,
  44906. oldY: oldY,
  44907. newX: x,
  44908. newY: y,
  44909. isAvailableBehavior: null
  44910. });
  44911. };
  44912. RoamController.prototype._mouseupHandler = function (e) {
  44913. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  44914. this._dragging = false;
  44915. }
  44916. };
  44917. RoamController.prototype._mousewheelHandler = function (e) {
  44918. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  44919. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  44920. var wheelDelta = e.wheelDelta;
  44921. var absWheelDeltaDelta = Math.abs(wheelDelta);
  44922. var originX = e.offsetX;
  44923. var originY = e.offsetY; // wheelDelta maybe -0 in chrome mac.
  44924. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  44925. return;
  44926. } // If both `shouldZoom` and `shouldMove` is true, trigger
  44927. // their event both, and the final behavior is determined
  44928. // by event listener themselves.
  44929. if (shouldZoom) {
  44930. // Convenience:
  44931. // Mac and VM Windows on Mac: scroll up: zoom out.
  44932. // Windows: scroll up: zoom in.
  44933. // FIXME: Should do more test in different environment.
  44934. // wheelDelta is too complicated in difference nvironment
  44935. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  44936. // although it has been normallized by zrender.
  44937. // wheelDelta of mouse wheel is bigger than touch pad.
  44938. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  44939. var scale = wheelDelta > 0 ? factor : 1 / factor;
  44940. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  44941. scale: scale,
  44942. originX: originX,
  44943. originY: originY,
  44944. isAvailableBehavior: null
  44945. });
  44946. }
  44947. if (shouldMove) {
  44948. // FIXME: Should do more test in different environment.
  44949. var absDelta = Math.abs(wheelDelta); // wheelDelta of mouse wheel is bigger than touch pad.
  44950. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  44951. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  44952. scrollDelta: scrollDelta,
  44953. originX: originX,
  44954. originY: originY,
  44955. isAvailableBehavior: null
  44956. });
  44957. }
  44958. };
  44959. RoamController.prototype._pinchHandler = function (e) {
  44960. if (isTaken(this._zr, 'globalPan')) {
  44961. return;
  44962. }
  44963. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  44964. checkPointerAndTrigger(this, 'zoom', null, e, {
  44965. scale: scale,
  44966. originX: e.pinchX,
  44967. originY: e.pinchY,
  44968. isAvailableBehavior: null
  44969. });
  44970. };
  44971. return RoamController;
  44972. }(Eventful);
  44973. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  44974. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  44975. // When mouse is out of roamController rect,
  44976. // default befavoius should not be be disabled, otherwise
  44977. // page sliding is disabled, contrary to expectation.
  44978. stop(e.event);
  44979. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  44980. }
  44981. }
  44982. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  44983. // Also provide behavior checker for event listener, for some case that
  44984. // multiple components share one listener.
  44985. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e); // TODO should not have type issue.
  44986. controller.trigger(eventName, contollerEvent);
  44987. } // settings: {
  44988. // zoomOnMouseWheel
  44989. // moveOnMouseMove
  44990. // moveOnMouseWheel
  44991. // }
  44992. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  44993. function isAvailableBehavior(behaviorToCheck, e, settings) {
  44994. var setting = settings[behaviorToCheck];
  44995. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  44996. }
  44997. /*
  44998. * Licensed to the Apache Software Foundation (ASF) under one
  44999. * or more contributor license agreements. See the NOTICE file
  45000. * distributed with this work for additional information
  45001. * regarding copyright ownership. The ASF licenses this file
  45002. * to you under the Apache License, Version 2.0 (the
  45003. * "License"); you may not use this file except in compliance
  45004. * with the License. You may obtain a copy of the License at
  45005. *
  45006. * http://www.apache.org/licenses/LICENSE-2.0
  45007. *
  45008. * Unless required by applicable law or agreed to in writing,
  45009. * software distributed under the License is distributed on an
  45010. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45011. * KIND, either express or implied. See the License for the
  45012. * specific language governing permissions and limitations
  45013. * under the License.
  45014. */
  45015. /**
  45016. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45017. */
  45018. /*
  45019. * Licensed to the Apache Software Foundation (ASF) under one
  45020. * or more contributor license agreements. See the NOTICE file
  45021. * distributed with this work for additional information
  45022. * regarding copyright ownership. The ASF licenses this file
  45023. * to you under the Apache License, Version 2.0 (the
  45024. * "License"); you may not use this file except in compliance
  45025. * with the License. You may obtain a copy of the License at
  45026. *
  45027. * http://www.apache.org/licenses/LICENSE-2.0
  45028. *
  45029. * Unless required by applicable law or agreed to in writing,
  45030. * software distributed under the License is distributed on an
  45031. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45032. * KIND, either express or implied. See the License for the
  45033. * specific language governing permissions and limitations
  45034. * under the License.
  45035. */
  45036. /**
  45037. * For geo and graph.
  45038. */
  45039. function updateViewOnPan(controllerHost, dx, dy) {
  45040. var target = controllerHost.target;
  45041. target.x += dx;
  45042. target.y += dy;
  45043. target.dirty();
  45044. }
  45045. /**
  45046. * For geo and graph.
  45047. */
  45048. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  45049. var target = controllerHost.target;
  45050. var zoomLimit = controllerHost.zoomLimit;
  45051. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  45052. newZoom *= zoomDelta;
  45053. if (zoomLimit) {
  45054. var zoomMin = zoomLimit.min || 0;
  45055. var zoomMax = zoomLimit.max || Infinity;
  45056. newZoom = Math.max(Math.min(zoomMax, newZoom), zoomMin);
  45057. }
  45058. var zoomScale = newZoom / controllerHost.zoom;
  45059. controllerHost.zoom = newZoom; // Keep the mouse center when scaling
  45060. target.x -= (zoomX - target.x) * (zoomScale - 1);
  45061. target.y -= (zoomY - target.y) * (zoomScale - 1);
  45062. target.scaleX *= zoomScale;
  45063. target.scaleY *= zoomScale;
  45064. target.dirty();
  45065. }
  45066. /*
  45067. * Licensed to the Apache Software Foundation (ASF) under one
  45068. * or more contributor license agreements. See the NOTICE file
  45069. * distributed with this work for additional information
  45070. * regarding copyright ownership. The ASF licenses this file
  45071. * to you under the Apache License, Version 2.0 (the
  45072. * "License"); you may not use this file except in compliance
  45073. * with the License. You may obtain a copy of the License at
  45074. *
  45075. * http://www.apache.org/licenses/LICENSE-2.0
  45076. *
  45077. * Unless required by applicable law or agreed to in writing,
  45078. * software distributed under the License is distributed on an
  45079. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45080. * KIND, either express or implied. See the License for the
  45081. * specific language governing permissions and limitations
  45082. * under the License.
  45083. */
  45084. /**
  45085. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45086. */
  45087. /*
  45088. * Licensed to the Apache Software Foundation (ASF) under one
  45089. * or more contributor license agreements. See the NOTICE file
  45090. * distributed with this work for additional information
  45091. * regarding copyright ownership. The ASF licenses this file
  45092. * to you under the Apache License, Version 2.0 (the
  45093. * "License"); you may not use this file except in compliance
  45094. * with the License. You may obtain a copy of the License at
  45095. *
  45096. * http://www.apache.org/licenses/LICENSE-2.0
  45097. *
  45098. * Unless required by applicable law or agreed to in writing,
  45099. * software distributed under the License is distributed on an
  45100. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45101. * KIND, either express or implied. See the License for the
  45102. * specific language governing permissions and limitations
  45103. * under the License.
  45104. */
  45105. var IRRELEVANT_EXCLUDES = {
  45106. 'axisPointer': 1,
  45107. 'tooltip': 1,
  45108. 'brush': 1
  45109. };
  45110. /**
  45111. * Avoid that: mouse click on a elements that is over geo or graph,
  45112. * but roam is triggered.
  45113. */
  45114. function onIrrelevantElement(e, api, targetCoordSysModel) {
  45115. var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.
  45116. var coordSys = model && model.coordinateSystem;
  45117. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  45118. }
  45119. /**
  45120. * Only these tags enable use `itemStyle` if they are named in SVG.
  45121. * Other tags like <text> <tspan> <image> might not suitable for `itemStyle`.
  45122. * They will not be considered to be styled until some requirements come.
  45123. */
  45124. var OPTION_STYLE_ENABLED_TAGS = ['rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path'];
  45125. var OPTION_STYLE_ENABLED_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS);
  45126. var STATE_TRIGGER_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat(['g']));
  45127. var LABEL_HOST_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat(['g']));
  45128. var mapLabelRaw = makeInner();
  45129. function getFixedItemStyle(model) {
  45130. var itemStyle = model.getItemStyle();
  45131. var areaColor = model.get('areaColor'); // If user want the color not to be changed when hover,
  45132. // they should both set areaColor and color to be null.
  45133. if (areaColor != null) {
  45134. itemStyle.fill = areaColor;
  45135. }
  45136. return itemStyle;
  45137. }
  45138. var MapDraw =
  45139. /** @class */
  45140. function () {
  45141. function MapDraw(api) {
  45142. var group = new Group();
  45143. this.uid = getUID('ec_map_draw');
  45144. this._controller = new RoamController(api.getZr());
  45145. this._controllerHost = {
  45146. target: group
  45147. };
  45148. this.group = group;
  45149. group.add(this._regionsGroup = new Group());
  45150. group.add(this._svgGroup = new Group());
  45151. }
  45152. MapDraw.prototype.draw = function (mapOrGeoModel, ecModel, api, fromView, payload) {
  45153. var isGeo = mapOrGeoModel.mainType === 'geo'; // Map series has data. GEO model that controlled by map series
  45154. // will be assigned with map data. Other GEO model has no data.
  45155. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  45156. isGeo && ecModel.eachComponent({
  45157. mainType: 'series',
  45158. subType: 'map'
  45159. }, function (mapSeries) {
  45160. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  45161. data = mapSeries.getData();
  45162. }
  45163. });
  45164. var geo = mapOrGeoModel.coordinateSystem;
  45165. var regionsGroup = this._regionsGroup;
  45166. var group = this.group;
  45167. var transformInfo = geo.getTransformInfo();
  45168. var transformInfoRaw = transformInfo.raw;
  45169. var transformInfoRoam = transformInfo.roam; // No animation when first draw or in action
  45170. var isFirstDraw = !regionsGroup.childAt(0) || payload;
  45171. if (isFirstDraw) {
  45172. group.x = transformInfoRoam.x;
  45173. group.y = transformInfoRoam.y;
  45174. group.scaleX = transformInfoRoam.scaleX;
  45175. group.scaleY = transformInfoRoam.scaleY;
  45176. group.dirty();
  45177. } else {
  45178. updateProps(group, transformInfoRoam, mapOrGeoModel);
  45179. }
  45180. var isVisualEncodedByVisualMap = data && data.getVisual('visualMeta') && data.getVisual('visualMeta').length > 0;
  45181. var viewBuildCtx = {
  45182. api: api,
  45183. geo: geo,
  45184. mapOrGeoModel: mapOrGeoModel,
  45185. data: data,
  45186. isVisualEncodedByVisualMap: isVisualEncodedByVisualMap,
  45187. isGeo: isGeo,
  45188. transformInfoRaw: transformInfoRaw
  45189. };
  45190. if (geo.resourceType === 'geoJSON') {
  45191. this._buildGeoJSON(viewBuildCtx);
  45192. } else if (geo.resourceType === 'geoSVG') {
  45193. this._buildSVG(viewBuildCtx);
  45194. }
  45195. this._updateController(mapOrGeoModel, ecModel, api);
  45196. this._updateMapSelectHandler(mapOrGeoModel, regionsGroup, api, fromView);
  45197. };
  45198. MapDraw.prototype._buildGeoJSON = function (viewBuildCtx) {
  45199. var regionsGroupByName = this._regionsGroupByName = createHashMap();
  45200. var regionsInfoByName = createHashMap();
  45201. var regionsGroup = this._regionsGroup;
  45202. var transformInfoRaw = viewBuildCtx.transformInfoRaw;
  45203. var mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
  45204. var data = viewBuildCtx.data;
  45205. var transformPoint = function (point) {
  45206. return [point[0] * transformInfoRaw.scaleX + transformInfoRaw.x, point[1] * transformInfoRaw.scaleY + transformInfoRaw.y];
  45207. };
  45208. regionsGroup.removeAll(); // Only when the resource is GeoJSON, there is `geo.regions`.
  45209. each(viewBuildCtx.geo.regions, function (region) {
  45210. var regionName = region.name; // Consider in GeoJson properties.name may be duplicated, for example,
  45211. // there is multiple region named "United Kindom" or "France" (so many
  45212. // colonies). And it is not appropriate to merge them in geo, which
  45213. // will make them share the same label and bring trouble in label
  45214. // location calculation.
  45215. var regionGroup = regionsGroupByName.get(regionName);
  45216. var _a = regionsInfoByName.get(regionName) || {},
  45217. dataIdx = _a.dataIdx,
  45218. regionModel = _a.regionModel;
  45219. if (!regionGroup) {
  45220. regionGroup = regionsGroupByName.set(regionName, new Group());
  45221. regionsGroup.add(regionGroup);
  45222. dataIdx = data ? data.indexOfName(regionName) : null;
  45223. regionModel = viewBuildCtx.isGeo ? mapOrGeoModel.getRegionModel(regionName) : data ? data.getItemModel(dataIdx) : null;
  45224. regionsInfoByName.set(regionName, {
  45225. dataIdx: dataIdx,
  45226. regionModel: regionModel
  45227. });
  45228. }
  45229. var compoundPath = new CompoundPath({
  45230. segmentIgnoreThreshold: 1,
  45231. shape: {
  45232. paths: []
  45233. }
  45234. });
  45235. regionGroup.add(compoundPath);
  45236. each(region.geometries, function (geometry) {
  45237. if (geometry.type !== 'polygon') {
  45238. return;
  45239. }
  45240. var points = [];
  45241. for (var i = 0; i < geometry.exterior.length; ++i) {
  45242. points.push(transformPoint(geometry.exterior[i]));
  45243. }
  45244. compoundPath.shape.paths.push(new Polygon({
  45245. segmentIgnoreThreshold: 1,
  45246. shape: {
  45247. points: points
  45248. }
  45249. }));
  45250. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); ++i) {
  45251. var interior = geometry.interiors[i];
  45252. var points_1 = [];
  45253. for (var j = 0; j < interior.length; ++j) {
  45254. points_1.push(transformPoint(interior[j]));
  45255. }
  45256. compoundPath.shape.paths.push(new Polygon({
  45257. segmentIgnoreThreshold: 1,
  45258. shape: {
  45259. points: points_1
  45260. }
  45261. }));
  45262. }
  45263. });
  45264. applyOptionStyleForRegion(viewBuildCtx, compoundPath, dataIdx, regionModel);
  45265. if (compoundPath instanceof Displayable) {
  45266. compoundPath.culling = true;
  45267. }
  45268. var centerPt = transformPoint(region.getCenter());
  45269. resetLabelForRegion(viewBuildCtx, compoundPath, regionName, regionModel, mapOrGeoModel, dataIdx, centerPt);
  45270. }); // Ensure children have been added to `regionGroup` before calling them.
  45271. regionsGroupByName.each(function (regionGroup, regionName) {
  45272. var _a = regionsInfoByName.get(regionName),
  45273. dataIdx = _a.dataIdx,
  45274. regionModel = _a.regionModel;
  45275. resetEventTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel, dataIdx);
  45276. resetTooltipForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel);
  45277. resetStateTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel);
  45278. }, this);
  45279. };
  45280. MapDraw.prototype._buildSVG = function (viewBuildCtx) {
  45281. var mapName = viewBuildCtx.geo.map;
  45282. var transformInfoRaw = viewBuildCtx.transformInfoRaw;
  45283. this._svgGroup.x = transformInfoRaw.x;
  45284. this._svgGroup.y = transformInfoRaw.y;
  45285. this._svgGroup.scaleX = transformInfoRaw.scaleX;
  45286. this._svgGroup.scaleY = transformInfoRaw.scaleY;
  45287. if (this._svgResourceChanged(mapName)) {
  45288. this._freeSVG();
  45289. this._useSVG(mapName);
  45290. }
  45291. var svgDispatcherMap = this._svgDispatcherMap = createHashMap();
  45292. var focusSelf = false;
  45293. each(this._svgGraphicRecord.named, function (namedItem) {
  45294. // Note that we also allow different elements have the same name.
  45295. // For example, a glyph of a city and the label of the city have
  45296. // the same name and their tooltip info can be defined in a single
  45297. // region option.
  45298. var regionName = namedItem.name;
  45299. var mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
  45300. var data = viewBuildCtx.data;
  45301. var svgNodeTagLower = namedItem.svgNodeTagLower;
  45302. var el = namedItem.el;
  45303. var dataIdx = data ? data.indexOfName(regionName) : null;
  45304. var regionModel = mapOrGeoModel.getRegionModel(regionName);
  45305. if (OPTION_STYLE_ENABLED_TAG_MAP.get(svgNodeTagLower) != null && el instanceof Displayable) {
  45306. applyOptionStyleForRegion(viewBuildCtx, el, dataIdx, regionModel);
  45307. }
  45308. if (el instanceof Displayable) {
  45309. el.culling = true;
  45310. } // We do not know how the SVG like so we'd better not to change z2.
  45311. // Otherwise it might bring some unexpected result. For example,
  45312. // an area hovered that make some inner city can not be clicked.
  45313. el.z2EmphasisLift = 0; // If self named:
  45314. if (!namedItem.namedFrom) {
  45315. // label should batter to be displayed based on the center of <g>
  45316. // if it is named rather than displayed on each child.
  45317. if (LABEL_HOST_MAP.get(svgNodeTagLower) != null) {
  45318. resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx, null);
  45319. }
  45320. resetEventTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx);
  45321. resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel);
  45322. if (STATE_TRIGGER_TAG_MAP.get(svgNodeTagLower) != null) {
  45323. var focus_1 = resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel);
  45324. if (focus_1 === 'self') {
  45325. focusSelf = true;
  45326. }
  45327. var els = svgDispatcherMap.get(regionName) || svgDispatcherMap.set(regionName, []);
  45328. els.push(el);
  45329. }
  45330. }
  45331. }, this);
  45332. this._enableBlurEntireSVG(focusSelf, viewBuildCtx);
  45333. };
  45334. MapDraw.prototype._enableBlurEntireSVG = function (focusSelf, viewBuildCtx) {
  45335. // It's a little complicated to support blurring the entire geoSVG in series-map.
  45336. // So do not suport it until some requirements come.
  45337. // At present, in series-map, only regions can be blurred.
  45338. if (focusSelf && viewBuildCtx.isGeo) {
  45339. var blurStyle = viewBuildCtx.mapOrGeoModel.getModel(['blur', 'itemStyle']).getItemStyle(); // Only suport `opacity` here. Because not sure that other props are suitable for
  45340. // all of the elements generated by SVG (especially for Text/TSpan/Image/... ).
  45341. var opacity_1 = blurStyle.opacity;
  45342. this._svgGraphicRecord.root.traverse(function (el) {
  45343. if (!el.isGroup) {
  45344. // PENDING: clear those settings to SVG elements when `_freeSVG`.
  45345. // (Currently it happen not to be needed.)
  45346. setDefaultStateProxy(el);
  45347. var style = el.ensureState('blur').style || {}; // Do not overwrite the region style that already set from region option.
  45348. if (style.opacity == null && opacity_1 != null) {
  45349. style.opacity = opacity_1;
  45350. } // If `ensureState('blur').style = {}`, there will be default opacity.
  45351. // Enable `stateTransition` (animation).
  45352. el.ensureState('emphasis');
  45353. }
  45354. });
  45355. }
  45356. };
  45357. MapDraw.prototype.remove = function () {
  45358. this._regionsGroup.removeAll();
  45359. this._regionsGroupByName = null;
  45360. this._svgGroup.removeAll();
  45361. this._freeSVG();
  45362. this._controller.dispose();
  45363. this._controllerHost = null;
  45364. };
  45365. MapDraw.prototype.findHighDownDispatchers = function (name, geoModel) {
  45366. if (name == null) {
  45367. return [];
  45368. }
  45369. var geo = geoModel.coordinateSystem;
  45370. if (geo.resourceType === 'geoJSON') {
  45371. var regionsGroupByName = this._regionsGroupByName;
  45372. if (regionsGroupByName) {
  45373. var regionGroup = regionsGroupByName.get(name);
  45374. return regionGroup ? [regionGroup] : [];
  45375. }
  45376. } else if (geo.resourceType === 'geoSVG') {
  45377. return this._svgDispatcherMap && this._svgDispatcherMap.get(name) || [];
  45378. }
  45379. };
  45380. MapDraw.prototype._svgResourceChanged = function (mapName) {
  45381. return this._svgMapName !== mapName;
  45382. };
  45383. MapDraw.prototype._useSVG = function (mapName) {
  45384. var resource = geoSourceManager.getGeoResource(mapName);
  45385. if (resource && resource.type === 'geoSVG') {
  45386. var svgGraphic = resource.useGraphic(this.uid);
  45387. this._svgGroup.add(svgGraphic.root);
  45388. this._svgGraphicRecord = svgGraphic;
  45389. this._svgMapName = mapName;
  45390. }
  45391. };
  45392. MapDraw.prototype._freeSVG = function () {
  45393. var mapName = this._svgMapName;
  45394. if (mapName == null) {
  45395. return;
  45396. }
  45397. var resource = geoSourceManager.getGeoResource(mapName);
  45398. if (resource && resource.type === 'geoSVG') {
  45399. resource.freeGraphic(this.uid);
  45400. }
  45401. this._svgGraphicRecord = null;
  45402. this._svgDispatcherMap = null;
  45403. this._svgGroup.removeAll();
  45404. this._svgMapName = null;
  45405. };
  45406. MapDraw.prototype._updateController = function (mapOrGeoModel, ecModel, api) {
  45407. var geo = mapOrGeoModel.coordinateSystem;
  45408. var controller = this._controller;
  45409. var controllerHost = this._controllerHost; // @ts-ignore FIXME:TS
  45410. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  45411. controllerHost.zoom = geo.getZoom(); // roamType is will be set default true if it is null
  45412. // @ts-ignore FIXME:TS
  45413. controller.enable(mapOrGeoModel.get('roam') || false);
  45414. var mainType = mapOrGeoModel.mainType;
  45415. function makeActionBase() {
  45416. var action = {
  45417. type: 'geoRoam',
  45418. componentType: mainType
  45419. };
  45420. action[mainType + 'Id'] = mapOrGeoModel.id;
  45421. return action;
  45422. }
  45423. controller.off('pan').on('pan', function (e) {
  45424. this._mouseDownFlag = false;
  45425. updateViewOnPan(controllerHost, e.dx, e.dy);
  45426. api.dispatchAction(extend(makeActionBase(), {
  45427. dx: e.dx,
  45428. dy: e.dy
  45429. }));
  45430. }, this);
  45431. controller.off('zoom').on('zoom', function (e) {
  45432. this._mouseDownFlag = false;
  45433. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  45434. api.dispatchAction(extend(makeActionBase(), {
  45435. zoom: e.scale,
  45436. originX: e.originX,
  45437. originY: e.originY
  45438. }));
  45439. }, this);
  45440. controller.setPointerChecker(function (e, x, y) {
  45441. return geo.containPoint([x, y]) && !onIrrelevantElement(e, api, mapOrGeoModel);
  45442. });
  45443. };
  45444. /**
  45445. * FIXME: this is a temporarily workaround.
  45446. * When `geoRoam` the elements need to be reset in `MapView['render']`, because the props like
  45447. * `ignore` might have been modified by `LabelManager`, and `LabelManager#addLabelsOfSeries`
  45448. * will subsequently cache `defaultAttr` like `ignore`. If do not do this reset, the modified
  45449. * props will have no chance to be restored.
  45450. * Note: this reset should be after `clearStates` in `renderSeries` becuase `useStates` in
  45451. * `renderSeries` will cache the modified `ignore` to `el._normalState`.
  45452. * TODO:
  45453. * Use clone/immutable in `LabelManager`?
  45454. */
  45455. MapDraw.prototype.resetForLabelLayout = function () {
  45456. this.group.traverse(function (el) {
  45457. var label = el.getTextContent();
  45458. if (label) {
  45459. label.ignore = mapLabelRaw(label).ignore;
  45460. }
  45461. });
  45462. };
  45463. MapDraw.prototype._updateMapSelectHandler = function (mapOrGeoModel, regionsGroup, api, fromView) {
  45464. var mapDraw = this;
  45465. regionsGroup.off('mousedown');
  45466. regionsGroup.off('click'); // @ts-ignore FIXME:TS resolve type conflict
  45467. if (mapOrGeoModel.get('selectedMode')) {
  45468. regionsGroup.on('mousedown', function () {
  45469. mapDraw._mouseDownFlag = true;
  45470. });
  45471. regionsGroup.on('click', function (e) {
  45472. if (!mapDraw._mouseDownFlag) {
  45473. return;
  45474. }
  45475. mapDraw._mouseDownFlag = false;
  45476. });
  45477. }
  45478. };
  45479. return MapDraw;
  45480. }();
  45481. function applyOptionStyleForRegion(viewBuildCtx, el, dataIndex, regionModel) {
  45482. // All of the path are using `itemStyle`, becuase
  45483. // (1) Some SVG also use fill on polyline (The different between
  45484. // polyline and polygon is "open" or "close" but not fill or not).
  45485. // (2) For the common props like opacity, if some use itemStyle
  45486. // and some use `lineStyle`, it might confuse users.
  45487. // (3) Most SVG use <path>, where can not detect wether draw a "line"
  45488. // or a filled shape, so use `itemStyle` for <path>.
  45489. var normalStyleModel = regionModel.getModel('itemStyle');
  45490. var emphasisStyleModel = regionModel.getModel(['emphasis', 'itemStyle']);
  45491. var blurStyleModel = regionModel.getModel(['blur', 'itemStyle']);
  45492. var selectStyleModel = regionModel.getModel(['select', 'itemStyle']); // NOTE: DONT use 'style' in visual when drawing map.
  45493. // This component is used for drawing underlying map for both geo component and map series.
  45494. var normalStyle = getFixedItemStyle(normalStyleModel);
  45495. var emphasisStyle = getFixedItemStyle(emphasisStyleModel);
  45496. var selectStyle = getFixedItemStyle(selectStyleModel);
  45497. var blurStyle = getFixedItemStyle(blurStyleModel); // Update the itemStyle if has data visual
  45498. var data = viewBuildCtx.data;
  45499. if (data) {
  45500. // Only visual color of each item will be used. It can be encoded by visualMap
  45501. // But visual color of series is used in symbol drawing
  45502. // Visual color for each series is for the symbol draw
  45503. var style = data.getItemVisual(dataIndex, 'style');
  45504. var decal = data.getItemVisual(dataIndex, 'decal');
  45505. if (viewBuildCtx.isVisualEncodedByVisualMap && style.fill) {
  45506. normalStyle.fill = style.fill;
  45507. }
  45508. if (decal) {
  45509. normalStyle.decal = createOrUpdatePatternFromDecal(decal, viewBuildCtx.api);
  45510. }
  45511. } // SVG text, tspan and image can be named but not supporeted
  45512. // to be styled by region option yet.
  45513. el.setStyle(normalStyle);
  45514. el.style.strokeNoScale = true;
  45515. el.ensureState('emphasis').style = emphasisStyle;
  45516. el.ensureState('select').style = selectStyle;
  45517. el.ensureState('blur').style = blurStyle; // Enable blur
  45518. setDefaultStateProxy(el);
  45519. }
  45520. function resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, // Exist only if `viewBuildCtx.data` exists.
  45521. dataIdx, // If labelXY not provided, use `textConfig.position: 'inside'`
  45522. labelXY) {
  45523. var data = viewBuildCtx.data;
  45524. var isGeo = viewBuildCtx.isGeo;
  45525. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  45526. var itemLayout = data && data.getItemLayout(dataIdx); // In the following cases label will be drawn
  45527. // 1. In map series and data value is NaN
  45528. // 2. In geo component
  45529. // 3. Region has no series legendIcon, which will be add a showLabel flag in mapSymbolLayout
  45530. if (isGeo || isDataNaN || itemLayout && itemLayout.showLabel) {
  45531. var query = !isGeo ? dataIdx : regionName;
  45532. var labelFetcher = void 0; // Consider dataIdx not found.
  45533. if (!data || dataIdx >= 0) {
  45534. labelFetcher = mapOrGeoModel;
  45535. }
  45536. var specifiedTextOpt = labelXY ? {
  45537. normal: {
  45538. align: 'center',
  45539. verticalAlign: 'middle'
  45540. }
  45541. } : null; // Caveat: must be called after `setDefaultStateProxy(el);` called.
  45542. // because textContent will be assign with `el.stateProxy` inside.
  45543. setLabelStyle(el, getLabelStatesModels(regionModel), {
  45544. labelFetcher: labelFetcher,
  45545. labelDataIndex: query,
  45546. defaultText: regionName
  45547. }, specifiedTextOpt);
  45548. var textEl = el.getTextContent();
  45549. if (textEl) {
  45550. mapLabelRaw(textEl).ignore = textEl.ignore;
  45551. if (el.textConfig && labelXY) {
  45552. // Compute a relative offset based on the el bounding rect.
  45553. var rect = el.getBoundingRect().clone(); // Need to make sure the percent position base on the same rect in normal and
  45554. // emphasis state. Otherwise if using boundingRect of el, but the emphasis state
  45555. // has borderWidth (even 0.5px), the text position will be changed obviously
  45556. // if the position is very big like ['1234%', '1345%'].
  45557. el.textConfig.layoutRect = rect;
  45558. el.textConfig.position = [(labelXY[0] - rect.x) / rect.width * 100 + '%', (labelXY[1] - rect.y) / rect.height * 100 + '%'];
  45559. }
  45560. } // PENDING:
  45561. // If labelLayout is enabled (test/label-layout.html), el.dataIndex should be specified.
  45562. // But el.dataIndex is also used to determine whether user event should be triggered,
  45563. // where el.seriesIndex or el.dataModel must be specified. At present for a single el
  45564. // there is not case that "only label layout enabled but user event disabled", so here
  45565. // we depends `resetEventTriggerForRegion` to do the job of setting `el.dataIndex`.
  45566. el.disableLabelAnimation = true;
  45567. } else {
  45568. el.removeTextContent();
  45569. el.removeTextConfig();
  45570. el.disableLabelAnimation = null;
  45571. }
  45572. }
  45573. function resetEventTriggerForRegion(viewBuildCtx, eventTrigger, regionName, regionModel, mapOrGeoModel, // Exist only if `viewBuildCtx.data` exists.
  45574. dataIdx) {
  45575. // setItemGraphicEl, setHoverStyle after all polygons and labels
  45576. // are added to the rigionGroup
  45577. if (viewBuildCtx.data) {
  45578. // FIXME: when series-map use a SVG map, and there are duplicated name specified
  45579. // on different SVG elements, after `data.setItemGraphicEl(...)`:
  45580. // (1) all of them will be mounted with `dataIndex`, `seriesIndex`, so that tooltip
  45581. // can be triggered only mouse hover. That's correct.
  45582. // (2) only the last element will be kept in `data`, so that if trigger tooltip
  45583. // by `dispatchAction`, only the last one can be found and triggered. That might be
  45584. // not correct. We will fix it in future if anyone demanding that.
  45585. viewBuildCtx.data.setItemGraphicEl(dataIdx, eventTrigger);
  45586. } // series-map will not trigger "geoselectchange" no matter it is
  45587. // based on a declared geo component. Becuause series-map will
  45588. // trigger "selectchange". If it trigger both the two events,
  45589. // If users call `chart.dispatchAction({type: 'toggleSelect'})`,
  45590. // it not easy to also fire event "geoselectchanged".
  45591. else {
  45592. // Package custom mouse event for geo component
  45593. getECData(eventTrigger).eventData = {
  45594. componentType: 'geo',
  45595. componentIndex: mapOrGeoModel.componentIndex,
  45596. geoIndex: mapOrGeoModel.componentIndex,
  45597. name: regionName,
  45598. region: regionModel && regionModel.option || {}
  45599. };
  45600. }
  45601. }
  45602. function resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) {
  45603. if (!viewBuildCtx.data) {
  45604. setTooltipConfig({
  45605. el: el,
  45606. componentModel: mapOrGeoModel,
  45607. itemName: regionName,
  45608. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  45609. itemTooltipOption: regionModel.get('tooltip')
  45610. });
  45611. }
  45612. }
  45613. function resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) {
  45614. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  45615. el.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode'); // @ts-ignore FIXME:TS fix the "compatible with each other"?
  45616. var emphasisModel = regionModel.getModel('emphasis');
  45617. var focus = emphasisModel.get('focus');
  45618. enableHoverEmphasis(el, focus, emphasisModel.get('blurScope'));
  45619. if (viewBuildCtx.isGeo) {
  45620. enableComponentHighDownFeatures(el, mapOrGeoModel, regionName);
  45621. }
  45622. return focus;
  45623. }
  45624. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  45625. var MapView =
  45626. /** @class */
  45627. function (_super) {
  45628. __extends(MapView, _super);
  45629. function MapView() {
  45630. var _this = _super !== null && _super.apply(this, arguments) || this;
  45631. _this.type = MapView.type;
  45632. return _this;
  45633. }
  45634. MapView.prototype.render = function (mapModel, ecModel, api, payload) {
  45635. // Not render if it is an toggleSelect action from self
  45636. if (payload && payload.type === 'mapToggleSelect' && payload.from === this.uid) {
  45637. return;
  45638. }
  45639. var group = this.group;
  45640. group.removeAll();
  45641. if (mapModel.getHostGeoModel()) {
  45642. return;
  45643. }
  45644. if (this._mapDraw && payload && payload.type === 'geoRoam') {
  45645. this._mapDraw.resetForLabelLayout();
  45646. } // Not update map if it is an roam action from self
  45647. if (!(payload && payload.type === 'geoRoam' && payload.componentType === 'series' && payload.seriesId === mapModel.id)) {
  45648. if (mapModel.needsDrawMap) {
  45649. var mapDraw = this._mapDraw || new MapDraw(api);
  45650. group.add(mapDraw.group);
  45651. mapDraw.draw(mapModel, ecModel, api, this, payload);
  45652. this._mapDraw = mapDraw;
  45653. } else {
  45654. // Remove drawed map
  45655. this._mapDraw && this._mapDraw.remove();
  45656. this._mapDraw = null;
  45657. }
  45658. } else {
  45659. var mapDraw = this._mapDraw;
  45660. mapDraw && group.add(mapDraw.group);
  45661. }
  45662. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend') && this._renderSymbols(mapModel, ecModel, api);
  45663. };
  45664. MapView.prototype.remove = function () {
  45665. this._mapDraw && this._mapDraw.remove();
  45666. this._mapDraw = null;
  45667. this.group.removeAll();
  45668. };
  45669. MapView.prototype.dispose = function () {
  45670. this._mapDraw && this._mapDraw.remove();
  45671. this._mapDraw = null;
  45672. };
  45673. MapView.prototype._renderSymbols = function (mapModel, ecModel, api) {
  45674. var originalData = mapModel.originalData;
  45675. var group = this.group;
  45676. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  45677. if (isNaN(value)) {
  45678. return;
  45679. }
  45680. var layout = originalData.getItemLayout(originalDataIndex);
  45681. if (!layout || !layout.point) {
  45682. // Not exists in map
  45683. return;
  45684. }
  45685. var point = layout.point;
  45686. var offset = layout.offset;
  45687. var circle = new Circle({
  45688. style: {
  45689. // Because the special of map draw.
  45690. // Which needs statistic of multiple series and draw on one map.
  45691. // And each series also need a symbol with legend color
  45692. //
  45693. // Layout and visual are put one the different data
  45694. // TODO
  45695. fill: mapModel.getData().getVisual('style').fill
  45696. },
  45697. shape: {
  45698. cx: point[0] + offset * 9,
  45699. cy: point[1],
  45700. r: 3
  45701. },
  45702. silent: true,
  45703. // Do not overlap the first series, on which labels are displayed.
  45704. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  45705. }); // Only the series that has the first value on the same region is in charge of rendering the label.
  45706. // But consider the case:
  45707. // series: [
  45708. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  45709. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  45710. // ]
  45711. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  45712. // For backward compatibility, we follow the rule that render label `A` by the
  45713. // settings on series `X` but render label `C` by the settings on series `Y`.
  45714. if (!offset) {
  45715. var fullData = mapModel.mainSeries.getData();
  45716. var name_1 = originalData.getName(originalDataIndex);
  45717. var fullIndex_1 = fullData.indexOfName(name_1);
  45718. var itemModel = originalData.getItemModel(originalDataIndex);
  45719. var labelModel = itemModel.getModel('label');
  45720. var regionGroup = fullData.getItemGraphicEl(fullIndex_1); // `getFormattedLabel` needs to use `getData` inside. Here
  45721. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  45722. // FIXME
  45723. // If this is not the `mainSeries`, the item model (like label formatter)
  45724. // set on original data item will never get. But it has been working
  45725. // like that from the begining, and this scenario is rarely encountered.
  45726. // So it won't be fixed until have to.
  45727. setLabelStyle(circle, getLabelStatesModels(itemModel), {
  45728. labelFetcher: {
  45729. getFormattedLabel: function (idx, state) {
  45730. return mapModel.getFormattedLabel(fullIndex_1, state);
  45731. }
  45732. }
  45733. });
  45734. circle.disableLabelAnimation = true;
  45735. if (!labelModel.get('position')) {
  45736. circle.setTextConfig({
  45737. position: 'bottom'
  45738. });
  45739. }
  45740. regionGroup.onHoverStateChange = function (toState) {
  45741. setStatesFlag(circle, toState);
  45742. };
  45743. }
  45744. group.add(circle);
  45745. });
  45746. };
  45747. MapView.type = 'map';
  45748. return MapView;
  45749. }(ChartView);
  45750. var MapSeries =
  45751. /** @class */
  45752. function (_super) {
  45753. __extends(MapSeries, _super);
  45754. function MapSeries() {
  45755. var _this = _super !== null && _super.apply(this, arguments) || this;
  45756. _this.type = MapSeries.type; // Only first map series of same mapType will drawMap.
  45757. _this.needsDrawMap = false; // Group of all map series with same mapType
  45758. _this.seriesGroup = [];
  45759. _this.getTooltipPosition = function (dataIndex) {
  45760. if (dataIndex != null) {
  45761. var name_1 = this.getData().getName(dataIndex);
  45762. var geo = this.coordinateSystem;
  45763. var region = geo.getRegion(name_1);
  45764. return region && geo.dataToPoint(region.getCenter());
  45765. }
  45766. };
  45767. return _this;
  45768. }
  45769. MapSeries.prototype.getInitialData = function (option) {
  45770. var data = createSeriesDataSimply(this, {
  45771. coordDimensions: ['value'],
  45772. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  45773. });
  45774. var dataNameMap = createHashMap();
  45775. var toAppendNames = [];
  45776. for (var i = 0, len = data.count(); i < len; i++) {
  45777. var name_2 = data.getName(i);
  45778. dataNameMap.set(name_2, true);
  45779. }
  45780. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap, this.option.nameProperty);
  45781. each(geoSource.regions, function (region) {
  45782. var name = region.name;
  45783. if (!dataNameMap.get(name)) {
  45784. toAppendNames.push(name);
  45785. }
  45786. }); // Complete data with missing regions. The consequent processes (like visual
  45787. // map and render) can not be performed without a "full data". For example,
  45788. // find `dataIndex` by name.
  45789. data.appendValues([], toAppendNames);
  45790. return data;
  45791. };
  45792. /**
  45793. * If no host geo model, return null, which means using a
  45794. * inner exclusive geo model.
  45795. */
  45796. MapSeries.prototype.getHostGeoModel = function () {
  45797. var geoIndex = this.option.geoIndex;
  45798. return geoIndex != null ? this.ecModel.getComponent('geo', geoIndex) : null;
  45799. };
  45800. MapSeries.prototype.getMapType = function () {
  45801. return (this.getHostGeoModel() || this).option.map;
  45802. }; // _fillOption(option, mapName) {
  45803. // Shallow clone
  45804. // option = zrUtil.extend({}, option);
  45805. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  45806. // return option;
  45807. // }
  45808. MapSeries.prototype.getRawValue = function (dataIndex) {
  45809. // Use value stored in data instead because it is calculated from multiple series
  45810. // FIXME Provide all value of multiple series ?
  45811. var data = this.getData();
  45812. return data.get(data.mapDimension('value'), dataIndex);
  45813. };
  45814. /**
  45815. * Get model of region
  45816. */
  45817. MapSeries.prototype.getRegionModel = function (regionName) {
  45818. var data = this.getData();
  45819. return data.getItemModel(data.indexOfName(regionName));
  45820. };
  45821. /**
  45822. * Map tooltip formatter
  45823. */
  45824. MapSeries.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  45825. // FIXME orignalData and data is a bit confusing
  45826. var data = this.getData();
  45827. var value = this.getRawValue(dataIndex);
  45828. var name = data.getName(dataIndex);
  45829. var seriesGroup = this.seriesGroup;
  45830. var seriesNames = [];
  45831. for (var i = 0; i < seriesGroup.length; i++) {
  45832. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  45833. var valueDim = data.mapDimension('value');
  45834. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  45835. seriesNames.push(seriesGroup[i].name);
  45836. }
  45837. }
  45838. return createTooltipMarkup('section', {
  45839. header: seriesNames.join(', '),
  45840. noHeader: !seriesNames.length,
  45841. blocks: [createTooltipMarkup('nameValue', {
  45842. name: name,
  45843. value: value
  45844. })]
  45845. });
  45846. };
  45847. MapSeries.prototype.setZoom = function (zoom) {
  45848. this.option.zoom = zoom;
  45849. };
  45850. MapSeries.prototype.setCenter = function (center) {
  45851. this.option.center = center;
  45852. };
  45853. MapSeries.prototype.getLegendIcon = function (opt) {
  45854. var iconType = opt.icon || 'roundRect';
  45855. var icon = createSymbol(iconType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill);
  45856. icon.setStyle(opt.itemStyle); // Map do not use itemStyle.borderWidth as border width
  45857. icon.style.stroke = 'none'; // No rotation because no series visual symbol for map
  45858. if (iconType.indexOf('empty') > -1) {
  45859. icon.style.stroke = icon.style.fill;
  45860. icon.style.fill = '#fff';
  45861. icon.style.lineWidth = 2;
  45862. }
  45863. return icon;
  45864. };
  45865. MapSeries.type = 'series.map';
  45866. MapSeries.dependencies = ['geo'];
  45867. MapSeries.layoutMode = 'box';
  45868. MapSeries.defaultOption = {
  45869. // 一级层叠
  45870. zlevel: 0,
  45871. // 二级层叠
  45872. z: 2,
  45873. coordinateSystem: 'geo',
  45874. // map should be explicitly specified since ec3.
  45875. map: '',
  45876. // If `geoIndex` is not specified, a exclusive geo will be
  45877. // created. Otherwise use the specified geo component, and
  45878. // `map` and `mapType` are ignored.
  45879. // geoIndex: 0,
  45880. // 'center' | 'left' | 'right' | 'x%' | {number}
  45881. left: 'center',
  45882. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  45883. top: 'center',
  45884. // right
  45885. // bottom
  45886. // width:
  45887. // height
  45888. // Aspect is width / height. Inited to be geoJson bbox aspect
  45889. // This parameter is used for scale this aspect
  45890. // Default value:
  45891. // for geoSVG source: 1,
  45892. // for geoJSON source: 0.75.
  45893. aspectScale: null,
  45894. ///// Layout with center and size
  45895. // If you wan't to put map in a fixed size box with right aspect ratio
  45896. // This two properties may more conveninet
  45897. // layoutCenter: [50%, 50%]
  45898. // layoutSize: 100
  45899. showLegendSymbol: true,
  45900. // Define left-top, right-bottom coords to control view
  45901. // For example, [ [180, 90], [-180, -90] ],
  45902. // higher priority than center and zoom
  45903. boundingCoords: null,
  45904. // Default on center of map
  45905. center: null,
  45906. zoom: 1,
  45907. scaleLimit: null,
  45908. selectedMode: true,
  45909. label: {
  45910. show: false,
  45911. color: '#000'
  45912. },
  45913. // scaleLimit: null,
  45914. itemStyle: {
  45915. borderWidth: 0.5,
  45916. borderColor: '#444',
  45917. areaColor: '#eee'
  45918. },
  45919. emphasis: {
  45920. label: {
  45921. show: true,
  45922. color: 'rgb(100,0,0)'
  45923. },
  45924. itemStyle: {
  45925. areaColor: 'rgba(255,215,0,0.8)'
  45926. }
  45927. },
  45928. select: {
  45929. label: {
  45930. show: true,
  45931. color: 'rgb(100,0,0)'
  45932. },
  45933. itemStyle: {
  45934. color: 'rgba(255,215,0,0.8)'
  45935. }
  45936. },
  45937. nameProperty: 'name'
  45938. };
  45939. return MapSeries;
  45940. }(SeriesModel);
  45941. function dataStatistics(datas, statisticType) {
  45942. var dataNameMap = {};
  45943. each(datas, function (data) {
  45944. data.each(data.mapDimension('value'), function (value, idx) {
  45945. // Add prefix to avoid conflict with Object.prototype.
  45946. var mapKey = 'ec-' + data.getName(idx);
  45947. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  45948. if (!isNaN(value)) {
  45949. dataNameMap[mapKey].push(value);
  45950. }
  45951. });
  45952. });
  45953. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  45954. var mapKey = 'ec-' + datas[0].getName(idx);
  45955. var sum = 0;
  45956. var min = Infinity;
  45957. var max = -Infinity;
  45958. var len = dataNameMap[mapKey].length;
  45959. for (var i = 0; i < len; i++) {
  45960. min = Math.min(min, dataNameMap[mapKey][i]);
  45961. max = Math.max(max, dataNameMap[mapKey][i]);
  45962. sum += dataNameMap[mapKey][i];
  45963. }
  45964. var result;
  45965. if (statisticType === 'min') {
  45966. result = min;
  45967. } else if (statisticType === 'max') {
  45968. result = max;
  45969. } else if (statisticType === 'average') {
  45970. result = sum / len;
  45971. } else {
  45972. result = sum;
  45973. }
  45974. return len === 0 ? NaN : result;
  45975. });
  45976. }
  45977. function mapDataStatistic(ecModel) {
  45978. var seriesGroups = {};
  45979. ecModel.eachSeriesByType('map', function (seriesModel) {
  45980. var hostGeoModel = seriesModel.getHostGeoModel();
  45981. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  45982. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  45983. });
  45984. each(seriesGroups, function (seriesList, key) {
  45985. var data = dataStatistics(map(seriesList, function (seriesModel) {
  45986. return seriesModel.getData();
  45987. }), seriesList[0].get('mapValueCalculation'));
  45988. for (var i = 0; i < seriesList.length; i++) {
  45989. seriesList[i].originalData = seriesList[i].getData();
  45990. } // FIXME Put where?
  45991. for (var i = 0; i < seriesList.length; i++) {
  45992. seriesList[i].seriesGroup = seriesList;
  45993. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  45994. seriesList[i].setData(data.cloneShallow());
  45995. seriesList[i].mainSeries = seriesList[0];
  45996. }
  45997. });
  45998. }
  45999. function mapSymbolLayout(ecModel) {
  46000. var processedMapType = {};
  46001. ecModel.eachSeriesByType('map', function (mapSeries) {
  46002. var mapType = mapSeries.getMapType();
  46003. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  46004. return;
  46005. }
  46006. var mapSymbolOffsets = {};
  46007. each(mapSeries.seriesGroup, function (subMapSeries) {
  46008. var geo = subMapSeries.coordinateSystem;
  46009. var data = subMapSeries.originalData;
  46010. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  46011. data.each(data.mapDimension('value'), function (value, idx) {
  46012. var name = data.getName(idx);
  46013. var region = geo.getRegion(name); // If input series.data is [11, 22, '-'/null/undefined, 44],
  46014. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  46015. // not be drawn. So here must validate if value is NaN.
  46016. if (!region || isNaN(value)) {
  46017. return;
  46018. }
  46019. var offset = mapSymbolOffsets[name] || 0;
  46020. var point = geo.dataToPoint(region.getCenter());
  46021. mapSymbolOffsets[name] = offset + 1;
  46022. data.setItemLayout(idx, {
  46023. point: point,
  46024. offset: offset
  46025. });
  46026. });
  46027. }
  46028. }); // Show label of those region not has legendIcon (which is offset 0)
  46029. var data = mapSeries.getData();
  46030. data.each(function (idx) {
  46031. var name = data.getName(idx);
  46032. var layout = data.getItemLayout(idx) || {};
  46033. layout.showLabel = !mapSymbolOffsets[name];
  46034. data.setItemLayout(idx, layout);
  46035. });
  46036. processedMapType[mapType] = true;
  46037. });
  46038. }
  46039. var v2ApplyTransform = applyTransform;
  46040. var View =
  46041. /** @class */
  46042. function (_super) {
  46043. __extends(View, _super);
  46044. function View(name) {
  46045. var _this = _super.call(this) || this;
  46046. _this.type = 'view';
  46047. _this.dimensions = ['x', 'y'];
  46048. /**
  46049. * Represents the transform brought by roam/zoom.
  46050. * If `View['_viewRect']` applies roam transform,
  46051. * we can get the final displayed rect.
  46052. */
  46053. _this._roamTransformable = new Transformable();
  46054. /**
  46055. * Represents the transform from `View['_rect']` to `View['_viewRect']`.
  46056. */
  46057. _this._rawTransformable = new Transformable();
  46058. _this.name = name;
  46059. return _this;
  46060. }
  46061. View.prototype.setBoundingRect = function (x, y, width, height) {
  46062. this._rect = new BoundingRect(x, y, width, height);
  46063. return this._rect;
  46064. };
  46065. /**
  46066. * @return {module:zrender/core/BoundingRect}
  46067. */
  46068. View.prototype.getBoundingRect = function () {
  46069. return this._rect;
  46070. };
  46071. View.prototype.setViewRect = function (x, y, width, height) {
  46072. this._transformTo(x, y, width, height);
  46073. this._viewRect = new BoundingRect(x, y, width, height);
  46074. };
  46075. /**
  46076. * Transformed to particular position and size
  46077. */
  46078. View.prototype._transformTo = function (x, y, width, height) {
  46079. var rect = this.getBoundingRect();
  46080. var rawTransform = this._rawTransformable;
  46081. rawTransform.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  46082. var rawParent = rawTransform.parent;
  46083. rawTransform.parent = null;
  46084. rawTransform.decomposeTransform();
  46085. rawTransform.parent = rawParent;
  46086. this._updateTransform();
  46087. };
  46088. /**
  46089. * Set center of view
  46090. */
  46091. View.prototype.setCenter = function (centerCoord) {
  46092. if (!centerCoord) {
  46093. return;
  46094. }
  46095. this._center = centerCoord;
  46096. this._updateCenterAndZoom();
  46097. };
  46098. View.prototype.setZoom = function (zoom) {
  46099. zoom = zoom || 1;
  46100. var zoomLimit = this.zoomLimit;
  46101. if (zoomLimit) {
  46102. if (zoomLimit.max != null) {
  46103. zoom = Math.min(zoomLimit.max, zoom);
  46104. }
  46105. if (zoomLimit.min != null) {
  46106. zoom = Math.max(zoomLimit.min, zoom);
  46107. }
  46108. }
  46109. this._zoom = zoom;
  46110. this._updateCenterAndZoom();
  46111. };
  46112. /**
  46113. * Get default center without roam
  46114. */
  46115. View.prototype.getDefaultCenter = function () {
  46116. // Rect before any transform
  46117. var rawRect = this.getBoundingRect();
  46118. var cx = rawRect.x + rawRect.width / 2;
  46119. var cy = rawRect.y + rawRect.height / 2;
  46120. return [cx, cy];
  46121. };
  46122. View.prototype.getCenter = function () {
  46123. return this._center || this.getDefaultCenter();
  46124. };
  46125. View.prototype.getZoom = function () {
  46126. return this._zoom || 1;
  46127. };
  46128. View.prototype.getRoamTransform = function () {
  46129. return this._roamTransformable.getLocalTransform();
  46130. };
  46131. /**
  46132. * Remove roam
  46133. */
  46134. View.prototype._updateCenterAndZoom = function () {
  46135. // Must update after view transform updated
  46136. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  46137. var roamTransform = this._roamTransformable;
  46138. var defaultCenter = this.getDefaultCenter();
  46139. var center = this.getCenter();
  46140. var zoom = this.getZoom();
  46141. center = applyTransform([], center, rawTransformMatrix);
  46142. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  46143. roamTransform.originX = center[0];
  46144. roamTransform.originY = center[1];
  46145. roamTransform.x = defaultCenter[0] - center[0];
  46146. roamTransform.y = defaultCenter[1] - center[1];
  46147. roamTransform.scaleX = roamTransform.scaleY = zoom;
  46148. this._updateTransform();
  46149. };
  46150. /**
  46151. * Update transform props on `this` based on the current
  46152. * `this._roamTransformable` and `this._rawTransformable`.
  46153. */
  46154. View.prototype._updateTransform = function () {
  46155. var roamTransformable = this._roamTransformable;
  46156. var rawTransformable = this._rawTransformable;
  46157. rawTransformable.parent = roamTransformable;
  46158. roamTransformable.updateTransform();
  46159. rawTransformable.updateTransform();
  46160. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  46161. this._rawTransform = rawTransformable.getLocalTransform();
  46162. this.invTransform = this.invTransform || [];
  46163. invert(this.invTransform, this.transform);
  46164. this.decomposeTransform();
  46165. };
  46166. View.prototype.getTransformInfo = function () {
  46167. var rawTransformable = this._rawTransformable;
  46168. var roamTransformable = this._roamTransformable; // Becuase roamTransformabel has `originX/originY` modified,
  46169. // but the caller of `getTransformInfo` can not handle `originX/originY`,
  46170. // so need to recalcualte them.
  46171. var dummyTransformable = new Transformable();
  46172. dummyTransformable.transform = roamTransformable.transform;
  46173. dummyTransformable.decomposeTransform();
  46174. return {
  46175. roam: {
  46176. x: dummyTransformable.x,
  46177. y: dummyTransformable.y,
  46178. scaleX: dummyTransformable.scaleX,
  46179. scaleY: dummyTransformable.scaleY
  46180. },
  46181. raw: {
  46182. x: rawTransformable.x,
  46183. y: rawTransformable.y,
  46184. scaleX: rawTransformable.scaleX,
  46185. scaleY: rawTransformable.scaleY
  46186. }
  46187. };
  46188. };
  46189. View.prototype.getViewRect = function () {
  46190. return this._viewRect;
  46191. };
  46192. /**
  46193. * Get view rect after roam transform
  46194. */
  46195. View.prototype.getViewRectAfterRoam = function () {
  46196. var rect = this.getBoundingRect().clone();
  46197. rect.applyTransform(this.transform);
  46198. return rect;
  46199. };
  46200. /**
  46201. * Convert a single (lon, lat) data item to (x, y) point.
  46202. */
  46203. View.prototype.dataToPoint = function (data, noRoam, out) {
  46204. var transform = noRoam ? this._rawTransform : this.transform;
  46205. out = out || [];
  46206. return transform ? v2ApplyTransform(out, data, transform) : copy(out, data);
  46207. };
  46208. /**
  46209. * Convert a (x, y) point to (lon, lat) data
  46210. */
  46211. View.prototype.pointToData = function (point) {
  46212. var invTransform = this.invTransform;
  46213. return invTransform ? v2ApplyTransform([], point, invTransform) : [point[0], point[1]];
  46214. };
  46215. View.prototype.convertToPixel = function (ecModel, finder, value) {
  46216. var coordSys = getCoordSys(finder);
  46217. return coordSys === this ? coordSys.dataToPoint(value) : null;
  46218. };
  46219. View.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  46220. var coordSys = getCoordSys(finder);
  46221. return coordSys === this ? coordSys.pointToData(pixel) : null;
  46222. };
  46223. /**
  46224. * @implements
  46225. */
  46226. View.prototype.containPoint = function (point) {
  46227. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  46228. };
  46229. View.dimensions = ['x', 'y'];
  46230. return View;
  46231. }(Transformable);
  46232. function getCoordSys(finder) {
  46233. var seriesModel = finder.seriesModel;
  46234. return seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  46235. }
  46236. var GEO_DEFAULT_PARAMS = {
  46237. 'geoJSON': {
  46238. aspectScale: 0.75,
  46239. invertLongitute: true
  46240. },
  46241. 'geoSVG': {
  46242. aspectScale: 1,
  46243. invertLongitute: false
  46244. }
  46245. };
  46246. var geo2DDimensions = ['lng', 'lat'];
  46247. var Geo =
  46248. /** @class */
  46249. function (_super) {
  46250. __extends(Geo, _super);
  46251. function Geo(name, map, opt) {
  46252. var _this = _super.call(this, name) || this;
  46253. _this.dimensions = geo2DDimensions;
  46254. _this.type = 'geo'; // Only store specified name coord via `addGeoCoord`.
  46255. _this._nameCoordMap = createHashMap();
  46256. _this.map = map;
  46257. var source = geoSourceManager.load(map, opt.nameMap, opt.nameProperty);
  46258. var resource = geoSourceManager.getGeoResource(map);
  46259. _this.resourceType = resource ? resource.type : null;
  46260. var defaultParmas = GEO_DEFAULT_PARAMS[resource.type];
  46261. _this._regionsMap = source.regionsMap;
  46262. _this._invertLongitute = defaultParmas.invertLongitute;
  46263. _this.regions = source.regions;
  46264. _this.aspectScale = retrieve2(opt.aspectScale, defaultParmas.aspectScale);
  46265. var boundingRect = source.boundingRect;
  46266. _this.setBoundingRect(boundingRect.x, boundingRect.y, boundingRect.width, boundingRect.height);
  46267. return _this;
  46268. }
  46269. /**
  46270. * Whether contain the given [lng, lat] coord.
  46271. */
  46272. // Never used yet.
  46273. // containCoord(coord: number[]) {
  46274. // const regions = this.regions;
  46275. // for (let i = 0; i < regions.length; i++) {
  46276. // const region = regions[i];
  46277. // if (region.type === 'geoJSON' && (region as GeoJSONRegion).contain(coord)) {
  46278. // return true;
  46279. // }
  46280. // }
  46281. // return false;
  46282. // }
  46283. Geo.prototype._transformTo = function (x, y, width, height) {
  46284. var rect = this.getBoundingRect();
  46285. var invertLongitute = this._invertLongitute;
  46286. rect = rect.clone();
  46287. if (invertLongitute) {
  46288. // Longitute is inverted
  46289. rect.y = -rect.y - rect.height;
  46290. }
  46291. var rawTransformable = this._rawTransformable;
  46292. rawTransformable.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  46293. var rawParent = rawTransformable.parent;
  46294. rawTransformable.parent = null;
  46295. rawTransformable.decomposeTransform();
  46296. rawTransformable.parent = rawParent;
  46297. if (invertLongitute) {
  46298. rawTransformable.scaleY = -rawTransformable.scaleY;
  46299. }
  46300. this._updateTransform();
  46301. };
  46302. Geo.prototype.getRegion = function (name) {
  46303. return this._regionsMap.get(name);
  46304. };
  46305. Geo.prototype.getRegionByCoord = function (coord) {
  46306. var regions = this.regions;
  46307. for (var i = 0; i < regions.length; i++) {
  46308. var region = regions[i];
  46309. if (region.type === 'geoJSON' && region.contain(coord)) {
  46310. return regions[i];
  46311. }
  46312. }
  46313. };
  46314. /**
  46315. * Add geoCoord for indexing by name
  46316. */
  46317. Geo.prototype.addGeoCoord = function (name, geoCoord) {
  46318. this._nameCoordMap.set(name, geoCoord);
  46319. };
  46320. /**
  46321. * Get geoCoord by name
  46322. */
  46323. Geo.prototype.getGeoCoord = function (name) {
  46324. var region = this._regionsMap.get(name); // calcualte center only on demand.
  46325. return this._nameCoordMap.get(name) || region && region.getCenter();
  46326. };
  46327. Geo.prototype.dataToPoint = function (data, noRoam, out) {
  46328. if (typeof data === 'string') {
  46329. // Map area name to geoCoord
  46330. data = this.getGeoCoord(data);
  46331. }
  46332. if (data) {
  46333. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  46334. }
  46335. };
  46336. Geo.prototype.convertToPixel = function (ecModel, finder, value) {
  46337. var coordSys = getCoordSys$1(finder);
  46338. return coordSys === this ? coordSys.dataToPoint(value) : null;
  46339. };
  46340. Geo.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  46341. var coordSys = getCoordSys$1(finder);
  46342. return coordSys === this ? coordSys.pointToData(pixel) : null;
  46343. };
  46344. return Geo;
  46345. }(View);
  46346. mixin(Geo, View);
  46347. function getCoordSys$1(finder) {
  46348. var geoModel = finder.geoModel;
  46349. var seriesModel = finder.seriesModel;
  46350. return geoModel ? geoModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem // For map series.
  46351. || (seriesModel.getReferringComponents('geo', SINGLE_REFERRING).models[0] || {}).coordinateSystem : null;
  46352. }
  46353. /**
  46354. * Resize method bound to the geo
  46355. */
  46356. function resizeGeo(geoModel, api) {
  46357. var boundingCoords = geoModel.get('boundingCoords');
  46358. if (boundingCoords != null) {
  46359. var leftTop = boundingCoords[0];
  46360. var rightBottom = boundingCoords[1];
  46361. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  46362. if ("development" !== 'production') {
  46363. console.error('Invalid boundingCoords');
  46364. }
  46365. } else {
  46366. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  46367. }
  46368. }
  46369. var rect = this.getBoundingRect();
  46370. var centerOption = geoModel.get('layoutCenter');
  46371. var sizeOption = geoModel.get('layoutSize');
  46372. var viewWidth = api.getWidth();
  46373. var viewHeight = api.getHeight();
  46374. var aspect = rect.width / rect.height * this.aspectScale;
  46375. var useCenterAndSize = false;
  46376. var center;
  46377. var size;
  46378. if (centerOption && sizeOption) {
  46379. center = [parsePercent$1(centerOption[0], viewWidth), parsePercent$1(centerOption[1], viewHeight)];
  46380. size = parsePercent$1(sizeOption, Math.min(viewWidth, viewHeight));
  46381. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  46382. useCenterAndSize = true;
  46383. } else {
  46384. if ("development" !== 'production') {
  46385. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  46386. }
  46387. }
  46388. }
  46389. var viewRect;
  46390. if (useCenterAndSize) {
  46391. viewRect = {};
  46392. if (aspect > 1) {
  46393. // Width is same with size
  46394. viewRect.width = size;
  46395. viewRect.height = size / aspect;
  46396. } else {
  46397. viewRect.height = size;
  46398. viewRect.width = size * aspect;
  46399. }
  46400. viewRect.y = center[1] - viewRect.height / 2;
  46401. viewRect.x = center[0] - viewRect.width / 2;
  46402. } else {
  46403. // Use left/top/width/height
  46404. var boxLayoutOption = geoModel.getBoxLayoutParams();
  46405. boxLayoutOption.aspect = aspect;
  46406. viewRect = getLayoutRect(boxLayoutOption, {
  46407. width: viewWidth,
  46408. height: viewHeight
  46409. });
  46410. }
  46411. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  46412. this.setCenter(geoModel.get('center'));
  46413. this.setZoom(geoModel.get('zoom'));
  46414. } // Back compat for ECharts2, where the coord map is set on map series:
  46415. // {type: 'map', geoCoord: {'cityA': [116.46,39.92], 'cityA': [119.12,24.61]}},
  46416. function setGeoCoords(geo, model) {
  46417. each(model.get('geoCoord'), function (geoCoord, name) {
  46418. geo.addGeoCoord(name, geoCoord);
  46419. });
  46420. }
  46421. var GeoCreator =
  46422. /** @class */
  46423. function () {
  46424. function GeoCreator() {
  46425. // For deciding which dimensions to use when creating list data
  46426. this.dimensions = geo2DDimensions;
  46427. }
  46428. GeoCreator.prototype.create = function (ecModel, api) {
  46429. var geoList = []; // FIXME Create each time may be slow
  46430. ecModel.eachComponent('geo', function (geoModel, idx) {
  46431. var name = geoModel.get('map');
  46432. var geo = new Geo(name + idx, name, {
  46433. nameMap: geoModel.get('nameMap'),
  46434. nameProperty: geoModel.get('nameProperty'),
  46435. aspectScale: geoModel.get('aspectScale')
  46436. });
  46437. geo.zoomLimit = geoModel.get('scaleLimit');
  46438. geoList.push(geo); // setGeoCoords(geo, geoModel);
  46439. geoModel.coordinateSystem = geo;
  46440. geo.model = geoModel; // Inject resize method
  46441. geo.resize = resizeGeo;
  46442. geo.resize(geoModel, api);
  46443. });
  46444. ecModel.eachSeries(function (seriesModel) {
  46445. var coordSys = seriesModel.get('coordinateSystem');
  46446. if (coordSys === 'geo') {
  46447. var geoIndex = seriesModel.get('geoIndex') || 0;
  46448. seriesModel.coordinateSystem = geoList[geoIndex];
  46449. }
  46450. }); // If has map series
  46451. var mapModelGroupBySeries = {};
  46452. ecModel.eachSeriesByType('map', function (seriesModel) {
  46453. if (!seriesModel.getHostGeoModel()) {
  46454. var mapType = seriesModel.getMapType();
  46455. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  46456. mapModelGroupBySeries[mapType].push(seriesModel);
  46457. }
  46458. });
  46459. each(mapModelGroupBySeries, function (mapSeries, mapType) {
  46460. var nameMapList = map(mapSeries, function (singleMapSeries) {
  46461. return singleMapSeries.get('nameMap');
  46462. });
  46463. var geo = new Geo(mapType, mapType, {
  46464. nameMap: mergeAll(nameMapList),
  46465. nameProperty: mapSeries[0].get('nameProperty'),
  46466. aspectScale: mapSeries[0].get('aspectScale')
  46467. });
  46468. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  46469. return singleMapSeries.get('scaleLimit');
  46470. }));
  46471. geoList.push(geo); // Inject resize method
  46472. geo.resize = resizeGeo;
  46473. geo.resize(mapSeries[0], api);
  46474. each(mapSeries, function (singleMapSeries) {
  46475. singleMapSeries.coordinateSystem = geo;
  46476. setGeoCoords(geo, singleMapSeries);
  46477. });
  46478. });
  46479. return geoList;
  46480. };
  46481. /**
  46482. * Fill given regions array
  46483. */
  46484. GeoCreator.prototype.getFilledRegions = function (originRegionArr, mapName, nameMap, nameProperty) {
  46485. // Not use the original
  46486. var regionsArr = (originRegionArr || []).slice();
  46487. var dataNameMap = createHashMap();
  46488. for (var i = 0; i < regionsArr.length; i++) {
  46489. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  46490. }
  46491. var source = geoSourceManager.load(mapName, nameMap, nameProperty);
  46492. each(source.regions, function (region) {
  46493. var name = region.name;
  46494. !dataNameMap.get(name) && regionsArr.push({
  46495. name: name
  46496. });
  46497. });
  46498. return regionsArr;
  46499. };
  46500. return GeoCreator;
  46501. }();
  46502. var geoCreator = new GeoCreator();
  46503. var GeoModel =
  46504. /** @class */
  46505. function (_super) {
  46506. __extends(GeoModel, _super);
  46507. function GeoModel() {
  46508. var _this = _super !== null && _super.apply(this, arguments) || this;
  46509. _this.type = GeoModel.type;
  46510. return _this;
  46511. }
  46512. GeoModel.prototype.init = function (option, parentModel, ecModel) {
  46513. var source = geoSourceManager.getGeoResource(option.map);
  46514. if (source && source.type === 'geoJSON') {
  46515. var itemStyle = option.itemStyle = option.itemStyle || {};
  46516. if (!('color' in itemStyle)) {
  46517. itemStyle.color = '#eee';
  46518. }
  46519. }
  46520. this.mergeDefaultAndTheme(option, ecModel); // Default label emphasis `show`
  46521. defaultEmphasis(option, 'label', ['show']);
  46522. };
  46523. GeoModel.prototype.optionUpdated = function () {
  46524. var _this = this;
  46525. var option = this.option;
  46526. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap, option.nameProperty);
  46527. var selectedMap = {};
  46528. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  46529. var regionName = regionOpt.name;
  46530. if (regionName) {
  46531. optionModelMap.set(regionName, new Model(regionOpt, _this, _this.ecModel));
  46532. if (regionOpt.selected) {
  46533. selectedMap[regionName] = true;
  46534. }
  46535. }
  46536. return optionModelMap;
  46537. }, createHashMap());
  46538. if (!option.selectedMap) {
  46539. option.selectedMap = selectedMap;
  46540. }
  46541. };
  46542. /**
  46543. * Get model of region.
  46544. */
  46545. GeoModel.prototype.getRegionModel = function (name) {
  46546. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  46547. };
  46548. /**
  46549. * Format label
  46550. * @param name Region name
  46551. */
  46552. GeoModel.prototype.getFormattedLabel = function (name, status) {
  46553. var regionModel = this.getRegionModel(name);
  46554. var formatter = status === 'normal' ? regionModel.get(['label', 'formatter']) : regionModel.get(['emphasis', 'label', 'formatter']);
  46555. var params = {
  46556. name: name
  46557. };
  46558. if (typeof formatter === 'function') {
  46559. params.status = status;
  46560. return formatter(params);
  46561. } else if (typeof formatter === 'string') {
  46562. return formatter.replace('{a}', name != null ? name : '');
  46563. }
  46564. };
  46565. GeoModel.prototype.setZoom = function (zoom) {
  46566. this.option.zoom = zoom;
  46567. };
  46568. GeoModel.prototype.setCenter = function (center) {
  46569. this.option.center = center;
  46570. }; // PENGING If selectedMode is null ?
  46571. GeoModel.prototype.select = function (name) {
  46572. var option = this.option;
  46573. var selectedMode = option.selectedMode;
  46574. if (!selectedMode) {
  46575. return;
  46576. }
  46577. if (selectedMode !== 'multiple') {
  46578. option.selectedMap = null;
  46579. }
  46580. var selectedMap = option.selectedMap || (option.selectedMap = {});
  46581. selectedMap[name] = true;
  46582. };
  46583. GeoModel.prototype.unSelect = function (name) {
  46584. var selectedMap = this.option.selectedMap;
  46585. if (selectedMap) {
  46586. selectedMap[name] = false;
  46587. }
  46588. };
  46589. GeoModel.prototype.toggleSelected = function (name) {
  46590. this[this.isSelected(name) ? 'unSelect' : 'select'](name);
  46591. };
  46592. GeoModel.prototype.isSelected = function (name) {
  46593. var selectedMap = this.option.selectedMap;
  46594. return !!(selectedMap && selectedMap[name]);
  46595. };
  46596. GeoModel.type = 'geo';
  46597. GeoModel.layoutMode = 'box';
  46598. GeoModel.defaultOption = {
  46599. zlevel: 0,
  46600. z: 0,
  46601. show: true,
  46602. left: 'center',
  46603. top: 'center',
  46604. // Default value:
  46605. // for geoSVG source: 1,
  46606. // for geoJSON source: 0.75.
  46607. aspectScale: null,
  46608. ///// Layout with center and size
  46609. // If you wan't to put map in a fixed size box with right aspect ratio
  46610. // This two properties may more conveninet
  46611. // layoutCenter: [50%, 50%]
  46612. // layoutSize: 100
  46613. silent: false,
  46614. // Map type
  46615. map: '',
  46616. // Define left-top, right-bottom coords to control view
  46617. // For example, [ [180, 90], [-180, -90] ]
  46618. boundingCoords: null,
  46619. // Default on center of map
  46620. center: null,
  46621. zoom: 1,
  46622. scaleLimit: null,
  46623. // selectedMode: false
  46624. label: {
  46625. show: false,
  46626. color: '#000'
  46627. },
  46628. itemStyle: {
  46629. borderWidth: 0.5,
  46630. borderColor: '#444' // Default color:
  46631. // + geoJSON: #eee
  46632. // + geoSVG: null (use SVG original `fill`)
  46633. // color: '#eee'
  46634. },
  46635. emphasis: {
  46636. label: {
  46637. show: true,
  46638. color: 'rgb(100,0,0)'
  46639. },
  46640. itemStyle: {
  46641. color: 'rgba(255,215,0,0.8)'
  46642. }
  46643. },
  46644. select: {
  46645. label: {
  46646. show: true,
  46647. color: 'rgb(100,0,0)'
  46648. },
  46649. itemStyle: {
  46650. color: 'rgba(255,215,0,0.8)'
  46651. }
  46652. },
  46653. regions: [] // tooltip: {
  46654. // show: false
  46655. // }
  46656. };
  46657. return GeoModel;
  46658. }(ComponentModel);
  46659. /*
  46660. * Licensed to the Apache Software Foundation (ASF) under one
  46661. * or more contributor license agreements. See the NOTICE file
  46662. * distributed with this work for additional information
  46663. * regarding copyright ownership. The ASF licenses this file
  46664. * to you under the Apache License, Version 2.0 (the
  46665. * "License"); you may not use this file except in compliance
  46666. * with the License. You may obtain a copy of the License at
  46667. *
  46668. * http://www.apache.org/licenses/LICENSE-2.0
  46669. *
  46670. * Unless required by applicable law or agreed to in writing,
  46671. * software distributed under the License is distributed on an
  46672. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46673. * KIND, either express or implied. See the License for the
  46674. * specific language governing permissions and limitations
  46675. * under the License.
  46676. */
  46677. /**
  46678. * AUTO-GENERATED FILE. DO NOT MODIFY.
  46679. */
  46680. /*
  46681. * Licensed to the Apache Software Foundation (ASF) under one
  46682. * or more contributor license agreements. See the NOTICE file
  46683. * distributed with this work for additional information
  46684. * regarding copyright ownership. The ASF licenses this file
  46685. * to you under the Apache License, Version 2.0 (the
  46686. * "License"); you may not use this file except in compliance
  46687. * with the License. You may obtain a copy of the License at
  46688. *
  46689. * http://www.apache.org/licenses/LICENSE-2.0
  46690. *
  46691. * Unless required by applicable law or agreed to in writing,
  46692. * software distributed under the License is distributed on an
  46693. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46694. * KIND, either express or implied. See the License for the
  46695. * specific language governing permissions and limitations
  46696. * under the License.
  46697. */
  46698. function updateCenterAndZoom(view, payload, zoomLimit) {
  46699. var previousZoom = view.getZoom();
  46700. var center = view.getCenter();
  46701. var zoom = payload.zoom;
  46702. var point = view.dataToPoint(center);
  46703. if (payload.dx != null && payload.dy != null) {
  46704. point[0] -= payload.dx;
  46705. point[1] -= payload.dy;
  46706. view.setCenter(view.pointToData(point));
  46707. }
  46708. if (zoom != null) {
  46709. if (zoomLimit) {
  46710. var zoomMin = zoomLimit.min || 0;
  46711. var zoomMax = zoomLimit.max || Infinity;
  46712. zoom = Math.max(Math.min(previousZoom * zoom, zoomMax), zoomMin) / previousZoom;
  46713. } // Zoom on given point(originX, originY)
  46714. view.scaleX *= zoom;
  46715. view.scaleY *= zoom;
  46716. var fixX = (payload.originX - view.x) * (zoom - 1);
  46717. var fixY = (payload.originY - view.y) * (zoom - 1);
  46718. view.x -= fixX;
  46719. view.y -= fixY;
  46720. view.updateTransform(); // Get the new center
  46721. view.setCenter(view.pointToData(point));
  46722. view.setZoom(zoom * previousZoom);
  46723. }
  46724. return {
  46725. center: view.getCenter(),
  46726. zoom: view.getZoom()
  46727. };
  46728. }
  46729. var GeoView =
  46730. /** @class */
  46731. function (_super) {
  46732. __extends(GeoView, _super);
  46733. function GeoView() {
  46734. var _this = _super !== null && _super.apply(this, arguments) || this;
  46735. _this.type = GeoView.type;
  46736. _this.focusBlurEnabled = true;
  46737. return _this;
  46738. }
  46739. GeoView.prototype.init = function (ecModel, api) {
  46740. this._api = api;
  46741. };
  46742. GeoView.prototype.render = function (geoModel, ecModel, api, payload) {
  46743. this._model = geoModel;
  46744. if (!geoModel.get('show')) {
  46745. this._mapDraw && this._mapDraw.remove();
  46746. this._mapDraw = null;
  46747. return;
  46748. }
  46749. if (!this._mapDraw) {
  46750. this._mapDraw = new MapDraw(api);
  46751. }
  46752. var mapDraw = this._mapDraw;
  46753. mapDraw.draw(geoModel, ecModel, api, this, payload);
  46754. mapDraw.group.on('click', this._handleRegionClick, this);
  46755. mapDraw.group.silent = geoModel.get('silent');
  46756. this.group.add(mapDraw.group);
  46757. this.updateSelectStatus(geoModel, ecModel, api);
  46758. };
  46759. GeoView.prototype._handleRegionClick = function (e) {
  46760. var eventData;
  46761. findEventDispatcher(e.target, function (current) {
  46762. return (eventData = getECData(current).eventData) != null;
  46763. }, true);
  46764. if (eventData) {
  46765. this._api.dispatchAction({
  46766. type: 'geoToggleSelect',
  46767. geoId: this._model.id,
  46768. name: eventData.name
  46769. });
  46770. }
  46771. };
  46772. GeoView.prototype.updateSelectStatus = function (model, ecModel, api) {
  46773. var _this = this;
  46774. this._mapDraw.group.traverse(function (node) {
  46775. var eventData = getECData(node).eventData;
  46776. if (eventData) {
  46777. _this._model.isSelected(eventData.name) ? api.enterSelect(node) : api.leaveSelect(node); // No need to traverse children.
  46778. return true;
  46779. }
  46780. });
  46781. };
  46782. GeoView.prototype.findHighDownDispatchers = function (name) {
  46783. return this._mapDraw && this._mapDraw.findHighDownDispatchers(name, this._model);
  46784. };
  46785. GeoView.prototype.dispose = function () {
  46786. this._mapDraw && this._mapDraw.remove();
  46787. };
  46788. GeoView.type = 'geo';
  46789. return GeoView;
  46790. }(ComponentView);
  46791. function install$9(registers) {
  46792. registers.registerCoordinateSystem('geo', geoCreator);
  46793. registers.registerComponentModel(GeoModel);
  46794. registers.registerComponentView(GeoView);
  46795. function makeAction(method, actionInfo) {
  46796. actionInfo.update = 'geo:updateSelectStatus';
  46797. registers.registerAction(actionInfo, function (payload, ecModel) {
  46798. var selected = {};
  46799. var allSelected = [];
  46800. ecModel.eachComponent({
  46801. mainType: 'geo',
  46802. query: payload
  46803. }, function (geoModel) {
  46804. geoModel[method](payload.name);
  46805. var geo = geoModel.coordinateSystem;
  46806. each(geo.regions, function (region) {
  46807. selected[region.name] = geoModel.isSelected(region.name) || false;
  46808. }); // Notice: there might be duplicated name in different regions.
  46809. var names = [];
  46810. each(selected, function (v, name) {
  46811. selected[name] && names.push(name);
  46812. });
  46813. allSelected.push({
  46814. geoIndex: geoModel.componentIndex,
  46815. // Use singular, the same naming convention as the event `selectchanged`.
  46816. name: names
  46817. });
  46818. });
  46819. return {
  46820. selected: selected,
  46821. allSelected: allSelected,
  46822. name: payload.name
  46823. };
  46824. });
  46825. }
  46826. makeAction('toggleSelected', {
  46827. type: 'geoToggleSelect',
  46828. event: 'geoselectchanged'
  46829. });
  46830. makeAction('select', {
  46831. type: 'geoSelect',
  46832. event: 'geoselected'
  46833. });
  46834. makeAction('unSelect', {
  46835. type: 'geoUnSelect',
  46836. event: 'geounselected'
  46837. });
  46838. /**
  46839. * @payload
  46840. * @property {string} [componentType=series]
  46841. * @property {number} [dx]
  46842. * @property {number} [dy]
  46843. * @property {number} [zoom]
  46844. * @property {number} [originX]
  46845. * @property {number} [originY]
  46846. */
  46847. registers.registerAction({
  46848. type: 'geoRoam',
  46849. event: 'geoRoam',
  46850. update: 'updateTransform'
  46851. }, function (payload, ecModel) {
  46852. var componentType = payload.componentType || 'series';
  46853. ecModel.eachComponent({
  46854. mainType: componentType,
  46855. query: payload
  46856. }, function (componentModel) {
  46857. var geo = componentModel.coordinateSystem;
  46858. if (geo.type !== 'geo') {
  46859. return;
  46860. }
  46861. var res = updateCenterAndZoom(geo, payload, componentModel.get('scaleLimit'));
  46862. componentModel.setCenter && componentModel.setCenter(res.center);
  46863. componentModel.setZoom && componentModel.setZoom(res.zoom); // All map series with same `map` use the same geo coordinate system
  46864. // So the center and zoom must be in sync. Include the series not selected by legend
  46865. if (componentType === 'series') {
  46866. each(componentModel.seriesGroup, function (seriesModel) {
  46867. seriesModel.setCenter(res.center);
  46868. seriesModel.setZoom(res.zoom);
  46869. });
  46870. }
  46871. });
  46872. });
  46873. }
  46874. function install$a(registers) {
  46875. use(install$9);
  46876. registers.registerChartView(MapView);
  46877. registers.registerSeriesModel(MapSeries);
  46878. registers.registerLayout(mapSymbolLayout);
  46879. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  46880. createLegacyDataSelectAction('map', registers.registerAction);
  46881. }
  46882. /**
  46883. * Initialize all computational message for following algorithm.
  46884. */
  46885. function init$2(inRoot) {
  46886. var root = inRoot;
  46887. root.hierNode = {
  46888. defaultAncestor: null,
  46889. ancestor: root,
  46890. prelim: 0,
  46891. modifier: 0,
  46892. change: 0,
  46893. shift: 0,
  46894. i: 0,
  46895. thread: null
  46896. };
  46897. var nodes = [root];
  46898. var node;
  46899. var children;
  46900. while (node = nodes.pop()) {
  46901. // jshint ignore:line
  46902. children = node.children;
  46903. if (node.isExpand && children.length) {
  46904. var n = children.length;
  46905. for (var i = n - 1; i >= 0; i--) {
  46906. var child = children[i];
  46907. child.hierNode = {
  46908. defaultAncestor: null,
  46909. ancestor: child,
  46910. prelim: 0,
  46911. modifier: 0,
  46912. change: 0,
  46913. shift: 0,
  46914. i: i,
  46915. thread: null
  46916. };
  46917. nodes.push(child);
  46918. }
  46919. }
  46920. }
  46921. }
  46922. /**
  46923. * The implementation of this function was originally copied from "d3.js"
  46924. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  46925. * with some modifications made for this program.
  46926. * See the license statement at the head of this file.
  46927. *
  46928. * Computes a preliminary x coordinate for node. Before that, this function is
  46929. * applied recursively to the children of node, as well as the function
  46930. * apportion(). After spacing out the children by calling executeShifts(), the
  46931. * node is placed to the midpoint of its outermost children.
  46932. */
  46933. function firstWalk(node, separation) {
  46934. var children = node.isExpand ? node.children : [];
  46935. var siblings = node.parentNode.children;
  46936. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  46937. if (children.length) {
  46938. executeShifts(node);
  46939. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  46940. if (subtreeW) {
  46941. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  46942. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  46943. } else {
  46944. node.hierNode.prelim = midPoint;
  46945. }
  46946. } else if (subtreeW) {
  46947. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  46948. }
  46949. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  46950. }
  46951. /**
  46952. * The implementation of this function was originally copied from "d3.js"
  46953. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  46954. * with some modifications made for this program.
  46955. * See the license statement at the head of this file.
  46956. *
  46957. * Computes all real x-coordinates by summing up the modifiers recursively.
  46958. */
  46959. function secondWalk(node) {
  46960. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  46961. node.setLayout({
  46962. x: nodeX
  46963. }, true);
  46964. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  46965. }
  46966. function separation(cb) {
  46967. return arguments.length ? cb : defaultSeparation;
  46968. }
  46969. /**
  46970. * Transform the common coordinate to radial coordinate.
  46971. */
  46972. function radialCoordinate(rad, r) {
  46973. rad -= Math.PI / 2;
  46974. return {
  46975. x: r * Math.cos(rad),
  46976. y: r * Math.sin(rad)
  46977. };
  46978. }
  46979. /**
  46980. * Get the layout position of the whole view.
  46981. */
  46982. function getViewRect$1(seriesModel, api) {
  46983. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  46984. width: api.getWidth(),
  46985. height: api.getHeight()
  46986. });
  46987. }
  46988. /**
  46989. * All other shifts, applied to the smaller subtrees between w- and w+, are
  46990. * performed by this function.
  46991. *
  46992. * The implementation of this function was originally copied from "d3.js"
  46993. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  46994. * with some modifications made for this program.
  46995. * See the license statement at the head of this file.
  46996. */
  46997. function executeShifts(node) {
  46998. var children = node.children;
  46999. var n = children.length;
  47000. var shift = 0;
  47001. var change = 0;
  47002. while (--n >= 0) {
  47003. var child = children[n];
  47004. child.hierNode.prelim += shift;
  47005. child.hierNode.modifier += shift;
  47006. change += child.hierNode.change;
  47007. shift += child.hierNode.shift + change;
  47008. }
  47009. }
  47010. /**
  47011. * The implementation of this function was originally copied from "d3.js"
  47012. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  47013. * with some modifications made for this program.
  47014. * See the license statement at the head of this file.
  47015. *
  47016. * The core of the algorithm. Here, a new subtree is combined with the
  47017. * previous subtrees. Threads are used to traverse the inside and outside
  47018. * contours of the left and right subtree up to the highest common level.
  47019. * Whenever two nodes of the inside contours conflict, we compute the left
  47020. * one of the greatest uncommon ancestors using the function nextAncestor()
  47021. * and call moveSubtree() to shift the subtree and prepare the shifts of
  47022. * smaller subtrees. Finally, we add a new thread (if necessary).
  47023. */
  47024. function apportion(subtreeV, subtreeW, ancestor, separation) {
  47025. if (subtreeW) {
  47026. var nodeOutRight = subtreeV;
  47027. var nodeInRight = subtreeV;
  47028. var nodeOutLeft = nodeInRight.parentNode.children[0];
  47029. var nodeInLeft = subtreeW;
  47030. var sumOutRight = nodeOutRight.hierNode.modifier;
  47031. var sumInRight = nodeInRight.hierNode.modifier;
  47032. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  47033. var sumInLeft = nodeInLeft.hierNode.modifier;
  47034. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  47035. nodeOutRight = nextRight(nodeOutRight);
  47036. nodeOutLeft = nextLeft(nodeOutLeft);
  47037. nodeOutRight.hierNode.ancestor = subtreeV;
  47038. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim - sumInRight + separation(nodeInLeft, nodeInRight);
  47039. if (shift > 0) {
  47040. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  47041. sumInRight += shift;
  47042. sumOutRight += shift;
  47043. }
  47044. sumInLeft += nodeInLeft.hierNode.modifier;
  47045. sumInRight += nodeInRight.hierNode.modifier;
  47046. sumOutRight += nodeOutRight.hierNode.modifier;
  47047. sumOutLeft += nodeOutLeft.hierNode.modifier;
  47048. }
  47049. if (nodeInLeft && !nextRight(nodeOutRight)) {
  47050. nodeOutRight.hierNode.thread = nodeInLeft;
  47051. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  47052. }
  47053. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  47054. nodeOutLeft.hierNode.thread = nodeInRight;
  47055. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  47056. ancestor = subtreeV;
  47057. }
  47058. }
  47059. return ancestor;
  47060. }
  47061. /**
  47062. * This function is used to traverse the right contour of a subtree.
  47063. * It returns the rightmost child of node or the thread of node. The function
  47064. * returns null if and only if node is on the highest depth of its subtree.
  47065. */
  47066. function nextRight(node) {
  47067. var children = node.children;
  47068. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  47069. }
  47070. /**
  47071. * This function is used to traverse the left contour of a subtree (or a subforest).
  47072. * It returns the leftmost child of node or the thread of node. The function
  47073. * returns null if and only if node is on the highest depth of its subtree.
  47074. */
  47075. function nextLeft(node) {
  47076. var children = node.children;
  47077. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  47078. }
  47079. /**
  47080. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  47081. * Otherwise, returns the specified ancestor.
  47082. */
  47083. function nextAncestor(nodeInLeft, node, ancestor) {
  47084. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode ? nodeInLeft.hierNode.ancestor : ancestor;
  47085. }
  47086. /**
  47087. * The implementation of this function was originally copied from "d3.js"
  47088. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  47089. * with some modifications made for this program.
  47090. * See the license statement at the head of this file.
  47091. *
  47092. * Shifts the current subtree rooted at wr.
  47093. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  47094. */
  47095. function moveSubtree(wl, wr, shift) {
  47096. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  47097. wr.hierNode.change -= change;
  47098. wr.hierNode.shift += shift;
  47099. wr.hierNode.modifier += shift;
  47100. wr.hierNode.prelim += shift;
  47101. wl.hierNode.change += change;
  47102. }
  47103. /**
  47104. * The implementation of this function was originally copied from "d3.js"
  47105. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  47106. * with some modifications made for this program.
  47107. * See the license statement at the head of this file.
  47108. */
  47109. function defaultSeparation(node1, node2) {
  47110. return node1.parentNode === node2.parentNode ? 1 : 2;
  47111. }
  47112. var TreeEdgeShape =
  47113. /** @class */
  47114. function () {
  47115. function TreeEdgeShape() {
  47116. this.parentPoint = [];
  47117. this.childPoints = [];
  47118. }
  47119. return TreeEdgeShape;
  47120. }();
  47121. var TreePath =
  47122. /** @class */
  47123. function (_super) {
  47124. __extends(TreePath, _super);
  47125. function TreePath(opts) {
  47126. return _super.call(this, opts) || this;
  47127. }
  47128. TreePath.prototype.getDefaultStyle = function () {
  47129. return {
  47130. stroke: '#000',
  47131. fill: null
  47132. };
  47133. };
  47134. TreePath.prototype.getDefaultShape = function () {
  47135. return new TreeEdgeShape();
  47136. };
  47137. TreePath.prototype.buildPath = function (ctx, shape) {
  47138. var childPoints = shape.childPoints;
  47139. var childLen = childPoints.length;
  47140. var parentPoint = shape.parentPoint;
  47141. var firstChildPos = childPoints[0];
  47142. var lastChildPos = childPoints[childLen - 1];
  47143. if (childLen === 1) {
  47144. ctx.moveTo(parentPoint[0], parentPoint[1]);
  47145. ctx.lineTo(firstChildPos[0], firstChildPos[1]);
  47146. return;
  47147. }
  47148. var orient = shape.orient;
  47149. var forkDim = orient === 'TB' || orient === 'BT' ? 0 : 1;
  47150. var otherDim = 1 - forkDim;
  47151. var forkPosition = parsePercent$1(shape.forkPosition, 1);
  47152. var tmpPoint = [];
  47153. tmpPoint[forkDim] = parentPoint[forkDim];
  47154. tmpPoint[otherDim] = parentPoint[otherDim] + (lastChildPos[otherDim] - parentPoint[otherDim]) * forkPosition;
  47155. ctx.moveTo(parentPoint[0], parentPoint[1]);
  47156. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  47157. ctx.moveTo(firstChildPos[0], firstChildPos[1]);
  47158. tmpPoint[forkDim] = firstChildPos[forkDim];
  47159. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  47160. tmpPoint[forkDim] = lastChildPos[forkDim];
  47161. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  47162. ctx.lineTo(lastChildPos[0], lastChildPos[1]);
  47163. for (var i = 1; i < childLen - 1; i++) {
  47164. var point = childPoints[i];
  47165. ctx.moveTo(point[0], point[1]);
  47166. tmpPoint[forkDim] = point[forkDim];
  47167. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  47168. }
  47169. };
  47170. return TreePath;
  47171. }(Path);
  47172. var TreeView =
  47173. /** @class */
  47174. function (_super) {
  47175. __extends(TreeView, _super);
  47176. function TreeView() {
  47177. var _this = _super !== null && _super.apply(this, arguments) || this;
  47178. _this.type = TreeView.type;
  47179. _this._mainGroup = new Group();
  47180. return _this;
  47181. }
  47182. TreeView.prototype.init = function (ecModel, api) {
  47183. this._controller = new RoamController(api.getZr());
  47184. this._controllerHost = {
  47185. target: this.group
  47186. };
  47187. this.group.add(this._mainGroup);
  47188. };
  47189. TreeView.prototype.render = function (seriesModel, ecModel, api) {
  47190. var data = seriesModel.getData();
  47191. var layoutInfo = seriesModel.layoutInfo;
  47192. var group = this._mainGroup;
  47193. var layout = seriesModel.get('layout');
  47194. if (layout === 'radial') {
  47195. group.x = layoutInfo.x + layoutInfo.width / 2;
  47196. group.y = layoutInfo.y + layoutInfo.height / 2;
  47197. } else {
  47198. group.x = layoutInfo.x;
  47199. group.y = layoutInfo.y;
  47200. }
  47201. this._updateViewCoordSys(seriesModel);
  47202. this._updateController(seriesModel, ecModel, api);
  47203. var oldData = this._data;
  47204. data.diff(oldData).add(function (newIdx) {
  47205. if (symbolNeedsDraw$1(data, newIdx)) {
  47206. // Create node and edge
  47207. updateNode(data, newIdx, null, group, seriesModel);
  47208. }
  47209. }).update(function (newIdx, oldIdx) {
  47210. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  47211. if (!symbolNeedsDraw$1(data, newIdx)) {
  47212. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  47213. return;
  47214. } // Update node and edge
  47215. updateNode(data, newIdx, symbolEl, group, seriesModel);
  47216. }).remove(function (oldIdx) {
  47217. var symbolEl = oldData.getItemGraphicEl(oldIdx); // When remove a collapsed node of subtree, since the collapsed
  47218. // node haven't been initialized with a symbol element,
  47219. // you can't found it's symbol element through index.
  47220. // so if we want to remove the symbol element we should insure
  47221. // that the symbol element is not null.
  47222. if (symbolEl) {
  47223. removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  47224. }
  47225. }).execute();
  47226. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  47227. this._updateNodeAndLinkScale(seriesModel);
  47228. if (seriesModel.get('expandAndCollapse') === true) {
  47229. data.eachItemGraphicEl(function (el, dataIndex) {
  47230. el.off('click').on('click', function () {
  47231. api.dispatchAction({
  47232. type: 'treeExpandAndCollapse',
  47233. seriesId: seriesModel.id,
  47234. dataIndex: dataIndex
  47235. });
  47236. });
  47237. });
  47238. }
  47239. this._data = data;
  47240. };
  47241. TreeView.prototype._updateViewCoordSys = function (seriesModel) {
  47242. var data = seriesModel.getData();
  47243. var points = [];
  47244. data.each(function (idx) {
  47245. var layout = data.getItemLayout(idx);
  47246. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  47247. points.push([+layout.x, +layout.y]);
  47248. }
  47249. });
  47250. var min = [];
  47251. var max = [];
  47252. fromPoints(points, min, max); // If don't Store min max when collapse the root node after roam,
  47253. // the root node will disappear.
  47254. var oldMin = this._min;
  47255. var oldMax = this._max; // If width or height is 0
  47256. if (max[0] - min[0] === 0) {
  47257. min[0] = oldMin ? oldMin[0] : min[0] - 1;
  47258. max[0] = oldMax ? oldMax[0] : max[0] + 1;
  47259. }
  47260. if (max[1] - min[1] === 0) {
  47261. min[1] = oldMin ? oldMin[1] : min[1] - 1;
  47262. max[1] = oldMax ? oldMax[1] : max[1] + 1;
  47263. }
  47264. var viewCoordSys = seriesModel.coordinateSystem = new View();
  47265. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  47266. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  47267. viewCoordSys.setCenter(seriesModel.get('center'));
  47268. viewCoordSys.setZoom(seriesModel.get('zoom')); // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  47269. this.group.attr({
  47270. x: viewCoordSys.x,
  47271. y: viewCoordSys.y,
  47272. scaleX: viewCoordSys.scaleX,
  47273. scaleY: viewCoordSys.scaleY
  47274. });
  47275. this._min = min;
  47276. this._max = max;
  47277. };
  47278. TreeView.prototype._updateController = function (seriesModel, ecModel, api) {
  47279. var _this = this;
  47280. var controller = this._controller;
  47281. var controllerHost = this._controllerHost;
  47282. var group = this.group;
  47283. controller.setPointerChecker(function (e, x, y) {
  47284. var rect = group.getBoundingRect();
  47285. rect.applyTransform(group.transform);
  47286. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  47287. });
  47288. controller.enable(seriesModel.get('roam'));
  47289. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  47290. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  47291. controller.off('pan').off('zoom').on('pan', function (e) {
  47292. updateViewOnPan(controllerHost, e.dx, e.dy);
  47293. api.dispatchAction({
  47294. seriesId: seriesModel.id,
  47295. type: 'treeRoam',
  47296. dx: e.dx,
  47297. dy: e.dy
  47298. });
  47299. }).on('zoom', function (e) {
  47300. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  47301. api.dispatchAction({
  47302. seriesId: seriesModel.id,
  47303. type: 'treeRoam',
  47304. zoom: e.scale,
  47305. originX: e.originX,
  47306. originY: e.originY
  47307. });
  47308. _this._updateNodeAndLinkScale(seriesModel); // Only update label layout on zoom
  47309. api.updateLabelLayout();
  47310. });
  47311. };
  47312. TreeView.prototype._updateNodeAndLinkScale = function (seriesModel) {
  47313. var data = seriesModel.getData();
  47314. var nodeScale = this._getNodeGlobalScale(seriesModel);
  47315. data.eachItemGraphicEl(function (el, idx) {
  47316. el.setSymbolScale(nodeScale);
  47317. });
  47318. };
  47319. TreeView.prototype._getNodeGlobalScale = function (seriesModel) {
  47320. var coordSys = seriesModel.coordinateSystem;
  47321. if (coordSys.type !== 'view') {
  47322. return 1;
  47323. }
  47324. var nodeScaleRatio = this._nodeScaleRatio;
  47325. var groupZoom = coordSys.scaleX || 1; // Scale node when zoom changes
  47326. var roamZoom = coordSys.getZoom();
  47327. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  47328. return nodeScale / groupZoom;
  47329. };
  47330. TreeView.prototype.dispose = function () {
  47331. this._controller && this._controller.dispose();
  47332. this._controllerHost = null;
  47333. };
  47334. TreeView.prototype.remove = function () {
  47335. this._mainGroup.removeAll();
  47336. this._data = null;
  47337. };
  47338. TreeView.type = 'tree';
  47339. return TreeView;
  47340. }(ChartView);
  47341. function symbolNeedsDraw$1(data, dataIndex) {
  47342. var layout = data.getItemLayout(dataIndex);
  47343. return layout && !isNaN(layout.x) && !isNaN(layout.y);
  47344. }
  47345. function updateNode(data, dataIndex, symbolEl, group, seriesModel) {
  47346. var isInit = !symbolEl;
  47347. var node = data.tree.getNodeByDataIndex(dataIndex);
  47348. var itemModel = node.getModel();
  47349. var visualColor = node.getVisual('style').fill;
  47350. var symbolInnerColor = node.isExpand === false && node.children.length !== 0 ? visualColor : '#fff';
  47351. var virtualRoot = data.tree.root;
  47352. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  47353. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  47354. var sourceLayout = source.getLayout();
  47355. var sourceOldLayout = sourceSymbolEl ? {
  47356. x: sourceSymbolEl.__oldX,
  47357. y: sourceSymbolEl.__oldY,
  47358. rawX: sourceSymbolEl.__radialOldRawX,
  47359. rawY: sourceSymbolEl.__radialOldRawY
  47360. } : sourceLayout;
  47361. var targetLayout = node.getLayout();
  47362. if (isInit) {
  47363. symbolEl = new Symbol(data, dataIndex, null, {
  47364. symbolInnerColor: symbolInnerColor,
  47365. useNameLabel: true
  47366. });
  47367. symbolEl.x = sourceOldLayout.x;
  47368. symbolEl.y = sourceOldLayout.y;
  47369. } else {
  47370. symbolEl.updateData(data, dataIndex, null, {
  47371. symbolInnerColor: symbolInnerColor,
  47372. useNameLabel: true
  47373. });
  47374. }
  47375. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  47376. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  47377. symbolEl.__radialRawX = targetLayout.rawX;
  47378. symbolEl.__radialRawY = targetLayout.rawY;
  47379. group.add(symbolEl);
  47380. data.setItemGraphicEl(dataIndex, symbolEl);
  47381. symbolEl.__oldX = symbolEl.x;
  47382. symbolEl.__oldY = symbolEl.y;
  47383. updateProps(symbolEl, {
  47384. x: targetLayout.x,
  47385. y: targetLayout.y
  47386. }, seriesModel);
  47387. var symbolPath = symbolEl.getSymbolPath();
  47388. if (seriesModel.get('layout') === 'radial') {
  47389. var realRoot = virtualRoot.children[0];
  47390. var rootLayout = realRoot.getLayout();
  47391. var length_1 = realRoot.children.length;
  47392. var rad = void 0;
  47393. var isLeft = void 0;
  47394. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  47395. var center = {
  47396. x: (realRoot.children[0].getLayout().x + realRoot.children[length_1 - 1].getLayout().x) / 2,
  47397. y: (realRoot.children[0].getLayout().y + realRoot.children[length_1 - 1].getLayout().y) / 2
  47398. };
  47399. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  47400. if (rad < 0) {
  47401. rad = Math.PI * 2 + rad;
  47402. }
  47403. isLeft = center.x < rootLayout.x;
  47404. if (isLeft) {
  47405. rad = rad - Math.PI;
  47406. }
  47407. } else {
  47408. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  47409. if (rad < 0) {
  47410. rad = Math.PI * 2 + rad;
  47411. }
  47412. if (node.children.length === 0 || node.children.length !== 0 && node.isExpand === false) {
  47413. isLeft = targetLayout.x < rootLayout.x;
  47414. if (isLeft) {
  47415. rad = rad - Math.PI;
  47416. }
  47417. } else {
  47418. isLeft = targetLayout.x > rootLayout.x;
  47419. if (!isLeft) {
  47420. rad = rad - Math.PI;
  47421. }
  47422. }
  47423. }
  47424. var textPosition = isLeft ? 'left' : 'right';
  47425. var normalLabelModel = itemModel.getModel('label');
  47426. var rotate = normalLabelModel.get('rotate');
  47427. var labelRotateRadian = rotate * (Math.PI / 180);
  47428. var textContent = symbolPath.getTextContent();
  47429. if (textContent) {
  47430. symbolPath.setTextConfig({
  47431. position: normalLabelModel.get('position') || textPosition,
  47432. rotation: rotate == null ? -rad : labelRotateRadian,
  47433. origin: 'center'
  47434. });
  47435. textContent.setStyle('verticalAlign', 'middle');
  47436. }
  47437. } // Handle status
  47438. var focus = itemModel.get(['emphasis', 'focus']);
  47439. var focusDataIndices = focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : null;
  47440. if (focusDataIndices) {
  47441. // Modify the focus to data indices.
  47442. getECData(symbolEl).focus = focusDataIndices;
  47443. }
  47444. drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group);
  47445. if (symbolEl.__edge) {
  47446. symbolEl.onHoverStateChange = function (toState) {
  47447. if (toState !== 'blur') {
  47448. // NOTE: Ensure the parent elements will been blurred firstly.
  47449. // According to the return of getAncestorsIndices and getDescendantIndices
  47450. // TODO: A bit tricky.
  47451. var parentEl = node.parentNode && data.getItemGraphicEl(node.parentNode.dataIndex);
  47452. if (!(parentEl && parentEl.hoverState === HOVER_STATE_BLUR)) {
  47453. setStatesFlag(symbolEl.__edge, toState);
  47454. }
  47455. }
  47456. };
  47457. }
  47458. }
  47459. function drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group) {
  47460. var itemModel = node.getModel();
  47461. var edgeShape = seriesModel.get('edgeShape');
  47462. var layout = seriesModel.get('layout');
  47463. var orient = seriesModel.getOrient();
  47464. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  47465. var edgeForkPosition = seriesModel.get('edgeForkPosition');
  47466. var lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  47467. var edge = symbolEl.__edge;
  47468. if (edgeShape === 'curve') {
  47469. if (node.parentNode && node.parentNode !== virtualRoot) {
  47470. if (!edge) {
  47471. edge = symbolEl.__edge = new BezierCurve({
  47472. shape: getEdgeShape(layout, orient, curvature, sourceOldLayout, sourceOldLayout)
  47473. });
  47474. }
  47475. updateProps(edge, {
  47476. shape: getEdgeShape(layout, orient, curvature, sourceLayout, targetLayout)
  47477. }, seriesModel);
  47478. }
  47479. } else if (edgeShape === 'polyline') {
  47480. if (layout === 'orthogonal') {
  47481. if (node !== virtualRoot && node.children && node.children.length !== 0 && node.isExpand === true) {
  47482. var children = node.children;
  47483. var childPoints = [];
  47484. for (var i = 0; i < children.length; i++) {
  47485. var childLayout = children[i].getLayout();
  47486. childPoints.push([childLayout.x, childLayout.y]);
  47487. }
  47488. if (!edge) {
  47489. edge = symbolEl.__edge = new TreePath({
  47490. shape: {
  47491. parentPoint: [targetLayout.x, targetLayout.y],
  47492. childPoints: [[targetLayout.x, targetLayout.y]],
  47493. orient: orient,
  47494. forkPosition: edgeForkPosition
  47495. }
  47496. });
  47497. }
  47498. updateProps(edge, {
  47499. shape: {
  47500. parentPoint: [targetLayout.x, targetLayout.y],
  47501. childPoints: childPoints
  47502. }
  47503. }, seriesModel);
  47504. }
  47505. } else {
  47506. if ("development" !== 'production') {
  47507. throw new Error('The polyline edgeShape can only be used in orthogonal layout');
  47508. }
  47509. }
  47510. }
  47511. if (edge) {
  47512. edge.useStyle(defaults({
  47513. strokeNoScale: true,
  47514. fill: null
  47515. }, lineStyle));
  47516. setStatesStylesFromModel(edge, itemModel, 'lineStyle');
  47517. setDefaultStateProxy(edge);
  47518. group.add(edge);
  47519. }
  47520. }
  47521. function removeNodeEdge(node, data, group, seriesModel, removeAnimationOpt) {
  47522. var virtualRoot = data.tree.root;
  47523. var _a = getSourceNode(virtualRoot, node),
  47524. source = _a.source,
  47525. sourceLayout = _a.sourceLayout;
  47526. var symbolEl = data.getItemGraphicEl(node.dataIndex);
  47527. if (!symbolEl) {
  47528. return;
  47529. }
  47530. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  47531. var sourceEdge = sourceSymbolEl.__edge; // 1. when expand the sub tree, delete the children node should delete the edge of
  47532. // the source at the same time. because the polyline edge shape is only owned by the source.
  47533. // 2.when the node is the only children of the source, delete the node should delete the edge of
  47534. // the source at the same time. the same reason as above.
  47535. var edge = symbolEl.__edge || (source.isExpand === false || source.children.length === 1 ? sourceEdge : undefined);
  47536. var edgeShape = seriesModel.get('edgeShape');
  47537. var layoutOpt = seriesModel.get('layout');
  47538. var orient = seriesModel.get('orient');
  47539. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  47540. if (edge) {
  47541. if (edgeShape === 'curve') {
  47542. removeElement(edge, {
  47543. shape: getEdgeShape(layoutOpt, orient, curvature, sourceLayout, sourceLayout),
  47544. style: {
  47545. opacity: 0
  47546. }
  47547. }, seriesModel, {
  47548. cb: function () {
  47549. group.remove(edge);
  47550. },
  47551. removeOpt: removeAnimationOpt
  47552. });
  47553. } else if (edgeShape === 'polyline' && seriesModel.get('layout') === 'orthogonal') {
  47554. removeElement(edge, {
  47555. shape: {
  47556. parentPoint: [sourceLayout.x, sourceLayout.y],
  47557. childPoints: [[sourceLayout.x, sourceLayout.y]]
  47558. },
  47559. style: {
  47560. opacity: 0
  47561. }
  47562. }, seriesModel, {
  47563. cb: function () {
  47564. group.remove(edge);
  47565. },
  47566. removeOpt: removeAnimationOpt
  47567. });
  47568. }
  47569. }
  47570. }
  47571. function getSourceNode(virtualRoot, node) {
  47572. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  47573. var sourceLayout;
  47574. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  47575. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  47576. }
  47577. return {
  47578. source: source,
  47579. sourceLayout: sourceLayout
  47580. };
  47581. }
  47582. function removeNode(data, dataIndex, symbolEl, group, seriesModel) {
  47583. var node = data.tree.getNodeByDataIndex(dataIndex);
  47584. var virtualRoot = data.tree.root;
  47585. var sourceLayout = getSourceNode(virtualRoot, node).sourceLayout; // Use same duration and easing with update to have more consistent animation.
  47586. var removeAnimationOpt = {
  47587. duration: seriesModel.get('animationDurationUpdate'),
  47588. easing: seriesModel.get('animationEasingUpdate')
  47589. };
  47590. removeElement(symbolEl, {
  47591. x: sourceLayout.x + 1,
  47592. y: sourceLayout.y + 1
  47593. }, seriesModel, {
  47594. cb: function () {
  47595. group.remove(symbolEl);
  47596. data.setItemGraphicEl(dataIndex, null);
  47597. },
  47598. removeOpt: removeAnimationOpt
  47599. });
  47600. symbolEl.fadeOut(null, {
  47601. fadeLabel: true,
  47602. animation: removeAnimationOpt
  47603. }); // remove edge as parent node
  47604. node.children.forEach(function (childNode) {
  47605. removeNodeEdge(childNode, data, group, seriesModel, removeAnimationOpt);
  47606. }); // remove edge as child node
  47607. removeNodeEdge(node, data, group, seriesModel, removeAnimationOpt);
  47608. }
  47609. function getEdgeShape(layoutOpt, orient, curvature, sourceLayout, targetLayout) {
  47610. var cpx1;
  47611. var cpy1;
  47612. var cpx2;
  47613. var cpy2;
  47614. var x1;
  47615. var x2;
  47616. var y1;
  47617. var y2;
  47618. if (layoutOpt === 'radial') {
  47619. x1 = sourceLayout.rawX;
  47620. y1 = sourceLayout.rawY;
  47621. x2 = targetLayout.rawX;
  47622. y2 = targetLayout.rawY;
  47623. var radialCoor1 = radialCoordinate(x1, y1);
  47624. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * curvature);
  47625. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * curvature);
  47626. var radialCoor4 = radialCoordinate(x2, y2);
  47627. return {
  47628. x1: radialCoor1.x || 0,
  47629. y1: radialCoor1.y || 0,
  47630. x2: radialCoor4.x || 0,
  47631. y2: radialCoor4.y || 0,
  47632. cpx1: radialCoor2.x || 0,
  47633. cpy1: radialCoor2.y || 0,
  47634. cpx2: radialCoor3.x || 0,
  47635. cpy2: radialCoor3.y || 0
  47636. };
  47637. } else {
  47638. x1 = sourceLayout.x;
  47639. y1 = sourceLayout.y;
  47640. x2 = targetLayout.x;
  47641. y2 = targetLayout.y;
  47642. if (orient === 'LR' || orient === 'RL') {
  47643. cpx1 = x1 + (x2 - x1) * curvature;
  47644. cpy1 = y1;
  47645. cpx2 = x2 + (x1 - x2) * curvature;
  47646. cpy2 = y2;
  47647. }
  47648. if (orient === 'TB' || orient === 'BT') {
  47649. cpx1 = x1;
  47650. cpy1 = y1 + (y2 - y1) * curvature;
  47651. cpx2 = x2;
  47652. cpy2 = y2 + (y1 - y2) * curvature;
  47653. }
  47654. }
  47655. return {
  47656. x1: x1,
  47657. y1: y1,
  47658. x2: x2,
  47659. y2: y2,
  47660. cpx1: cpx1,
  47661. cpy1: cpy1,
  47662. cpx2: cpx2,
  47663. cpy2: cpy2
  47664. };
  47665. }
  47666. var inner$7 = makeInner();
  47667. function linkSeriesData(opt) {
  47668. var mainData = opt.mainData;
  47669. var datas = opt.datas;
  47670. if (!datas) {
  47671. datas = {
  47672. main: mainData
  47673. };
  47674. opt.datasAttr = {
  47675. main: 'data'
  47676. };
  47677. }
  47678. opt.datas = opt.mainData = null;
  47679. linkAll(mainData, datas, opt); // Porxy data original methods.
  47680. each(datas, function (data) {
  47681. each(mainData.TRANSFERABLE_METHODS, function (methodName) {
  47682. data.wrapMethod(methodName, curry(transferInjection, opt));
  47683. });
  47684. }); // Beyond transfer, additional features should be added to `cloneShallow`.
  47685. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt)); // Only mainData trigger change, because struct.update may trigger
  47686. // another changable methods, which may bring about dead lock.
  47687. each(mainData.CHANGABLE_METHODS, function (methodName) {
  47688. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  47689. }); // Make sure datas contains mainData.
  47690. assert(datas[mainData.dataType] === mainData);
  47691. }
  47692. function transferInjection(opt, res) {
  47693. if (isMainData(this)) {
  47694. // Transfer datas to new main data.
  47695. var datas = extend({}, inner$7(this).datas);
  47696. datas[this.dataType] = res;
  47697. linkAll(res, datas, opt);
  47698. } else {
  47699. // Modify the reference in main data to point newData.
  47700. linkSingle(res, this.dataType, inner$7(this).mainData, opt);
  47701. }
  47702. return res;
  47703. }
  47704. function changeInjection(opt, res) {
  47705. opt.struct && opt.struct.update();
  47706. return res;
  47707. }
  47708. function cloneShallowInjection(opt, res) {
  47709. // cloneShallow, which brings about some fragilities, may be inappropriate
  47710. // to be exposed as an API. So for implementation simplicity we can make
  47711. // the restriction that cloneShallow of not-mainData should not be invoked
  47712. // outside, but only be invoked here.
  47713. each(inner$7(res).datas, function (data, dataType) {
  47714. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  47715. });
  47716. return res;
  47717. }
  47718. /**
  47719. * Supplement method to List.
  47720. *
  47721. * @public
  47722. * @param [dataType] If not specified, return mainData.
  47723. */
  47724. function getLinkedData(dataType) {
  47725. var mainData = inner$7(this).mainData;
  47726. return dataType == null || mainData == null ? mainData : inner$7(mainData).datas[dataType];
  47727. }
  47728. /**
  47729. * Get list of all linked data
  47730. */
  47731. function getLinkedDataAll() {
  47732. var mainData = inner$7(this).mainData;
  47733. return mainData == null ? [{
  47734. data: mainData
  47735. }] : map(keys(inner$7(mainData).datas), function (type) {
  47736. return {
  47737. type: type,
  47738. data: inner$7(mainData).datas[type]
  47739. };
  47740. });
  47741. }
  47742. function isMainData(data) {
  47743. return inner$7(data).mainData === data;
  47744. }
  47745. function linkAll(mainData, datas, opt) {
  47746. inner$7(mainData).datas = {};
  47747. each(datas, function (data, dataType) {
  47748. linkSingle(data, dataType, mainData, opt);
  47749. });
  47750. }
  47751. function linkSingle(data, dataType, mainData, opt) {
  47752. inner$7(mainData).datas[dataType] = data;
  47753. inner$7(data).mainData = mainData;
  47754. data.dataType = dataType;
  47755. if (opt.struct) {
  47756. data[opt.structAttr] = opt.struct;
  47757. opt.struct[opt.datasAttr[dataType]] = data;
  47758. } // Supplement method.
  47759. data.getLinkedData = getLinkedData;
  47760. data.getLinkedDataAll = getLinkedDataAll;
  47761. }
  47762. var TreeNode =
  47763. /** @class */
  47764. function () {
  47765. function TreeNode(name, hostTree) {
  47766. this.depth = 0;
  47767. this.height = 0;
  47768. /**
  47769. * Reference to list item.
  47770. * Do not persistent dataIndex outside,
  47771. * besause it may be changed by list.
  47772. * If dataIndex -1,
  47773. * this node is logical deleted (filtered) in list.
  47774. */
  47775. this.dataIndex = -1;
  47776. this.children = [];
  47777. this.viewChildren = [];
  47778. this.isExpand = false;
  47779. this.name = name || '';
  47780. this.hostTree = hostTree;
  47781. }
  47782. /**
  47783. * The node is removed.
  47784. */
  47785. TreeNode.prototype.isRemoved = function () {
  47786. return this.dataIndex < 0;
  47787. };
  47788. TreeNode.prototype.eachNode = function (options, cb, context) {
  47789. if (typeof options === 'function') {
  47790. context = cb;
  47791. cb = options;
  47792. options = null;
  47793. }
  47794. options = options || {};
  47795. if (isString(options)) {
  47796. options = {
  47797. order: options
  47798. };
  47799. }
  47800. var order = options.order || 'preorder';
  47801. var children = this[options.attr || 'children'];
  47802. var suppressVisitSub;
  47803. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  47804. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  47805. children[i].eachNode(options, cb, context);
  47806. }
  47807. order === 'postorder' && cb.call(context, this);
  47808. };
  47809. /**
  47810. * Update depth and height of this subtree.
  47811. */
  47812. TreeNode.prototype.updateDepthAndHeight = function (depth) {
  47813. var height = 0;
  47814. this.depth = depth;
  47815. for (var i = 0; i < this.children.length; i++) {
  47816. var child = this.children[i];
  47817. child.updateDepthAndHeight(depth + 1);
  47818. if (child.height > height) {
  47819. height = child.height;
  47820. }
  47821. }
  47822. this.height = height + 1;
  47823. };
  47824. TreeNode.prototype.getNodeById = function (id) {
  47825. if (this.getId() === id) {
  47826. return this;
  47827. }
  47828. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  47829. var res = children[i].getNodeById(id);
  47830. if (res) {
  47831. return res;
  47832. }
  47833. }
  47834. };
  47835. TreeNode.prototype.contains = function (node) {
  47836. if (node === this) {
  47837. return true;
  47838. }
  47839. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  47840. var res = children[i].contains(node);
  47841. if (res) {
  47842. return res;
  47843. }
  47844. }
  47845. };
  47846. /**
  47847. * @param includeSelf Default false.
  47848. * @return order: [root, child, grandchild, ...]
  47849. */
  47850. TreeNode.prototype.getAncestors = function (includeSelf) {
  47851. var ancestors = [];
  47852. var node = includeSelf ? this : this.parentNode;
  47853. while (node) {
  47854. ancestors.push(node);
  47855. node = node.parentNode;
  47856. }
  47857. ancestors.reverse();
  47858. return ancestors;
  47859. };
  47860. TreeNode.prototype.getAncestorsIndices = function () {
  47861. var indices = [];
  47862. var currNode = this;
  47863. while (currNode) {
  47864. indices.push(currNode.dataIndex);
  47865. currNode = currNode.parentNode;
  47866. }
  47867. indices.reverse();
  47868. return indices;
  47869. };
  47870. TreeNode.prototype.getDescendantIndices = function () {
  47871. var indices = [];
  47872. this.eachNode(function (childNode) {
  47873. indices.push(childNode.dataIndex);
  47874. });
  47875. return indices;
  47876. };
  47877. TreeNode.prototype.getValue = function (dimension) {
  47878. var data = this.hostTree.data;
  47879. return data.getStore().get(data.getDimensionIndex(dimension || 'value'), this.dataIndex);
  47880. };
  47881. TreeNode.prototype.setLayout = function (layout, merge) {
  47882. this.dataIndex >= 0 && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge);
  47883. };
  47884. /**
  47885. * @return {Object} layout
  47886. */
  47887. TreeNode.prototype.getLayout = function () {
  47888. return this.hostTree.data.getItemLayout(this.dataIndex);
  47889. }; // @depcrecated
  47890. // getModel<T = unknown, S extends keyof T = keyof T>(path: S): Model<T[S]>
  47891. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  47892. TreeNode.prototype.getModel = function (path) {
  47893. if (this.dataIndex < 0) {
  47894. return;
  47895. }
  47896. var hostTree = this.hostTree;
  47897. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  47898. return itemModel.getModel(path);
  47899. }; // TODO: TYPE More specific model
  47900. TreeNode.prototype.getLevelModel = function () {
  47901. return (this.hostTree.levelModels || [])[this.depth];
  47902. };
  47903. TreeNode.prototype.setVisual = function (key, value) {
  47904. this.dataIndex >= 0 && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  47905. };
  47906. /**
  47907. * Get item visual
  47908. * FIXME: make return type better
  47909. */
  47910. TreeNode.prototype.getVisual = function (key) {
  47911. return this.hostTree.data.getItemVisual(this.dataIndex, key);
  47912. };
  47913. TreeNode.prototype.getRawIndex = function () {
  47914. return this.hostTree.data.getRawIndex(this.dataIndex);
  47915. };
  47916. TreeNode.prototype.getId = function () {
  47917. return this.hostTree.data.getId(this.dataIndex);
  47918. };
  47919. /**
  47920. * index in parent's children
  47921. */
  47922. TreeNode.prototype.getChildIndex = function () {
  47923. if (this.parentNode) {
  47924. var children = this.parentNode.children;
  47925. for (var i = 0; i < children.length; ++i) {
  47926. if (children[i] === this) {
  47927. return i;
  47928. }
  47929. }
  47930. return -1;
  47931. }
  47932. return -1;
  47933. };
  47934. /**
  47935. * if this is an ancestor of another node
  47936. *
  47937. * @param node another node
  47938. * @return if is ancestor
  47939. */
  47940. TreeNode.prototype.isAncestorOf = function (node) {
  47941. var parent = node.parentNode;
  47942. while (parent) {
  47943. if (parent === this) {
  47944. return true;
  47945. }
  47946. parent = parent.parentNode;
  47947. }
  47948. return false;
  47949. };
  47950. /**
  47951. * if this is an descendant of another node
  47952. *
  47953. * @param node another node
  47954. * @return if is descendant
  47955. */
  47956. TreeNode.prototype.isDescendantOf = function (node) {
  47957. return node !== this && node.isAncestorOf(this);
  47958. };
  47959. return TreeNode;
  47960. }();
  47961. var Tree =
  47962. /** @class */
  47963. function () {
  47964. function Tree(hostModel) {
  47965. this.type = 'tree';
  47966. this._nodes = [];
  47967. this.hostModel = hostModel;
  47968. }
  47969. Tree.prototype.eachNode = function (options, cb, context) {
  47970. this.root.eachNode(options, cb, context);
  47971. };
  47972. Tree.prototype.getNodeByDataIndex = function (dataIndex) {
  47973. var rawIndex = this.data.getRawIndex(dataIndex);
  47974. return this._nodes[rawIndex];
  47975. };
  47976. Tree.prototype.getNodeById = function (name) {
  47977. return this.root.getNodeById(name);
  47978. };
  47979. /**
  47980. * Update item available by list,
  47981. * when list has been performed options like 'filterSelf' or 'map'.
  47982. */
  47983. Tree.prototype.update = function () {
  47984. var data = this.data;
  47985. var nodes = this._nodes;
  47986. for (var i = 0, len = nodes.length; i < len; i++) {
  47987. nodes[i].dataIndex = -1;
  47988. }
  47989. for (var i = 0, len = data.count(); i < len; i++) {
  47990. nodes[data.getRawIndex(i)].dataIndex = i;
  47991. }
  47992. };
  47993. /**
  47994. * Clear all layouts
  47995. */
  47996. Tree.prototype.clearLayouts = function () {
  47997. this.data.clearItemLayouts();
  47998. };
  47999. /**
  48000. * data node format:
  48001. * {
  48002. * name: ...
  48003. * value: ...
  48004. * children: [
  48005. * {
  48006. * name: ...
  48007. * value: ...
  48008. * children: ...
  48009. * },
  48010. * ...
  48011. * ]
  48012. * }
  48013. */
  48014. Tree.createTree = function (dataRoot, hostModel, beforeLink) {
  48015. var tree = new Tree(hostModel);
  48016. var listData = [];
  48017. var dimMax = 1;
  48018. buildHierarchy(dataRoot);
  48019. function buildHierarchy(dataNode, parentNode) {
  48020. var value = dataNode.value;
  48021. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  48022. listData.push(dataNode);
  48023. var node = new TreeNode(convertOptionIdName(dataNode.name, ''), tree);
  48024. parentNode ? addChild(node, parentNode) : tree.root = node;
  48025. tree._nodes.push(node);
  48026. var children = dataNode.children;
  48027. if (children) {
  48028. for (var i = 0; i < children.length; i++) {
  48029. buildHierarchy(children[i], node);
  48030. }
  48031. }
  48032. }
  48033. tree.root.updateDepthAndHeight(0);
  48034. var dimensions = prepareSeriesDataSchema(listData, {
  48035. coordDimensions: ['value'],
  48036. dimensionsCount: dimMax
  48037. }).dimensions;
  48038. var list = new SeriesData(dimensions, hostModel);
  48039. list.initData(listData);
  48040. beforeLink && beforeLink(list);
  48041. linkSeriesData({
  48042. mainData: list,
  48043. struct: tree,
  48044. structAttr: 'tree'
  48045. });
  48046. tree.update();
  48047. return tree;
  48048. };
  48049. return Tree;
  48050. }();
  48051. /**
  48052. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  48053. * so this function is not ready and not necessary to be public.
  48054. */
  48055. function addChild(child, node) {
  48056. var children = node.children;
  48057. if (child.parentNode === node) {
  48058. return;
  48059. }
  48060. children.push(child);
  48061. child.parentNode = node;
  48062. }
  48063. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  48064. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  48065. var root = seriesModel.getData().tree.root;
  48066. var targetNode = payload.targetNode;
  48067. if (typeof targetNode === 'string') {
  48068. targetNode = root.getNodeById(targetNode);
  48069. }
  48070. if (targetNode && root.contains(targetNode)) {
  48071. return {
  48072. node: targetNode
  48073. };
  48074. }
  48075. var targetNodeId = payload.targetNodeId;
  48076. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  48077. return {
  48078. node: targetNode
  48079. };
  48080. }
  48081. }
  48082. } // Not includes the given node at the last item.
  48083. function getPathToRoot(node) {
  48084. var path = [];
  48085. while (node) {
  48086. node = node.parentNode;
  48087. node && path.push(node);
  48088. }
  48089. return path.reverse();
  48090. }
  48091. function aboveViewRoot(viewRoot, node) {
  48092. var viewPath = getPathToRoot(viewRoot);
  48093. return indexOf(viewPath, node) >= 0;
  48094. } // From root to the input node (the input node will be included).
  48095. function wrapTreePathInfo(node, seriesModel) {
  48096. var treePathInfo = [];
  48097. while (node) {
  48098. var nodeDataIndex = node.dataIndex;
  48099. treePathInfo.push({
  48100. name: node.name,
  48101. dataIndex: nodeDataIndex,
  48102. value: seriesModel.getRawValue(nodeDataIndex)
  48103. });
  48104. node = node.parentNode;
  48105. }
  48106. treePathInfo.reverse();
  48107. return treePathInfo;
  48108. }
  48109. var TreeSeriesModel =
  48110. /** @class */
  48111. function (_super) {
  48112. __extends(TreeSeriesModel, _super);
  48113. function TreeSeriesModel() {
  48114. var _this = _super !== null && _super.apply(this, arguments) || this;
  48115. _this.hasSymbolVisual = true; // Do it self.
  48116. _this.ignoreStyleOnData = true;
  48117. return _this;
  48118. }
  48119. /**
  48120. * Init a tree data structure from data in option series
  48121. */
  48122. TreeSeriesModel.prototype.getInitialData = function (option) {
  48123. //create an virtual root
  48124. var root = {
  48125. name: option.name,
  48126. children: option.data
  48127. };
  48128. var leaves = option.leaves || {};
  48129. var leavesModel = new Model(leaves, this, this.ecModel);
  48130. var tree = Tree.createTree(root, this, beforeLink);
  48131. function beforeLink(nodeData) {
  48132. nodeData.wrapMethod('getItemModel', function (model, idx) {
  48133. var node = tree.getNodeByDataIndex(idx);
  48134. if (!(node && node.children.length && node.isExpand)) {
  48135. model.parentModel = leavesModel;
  48136. }
  48137. return model;
  48138. });
  48139. }
  48140. var treeDepth = 0;
  48141. tree.eachNode('preorder', function (node) {
  48142. if (node.depth > treeDepth) {
  48143. treeDepth = node.depth;
  48144. }
  48145. });
  48146. var expandAndCollapse = option.expandAndCollapse;
  48147. var expandTreeDepth = expandAndCollapse && option.initialTreeDepth >= 0 ? option.initialTreeDepth : treeDepth;
  48148. tree.root.eachNode('preorder', function (node) {
  48149. var item = node.hostTree.data.getRawDataItem(node.dataIndex); // Add item.collapsed != null, because users can collapse node original in the series.data.
  48150. node.isExpand = item && item.collapsed != null ? !item.collapsed : node.depth <= expandTreeDepth;
  48151. });
  48152. return tree.data;
  48153. };
  48154. /**
  48155. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  48156. * @returns {string} orient
  48157. */
  48158. TreeSeriesModel.prototype.getOrient = function () {
  48159. var orient = this.get('orient');
  48160. if (orient === 'horizontal') {
  48161. orient = 'LR';
  48162. } else if (orient === 'vertical') {
  48163. orient = 'TB';
  48164. }
  48165. return orient;
  48166. };
  48167. TreeSeriesModel.prototype.setZoom = function (zoom) {
  48168. this.option.zoom = zoom;
  48169. };
  48170. TreeSeriesModel.prototype.setCenter = function (center) {
  48171. this.option.center = center;
  48172. };
  48173. TreeSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  48174. var tree = this.getData().tree;
  48175. var realRoot = tree.root.children[0];
  48176. var node = tree.getNodeByDataIndex(dataIndex);
  48177. var value = node.getValue();
  48178. var name = node.name;
  48179. while (node && node !== realRoot) {
  48180. name = node.parentNode.name + '.' + name;
  48181. node = node.parentNode;
  48182. }
  48183. return createTooltipMarkup('nameValue', {
  48184. name: name,
  48185. value: value,
  48186. noValue: isNaN(value) || value == null
  48187. });
  48188. }; // Add tree path to tooltip param
  48189. TreeSeriesModel.prototype.getDataParams = function (dataIndex) {
  48190. var params = _super.prototype.getDataParams.apply(this, arguments);
  48191. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  48192. params.treeAncestors = wrapTreePathInfo(node, this);
  48193. return params;
  48194. };
  48195. TreeSeriesModel.type = 'series.tree'; // can support the position parameters 'left', 'top','right','bottom', 'width',
  48196. // 'height' in the setOption() with 'merge' mode normal.
  48197. TreeSeriesModel.layoutMode = 'box';
  48198. TreeSeriesModel.defaultOption = {
  48199. zlevel: 0,
  48200. z: 2,
  48201. coordinateSystem: 'view',
  48202. // the position of the whole view
  48203. left: '12%',
  48204. top: '12%',
  48205. right: '12%',
  48206. bottom: '12%',
  48207. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  48208. layout: 'orthogonal',
  48209. // value can be 'polyline'
  48210. edgeShape: 'curve',
  48211. edgeForkPosition: '50%',
  48212. // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  48213. roam: false,
  48214. // Symbol size scale ratio in roam
  48215. nodeScaleRatio: 0.4,
  48216. // Default on center of graph
  48217. center: null,
  48218. zoom: 1,
  48219. orient: 'LR',
  48220. symbol: 'emptyCircle',
  48221. symbolSize: 7,
  48222. expandAndCollapse: true,
  48223. initialTreeDepth: 2,
  48224. lineStyle: {
  48225. color: '#ccc',
  48226. width: 1.5,
  48227. curveness: 0.5
  48228. },
  48229. itemStyle: {
  48230. color: 'lightsteelblue',
  48231. // borderColor: '#c23531',
  48232. borderWidth: 1.5
  48233. },
  48234. label: {
  48235. show: true
  48236. },
  48237. animationEasing: 'linear',
  48238. animationDuration: 700,
  48239. animationDurationUpdate: 500
  48240. };
  48241. return TreeSeriesModel;
  48242. }(SeriesModel);
  48243. /*
  48244. * Licensed to the Apache Software Foundation (ASF) under one
  48245. * or more contributor license agreements. See the NOTICE file
  48246. * distributed with this work for additional information
  48247. * regarding copyright ownership. The ASF licenses this file
  48248. * to you under the Apache License, Version 2.0 (the
  48249. * "License"); you may not use this file except in compliance
  48250. * with the License. You may obtain a copy of the License at
  48251. *
  48252. * http://www.apache.org/licenses/LICENSE-2.0
  48253. *
  48254. * Unless required by applicable law or agreed to in writing,
  48255. * software distributed under the License is distributed on an
  48256. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48257. * KIND, either express or implied. See the License for the
  48258. * specific language governing permissions and limitations
  48259. * under the License.
  48260. */
  48261. /**
  48262. * AUTO-GENERATED FILE. DO NOT MODIFY.
  48263. */
  48264. /*
  48265. * Licensed to the Apache Software Foundation (ASF) under one
  48266. * or more contributor license agreements. See the NOTICE file
  48267. * distributed with this work for additional information
  48268. * regarding copyright ownership. The ASF licenses this file
  48269. * to you under the Apache License, Version 2.0 (the
  48270. * "License"); you may not use this file except in compliance
  48271. * with the License. You may obtain a copy of the License at
  48272. *
  48273. * http://www.apache.org/licenses/LICENSE-2.0
  48274. *
  48275. * Unless required by applicable law or agreed to in writing,
  48276. * software distributed under the License is distributed on an
  48277. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48278. * KIND, either express or implied. See the License for the
  48279. * specific language governing permissions and limitations
  48280. * under the License.
  48281. */
  48282. /**
  48283. * Traverse the tree from bottom to top and do something
  48284. */
  48285. function eachAfter(root, callback, separation) {
  48286. var nodes = [root];
  48287. var next = [];
  48288. var node;
  48289. while (node = nodes.pop()) {
  48290. // jshint ignore:line
  48291. next.push(node);
  48292. if (node.isExpand) {
  48293. var children = node.children;
  48294. if (children.length) {
  48295. for (var i = 0; i < children.length; i++) {
  48296. nodes.push(children[i]);
  48297. }
  48298. }
  48299. }
  48300. }
  48301. while (node = next.pop()) {
  48302. // jshint ignore:line
  48303. callback(node, separation);
  48304. }
  48305. }
  48306. /**
  48307. * Traverse the tree from top to bottom and do something
  48308. */
  48309. function eachBefore(root, callback) {
  48310. var nodes = [root];
  48311. var node;
  48312. while (node = nodes.pop()) {
  48313. // jshint ignore:line
  48314. callback(node);
  48315. if (node.isExpand) {
  48316. var children = node.children;
  48317. if (children.length) {
  48318. for (var i = children.length - 1; i >= 0; i--) {
  48319. nodes.push(children[i]);
  48320. }
  48321. }
  48322. }
  48323. }
  48324. }
  48325. function treeLayout(ecModel, api) {
  48326. ecModel.eachSeriesByType('tree', function (seriesModel) {
  48327. commonLayout(seriesModel, api);
  48328. });
  48329. }
  48330. function commonLayout(seriesModel, api) {
  48331. var layoutInfo = getViewRect$1(seriesModel, api);
  48332. seriesModel.layoutInfo = layoutInfo;
  48333. var layout = seriesModel.get('layout');
  48334. var width = 0;
  48335. var height = 0;
  48336. var separation$1 = null;
  48337. if (layout === 'radial') {
  48338. width = 2 * Math.PI;
  48339. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  48340. separation$1 = separation(function (node1, node2) {
  48341. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  48342. });
  48343. } else {
  48344. width = layoutInfo.width;
  48345. height = layoutInfo.height;
  48346. separation$1 = separation();
  48347. }
  48348. var virtualRoot = seriesModel.getData().tree.root;
  48349. var realRoot = virtualRoot.children[0];
  48350. if (realRoot) {
  48351. init$2(virtualRoot);
  48352. eachAfter(realRoot, firstWalk, separation$1);
  48353. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  48354. eachBefore(realRoot, secondWalk);
  48355. var left_1 = realRoot;
  48356. var right_1 = realRoot;
  48357. var bottom_1 = realRoot;
  48358. eachBefore(realRoot, function (node) {
  48359. var x = node.getLayout().x;
  48360. if (x < left_1.getLayout().x) {
  48361. left_1 = node;
  48362. }
  48363. if (x > right_1.getLayout().x) {
  48364. right_1 = node;
  48365. }
  48366. if (node.depth > bottom_1.depth) {
  48367. bottom_1 = node;
  48368. }
  48369. });
  48370. var delta = left_1 === right_1 ? 1 : separation$1(left_1, right_1) / 2;
  48371. var tx_1 = delta - left_1.getLayout().x;
  48372. var kx_1 = 0;
  48373. var ky_1 = 0;
  48374. var coorX_1 = 0;
  48375. var coorY_1 = 0;
  48376. if (layout === 'radial') {
  48377. kx_1 = width / (right_1.getLayout().x + delta + tx_1); // here we use (node.depth - 1), bucause the real root's depth is 1
  48378. ky_1 = height / (bottom_1.depth - 1 || 1);
  48379. eachBefore(realRoot, function (node) {
  48380. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  48381. coorY_1 = (node.depth - 1) * ky_1;
  48382. var finalCoor = radialCoordinate(coorX_1, coorY_1);
  48383. node.setLayout({
  48384. x: finalCoor.x,
  48385. y: finalCoor.y,
  48386. rawX: coorX_1,
  48387. rawY: coorY_1
  48388. }, true);
  48389. });
  48390. } else {
  48391. var orient_1 = seriesModel.getOrient();
  48392. if (orient_1 === 'RL' || orient_1 === 'LR') {
  48393. ky_1 = height / (right_1.getLayout().x + delta + tx_1);
  48394. kx_1 = width / (bottom_1.depth - 1 || 1);
  48395. eachBefore(realRoot, function (node) {
  48396. coorY_1 = (node.getLayout().x + tx_1) * ky_1;
  48397. coorX_1 = orient_1 === 'LR' ? (node.depth - 1) * kx_1 : width - (node.depth - 1) * kx_1;
  48398. node.setLayout({
  48399. x: coorX_1,
  48400. y: coorY_1
  48401. }, true);
  48402. });
  48403. } else if (orient_1 === 'TB' || orient_1 === 'BT') {
  48404. kx_1 = width / (right_1.getLayout().x + delta + tx_1);
  48405. ky_1 = height / (bottom_1.depth - 1 || 1);
  48406. eachBefore(realRoot, function (node) {
  48407. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  48408. coorY_1 = orient_1 === 'TB' ? (node.depth - 1) * ky_1 : height - (node.depth - 1) * ky_1;
  48409. node.setLayout({
  48410. x: coorX_1,
  48411. y: coorY_1
  48412. }, true);
  48413. });
  48414. }
  48415. }
  48416. }
  48417. }
  48418. function treeVisual(ecModel) {
  48419. ecModel.eachSeriesByType('tree', function (seriesModel) {
  48420. var data = seriesModel.getData();
  48421. var tree = data.tree;
  48422. tree.eachNode(function (node) {
  48423. var model = node.getModel(); // TODO Optimize
  48424. var style = model.getModel('itemStyle').getItemStyle();
  48425. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  48426. extend(existsStyle, style);
  48427. });
  48428. });
  48429. }
  48430. function installTreeAction(registers) {
  48431. registers.registerAction({
  48432. type: 'treeExpandAndCollapse',
  48433. event: 'treeExpandAndCollapse',
  48434. update: 'update'
  48435. }, function (payload, ecModel) {
  48436. ecModel.eachComponent({
  48437. mainType: 'series',
  48438. subType: 'tree',
  48439. query: payload
  48440. }, function (seriesModel) {
  48441. var dataIndex = payload.dataIndex;
  48442. var tree = seriesModel.getData().tree;
  48443. var node = tree.getNodeByDataIndex(dataIndex);
  48444. node.isExpand = !node.isExpand;
  48445. });
  48446. });
  48447. registers.registerAction({
  48448. type: 'treeRoam',
  48449. event: 'treeRoam',
  48450. // Here we set 'none' instead of 'update', because roam action
  48451. // just need to update the transform matrix without having to recalculate
  48452. // the layout. So don't need to go through the whole update process, such
  48453. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  48454. update: 'none'
  48455. }, function (payload, ecModel) {
  48456. ecModel.eachComponent({
  48457. mainType: 'series',
  48458. subType: 'tree',
  48459. query: payload
  48460. }, function (seriesModel) {
  48461. var coordSys = seriesModel.coordinateSystem;
  48462. var res = updateCenterAndZoom(coordSys, payload);
  48463. seriesModel.setCenter && seriesModel.setCenter(res.center);
  48464. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  48465. });
  48466. });
  48467. }
  48468. function install$b(registers) {
  48469. registers.registerChartView(TreeView);
  48470. registers.registerSeriesModel(TreeSeriesModel);
  48471. registers.registerLayout(treeLayout);
  48472. registers.registerVisual(treeVisual);
  48473. installTreeAction(registers);
  48474. }
  48475. var noop$1 = function () {};
  48476. var actionTypes = ['treemapZoomToNode', 'treemapRender', 'treemapMove'];
  48477. function installTreemapAction(registers) {
  48478. for (var i = 0; i < actionTypes.length; i++) {
  48479. registers.registerAction({
  48480. type: actionTypes[i],
  48481. update: 'updateView'
  48482. }, noop$1);
  48483. }
  48484. registers.registerAction({
  48485. type: 'treemapRootToNode',
  48486. update: 'updateView'
  48487. }, function (payload, ecModel) {
  48488. ecModel.eachComponent({
  48489. mainType: 'series',
  48490. subType: 'treemap',
  48491. query: payload
  48492. }, handleRootToNode);
  48493. function handleRootToNode(model, index) {
  48494. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  48495. var targetInfo = retrieveTargetInfo(payload, types, model);
  48496. if (targetInfo) {
  48497. var originViewRoot = model.getViewRoot();
  48498. if (originViewRoot) {
  48499. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  48500. }
  48501. model.resetViewRoot(targetInfo.node);
  48502. }
  48503. }
  48504. });
  48505. }
  48506. function enableAriaDecalForTree(seriesModel) {
  48507. var data = seriesModel.getData();
  48508. var tree = data.tree;
  48509. var decalPaletteScope = {};
  48510. tree.eachNode(function (node) {
  48511. // Use decal of level 1 node
  48512. var current = node;
  48513. while (current && current.depth > 1) {
  48514. current = current.parentNode;
  48515. }
  48516. var decal = getDecalFromPalette(seriesModel.ecModel, current.name || current.dataIndex + '', decalPaletteScope);
  48517. node.setVisual('decal', decal);
  48518. });
  48519. }
  48520. var TreemapSeriesModel =
  48521. /** @class */
  48522. function (_super) {
  48523. __extends(TreemapSeriesModel, _super);
  48524. function TreemapSeriesModel() {
  48525. var _this = _super !== null && _super.apply(this, arguments) || this;
  48526. _this.type = TreemapSeriesModel.type;
  48527. _this.preventUsingHoverLayer = true;
  48528. return _this;
  48529. }
  48530. /**
  48531. * @override
  48532. */
  48533. TreemapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  48534. // Create a virtual root.
  48535. var root = {
  48536. name: option.name,
  48537. children: option.data
  48538. };
  48539. completeTreeValue(root);
  48540. var levels = option.levels || []; // Used in "visual priority" in `treemapVisual.js`.
  48541. // This way is a little tricky, must satisfy the precondition:
  48542. // 1. There is no `treeNode.getModel('itemStyle.xxx')` used.
  48543. // 2. The `Model.prototype.getModel()` will not use any clone-like way.
  48544. var designatedVisualItemStyle = this.designatedVisualItemStyle = {};
  48545. var designatedVisualModel = new Model({
  48546. itemStyle: designatedVisualItemStyle
  48547. }, this, ecModel);
  48548. levels = option.levels = setDefault(levels, ecModel);
  48549. var levelModels = map(levels || [], function (levelDefine) {
  48550. return new Model(levelDefine, designatedVisualModel, ecModel);
  48551. }, this); // Make sure always a new tree is created when setOption,
  48552. // in TreemapView, we check whether oldTree === newTree
  48553. // to choose mappings approach among old shapes and new shapes.
  48554. var tree = Tree.createTree(root, this, beforeLink);
  48555. function beforeLink(nodeData) {
  48556. nodeData.wrapMethod('getItemModel', function (model, idx) {
  48557. var node = tree.getNodeByDataIndex(idx);
  48558. var levelModel = node ? levelModels[node.depth] : null; // If no levelModel, we also need `designatedVisualModel`.
  48559. model.parentModel = levelModel || designatedVisualModel;
  48560. return model;
  48561. });
  48562. }
  48563. return tree.data;
  48564. };
  48565. TreemapSeriesModel.prototype.optionUpdated = function () {
  48566. this.resetViewRoot();
  48567. };
  48568. /**
  48569. * @override
  48570. * @param {number} dataIndex
  48571. * @param {boolean} [mutipleSeries=false]
  48572. */
  48573. TreemapSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  48574. var data = this.getData();
  48575. var value = this.getRawValue(dataIndex);
  48576. var name = data.getName(dataIndex);
  48577. return createTooltipMarkup('nameValue', {
  48578. name: name,
  48579. value: value
  48580. });
  48581. };
  48582. /**
  48583. * Add tree path to tooltip param
  48584. *
  48585. * @override
  48586. * @param {number} dataIndex
  48587. * @return {Object}
  48588. */
  48589. TreemapSeriesModel.prototype.getDataParams = function (dataIndex) {
  48590. var params = _super.prototype.getDataParams.apply(this, arguments);
  48591. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  48592. params.treeAncestors = wrapTreePathInfo(node, this); // compatitable the previous code.
  48593. params.treePathInfo = params.treeAncestors;
  48594. return params;
  48595. };
  48596. /**
  48597. * @public
  48598. * @param {Object} layoutInfo {
  48599. * x: containerGroup x
  48600. * y: containerGroup y
  48601. * width: containerGroup width
  48602. * height: containerGroup height
  48603. * }
  48604. */
  48605. TreemapSeriesModel.prototype.setLayoutInfo = function (layoutInfo) {
  48606. /**
  48607. * @readOnly
  48608. * @type {Object}
  48609. */
  48610. this.layoutInfo = this.layoutInfo || {};
  48611. extend(this.layoutInfo, layoutInfo);
  48612. };
  48613. /**
  48614. * @param {string} id
  48615. * @return {number} index
  48616. */
  48617. TreemapSeriesModel.prototype.mapIdToIndex = function (id) {
  48618. // A feature is implemented:
  48619. // index is monotone increasing with the sequence of
  48620. // input id at the first time.
  48621. // This feature can make sure that each data item and its
  48622. // mapped color have the same index between data list and
  48623. // color list at the beginning, which is useful for user
  48624. // to adjust data-color mapping.
  48625. /**
  48626. * @private
  48627. * @type {Object}
  48628. */
  48629. var idIndexMap = this._idIndexMap;
  48630. if (!idIndexMap) {
  48631. idIndexMap = this._idIndexMap = createHashMap();
  48632. /**
  48633. * @private
  48634. * @type {number}
  48635. */
  48636. this._idIndexMapCount = 0;
  48637. }
  48638. var index = idIndexMap.get(id);
  48639. if (index == null) {
  48640. idIndexMap.set(id, index = this._idIndexMapCount++);
  48641. }
  48642. return index;
  48643. };
  48644. TreemapSeriesModel.prototype.getViewRoot = function () {
  48645. return this._viewRoot;
  48646. };
  48647. TreemapSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  48648. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  48649. var root = this.getRawData().tree.root;
  48650. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  48651. this._viewRoot = root;
  48652. }
  48653. };
  48654. TreemapSeriesModel.prototype.enableAriaDecal = function () {
  48655. enableAriaDecalForTree(this);
  48656. };
  48657. TreemapSeriesModel.type = 'series.treemap';
  48658. TreemapSeriesModel.layoutMode = 'box';
  48659. TreemapSeriesModel.defaultOption = {
  48660. // Disable progressive rendering
  48661. progressive: 0,
  48662. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  48663. left: 'center',
  48664. top: 'middle',
  48665. width: '80%',
  48666. height: '80%',
  48667. sort: true,
  48668. clipWindow: 'origin',
  48669. squareRatio: 0.5 * (1 + Math.sqrt(5)),
  48670. leafDepth: null,
  48671. drillDownIcon: '▶',
  48672. // to align specialized icon. ▷▶❒❐▼✚
  48673. zoomToNodeRatio: 0.32 * 0.32,
  48674. roam: true,
  48675. nodeClick: 'zoomToNode',
  48676. animation: true,
  48677. animationDurationUpdate: 900,
  48678. animationEasing: 'quinticInOut',
  48679. breadcrumb: {
  48680. show: true,
  48681. height: 22,
  48682. left: 'center',
  48683. top: 'bottom',
  48684. // right
  48685. // bottom
  48686. emptyItemWidth: 25,
  48687. itemStyle: {
  48688. color: 'rgba(0,0,0,0.7)',
  48689. textStyle: {
  48690. color: '#fff'
  48691. }
  48692. }
  48693. },
  48694. label: {
  48695. show: true,
  48696. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  48697. distance: 0,
  48698. padding: 5,
  48699. position: 'inside',
  48700. // formatter: null,
  48701. color: '#fff',
  48702. overflow: 'truncate' // align
  48703. // verticalAlign
  48704. },
  48705. upperLabel: {
  48706. show: false,
  48707. position: [0, '50%'],
  48708. height: 20,
  48709. // formatter: null,
  48710. // color: '#fff',
  48711. overflow: 'truncate',
  48712. // align: null,
  48713. verticalAlign: 'middle'
  48714. },
  48715. itemStyle: {
  48716. color: null,
  48717. colorAlpha: null,
  48718. colorSaturation: null,
  48719. borderWidth: 0,
  48720. gapWidth: 0,
  48721. borderColor: '#fff',
  48722. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  48723. // border color is evaluated by color of current node and
  48724. // borderColorSaturation.
  48725. },
  48726. emphasis: {
  48727. upperLabel: {
  48728. show: true,
  48729. position: [0, '50%'],
  48730. ellipsis: true,
  48731. verticalAlign: 'middle'
  48732. }
  48733. },
  48734. visualDimension: 0,
  48735. visualMin: null,
  48736. visualMax: null,
  48737. color: [],
  48738. // level[n].color (if necessary).
  48739. // + Specify color list of each level. level[0].color would be global
  48740. // color list if not specified. (see method `setDefault`).
  48741. // + But set as a empty array to forbid fetch color from global palette
  48742. // when using nodeModel.get('color'), otherwise nodes on deep level
  48743. // will always has color palette set and are not able to inherit color
  48744. // from parent node.
  48745. // + TreemapSeries.color can not be set as 'none', otherwise effect
  48746. // legend color fetching (see seriesColor.js).
  48747. colorAlpha: null,
  48748. colorSaturation: null,
  48749. colorMappingBy: 'index',
  48750. visibleMin: 10,
  48751. // be rendered. Only works when sort is 'asc' or 'desc'.
  48752. childrenVisibleMin: null,
  48753. // grandchildren will not show.
  48754. // Why grandchildren? If not grandchildren but children,
  48755. // some siblings show children and some not,
  48756. // the appearance may be mess and not consistent,
  48757. levels: [] // Each item: {
  48758. // visibleMin, itemStyle, visualDimension, label
  48759. // }
  48760. // data: {
  48761. // value: [],
  48762. // children: [],
  48763. // link: 'http://xxx.xxx.xxx',
  48764. // target: 'blank' or 'self'
  48765. // }
  48766. };
  48767. return TreemapSeriesModel;
  48768. }(SeriesModel);
  48769. /**
  48770. * @param {Object} dataNode
  48771. */
  48772. function completeTreeValue(dataNode) {
  48773. // Postorder travel tree.
  48774. // If value of none-leaf node is not set,
  48775. // calculate it by suming up the value of all children.
  48776. var sum = 0;
  48777. each(dataNode.children, function (child) {
  48778. completeTreeValue(child);
  48779. var childValue = child.value;
  48780. isArray(childValue) && (childValue = childValue[0]);
  48781. sum += childValue;
  48782. });
  48783. var thisValue = dataNode.value;
  48784. if (isArray(thisValue)) {
  48785. thisValue = thisValue[0];
  48786. }
  48787. if (thisValue == null || isNaN(thisValue)) {
  48788. thisValue = sum;
  48789. } // Value should not less than 0.
  48790. if (thisValue < 0) {
  48791. thisValue = 0;
  48792. }
  48793. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  48794. }
  48795. /**
  48796. * set default to level configuration
  48797. */
  48798. function setDefault(levels, ecModel) {
  48799. var globalColorList = normalizeToArray(ecModel.get('color'));
  48800. var globalDecalList = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  48801. if (!globalColorList) {
  48802. return;
  48803. }
  48804. levels = levels || [];
  48805. var hasColorDefine;
  48806. var hasDecalDefine;
  48807. each(levels, function (levelDefine) {
  48808. var model = new Model(levelDefine);
  48809. var modelColor = model.get('color');
  48810. var modelDecal = model.get('decal');
  48811. if (model.get(['itemStyle', 'color']) || modelColor && modelColor !== 'none') {
  48812. hasColorDefine = true;
  48813. }
  48814. if (model.get(['itemStyle', 'decal']) || modelDecal && modelDecal !== 'none') {
  48815. hasDecalDefine = true;
  48816. }
  48817. });
  48818. var level0 = levels[0] || (levels[0] = {});
  48819. if (!hasColorDefine) {
  48820. level0.color = globalColorList.slice();
  48821. }
  48822. if (!hasDecalDefine && globalDecalList) {
  48823. level0.decal = globalDecalList.slice();
  48824. }
  48825. return levels;
  48826. }
  48827. var TEXT_PADDING = 8;
  48828. var ITEM_GAP = 8;
  48829. var ARRAY_LENGTH = 5;
  48830. var Breadcrumb =
  48831. /** @class */
  48832. function () {
  48833. function Breadcrumb(containerGroup) {
  48834. this.group = new Group();
  48835. containerGroup.add(this.group);
  48836. }
  48837. Breadcrumb.prototype.render = function (seriesModel, api, targetNode, onSelect) {
  48838. var model = seriesModel.getModel('breadcrumb');
  48839. var thisGroup = this.group;
  48840. thisGroup.removeAll();
  48841. if (!model.get('show') || !targetNode) {
  48842. return;
  48843. }
  48844. var normalStyleModel = model.getModel('itemStyle'); // let emphasisStyleModel = model.getModel('emphasis.itemStyle');
  48845. var textStyleModel = normalStyleModel.getModel('textStyle');
  48846. var layoutParam = {
  48847. pos: {
  48848. left: model.get('left'),
  48849. right: model.get('right'),
  48850. top: model.get('top'),
  48851. bottom: model.get('bottom')
  48852. },
  48853. box: {
  48854. width: api.getWidth(),
  48855. height: api.getHeight()
  48856. },
  48857. emptyItemWidth: model.get('emptyItemWidth'),
  48858. totalWidth: 0,
  48859. renderList: []
  48860. };
  48861. this._prepare(targetNode, layoutParam, textStyleModel);
  48862. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  48863. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  48864. };
  48865. /**
  48866. * Prepare render list and total width
  48867. * @private
  48868. */
  48869. Breadcrumb.prototype._prepare = function (targetNode, layoutParam, textStyleModel) {
  48870. for (var node = targetNode; node; node = node.parentNode) {
  48871. var text = convertOptionIdName(node.getModel().get('name'), '');
  48872. var textRect = textStyleModel.getTextRect(text);
  48873. var itemWidth = Math.max(textRect.width + TEXT_PADDING * 2, layoutParam.emptyItemWidth);
  48874. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  48875. layoutParam.renderList.push({
  48876. node: node,
  48877. text: text,
  48878. width: itemWidth
  48879. });
  48880. }
  48881. };
  48882. /**
  48883. * @private
  48884. */
  48885. Breadcrumb.prototype._renderContent = function (seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect) {
  48886. // Start rendering.
  48887. var lastX = 0;
  48888. var emptyItemWidth = layoutParam.emptyItemWidth;
  48889. var height = seriesModel.get(['breadcrumb', 'height']);
  48890. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  48891. var totalWidth = layoutParam.totalWidth;
  48892. var renderList = layoutParam.renderList;
  48893. for (var i = renderList.length - 1; i >= 0; i--) {
  48894. var item = renderList[i];
  48895. var itemNode = item.node;
  48896. var itemWidth = item.width;
  48897. var text = item.text; // Hdie text and shorten width if necessary.
  48898. if (totalWidth > availableSize.width) {
  48899. totalWidth -= itemWidth - emptyItemWidth;
  48900. itemWidth = emptyItemWidth;
  48901. text = null;
  48902. }
  48903. var el = new Polygon({
  48904. shape: {
  48905. points: makeItemPoints(lastX, 0, itemWidth, height, i === renderList.length - 1, i === 0)
  48906. },
  48907. style: defaults(normalStyleModel.getItemStyle(), {
  48908. lineJoin: 'bevel'
  48909. }),
  48910. textContent: new ZRText({
  48911. style: {
  48912. text: text,
  48913. fill: textStyleModel.getTextColor(),
  48914. font: textStyleModel.getFont()
  48915. }
  48916. }),
  48917. textConfig: {
  48918. position: 'inside'
  48919. },
  48920. z2: Z2_EMPHASIS_LIFT * 1e4,
  48921. onclick: curry(onSelect, itemNode)
  48922. });
  48923. el.disableLabelAnimation = true;
  48924. this.group.add(el);
  48925. packEventData(el, seriesModel, itemNode);
  48926. lastX += itemWidth + ITEM_GAP;
  48927. }
  48928. };
  48929. Breadcrumb.prototype.remove = function () {
  48930. this.group.removeAll();
  48931. };
  48932. return Breadcrumb;
  48933. }();
  48934. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  48935. var points = [[head ? x : x - ARRAY_LENGTH, y], [x + itemWidth, y], [x + itemWidth, y + itemHeight], [head ? x : x - ARRAY_LENGTH, y + itemHeight]];
  48936. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  48937. !head && points.push([x, y + itemHeight / 2]);
  48938. return points;
  48939. } // Package custom mouse event.
  48940. function packEventData(el, seriesModel, itemNode) {
  48941. getECData(el).eventData = {
  48942. componentType: 'series',
  48943. componentSubType: 'treemap',
  48944. componentIndex: seriesModel.componentIndex,
  48945. seriesIndex: seriesModel.componentIndex,
  48946. seriesName: seriesModel.name,
  48947. seriesType: 'treemap',
  48948. selfType: 'breadcrumb',
  48949. nodeData: {
  48950. dataIndex: itemNode && itemNode.dataIndex,
  48951. name: itemNode && itemNode.name
  48952. },
  48953. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  48954. };
  48955. }
  48956. /*
  48957. * Licensed to the Apache Software Foundation (ASF) under one
  48958. * or more contributor license agreements. See the NOTICE file
  48959. * distributed with this work for additional information
  48960. * regarding copyright ownership. The ASF licenses this file
  48961. * to you under the Apache License, Version 2.0 (the
  48962. * "License"); you may not use this file except in compliance
  48963. * with the License. You may obtain a copy of the License at
  48964. *
  48965. * http://www.apache.org/licenses/LICENSE-2.0
  48966. *
  48967. * Unless required by applicable law or agreed to in writing,
  48968. * software distributed under the License is distributed on an
  48969. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48970. * KIND, either express or implied. See the License for the
  48971. * specific language governing permissions and limitations
  48972. * under the License.
  48973. */
  48974. /**
  48975. * AUTO-GENERATED FILE. DO NOT MODIFY.
  48976. */
  48977. /*
  48978. * Licensed to the Apache Software Foundation (ASF) under one
  48979. * or more contributor license agreements. See the NOTICE file
  48980. * distributed with this work for additional information
  48981. * regarding copyright ownership. The ASF licenses this file
  48982. * to you under the Apache License, Version 2.0 (the
  48983. * "License"); you may not use this file except in compliance
  48984. * with the License. You may obtain a copy of the License at
  48985. *
  48986. * http://www.apache.org/licenses/LICENSE-2.0
  48987. *
  48988. * Unless required by applicable law or agreed to in writing,
  48989. * software distributed under the License is distributed on an
  48990. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48991. * KIND, either express or implied. See the License for the
  48992. * specific language governing permissions and limitations
  48993. * under the License.
  48994. */
  48995. /**
  48996. * Animate multiple elements with a single done-callback.
  48997. *
  48998. * @example
  48999. * animation
  49000. * .createWrap()
  49001. * .add(el1, {x: 10, y: 10})
  49002. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  49003. * .done(function () { // done })
  49004. * .start('cubicOut');
  49005. */
  49006. var AnimationWrap =
  49007. /** @class */
  49008. function () {
  49009. function AnimationWrap() {
  49010. this._storage = [];
  49011. this._elExistsMap = {};
  49012. }
  49013. /**
  49014. * Caution: a el can only be added once, otherwise 'done'
  49015. * might not be called. This method checks this (by el.id),
  49016. * suppresses adding and returns false when existing el found.
  49017. *
  49018. * @return Whether adding succeeded.
  49019. */
  49020. AnimationWrap.prototype.add = function (el, target, duration, delay, easing) {
  49021. if (this._elExistsMap[el.id]) {
  49022. return false;
  49023. }
  49024. this._elExistsMap[el.id] = true;
  49025. this._storage.push({
  49026. el: el,
  49027. target: target,
  49028. duration: duration,
  49029. delay: delay,
  49030. easing: easing
  49031. });
  49032. return true;
  49033. };
  49034. /**
  49035. * Only execute when animation done/aborted.
  49036. */
  49037. AnimationWrap.prototype.finished = function (callback) {
  49038. this._finishedCallback = callback;
  49039. return this;
  49040. };
  49041. /**
  49042. * Will stop exist animation firstly.
  49043. */
  49044. AnimationWrap.prototype.start = function () {
  49045. var _this = this;
  49046. var count = this._storage.length;
  49047. var checkTerminate = function () {
  49048. count--;
  49049. if (count <= 0) {
  49050. // Guard.
  49051. _this._storage.length = 0;
  49052. _this._elExistsMap = {};
  49053. _this._finishedCallback && _this._finishedCallback();
  49054. }
  49055. };
  49056. for (var i = 0, len = this._storage.length; i < len; i++) {
  49057. var item = this._storage[i];
  49058. item.el.animateTo(item.target, {
  49059. duration: item.duration,
  49060. delay: item.delay,
  49061. easing: item.easing,
  49062. setToFinal: true,
  49063. done: checkTerminate,
  49064. aborted: checkTerminate
  49065. });
  49066. }
  49067. return this;
  49068. };
  49069. return AnimationWrap;
  49070. }();
  49071. function createWrap() {
  49072. return new AnimationWrap();
  49073. }
  49074. var Group$1 = Group;
  49075. var Rect$1 = Rect;
  49076. var DRAG_THRESHOLD = 3;
  49077. var PATH_LABEL_NOAMAL = 'label';
  49078. var PATH_UPPERLABEL_NORMAL = 'upperLabel'; // Should larger than emphasis states lift z
  49079. var Z2_BASE = Z2_EMPHASIS_LIFT * 10; // Should bigger than every z2.
  49080. var Z2_BG = Z2_EMPHASIS_LIFT * 2;
  49081. var Z2_CONTENT = Z2_EMPHASIS_LIFT * 3;
  49082. var getStateItemStyle = makeStyleMapper([['fill', 'color'], // `borderColor` and `borderWidth` has been occupied,
  49083. // so use `stroke` to indicate the stroke of the rect.
  49084. ['stroke', 'strokeColor'], ['lineWidth', 'strokeWidth'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  49085. // So do not transfer decal directly.
  49086. ]);
  49087. var getItemStyleNormal = function (model) {
  49088. // Normal style props should include emphasis style props.
  49089. var itemStyle = getStateItemStyle(model); // Clear styles set by emphasis.
  49090. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  49091. return itemStyle;
  49092. };
  49093. var inner$8 = makeInner();
  49094. var TreemapView =
  49095. /** @class */
  49096. function (_super) {
  49097. __extends(TreemapView, _super);
  49098. function TreemapView() {
  49099. var _this = _super !== null && _super.apply(this, arguments) || this;
  49100. _this.type = TreemapView.type;
  49101. _this._state = 'ready';
  49102. _this._storage = createStorage();
  49103. return _this;
  49104. }
  49105. /**
  49106. * @override
  49107. */
  49108. TreemapView.prototype.render = function (seriesModel, ecModel, api, payload) {
  49109. var models = ecModel.findComponents({
  49110. mainType: 'series',
  49111. subType: 'treemap',
  49112. query: payload
  49113. });
  49114. if (indexOf(models, seriesModel) < 0) {
  49115. return;
  49116. }
  49117. this.seriesModel = seriesModel;
  49118. this.api = api;
  49119. this.ecModel = ecModel;
  49120. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  49121. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  49122. var payloadType = payload && payload.type;
  49123. var layoutInfo = seriesModel.layoutInfo;
  49124. var isInit = !this._oldTree;
  49125. var thisStorage = this._storage; // Mark new root when action is treemapRootToNode.
  49126. var reRoot = payloadType === 'treemapRootToNode' && targetInfo && thisStorage ? {
  49127. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  49128. direction: payload.direction
  49129. } : null;
  49130. var containerGroup = this._giveContainerGroup(layoutInfo);
  49131. var hasAnimation = seriesModel.get('animation');
  49132. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  49133. hasAnimation && !isInit && (!payloadType || payloadType === 'treemapZoomToNode' || payloadType === 'treemapRootToNode') ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot) : renderResult.renderFinally();
  49134. this._resetController(api);
  49135. this._renderBreadcrumb(seriesModel, api, targetInfo);
  49136. };
  49137. TreemapView.prototype._giveContainerGroup = function (layoutInfo) {
  49138. var containerGroup = this._containerGroup;
  49139. if (!containerGroup) {
  49140. // FIXME
  49141. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  49142. containerGroup = this._containerGroup = new Group$1();
  49143. this._initEvents(containerGroup);
  49144. this.group.add(containerGroup);
  49145. }
  49146. containerGroup.x = layoutInfo.x;
  49147. containerGroup.y = layoutInfo.y;
  49148. return containerGroup;
  49149. };
  49150. TreemapView.prototype._doRender = function (containerGroup, seriesModel, reRoot) {
  49151. var thisTree = seriesModel.getData().tree;
  49152. var oldTree = this._oldTree; // Clear last shape records.
  49153. var lastsForAnimation = createStorage();
  49154. var thisStorage = createStorage();
  49155. var oldStorage = this._storage;
  49156. var willInvisibleEls = [];
  49157. function doRenderNode(thisNode, oldNode, parentGroup, depth) {
  49158. return renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth);
  49159. } // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  49160. // the oldTree is actually losted, so we can not find all of the old graphic
  49161. // elements from tree. So we use this stragegy: make element storage, move
  49162. // from old storage to new storage, clear old storage.
  49163. dualTravel(thisTree.root ? [thisTree.root] : [], oldTree && oldTree.root ? [oldTree.root] : [], containerGroup, thisTree === oldTree || !oldTree, 0); // Process all removing.
  49164. var willDeleteEls = clearStorage(oldStorage);
  49165. this._oldTree = thisTree;
  49166. this._storage = thisStorage;
  49167. return {
  49168. lastsForAnimation: lastsForAnimation,
  49169. willDeleteEls: willDeleteEls,
  49170. renderFinally: renderFinally
  49171. };
  49172. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  49173. // When 'render' is triggered by action,
  49174. // 'this' and 'old' may be the same tree,
  49175. // we use rawIndex in that case.
  49176. if (sameTree) {
  49177. oldViewChildren = thisViewChildren;
  49178. each(thisViewChildren, function (child, index) {
  49179. !child.isRemoved() && processNode(index, index);
  49180. });
  49181. } // Diff hierarchically (diff only in each subtree, but not whole).
  49182. // because, consistency of view is important.
  49183. else {
  49184. new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  49185. }
  49186. function getKey(node) {
  49187. // Identify by name or raw index.
  49188. return node.getId();
  49189. }
  49190. function processNode(newIndex, oldIndex) {
  49191. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  49192. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  49193. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  49194. group && dualTravel(thisNode && thisNode.viewChildren || [], oldNode && oldNode.viewChildren || [], group, sameTree, depth + 1);
  49195. }
  49196. }
  49197. function clearStorage(storage) {
  49198. var willDeleteEls = createStorage();
  49199. storage && each(storage, function (store, storageName) {
  49200. var delEls = willDeleteEls[storageName];
  49201. each(store, function (el) {
  49202. el && (delEls.push(el), inner$8(el).willDelete = true);
  49203. });
  49204. });
  49205. return willDeleteEls;
  49206. }
  49207. function renderFinally() {
  49208. each(willDeleteEls, function (els) {
  49209. each(els, function (el) {
  49210. el.parent && el.parent.remove(el);
  49211. });
  49212. });
  49213. each(willInvisibleEls, function (el) {
  49214. el.invisible = true; // Setting invisible is for optimizing, so no need to set dirty,
  49215. // just mark as invisible.
  49216. el.dirty();
  49217. });
  49218. }
  49219. };
  49220. TreemapView.prototype._doAnimation = function (containerGroup, renderResult, seriesModel, reRoot) {
  49221. var durationOption = seriesModel.get('animationDurationUpdate');
  49222. var easingOption = seriesModel.get('animationEasing'); // TODO: do not support function until necessary.
  49223. var duration = (isFunction(durationOption) ? 0 : durationOption) || 0;
  49224. var easing = (isFunction(easingOption) ? null : easingOption) || 'cubicOut';
  49225. var animationWrap = createWrap(); // Make delete animations.
  49226. each(renderResult.willDeleteEls, function (store, storageName) {
  49227. each(store, function (el, rawIndex) {
  49228. if (el.invisible) {
  49229. return;
  49230. }
  49231. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  49232. var target;
  49233. var innerStore = inner$8(parent);
  49234. if (reRoot && reRoot.direction === 'drillDown') {
  49235. target = parent === reRoot.rootNodeGroup // This is the content element of view root.
  49236. // Only `content` will enter this branch, because
  49237. // `background` and `nodeGroup` will not be deleted.
  49238. ? {
  49239. shape: {
  49240. x: 0,
  49241. y: 0,
  49242. width: innerStore.nodeWidth,
  49243. height: innerStore.nodeHeight
  49244. },
  49245. style: {
  49246. opacity: 0
  49247. }
  49248. } // Others.
  49249. : {
  49250. style: {
  49251. opacity: 0
  49252. }
  49253. };
  49254. } else {
  49255. var targetX = 0;
  49256. var targetY = 0;
  49257. if (!innerStore.willDelete) {
  49258. // Let node animate to right-bottom corner, cooperating with fadeout,
  49259. // which is appropriate for user understanding.
  49260. // Divided by 2 for reRoot rolling up effect.
  49261. targetX = innerStore.nodeWidth / 2;
  49262. targetY = innerStore.nodeHeight / 2;
  49263. }
  49264. target = storageName === 'nodeGroup' ? {
  49265. x: targetX,
  49266. y: targetY,
  49267. style: {
  49268. opacity: 0
  49269. }
  49270. } : {
  49271. shape: {
  49272. x: targetX,
  49273. y: targetY,
  49274. width: 0,
  49275. height: 0
  49276. },
  49277. style: {
  49278. opacity: 0
  49279. }
  49280. };
  49281. } // TODO: do not support delay until necessary.
  49282. target && animationWrap.add(el, target, duration, 0, easing);
  49283. });
  49284. }); // Make other animations
  49285. each(this._storage, function (store, storageName) {
  49286. each(store, function (el, rawIndex) {
  49287. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  49288. var target = {};
  49289. if (!last) {
  49290. return;
  49291. }
  49292. if (el instanceof Group) {
  49293. if (last.oldX != null) {
  49294. target.x = el.x;
  49295. target.y = el.y;
  49296. el.x = last.oldX;
  49297. el.y = last.oldY;
  49298. }
  49299. } else {
  49300. if (last.oldShape) {
  49301. target.shape = extend({}, el.shape);
  49302. el.setShape(last.oldShape);
  49303. }
  49304. if (last.fadein) {
  49305. el.setStyle('opacity', 0);
  49306. target.style = {
  49307. opacity: 1
  49308. };
  49309. } // When animation is stopped for succedent animation starting,
  49310. // el.style.opacity might not be 1
  49311. else if (el.style.opacity !== 1) {
  49312. target.style = {
  49313. opacity: 1
  49314. };
  49315. }
  49316. }
  49317. animationWrap.add(el, target, duration, 0, easing);
  49318. });
  49319. }, this);
  49320. this._state = 'animating';
  49321. animationWrap.finished(bind(function () {
  49322. this._state = 'ready';
  49323. renderResult.renderFinally();
  49324. }, this)).start();
  49325. };
  49326. TreemapView.prototype._resetController = function (api) {
  49327. var controller = this._controller; // Init controller.
  49328. if (!controller) {
  49329. controller = this._controller = new RoamController(api.getZr());
  49330. controller.enable(this.seriesModel.get('roam'));
  49331. controller.on('pan', bind(this._onPan, this));
  49332. controller.on('zoom', bind(this._onZoom, this));
  49333. }
  49334. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  49335. controller.setPointerChecker(function (e, x, y) {
  49336. return rect.contain(x, y);
  49337. });
  49338. };
  49339. TreemapView.prototype._clearController = function () {
  49340. var controller = this._controller;
  49341. if (controller) {
  49342. controller.dispose();
  49343. controller = null;
  49344. }
  49345. };
  49346. TreemapView.prototype._onPan = function (e) {
  49347. if (this._state !== 'animating' && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)) {
  49348. // These param must not be cached.
  49349. var root = this.seriesModel.getData().tree.root;
  49350. if (!root) {
  49351. return;
  49352. }
  49353. var rootLayout = root.getLayout();
  49354. if (!rootLayout) {
  49355. return;
  49356. }
  49357. this.api.dispatchAction({
  49358. type: 'treemapMove',
  49359. from: this.uid,
  49360. seriesId: this.seriesModel.id,
  49361. rootRect: {
  49362. x: rootLayout.x + e.dx,
  49363. y: rootLayout.y + e.dy,
  49364. width: rootLayout.width,
  49365. height: rootLayout.height
  49366. }
  49367. });
  49368. }
  49369. };
  49370. TreemapView.prototype._onZoom = function (e) {
  49371. var mouseX = e.originX;
  49372. var mouseY = e.originY;
  49373. if (this._state !== 'animating') {
  49374. // These param must not be cached.
  49375. var root = this.seriesModel.getData().tree.root;
  49376. if (!root) {
  49377. return;
  49378. }
  49379. var rootLayout = root.getLayout();
  49380. if (!rootLayout) {
  49381. return;
  49382. }
  49383. var rect = new BoundingRect(rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height);
  49384. var layoutInfo = this.seriesModel.layoutInfo; // Transform mouse coord from global to containerGroup.
  49385. mouseX -= layoutInfo.x;
  49386. mouseY -= layoutInfo.y; // Scale root bounding rect.
  49387. var m = create$1();
  49388. translate(m, m, [-mouseX, -mouseY]);
  49389. scale$1(m, m, [e.scale, e.scale]);
  49390. translate(m, m, [mouseX, mouseY]);
  49391. rect.applyTransform(m);
  49392. this.api.dispatchAction({
  49393. type: 'treemapRender',
  49394. from: this.uid,
  49395. seriesId: this.seriesModel.id,
  49396. rootRect: {
  49397. x: rect.x,
  49398. y: rect.y,
  49399. width: rect.width,
  49400. height: rect.height
  49401. }
  49402. });
  49403. }
  49404. };
  49405. TreemapView.prototype._initEvents = function (containerGroup) {
  49406. var _this = this;
  49407. containerGroup.on('click', function (e) {
  49408. if (_this._state !== 'ready') {
  49409. return;
  49410. }
  49411. var nodeClick = _this.seriesModel.get('nodeClick', true);
  49412. if (!nodeClick) {
  49413. return;
  49414. }
  49415. var targetInfo = _this.findTarget(e.offsetX, e.offsetY);
  49416. if (!targetInfo) {
  49417. return;
  49418. }
  49419. var node = targetInfo.node;
  49420. if (node.getLayout().isLeafRoot) {
  49421. _this._rootToNode(targetInfo);
  49422. } else {
  49423. if (nodeClick === 'zoomToNode') {
  49424. _this._zoomToNode(targetInfo);
  49425. } else if (nodeClick === 'link') {
  49426. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  49427. var link = itemModel.get('link', true);
  49428. var linkTarget = itemModel.get('target', true) || 'blank';
  49429. link && windowOpen(link, linkTarget);
  49430. }
  49431. }
  49432. }, this);
  49433. };
  49434. TreemapView.prototype._renderBreadcrumb = function (seriesModel, api, targetInfo) {
  49435. var _this = this;
  49436. if (!targetInfo) {
  49437. targetInfo = seriesModel.get('leafDepth', true) != null ? {
  49438. node: seriesModel.getViewRoot()
  49439. } // FIXME
  49440. // better way?
  49441. // Find breadcrumb tail on center of containerGroup.
  49442. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  49443. if (!targetInfo) {
  49444. targetInfo = {
  49445. node: seriesModel.getData().tree.root
  49446. };
  49447. }
  49448. }
  49449. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group))).render(seriesModel, api, targetInfo.node, function (node) {
  49450. if (_this._state !== 'animating') {
  49451. aboveViewRoot(seriesModel.getViewRoot(), node) ? _this._rootToNode({
  49452. node: node
  49453. }) : _this._zoomToNode({
  49454. node: node
  49455. });
  49456. }
  49457. });
  49458. };
  49459. /**
  49460. * @override
  49461. */
  49462. TreemapView.prototype.remove = function () {
  49463. this._clearController();
  49464. this._containerGroup && this._containerGroup.removeAll();
  49465. this._storage = createStorage();
  49466. this._state = 'ready';
  49467. this._breadcrumb && this._breadcrumb.remove();
  49468. };
  49469. TreemapView.prototype.dispose = function () {
  49470. this._clearController();
  49471. };
  49472. TreemapView.prototype._zoomToNode = function (targetInfo) {
  49473. this.api.dispatchAction({
  49474. type: 'treemapZoomToNode',
  49475. from: this.uid,
  49476. seriesId: this.seriesModel.id,
  49477. targetNode: targetInfo.node
  49478. });
  49479. };
  49480. TreemapView.prototype._rootToNode = function (targetInfo) {
  49481. this.api.dispatchAction({
  49482. type: 'treemapRootToNode',
  49483. from: this.uid,
  49484. seriesId: this.seriesModel.id,
  49485. targetNode: targetInfo.node
  49486. });
  49487. };
  49488. /**
  49489. * @public
  49490. * @param {number} x Global coord x.
  49491. * @param {number} y Global coord y.
  49492. * @return {Object} info If not found, return undefined;
  49493. * @return {number} info.node Target node.
  49494. * @return {number} info.offsetX x refer to target node.
  49495. * @return {number} info.offsetY y refer to target node.
  49496. */
  49497. TreemapView.prototype.findTarget = function (x, y) {
  49498. var targetInfo;
  49499. var viewRoot = this.seriesModel.getViewRoot();
  49500. viewRoot.eachNode({
  49501. attr: 'viewChildren',
  49502. order: 'preorder'
  49503. }, function (node) {
  49504. var bgEl = this._storage.background[node.getRawIndex()]; // If invisible, there might be no element.
  49505. if (bgEl) {
  49506. var point = bgEl.transformCoordToLocal(x, y);
  49507. var shape = bgEl.shape; // For performance consideration, dont use 'getBoundingRect'.
  49508. if (shape.x <= point[0] && point[0] <= shape.x + shape.width && shape.y <= point[1] && point[1] <= shape.y + shape.height) {
  49509. targetInfo = {
  49510. node: node,
  49511. offsetX: point[0],
  49512. offsetY: point[1]
  49513. };
  49514. } else {
  49515. return false; // Suppress visit subtree.
  49516. }
  49517. }
  49518. }, this);
  49519. return targetInfo;
  49520. };
  49521. TreemapView.type = 'treemap';
  49522. return TreemapView;
  49523. }(ChartView);
  49524. /**
  49525. * @inner
  49526. */
  49527. function createStorage() {
  49528. return {
  49529. nodeGroup: [],
  49530. background: [],
  49531. content: []
  49532. };
  49533. }
  49534. /**
  49535. * @inner
  49536. * @return Return undefined means do not travel further.
  49537. */
  49538. function renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth) {
  49539. // Whether under viewRoot.
  49540. if (!thisNode) {
  49541. // Deleting nodes will be performed finally. This method just find
  49542. // element from old storage, or create new element, set them to new
  49543. // storage, and set styles.
  49544. return;
  49545. } // -------------------------------------------------------------------
  49546. // Start of closure variables available in "Procedures in renderNode".
  49547. var thisLayout = thisNode.getLayout();
  49548. var data = seriesModel.getData();
  49549. var nodeModel = thisNode.getModel(); // Only for enabling highlight/downplay. Clear firstly.
  49550. // Because some node will not be rendered.
  49551. data.setItemGraphicEl(thisNode.dataIndex, null);
  49552. if (!thisLayout || !thisLayout.isInView) {
  49553. return;
  49554. }
  49555. var thisWidth = thisLayout.width;
  49556. var thisHeight = thisLayout.height;
  49557. var borderWidth = thisLayout.borderWidth;
  49558. var thisInvisible = thisLayout.invisible;
  49559. var thisRawIndex = thisNode.getRawIndex();
  49560. var oldRawIndex = oldNode && oldNode.getRawIndex();
  49561. var thisViewChildren = thisNode.viewChildren;
  49562. var upperHeight = thisLayout.upperHeight;
  49563. var isParent = thisViewChildren && thisViewChildren.length;
  49564. var itemStyleNormalModel = nodeModel.getModel('itemStyle');
  49565. var itemStyleEmphasisModel = nodeModel.getModel(['emphasis', 'itemStyle']);
  49566. var itemStyleBlurModel = nodeModel.getModel(['blur', 'itemStyle']);
  49567. var itemStyleSelectModel = nodeModel.getModel(['select', 'itemStyle']);
  49568. var borderRadius = itemStyleNormalModel.get('borderRadius') || 0; // End of closure ariables available in "Procedures in renderNode".
  49569. // -----------------------------------------------------------------
  49570. // Node group
  49571. var group = giveGraphic('nodeGroup', Group$1);
  49572. if (!group) {
  49573. return;
  49574. }
  49575. parentGroup.add(group); // x,y are not set when el is above view root.
  49576. group.x = thisLayout.x || 0;
  49577. group.y = thisLayout.y || 0;
  49578. group.markRedraw();
  49579. inner$8(group).nodeWidth = thisWidth;
  49580. inner$8(group).nodeHeight = thisHeight;
  49581. if (thisLayout.isAboveViewRoot) {
  49582. return group;
  49583. } // Background
  49584. var bg = giveGraphic('background', Rect$1, depth, Z2_BG);
  49585. bg && renderBackground(group, bg, isParent && thisLayout.upperLabelHeight);
  49586. var focus = nodeModel.get(['emphasis', 'focus']);
  49587. var blurScope = nodeModel.get(['emphasis', 'blurScope']);
  49588. var focusOrIndices = focus === 'ancestor' ? thisNode.getAncestorsIndices() : focus === 'descendant' ? thisNode.getDescendantIndices() : focus; // No children, render content.
  49589. if (isParent) {
  49590. // Because of the implementation about "traverse" in graphic hover style, we
  49591. // can not set hover listener on the "group" of non-leaf node. Otherwise the
  49592. // hover event from the descendents will be listenered.
  49593. if (isHighDownDispatcher(group)) {
  49594. setAsHighDownDispatcher(group, false);
  49595. }
  49596. if (bg) {
  49597. setAsHighDownDispatcher(bg, true); // Only for enabling highlight/downplay.
  49598. data.setItemGraphicEl(thisNode.dataIndex, bg);
  49599. enableHoverFocus(bg, focusOrIndices, blurScope);
  49600. }
  49601. } else {
  49602. var content = giveGraphic('content', Rect$1, depth, Z2_CONTENT);
  49603. content && renderContent(group, content);
  49604. bg.disableMorphing = true;
  49605. if (bg && isHighDownDispatcher(bg)) {
  49606. setAsHighDownDispatcher(bg, false);
  49607. }
  49608. setAsHighDownDispatcher(group, true); // Only for enabling highlight/downplay.
  49609. data.setItemGraphicEl(thisNode.dataIndex, group);
  49610. enableHoverFocus(group, focusOrIndices, blurScope);
  49611. }
  49612. return group; // ----------------------------
  49613. // | Procedures in renderNode |
  49614. // ----------------------------
  49615. function renderBackground(group, bg, useUpperLabel) {
  49616. var ecData = getECData(bg); // For tooltip.
  49617. ecData.dataIndex = thisNode.dataIndex;
  49618. ecData.seriesIndex = seriesModel.seriesIndex;
  49619. bg.setShape({
  49620. x: 0,
  49621. y: 0,
  49622. width: thisWidth,
  49623. height: thisHeight,
  49624. r: borderRadius
  49625. });
  49626. if (thisInvisible) {
  49627. // If invisible, do not set visual, otherwise the element will
  49628. // change immediately before animation. We think it is OK to
  49629. // remain its origin color when moving out of the view window.
  49630. processInvisible(bg);
  49631. } else {
  49632. bg.invisible = false;
  49633. var style = thisNode.getVisual('style');
  49634. var visualBorderColor = style.stroke;
  49635. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  49636. normalStyle.fill = visualBorderColor;
  49637. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  49638. emphasisStyle.fill = itemStyleEmphasisModel.get('borderColor');
  49639. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  49640. blurStyle.fill = itemStyleBlurModel.get('borderColor');
  49641. var selectStyle = getStateItemStyle(itemStyleSelectModel);
  49642. selectStyle.fill = itemStyleSelectModel.get('borderColor');
  49643. if (useUpperLabel) {
  49644. var upperLabelWidth = thisWidth - 2 * borderWidth;
  49645. prepareText( // PENDING: convert ZRColor to ColorString for text.
  49646. bg, visualBorderColor, style.opacity, {
  49647. x: borderWidth,
  49648. y: 0,
  49649. width: upperLabelWidth,
  49650. height: upperHeight
  49651. });
  49652. } // For old bg.
  49653. else {
  49654. bg.removeTextContent();
  49655. }
  49656. bg.setStyle(normalStyle);
  49657. bg.ensureState('emphasis').style = emphasisStyle;
  49658. bg.ensureState('blur').style = blurStyle;
  49659. bg.ensureState('select').style = selectStyle;
  49660. setDefaultStateProxy(bg);
  49661. }
  49662. group.add(bg);
  49663. }
  49664. function renderContent(group, content) {
  49665. var ecData = getECData(content); // For tooltip.
  49666. ecData.dataIndex = thisNode.dataIndex;
  49667. ecData.seriesIndex = seriesModel.seriesIndex;
  49668. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  49669. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  49670. content.culling = true;
  49671. content.setShape({
  49672. x: borderWidth,
  49673. y: borderWidth,
  49674. width: contentWidth,
  49675. height: contentHeight,
  49676. r: borderRadius
  49677. });
  49678. if (thisInvisible) {
  49679. // If invisible, do not set visual, otherwise the element will
  49680. // change immediately before animation. We think it is OK to
  49681. // remain its origin color when moving out of the view window.
  49682. processInvisible(content);
  49683. } else {
  49684. content.invisible = false;
  49685. var nodeStyle = thisNode.getVisual('style');
  49686. var visualColor = nodeStyle.fill;
  49687. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  49688. normalStyle.fill = visualColor;
  49689. normalStyle.decal = nodeStyle.decal;
  49690. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  49691. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  49692. var selectStyle = getStateItemStyle(itemStyleSelectModel); // PENDING: convert ZRColor to ColorString for text.
  49693. prepareText(content, visualColor, nodeStyle.opacity, null);
  49694. content.setStyle(normalStyle);
  49695. content.ensureState('emphasis').style = emphasisStyle;
  49696. content.ensureState('blur').style = blurStyle;
  49697. content.ensureState('select').style = selectStyle;
  49698. setDefaultStateProxy(content);
  49699. }
  49700. group.add(content);
  49701. }
  49702. function processInvisible(element) {
  49703. // Delay invisible setting utill animation finished,
  49704. // avoid element vanish suddenly before animation.
  49705. !element.invisible && willInvisibleEls.push(element);
  49706. }
  49707. function prepareText(rectEl, visualColor, visualOpacity, // Can be null/undefined
  49708. upperLabelRect) {
  49709. var normalLabelModel = nodeModel.getModel(upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL);
  49710. var defaultText = convertOptionIdName(nodeModel.get('name'), null);
  49711. var isShow = normalLabelModel.getShallow('show');
  49712. setLabelStyle(rectEl, getLabelStatesModels(nodeModel, upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL), {
  49713. defaultText: isShow ? defaultText : null,
  49714. inheritColor: visualColor,
  49715. defaultOpacity: visualOpacity,
  49716. labelFetcher: seriesModel,
  49717. labelDataIndex: thisNode.dataIndex
  49718. });
  49719. var textEl = rectEl.getTextContent();
  49720. if (!textEl) {
  49721. return;
  49722. }
  49723. var textStyle = textEl.style;
  49724. var textPadding = normalizeCssArray(textStyle.padding || 0);
  49725. if (upperLabelRect) {
  49726. rectEl.setTextConfig({
  49727. layoutRect: upperLabelRect
  49728. });
  49729. textEl.disableLabelLayout = true;
  49730. }
  49731. textEl.beforeUpdate = function () {
  49732. var width = Math.max((upperLabelRect ? upperLabelRect.width : rectEl.shape.width) - textPadding[1] - textPadding[3], 0);
  49733. var height = Math.max((upperLabelRect ? upperLabelRect.height : rectEl.shape.height) - textPadding[0] - textPadding[2], 0);
  49734. if (textStyle.width !== width || textStyle.height !== height) {
  49735. textEl.setStyle({
  49736. width: width,
  49737. height: height
  49738. });
  49739. }
  49740. };
  49741. textStyle.truncateMinChar = 2;
  49742. textStyle.lineOverflow = 'truncate';
  49743. addDrillDownIcon(textStyle, upperLabelRect, thisLayout);
  49744. var textEmphasisState = textEl.getState('emphasis');
  49745. addDrillDownIcon(textEmphasisState ? textEmphasisState.style : null, upperLabelRect, thisLayout);
  49746. }
  49747. function addDrillDownIcon(style, upperLabelRect, thisLayout) {
  49748. var text = style ? style.text : null;
  49749. if (!upperLabelRect && thisLayout.isLeafRoot && text != null) {
  49750. var iconChar = seriesModel.get('drillDownIcon', true);
  49751. style.text = iconChar ? iconChar + ' ' + text : text;
  49752. }
  49753. }
  49754. function giveGraphic(storageName, Ctor, depth, z) {
  49755. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  49756. var lasts = lastsForAnimation[storageName];
  49757. if (element) {
  49758. // Remove from oldStorage
  49759. oldStorage[storageName][oldRawIndex] = null;
  49760. prepareAnimationWhenHasOld(lasts, element);
  49761. } // If invisible and no old element, do not create new element (for optimizing).
  49762. else if (!thisInvisible) {
  49763. element = new Ctor();
  49764. if (element instanceof Displayable) {
  49765. element.z2 = calculateZ2(depth, z);
  49766. }
  49767. prepareAnimationWhenNoOld(lasts, element);
  49768. } // Set to thisStorage
  49769. return thisStorage[storageName][thisRawIndex] = element;
  49770. }
  49771. function prepareAnimationWhenHasOld(lasts, element) {
  49772. var lastCfg = lasts[thisRawIndex] = {};
  49773. if (element instanceof Group$1) {
  49774. lastCfg.oldX = element.x;
  49775. lastCfg.oldY = element.y;
  49776. } else {
  49777. lastCfg.oldShape = extend({}, element.shape);
  49778. }
  49779. } // If a element is new, we need to find the animation start point carefully,
  49780. // otherwise it will looks strange when 'zoomToNode'.
  49781. function prepareAnimationWhenNoOld(lasts, element) {
  49782. var lastCfg = lasts[thisRawIndex] = {};
  49783. var parentNode = thisNode.parentNode;
  49784. var isGroup = element instanceof Group;
  49785. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  49786. var parentOldX = 0;
  49787. var parentOldY = 0; // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  49788. // For convenience, get old bounding rect from background.
  49789. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  49790. if (!reRoot && parentOldBg && parentOldBg.oldShape) {
  49791. parentOldX = parentOldBg.oldShape.width;
  49792. parentOldY = parentOldBg.oldShape.height;
  49793. } // When no parent old shape found, its parent is new too,
  49794. // so we can just use {x:0, y:0}.
  49795. if (isGroup) {
  49796. lastCfg.oldX = 0;
  49797. lastCfg.oldY = parentOldY;
  49798. } else {
  49799. lastCfg.oldShape = {
  49800. x: parentOldX,
  49801. y: parentOldY,
  49802. width: 0,
  49803. height: 0
  49804. };
  49805. }
  49806. } // Fade in, user can be aware that these nodes are new.
  49807. lastCfg.fadein = !isGroup;
  49808. }
  49809. } // We can not set all backgroud with the same z, Because the behaviour of
  49810. // drill down and roll up differ background creation sequence from tree
  49811. // hierarchy sequence, which cause that lowser background element overlap
  49812. // upper ones. So we calculate z based on depth.
  49813. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  49814. // treemap with large z overlaps other components.
  49815. function calculateZ2(depth, z2InLevel) {
  49816. return depth * Z2_BASE + z2InLevel;
  49817. }
  49818. var each$3 = each;
  49819. var isObject$3 = isObject;
  49820. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  49821. var VisualMapping =
  49822. /** @class */
  49823. function () {
  49824. function VisualMapping(option) {
  49825. var mappingMethod = option.mappingMethod;
  49826. var visualType = option.type;
  49827. var thisOption = this.option = clone(option);
  49828. this.type = visualType;
  49829. this.mappingMethod = mappingMethod;
  49830. this._normalizeData = normalizers[mappingMethod];
  49831. var visualHandler = VisualMapping.visualHandlers[visualType];
  49832. this.applyVisual = visualHandler.applyVisual;
  49833. this.getColorMapper = visualHandler.getColorMapper;
  49834. this._normalizedToVisual = visualHandler._normalizedToVisual[mappingMethod];
  49835. if (mappingMethod === 'piecewise') {
  49836. normalizeVisualRange(thisOption);
  49837. preprocessForPiecewise(thisOption);
  49838. } else if (mappingMethod === 'category') {
  49839. thisOption.categories ? preprocessForSpecifiedCategory(thisOption) // categories is ordinal when thisOption.categories not specified,
  49840. // which need no more preprocess except normalize visual.
  49841. : normalizeVisualRange(thisOption, true);
  49842. } else {
  49843. // mappingMethod === 'linear' or 'fixed'
  49844. assert(mappingMethod !== 'linear' || thisOption.dataExtent);
  49845. normalizeVisualRange(thisOption);
  49846. }
  49847. }
  49848. VisualMapping.prototype.mapValueToVisual = function (value) {
  49849. var normalized = this._normalizeData(value);
  49850. return this._normalizedToVisual(normalized, value);
  49851. };
  49852. VisualMapping.prototype.getNormalizer = function () {
  49853. return bind(this._normalizeData, this);
  49854. };
  49855. /**
  49856. * List available visual types.
  49857. *
  49858. * @public
  49859. * @return {Array.<string>}
  49860. */
  49861. VisualMapping.listVisualTypes = function () {
  49862. return keys(VisualMapping.visualHandlers);
  49863. }; // /**
  49864. // * @public
  49865. // */
  49866. // static addVisualHandler(name, handler) {
  49867. // visualHandlers[name] = handler;
  49868. // }
  49869. /**
  49870. * @public
  49871. */
  49872. VisualMapping.isValidType = function (visualType) {
  49873. return VisualMapping.visualHandlers.hasOwnProperty(visualType);
  49874. };
  49875. /**
  49876. * Convinent method.
  49877. * Visual can be Object or Array or primary type.
  49878. */
  49879. VisualMapping.eachVisual = function (visual, callback, context) {
  49880. if (isObject(visual)) {
  49881. each(visual, callback, context);
  49882. } else {
  49883. callback.call(context, visual);
  49884. }
  49885. };
  49886. VisualMapping.mapVisual = function (visual, callback, context) {
  49887. var isPrimary;
  49888. var newVisual = isArray(visual) ? [] : isObject(visual) ? {} : (isPrimary = true, null);
  49889. VisualMapping.eachVisual(visual, function (v, key) {
  49890. var newVal = callback.call(context, v, key);
  49891. isPrimary ? newVisual = newVal : newVisual[key] = newVal;
  49892. });
  49893. return newVisual;
  49894. };
  49895. /**
  49896. * Retrieve visual properties from given object.
  49897. */
  49898. VisualMapping.retrieveVisuals = function (obj) {
  49899. var ret = {};
  49900. var hasVisual;
  49901. obj && each$3(VisualMapping.visualHandlers, function (h, visualType) {
  49902. if (obj.hasOwnProperty(visualType)) {
  49903. ret[visualType] = obj[visualType];
  49904. hasVisual = true;
  49905. }
  49906. });
  49907. return hasVisual ? ret : null;
  49908. };
  49909. /**
  49910. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  49911. *
  49912. * @public
  49913. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  49914. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  49915. * @return {Array.<string>} Sorted visual types.
  49916. */
  49917. VisualMapping.prepareVisualTypes = function (visualTypes) {
  49918. if (isArray(visualTypes)) {
  49919. visualTypes = visualTypes.slice();
  49920. } else if (isObject$3(visualTypes)) {
  49921. var types_1 = [];
  49922. each$3(visualTypes, function (item, type) {
  49923. types_1.push(type);
  49924. });
  49925. visualTypes = types_1;
  49926. } else {
  49927. return [];
  49928. }
  49929. visualTypes.sort(function (type1, type2) {
  49930. // color should be front of colorSaturation, colorAlpha, ...
  49931. // symbol and symbolSize do not matter.
  49932. return type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0 ? 1 : -1;
  49933. });
  49934. return visualTypes;
  49935. };
  49936. /**
  49937. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  49938. * Other visuals are only depends on themself.
  49939. */
  49940. VisualMapping.dependsOn = function (visualType1, visualType2) {
  49941. return visualType2 === 'color' ? !!(visualType1 && visualType1.indexOf(visualType2) === 0) : visualType1 === visualType2;
  49942. };
  49943. /**
  49944. * @param value
  49945. * @param pieceList [{value: ..., interval: [min, max]}, ...]
  49946. * Always from small to big.
  49947. * @param findClosestWhenOutside Default to be false
  49948. * @return index
  49949. */
  49950. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  49951. var possibleI;
  49952. var abs = Infinity; // value has the higher priority.
  49953. for (var i = 0, len = pieceList.length; i < len; i++) {
  49954. var pieceValue = pieceList[i].value;
  49955. if (pieceValue != null) {
  49956. if (pieceValue === value // FIXME
  49957. // It is supposed to compare value according to value type of dimension,
  49958. // but currently value type can exactly be string or number.
  49959. // Compromise for numeric-like string (like '12'), especially
  49960. // in the case that visualMap.categories is ['22', '33'].
  49961. || typeof pieceValue === 'string' && pieceValue === value + '') {
  49962. return i;
  49963. }
  49964. findClosestWhenOutside && updatePossible(pieceValue, i);
  49965. }
  49966. }
  49967. for (var i = 0, len = pieceList.length; i < len; i++) {
  49968. var piece = pieceList[i];
  49969. var interval = piece.interval;
  49970. var close_1 = piece.close;
  49971. if (interval) {
  49972. if (interval[0] === -Infinity) {
  49973. if (littleThan(close_1[1], value, interval[1])) {
  49974. return i;
  49975. }
  49976. } else if (interval[1] === Infinity) {
  49977. if (littleThan(close_1[0], interval[0], value)) {
  49978. return i;
  49979. }
  49980. } else if (littleThan(close_1[0], interval[0], value) && littleThan(close_1[1], value, interval[1])) {
  49981. return i;
  49982. }
  49983. findClosestWhenOutside && updatePossible(interval[0], i);
  49984. findClosestWhenOutside && updatePossible(interval[1], i);
  49985. }
  49986. }
  49987. if (findClosestWhenOutside) {
  49988. return value === Infinity ? pieceList.length - 1 : value === -Infinity ? 0 : possibleI;
  49989. }
  49990. function updatePossible(val, index) {
  49991. var newAbs = Math.abs(val - value);
  49992. if (newAbs < abs) {
  49993. abs = newAbs;
  49994. possibleI = index;
  49995. }
  49996. }
  49997. };
  49998. VisualMapping.visualHandlers = {
  49999. color: {
  50000. applyVisual: makeApplyVisual('color'),
  50001. getColorMapper: function () {
  50002. var thisOption = this.option;
  50003. return bind(thisOption.mappingMethod === 'category' ? function (value, isNormalized) {
  50004. !isNormalized && (value = this._normalizeData(value));
  50005. return doMapCategory.call(this, value);
  50006. } : function (value, isNormalized, out) {
  50007. // If output rgb array
  50008. // which will be much faster and useful in pixel manipulation
  50009. var returnRGBArray = !!out;
  50010. !isNormalized && (value = this._normalizeData(value));
  50011. out = fastLerp(value, thisOption.parsedVisual, out);
  50012. return returnRGBArray ? out : stringify(out, 'rgba');
  50013. }, this);
  50014. },
  50015. _normalizedToVisual: {
  50016. linear: function (normalized) {
  50017. return stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  50018. },
  50019. category: doMapCategory,
  50020. piecewise: function (normalized, value) {
  50021. var result = getSpecifiedVisual.call(this, value);
  50022. if (result == null) {
  50023. result = stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  50024. }
  50025. return result;
  50026. },
  50027. fixed: doMapFixed
  50028. }
  50029. },
  50030. colorHue: makePartialColorVisualHandler(function (color$1, value) {
  50031. return modifyHSL(color$1, value);
  50032. }),
  50033. colorSaturation: makePartialColorVisualHandler(function (color$1, value) {
  50034. return modifyHSL(color$1, null, value);
  50035. }),
  50036. colorLightness: makePartialColorVisualHandler(function (color$1, value) {
  50037. return modifyHSL(color$1, null, null, value);
  50038. }),
  50039. colorAlpha: makePartialColorVisualHandler(function (color$1, value) {
  50040. return modifyAlpha(color$1, value);
  50041. }),
  50042. decal: {
  50043. applyVisual: makeApplyVisual('decal'),
  50044. _normalizedToVisual: {
  50045. linear: null,
  50046. category: doMapCategory,
  50047. piecewise: null,
  50048. fixed: null
  50049. }
  50050. },
  50051. opacity: {
  50052. applyVisual: makeApplyVisual('opacity'),
  50053. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  50054. },
  50055. liftZ: {
  50056. applyVisual: makeApplyVisual('liftZ'),
  50057. _normalizedToVisual: {
  50058. linear: doMapFixed,
  50059. category: doMapFixed,
  50060. piecewise: doMapFixed,
  50061. fixed: doMapFixed
  50062. }
  50063. },
  50064. symbol: {
  50065. applyVisual: function (value, getter, setter) {
  50066. var symbolCfg = this.mapValueToVisual(value);
  50067. setter('symbol', symbolCfg);
  50068. },
  50069. _normalizedToVisual: {
  50070. linear: doMapToArray,
  50071. category: doMapCategory,
  50072. piecewise: function (normalized, value) {
  50073. var result = getSpecifiedVisual.call(this, value);
  50074. if (result == null) {
  50075. result = doMapToArray.call(this, normalized);
  50076. }
  50077. return result;
  50078. },
  50079. fixed: doMapFixed
  50080. }
  50081. },
  50082. symbolSize: {
  50083. applyVisual: makeApplyVisual('symbolSize'),
  50084. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  50085. }
  50086. };
  50087. return VisualMapping;
  50088. }();
  50089. function preprocessForPiecewise(thisOption) {
  50090. var pieceList = thisOption.pieceList;
  50091. thisOption.hasSpecialVisual = false;
  50092. each(pieceList, function (piece, index) {
  50093. piece.originIndex = index; // piece.visual is "result visual value" but not
  50094. // a visual range, so it does not need to be normalized.
  50095. if (piece.visual != null) {
  50096. thisOption.hasSpecialVisual = true;
  50097. }
  50098. });
  50099. }
  50100. function preprocessForSpecifiedCategory(thisOption) {
  50101. // Hash categories.
  50102. var categories = thisOption.categories;
  50103. var categoryMap = thisOption.categoryMap = {};
  50104. var visual = thisOption.visual;
  50105. each$3(categories, function (cate, index) {
  50106. categoryMap[cate] = index;
  50107. }); // Process visual map input.
  50108. if (!isArray(visual)) {
  50109. var visualArr_1 = [];
  50110. if (isObject(visual)) {
  50111. each$3(visual, function (v, cate) {
  50112. var index = categoryMap[cate];
  50113. visualArr_1[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  50114. });
  50115. } else {
  50116. // Is primary type, represents default visual.
  50117. visualArr_1[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  50118. }
  50119. visual = setVisualToOption(thisOption, visualArr_1);
  50120. } // Remove categories that has no visual,
  50121. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  50122. for (var i = categories.length - 1; i >= 0; i--) {
  50123. if (visual[i] == null) {
  50124. delete categoryMap[categories[i]];
  50125. categories.pop();
  50126. }
  50127. }
  50128. }
  50129. function normalizeVisualRange(thisOption, isCategory) {
  50130. var visual = thisOption.visual;
  50131. var visualArr = [];
  50132. if (isObject(visual)) {
  50133. each$3(visual, function (v) {
  50134. visualArr.push(v);
  50135. });
  50136. } else if (visual != null) {
  50137. visualArr.push(visual);
  50138. }
  50139. var doNotNeedPair = {
  50140. color: 1,
  50141. symbol: 1
  50142. };
  50143. if (!isCategory && visualArr.length === 1 && !doNotNeedPair.hasOwnProperty(thisOption.type)) {
  50144. // Do not care visualArr.length === 0, which is illegal.
  50145. visualArr[1] = visualArr[0];
  50146. }
  50147. setVisualToOption(thisOption, visualArr);
  50148. }
  50149. function makePartialColorVisualHandler(applyValue) {
  50150. return {
  50151. applyVisual: function (value, getter, setter) {
  50152. // Only used in HSL
  50153. var colorChannel = this.mapValueToVisual(value); // Must not be array value
  50154. setter('color', applyValue(getter('color'), colorChannel));
  50155. },
  50156. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  50157. };
  50158. }
  50159. function doMapToArray(normalized) {
  50160. var visual = this.option.visual;
  50161. return visual[Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))] || {}; // TODO {}?
  50162. }
  50163. function makeApplyVisual(visualType) {
  50164. return function (value, getter, setter) {
  50165. setter(visualType, this.mapValueToVisual(value));
  50166. };
  50167. }
  50168. function doMapCategory(normalized) {
  50169. var visual = this.option.visual;
  50170. return visual[this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX ? normalized % visual.length : normalized];
  50171. }
  50172. function doMapFixed() {
  50173. // visual will be convert to array.
  50174. return this.option.visual[0];
  50175. }
  50176. /**
  50177. * Create mapped to numeric visual
  50178. */
  50179. function createNormalizedToNumericVisual(sourceExtent) {
  50180. return {
  50181. linear: function (normalized) {
  50182. return linearMap(normalized, sourceExtent, this.option.visual, true);
  50183. },
  50184. category: doMapCategory,
  50185. piecewise: function (normalized, value) {
  50186. var result = getSpecifiedVisual.call(this, value);
  50187. if (result == null) {
  50188. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  50189. }
  50190. return result;
  50191. },
  50192. fixed: doMapFixed
  50193. };
  50194. }
  50195. function getSpecifiedVisual(value) {
  50196. var thisOption = this.option;
  50197. var pieceList = thisOption.pieceList;
  50198. if (thisOption.hasSpecialVisual) {
  50199. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  50200. var piece = pieceList[pieceIndex];
  50201. if (piece && piece.visual) {
  50202. return piece.visual[this.type];
  50203. }
  50204. }
  50205. }
  50206. function setVisualToOption(thisOption, visualArr) {
  50207. thisOption.visual = visualArr;
  50208. if (thisOption.type === 'color') {
  50209. thisOption.parsedVisual = map(visualArr, function (item) {
  50210. return parse(item);
  50211. });
  50212. }
  50213. return visualArr;
  50214. }
  50215. /**
  50216. * Normalizers by mapping methods.
  50217. */
  50218. var normalizers = {
  50219. linear: function (value) {
  50220. return linearMap(value, this.option.dataExtent, [0, 1], true);
  50221. },
  50222. piecewise: function (value) {
  50223. var pieceList = this.option.pieceList;
  50224. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  50225. if (pieceIndex != null) {
  50226. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  50227. }
  50228. },
  50229. category: function (value) {
  50230. var index = this.option.categories ? this.option.categoryMap[value] : value; // ordinal value
  50231. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  50232. },
  50233. fixed: noop
  50234. };
  50235. function littleThan(close, a, b) {
  50236. return close ? a <= b : a < b;
  50237. }
  50238. var ITEM_STYLE_NORMAL = 'itemStyle';
  50239. var inner$9 = makeInner();
  50240. var treemapVisual = {
  50241. seriesType: 'treemap',
  50242. reset: function (seriesModel) {
  50243. var tree = seriesModel.getData().tree;
  50244. var root = tree.root;
  50245. if (root.isRemoved()) {
  50246. return;
  50247. }
  50248. travelTree(root, // Visual should calculate from tree root but not view root.
  50249. {}, seriesModel.getViewRoot().getAncestors(), seriesModel);
  50250. }
  50251. };
  50252. function travelTree(node, designatedVisual, viewRootAncestors, seriesModel) {
  50253. var nodeModel = node.getModel();
  50254. var nodeLayout = node.getLayout();
  50255. var data = node.hostTree.data; // Optimize
  50256. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  50257. return;
  50258. }
  50259. var nodeItemStyleModel = nodeModel.getModel(ITEM_STYLE_NORMAL);
  50260. var visuals = buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel);
  50261. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style'); // calculate border color
  50262. var borderColor = nodeItemStyleModel.get('borderColor');
  50263. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  50264. var thisNodeColor;
  50265. if (borderColorSaturation != null) {
  50266. // For performance, do not always execute 'calculateColor'.
  50267. thisNodeColor = calculateColor(visuals);
  50268. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  50269. }
  50270. existsStyle.stroke = borderColor;
  50271. var viewChildren = node.viewChildren;
  50272. if (!viewChildren || !viewChildren.length) {
  50273. thisNodeColor = calculateColor(visuals); // Apply visual to this node.
  50274. existsStyle.fill = thisNodeColor;
  50275. } else {
  50276. var mapping_1 = buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren); // Designate visual to children.
  50277. each(viewChildren, function (child, index) {
  50278. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  50279. if (child.depth >= viewRootAncestors.length || child === viewRootAncestors[child.depth]) {
  50280. var childVisual = mapVisual(nodeModel, visuals, child, index, mapping_1, seriesModel);
  50281. travelTree(child, childVisual, viewRootAncestors, seriesModel);
  50282. }
  50283. });
  50284. }
  50285. }
  50286. function buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel) {
  50287. var visuals = extend({}, designatedVisual);
  50288. var designatedVisualItemStyle = seriesModel.designatedVisualItemStyle;
  50289. each(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  50290. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  50291. designatedVisualItemStyle[visualName] = designatedVisual[visualName];
  50292. var val = nodeItemStyleModel.get(visualName);
  50293. designatedVisualItemStyle[visualName] = null;
  50294. val != null && (visuals[visualName] = val);
  50295. });
  50296. return visuals;
  50297. }
  50298. function calculateColor(visuals) {
  50299. var color = getValueVisualDefine(visuals, 'color');
  50300. if (color) {
  50301. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  50302. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  50303. if (colorSaturation) {
  50304. color = modifyHSL(color, null, null, colorSaturation);
  50305. }
  50306. if (colorAlpha) {
  50307. color = modifyAlpha(color, colorAlpha);
  50308. }
  50309. return color;
  50310. }
  50311. }
  50312. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  50313. return thisNodeColor != null // Can only be string
  50314. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation) : null;
  50315. }
  50316. function getValueVisualDefine(visuals, name) {
  50317. var value = visuals[name];
  50318. if (value != null && value !== 'none') {
  50319. return value;
  50320. }
  50321. }
  50322. function buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren) {
  50323. if (!viewChildren || !viewChildren.length) {
  50324. return;
  50325. }
  50326. var rangeVisual = getRangeVisual(nodeModel, 'color') || visuals.color != null && visuals.color !== 'none' && (getRangeVisual(nodeModel, 'colorAlpha') || getRangeVisual(nodeModel, 'colorSaturation'));
  50327. if (!rangeVisual) {
  50328. return;
  50329. }
  50330. var visualMin = nodeModel.get('visualMin');
  50331. var visualMax = nodeModel.get('visualMax');
  50332. var dataExtent = nodeLayout.dataExtent.slice();
  50333. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  50334. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  50335. var colorMappingBy = nodeModel.get('colorMappingBy');
  50336. var opt = {
  50337. type: rangeVisual.name,
  50338. dataExtent: dataExtent,
  50339. visual: rangeVisual.range
  50340. };
  50341. if (opt.type === 'color' && (colorMappingBy === 'index' || colorMappingBy === 'id')) {
  50342. opt.mappingMethod = 'category';
  50343. opt.loop = true; // categories is ordinal, so do not set opt.categories.
  50344. } else {
  50345. opt.mappingMethod = 'linear';
  50346. }
  50347. var mapping = new VisualMapping(opt);
  50348. inner$9(mapping).drColorMappingBy = colorMappingBy;
  50349. return mapping;
  50350. } // Notice: If we dont have the attribute 'colorRange', but only use
  50351. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  50352. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  50353. // this problem will be encountered:
  50354. // If a level-1 node dont have children, and its siblings has children,
  50355. // and colorRange is set on level-1, then the node can not be colored.
  50356. // So we separate 'colorRange' and 'color' to different attributes.
  50357. function getRangeVisual(nodeModel, name) {
  50358. // 'colorRange', 'colorARange', 'colorSRange'.
  50359. // If not exsits on this node, fetch from levels and series.
  50360. var range = nodeModel.get(name);
  50361. return isArray(range) && range.length ? {
  50362. name: name,
  50363. range: range
  50364. } : null;
  50365. }
  50366. function mapVisual(nodeModel, visuals, child, index, mapping, seriesModel) {
  50367. var childVisuals = extend({}, visuals);
  50368. if (mapping) {
  50369. // Only support color, colorAlpha, colorSaturation.
  50370. var mappingType = mapping.type;
  50371. var colorMappingBy = mappingType === 'color' && inner$9(mapping).drColorMappingBy;
  50372. var value = colorMappingBy === 'index' ? index : colorMappingBy === 'id' ? seriesModel.mapIdToIndex(child.getId()) : child.getValue(nodeModel.get('visualDimension'));
  50373. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  50374. }
  50375. return childVisuals;
  50376. }
  50377. var mathMax$7 = Math.max;
  50378. var mathMin$7 = Math.min;
  50379. var retrieveValue = retrieve;
  50380. var each$4 = each;
  50381. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  50382. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  50383. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  50384. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  50385. /**
  50386. * @public
  50387. */
  50388. var treemapLayout = {
  50389. seriesType: 'treemap',
  50390. reset: function (seriesModel, ecModel, api, payload) {
  50391. // Layout result in each node:
  50392. // {x, y, width, height, area, borderWidth}
  50393. var ecWidth = api.getWidth();
  50394. var ecHeight = api.getHeight();
  50395. var seriesOption = seriesModel.option;
  50396. var layoutInfo = getLayoutRect(seriesModel.getBoxLayoutParams(), {
  50397. width: api.getWidth(),
  50398. height: api.getHeight()
  50399. });
  50400. var size = seriesOption.size || []; // Compatible with ec2.
  50401. var containerWidth = parsePercent$1(retrieveValue(layoutInfo.width, size[0]), ecWidth);
  50402. var containerHeight = parsePercent$1(retrieveValue(layoutInfo.height, size[1]), ecHeight); // Fetch payload info.
  50403. var payloadType = payload && payload.type;
  50404. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  50405. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  50406. var rootRect = payloadType === 'treemapRender' || payloadType === 'treemapMove' ? payload.rootRect : null;
  50407. var viewRoot = seriesModel.getViewRoot();
  50408. var viewAbovePath = getPathToRoot(viewRoot);
  50409. if (payloadType !== 'treemapMove') {
  50410. var rootSize = payloadType === 'treemapZoomToNode' ? estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) : rootRect ? [rootRect.width, rootRect.height] : [containerWidth, containerHeight];
  50411. var sort_1 = seriesOption.sort;
  50412. if (sort_1 && sort_1 !== 'asc' && sort_1 !== 'desc') {
  50413. // Default to be desc order.
  50414. sort_1 = 'desc';
  50415. }
  50416. var options = {
  50417. squareRatio: seriesOption.squareRatio,
  50418. sort: sort_1,
  50419. leafDepth: seriesOption.leafDepth
  50420. }; // layout should be cleared because using updateView but not update.
  50421. viewRoot.hostTree.clearLayouts(); // TODO
  50422. // optimize: if out of view clip, do not layout.
  50423. // But take care that if do not render node out of view clip,
  50424. // how to calculate start po
  50425. var viewRootLayout_1 = {
  50426. x: 0,
  50427. y: 0,
  50428. width: rootSize[0],
  50429. height: rootSize[1],
  50430. area: rootSize[0] * rootSize[1]
  50431. };
  50432. viewRoot.setLayout(viewRootLayout_1);
  50433. squarify(viewRoot, options, false, 0); // Supplement layout.
  50434. viewRootLayout_1 = viewRoot.getLayout();
  50435. each$4(viewAbovePath, function (node, index) {
  50436. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  50437. node.setLayout(extend({
  50438. dataExtent: [childValue, childValue],
  50439. borderWidth: 0,
  50440. upperHeight: 0
  50441. }, viewRootLayout_1));
  50442. });
  50443. }
  50444. var treeRoot = seriesModel.getData().tree.root;
  50445. treeRoot.setLayout(calculateRootPosition(layoutInfo, rootRect, targetInfo), true);
  50446. seriesModel.setLayoutInfo(layoutInfo); // FIXME
  50447. // 现在没有clip功能,暂时取ec高宽。
  50448. prunning(treeRoot, // Transform to base element coordinate system.
  50449. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight), viewAbovePath, viewRoot, 0);
  50450. }
  50451. };
  50452. /**
  50453. * Layout treemap with squarify algorithm.
  50454. * The original presentation of this algorithm
  50455. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  50456. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  50457. * The implementation of this algorithm was originally copied from "d3.js"
  50458. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  50459. * with some modifications made for this program.
  50460. * See the license statement at the head of this file.
  50461. *
  50462. * @protected
  50463. * @param {module:echarts/data/Tree~TreeNode} node
  50464. * @param {Object} options
  50465. * @param {string} options.sort 'asc' or 'desc'
  50466. * @param {number} options.squareRatio
  50467. * @param {boolean} hideChildren
  50468. * @param {number} depth
  50469. */
  50470. function squarify(node, options, hideChildren, depth) {
  50471. var width;
  50472. var height;
  50473. if (node.isRemoved()) {
  50474. return;
  50475. }
  50476. var thisLayout = node.getLayout();
  50477. width = thisLayout.width;
  50478. height = thisLayout.height; // Considering border and gap
  50479. var nodeModel = node.getModel();
  50480. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  50481. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  50482. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  50483. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  50484. var layoutOffset = borderWidth - halfGapWidth;
  50485. var layoutOffsetUpper = upperHeight - halfGapWidth;
  50486. node.setLayout({
  50487. borderWidth: borderWidth,
  50488. upperHeight: upperHeight,
  50489. upperLabelHeight: upperLabelHeight
  50490. }, true);
  50491. width = mathMax$7(width - 2 * layoutOffset, 0);
  50492. height = mathMax$7(height - layoutOffset - layoutOffsetUpper, 0);
  50493. var totalArea = width * height;
  50494. var viewChildren = initChildren(node, nodeModel, totalArea, options, hideChildren, depth);
  50495. if (!viewChildren.length) {
  50496. return;
  50497. }
  50498. var rect = {
  50499. x: layoutOffset,
  50500. y: layoutOffsetUpper,
  50501. width: width,
  50502. height: height
  50503. };
  50504. var rowFixedLength = mathMin$7(width, height);
  50505. var best = Infinity; // the best row score so far
  50506. var row = [];
  50507. row.area = 0;
  50508. for (var i = 0, len = viewChildren.length; i < len;) {
  50509. var child = viewChildren[i];
  50510. row.push(child);
  50511. row.area += child.getLayout().area;
  50512. var score = worst(row, rowFixedLength, options.squareRatio); // continue with this orientation
  50513. if (score <= best) {
  50514. i++;
  50515. best = score;
  50516. } // abort, and try a different orientation
  50517. else {
  50518. row.area -= row.pop().getLayout().area;
  50519. position(row, rowFixedLength, rect, halfGapWidth, false);
  50520. rowFixedLength = mathMin$7(rect.width, rect.height);
  50521. row.length = row.area = 0;
  50522. best = Infinity;
  50523. }
  50524. }
  50525. if (row.length) {
  50526. position(row, rowFixedLength, rect, halfGapWidth, true);
  50527. }
  50528. if (!hideChildren) {
  50529. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  50530. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  50531. hideChildren = true;
  50532. }
  50533. }
  50534. for (var i = 0, len = viewChildren.length; i < len; i++) {
  50535. squarify(viewChildren[i], options, hideChildren, depth + 1);
  50536. }
  50537. }
  50538. /**
  50539. * Set area to each child, and calculate data extent for visual coding.
  50540. */
  50541. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  50542. var viewChildren = node.children || [];
  50543. var orderBy = options.sort;
  50544. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  50545. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth; // leafDepth has higher priority.
  50546. if (hideChildren && !overLeafDepth) {
  50547. return node.viewChildren = [];
  50548. } // Sort children, order by desc.
  50549. viewChildren = filter(viewChildren, function (child) {
  50550. return !child.isRemoved();
  50551. });
  50552. sort$1(viewChildren, orderBy);
  50553. var info = statistic(nodeModel, viewChildren, orderBy);
  50554. if (info.sum === 0) {
  50555. return node.viewChildren = [];
  50556. }
  50557. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  50558. if (info.sum === 0) {
  50559. return node.viewChildren = [];
  50560. } // Set area to each child.
  50561. for (var i = 0, len = viewChildren.length; i < len; i++) {
  50562. var area = viewChildren[i].getValue() / info.sum * totalArea; // Do not use setLayout({...}, true), because it is needed to clear last layout.
  50563. viewChildren[i].setLayout({
  50564. area: area
  50565. });
  50566. }
  50567. if (overLeafDepth) {
  50568. viewChildren.length && node.setLayout({
  50569. isLeafRoot: true
  50570. }, true);
  50571. viewChildren.length = 0;
  50572. }
  50573. node.viewChildren = viewChildren;
  50574. node.setLayout({
  50575. dataExtent: info.dataExtent
  50576. }, true);
  50577. return viewChildren;
  50578. }
  50579. /**
  50580. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  50581. */
  50582. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  50583. // visibleMin is not supported yet when no option.sort.
  50584. if (!orderBy) {
  50585. return sum;
  50586. }
  50587. var visibleMin = nodeModel.get('visibleMin');
  50588. var len = orderedChildren.length;
  50589. var deletePoint = len; // Always travel from little value to big value.
  50590. for (var i = len - 1; i >= 0; i--) {
  50591. var value = orderedChildren[orderBy === 'asc' ? len - i - 1 : i].getValue();
  50592. if (value / sum * totalArea < visibleMin) {
  50593. deletePoint = i;
  50594. sum -= value;
  50595. }
  50596. }
  50597. orderBy === 'asc' ? orderedChildren.splice(0, len - deletePoint) : orderedChildren.splice(deletePoint, len - deletePoint);
  50598. return sum;
  50599. }
  50600. /**
  50601. * Sort
  50602. */
  50603. function sort$1(viewChildren, orderBy) {
  50604. if (orderBy) {
  50605. viewChildren.sort(function (a, b) {
  50606. var diff = orderBy === 'asc' ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  50607. return diff === 0 ? orderBy === 'asc' ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex : diff;
  50608. });
  50609. }
  50610. return viewChildren;
  50611. }
  50612. /**
  50613. * Statistic
  50614. */
  50615. function statistic(nodeModel, children, orderBy) {
  50616. // Calculate sum.
  50617. var sum = 0;
  50618. for (var i = 0, len = children.length; i < len; i++) {
  50619. sum += children[i].getValue();
  50620. } // Statistic data extent for latter visual coding.
  50621. // Notice: data extent should be calculate based on raw children
  50622. // but not filtered view children, otherwise visual mapping will not
  50623. // be stable when zoom (where children is filtered by visibleMin).
  50624. var dimension = nodeModel.get('visualDimension');
  50625. var dataExtent; // The same as area dimension.
  50626. if (!children || !children.length) {
  50627. dataExtent = [NaN, NaN];
  50628. } else if (dimension === 'value' && orderBy) {
  50629. dataExtent = [children[children.length - 1].getValue(), children[0].getValue()];
  50630. orderBy === 'asc' && dataExtent.reverse();
  50631. } // Other dimension.
  50632. else {
  50633. dataExtent = [Infinity, -Infinity];
  50634. each$4(children, function (child) {
  50635. var value = child.getValue(dimension);
  50636. value < dataExtent[0] && (dataExtent[0] = value);
  50637. value > dataExtent[1] && (dataExtent[1] = value);
  50638. });
  50639. }
  50640. return {
  50641. sum: sum,
  50642. dataExtent: dataExtent
  50643. };
  50644. }
  50645. /**
  50646. * Computes the score for the specified row,
  50647. * as the worst aspect ratio.
  50648. */
  50649. function worst(row, rowFixedLength, ratio) {
  50650. var areaMax = 0;
  50651. var areaMin = Infinity;
  50652. for (var i = 0, area = void 0, len = row.length; i < len; i++) {
  50653. area = row[i].getLayout().area;
  50654. if (area) {
  50655. area < areaMin && (areaMin = area);
  50656. area > areaMax && (areaMax = area);
  50657. }
  50658. }
  50659. var squareArea = row.area * row.area;
  50660. var f = rowFixedLength * rowFixedLength * ratio;
  50661. return squareArea ? mathMax$7(f * areaMax / squareArea, squareArea / (f * areaMin)) : Infinity;
  50662. }
  50663. /**
  50664. * Positions the specified row of nodes. Modifies `rect`.
  50665. */
  50666. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  50667. // When rowFixedLength === rect.width,
  50668. // it is horizontal subdivision,
  50669. // rowFixedLength is the width of the subdivision,
  50670. // rowOtherLength is the height of the subdivision,
  50671. // and nodes will be positioned from left to right.
  50672. // wh[idx0WhenH] means: when horizontal,
  50673. // wh[idx0WhenH] => wh[0] => 'width'.
  50674. // xy[idx1WhenH] => xy[1] => 'y'.
  50675. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  50676. var idx1WhenH = 1 - idx0WhenH;
  50677. var xy = ['x', 'y'];
  50678. var wh = ['width', 'height'];
  50679. var last = rect[xy[idx0WhenH]];
  50680. var rowOtherLength = rowFixedLength ? row.area / rowFixedLength : 0;
  50681. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  50682. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  50683. }
  50684. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  50685. var node = row[i];
  50686. var nodeLayout = {};
  50687. var step = rowOtherLength ? node.getLayout().area / rowOtherLength : 0;
  50688. 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.
  50689. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  50690. var modWH = i === rowLen - 1 || remain < step ? remain : step;
  50691. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$7(modWH - 2 * halfGapWidth, 0);
  50692. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$7(halfGapWidth, wh1 / 2);
  50693. nodeLayout[xy[idx0WhenH]] = last + mathMin$7(halfGapWidth, wh0 / 2);
  50694. last += modWH;
  50695. node.setLayout(nodeLayout, true);
  50696. }
  50697. rect[xy[idx1WhenH]] += rowOtherLength;
  50698. rect[wh[idx1WhenH]] -= rowOtherLength;
  50699. } // Return [containerWidth, containerHeight] as default.
  50700. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  50701. // If targetInfo.node exists, we zoom to the node,
  50702. // so estimate whold width and heigth by target node.
  50703. var currNode = (targetInfo || {}).node;
  50704. var defaultSize = [containerWidth, containerHeight];
  50705. if (!currNode || currNode === viewRoot) {
  50706. return defaultSize;
  50707. }
  50708. var parent;
  50709. var viewArea = containerWidth * containerHeight;
  50710. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  50711. while (parent = currNode.parentNode) {
  50712. // jshint ignore:line
  50713. var sum = 0;
  50714. var siblings = parent.children;
  50715. for (var i = 0, len = siblings.length; i < len; i++) {
  50716. sum += siblings[i].getValue();
  50717. }
  50718. var currNodeValue = currNode.getValue();
  50719. if (currNodeValue === 0) {
  50720. return defaultSize;
  50721. }
  50722. area *= sum / currNodeValue; // Considering border, suppose aspect ratio is 1.
  50723. var parentModel = parent.getModel();
  50724. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  50725. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel));
  50726. area += 4 * borderWidth * borderWidth + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  50727. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  50728. currNode = parent;
  50729. }
  50730. area < viewArea && (area = viewArea);
  50731. var scale = Math.pow(area / viewArea, 0.5);
  50732. return [containerWidth * scale, containerHeight * scale];
  50733. } // Root postion base on coord of containerGroup
  50734. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  50735. if (rootRect) {
  50736. return {
  50737. x: rootRect.x,
  50738. y: rootRect.y
  50739. };
  50740. }
  50741. var defaultPosition = {
  50742. x: 0,
  50743. y: 0
  50744. };
  50745. if (!targetInfo) {
  50746. return defaultPosition;
  50747. } // If targetInfo is fetched by 'retrieveTargetInfo',
  50748. // old tree and new tree are the same tree,
  50749. // so the node still exists and we can visit it.
  50750. var targetNode = targetInfo.node;
  50751. var layout = targetNode.getLayout();
  50752. if (!layout) {
  50753. return defaultPosition;
  50754. } // Transform coord from local to container.
  50755. var targetCenter = [layout.width / 2, layout.height / 2];
  50756. var node = targetNode;
  50757. while (node) {
  50758. var nodeLayout = node.getLayout();
  50759. targetCenter[0] += nodeLayout.x;
  50760. targetCenter[1] += nodeLayout.y;
  50761. node = node.parentNode;
  50762. }
  50763. return {
  50764. x: layoutInfo.width / 2 - targetCenter[0],
  50765. y: layoutInfo.height / 2 - targetCenter[1]
  50766. };
  50767. } // Mark nodes visible for prunning when visual coding and rendering.
  50768. // Prunning depends on layout and root position, so we have to do it after layout.
  50769. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  50770. var nodeLayout = node.getLayout();
  50771. var nodeInViewAbovePath = viewAbovePath[depth];
  50772. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  50773. if (nodeInViewAbovePath && !isAboveViewRoot || depth === viewAbovePath.length && node !== viewRoot) {
  50774. return;
  50775. }
  50776. node.setLayout({
  50777. // isInView means: viewRoot sub tree + viewAbovePath
  50778. isInView: true,
  50779. // invisible only means: outside view clip so that the node can not
  50780. // see but still layout for animation preparation but not render.
  50781. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  50782. isAboveViewRoot: isAboveViewRoot
  50783. }, true); // Transform to child coordinate.
  50784. var childClipRect = new BoundingRect(clipRect.x - nodeLayout.x, clipRect.y - nodeLayout.y, clipRect.width, clipRect.height);
  50785. each$4(node.viewChildren || [], function (child) {
  50786. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  50787. });
  50788. }
  50789. function getUpperLabelHeight(model) {
  50790. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  50791. }
  50792. function install$c(registers) {
  50793. registers.registerSeriesModel(TreemapSeriesModel);
  50794. registers.registerChartView(TreemapView);
  50795. registers.registerVisual(treemapVisual);
  50796. registers.registerLayout(treemapLayout);
  50797. installTreemapAction(registers);
  50798. }
  50799. /*
  50800. * Licensed to the Apache Software Foundation (ASF) under one
  50801. * or more contributor license agreements. See the NOTICE file
  50802. * distributed with this work for additional information
  50803. * regarding copyright ownership. The ASF licenses this file
  50804. * to you under the Apache License, Version 2.0 (the
  50805. * "License"); you may not use this file except in compliance
  50806. * with the License. You may obtain a copy of the License at
  50807. *
  50808. * http://www.apache.org/licenses/LICENSE-2.0
  50809. *
  50810. * Unless required by applicable law or agreed to in writing,
  50811. * software distributed under the License is distributed on an
  50812. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50813. * KIND, either express or implied. See the License for the
  50814. * specific language governing permissions and limitations
  50815. * under the License.
  50816. */
  50817. /**
  50818. * AUTO-GENERATED FILE. DO NOT MODIFY.
  50819. */
  50820. /*
  50821. * Licensed to the Apache Software Foundation (ASF) under one
  50822. * or more contributor license agreements. See the NOTICE file
  50823. * distributed with this work for additional information
  50824. * regarding copyright ownership. The ASF licenses this file
  50825. * to you under the Apache License, Version 2.0 (the
  50826. * "License"); you may not use this file except in compliance
  50827. * with the License. You may obtain a copy of the License at
  50828. *
  50829. * http://www.apache.org/licenses/LICENSE-2.0
  50830. *
  50831. * Unless required by applicable law or agreed to in writing,
  50832. * software distributed under the License is distributed on an
  50833. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50834. * KIND, either express or implied. See the License for the
  50835. * specific language governing permissions and limitations
  50836. * under the License.
  50837. */
  50838. function categoryFilter(ecModel) {
  50839. var legendModels = ecModel.findComponents({
  50840. mainType: 'legend'
  50841. });
  50842. if (!legendModels || !legendModels.length) {
  50843. return;
  50844. }
  50845. ecModel.eachSeriesByType('graph', function (graphSeries) {
  50846. var categoriesData = graphSeries.getCategoriesData();
  50847. var graph = graphSeries.getGraph();
  50848. var data = graph.data;
  50849. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  50850. data.filterSelf(function (idx) {
  50851. var model = data.getItemModel(idx);
  50852. var category = model.getShallow('category');
  50853. if (category != null) {
  50854. if (typeof category === 'number') {
  50855. category = categoryNames[category];
  50856. } // If in any legend component the status is not selected.
  50857. for (var i = 0; i < legendModels.length; i++) {
  50858. if (!legendModels[i].isSelected(category)) {
  50859. return false;
  50860. }
  50861. }
  50862. }
  50863. return true;
  50864. });
  50865. });
  50866. }
  50867. function categoryVisual(ecModel) {
  50868. var paletteScope = {};
  50869. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50870. var categoriesData = seriesModel.getCategoriesData();
  50871. var data = seriesModel.getData();
  50872. var categoryNameIdxMap = {};
  50873. categoriesData.each(function (idx) {
  50874. var name = categoriesData.getName(idx); // Add prefix to avoid conflict with Object.prototype.
  50875. categoryNameIdxMap['ec-' + name] = idx;
  50876. var itemModel = categoriesData.getItemModel(idx);
  50877. var style = itemModel.getModel('itemStyle').getItemStyle();
  50878. if (!style.fill) {
  50879. // Get color from palette.
  50880. style.fill = seriesModel.getColorFromPalette(name, paletteScope);
  50881. }
  50882. categoriesData.setItemVisual(idx, 'style', style);
  50883. var symbolVisualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  50884. for (var i = 0; i < symbolVisualList.length; i++) {
  50885. var symbolVisual = itemModel.getShallow(symbolVisualList[i], true);
  50886. if (symbolVisual != null) {
  50887. categoriesData.setItemVisual(idx, symbolVisualList[i], symbolVisual);
  50888. }
  50889. }
  50890. }); // Assign category color to visual
  50891. if (categoriesData.count()) {
  50892. data.each(function (idx) {
  50893. var model = data.getItemModel(idx);
  50894. var categoryIdx = model.getShallow('category');
  50895. if (categoryIdx != null) {
  50896. if (typeof categoryIdx === 'string') {
  50897. categoryIdx = categoryNameIdxMap['ec-' + categoryIdx];
  50898. }
  50899. var categoryStyle = categoriesData.getItemVisual(categoryIdx, 'style');
  50900. var style = data.ensureUniqueItemVisual(idx, 'style');
  50901. extend(style, categoryStyle);
  50902. var visualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  50903. for (var i = 0; i < visualList.length; i++) {
  50904. data.setItemVisual(idx, visualList[i], categoriesData.getItemVisual(categoryIdx, visualList[i]));
  50905. }
  50906. }
  50907. });
  50908. }
  50909. });
  50910. }
  50911. function normalize$2(a) {
  50912. if (!(a instanceof Array)) {
  50913. a = [a, a];
  50914. }
  50915. return a;
  50916. }
  50917. function graphEdgeVisual(ecModel) {
  50918. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50919. var graph = seriesModel.getGraph();
  50920. var edgeData = seriesModel.getEdgeData();
  50921. var symbolType = normalize$2(seriesModel.get('edgeSymbol'));
  50922. var symbolSize = normalize$2(seriesModel.get('edgeSymbolSize')); // const colorQuery = ['lineStyle', 'color'] as const;
  50923. // const opacityQuery = ['lineStyle', 'opacity'] as const;
  50924. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  50925. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  50926. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  50927. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  50928. edgeData.setVisual('style', seriesModel.getModel('lineStyle').getLineStyle());
  50929. edgeData.each(function (idx) {
  50930. var itemModel = edgeData.getItemModel(idx);
  50931. var edge = graph.getEdgeByIndex(idx);
  50932. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  50933. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true)); // Edge visual must after node visual
  50934. var style = itemModel.getModel('lineStyle').getLineStyle();
  50935. var existsStyle = edgeData.ensureUniqueItemVisual(idx, 'style');
  50936. extend(existsStyle, style);
  50937. switch (existsStyle.stroke) {
  50938. case 'source':
  50939. {
  50940. var nodeStyle = edge.node1.getVisual('style');
  50941. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  50942. break;
  50943. }
  50944. case 'target':
  50945. {
  50946. var nodeStyle = edge.node2.getVisual('style');
  50947. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  50948. break;
  50949. }
  50950. }
  50951. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  50952. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  50953. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  50954. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  50955. });
  50956. });
  50957. }
  50958. var KEY_DELIMITER = '-->';
  50959. /**
  50960. * params handler
  50961. * @param {module:echarts/model/SeriesModel} seriesModel
  50962. * @returns {*}
  50963. */
  50964. var getAutoCurvenessParams = function (seriesModel) {
  50965. return seriesModel.get('autoCurveness') || null;
  50966. };
  50967. /**
  50968. * Generate a list of edge curvatures, 20 is the default
  50969. * @param {module:echarts/model/SeriesModel} seriesModel
  50970. * @param {number} appendLength
  50971. * @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]
  50972. */
  50973. var createCurveness = function (seriesModel, appendLength) {
  50974. var autoCurvenessParmas = getAutoCurvenessParams(seriesModel);
  50975. var length = 20;
  50976. var curvenessList = []; // handler the function set
  50977. if (typeof autoCurvenessParmas === 'number') {
  50978. length = autoCurvenessParmas;
  50979. } else if (isArray(autoCurvenessParmas)) {
  50980. seriesModel.__curvenessList = autoCurvenessParmas;
  50981. return;
  50982. } // append length
  50983. if (appendLength > length) {
  50984. length = appendLength;
  50985. } // make sure the length is even
  50986. var len = length % 2 ? length + 2 : length + 3;
  50987. curvenessList = [];
  50988. for (var i = 0; i < len; i++) {
  50989. curvenessList.push((i % 2 ? i + 1 : i) / 10 * (i % 2 ? -1 : 1));
  50990. }
  50991. seriesModel.__curvenessList = curvenessList;
  50992. };
  50993. /**
  50994. * Create different cache key data in the positive and negative directions, in order to set the curvature later
  50995. * @param {number|string|module:echarts/data/Graph.Node} n1
  50996. * @param {number|string|module:echarts/data/Graph.Node} n2
  50997. * @param {module:echarts/model/SeriesModel} seriesModel
  50998. * @returns {string} key
  50999. */
  51000. var getKeyOfEdges = function (n1, n2, seriesModel) {
  51001. var source = [n1.id, n1.dataIndex].join('.');
  51002. var target = [n2.id, n2.dataIndex].join('.');
  51003. return [seriesModel.uid, source, target].join(KEY_DELIMITER);
  51004. };
  51005. /**
  51006. * get opposite key
  51007. * @param {string} key
  51008. * @returns {string}
  51009. */
  51010. var getOppositeKey = function (key) {
  51011. var keys = key.split(KEY_DELIMITER);
  51012. return [keys[0], keys[2], keys[1]].join(KEY_DELIMITER);
  51013. };
  51014. /**
  51015. * get edgeMap with key
  51016. * @param edge
  51017. * @param {module:echarts/model/SeriesModel} seriesModel
  51018. */
  51019. var getEdgeFromMap = function (edge, seriesModel) {
  51020. var key = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  51021. return seriesModel.__edgeMap[key];
  51022. };
  51023. /**
  51024. * calculate all cases total length
  51025. * @param edge
  51026. * @param seriesModel
  51027. * @returns {number}
  51028. */
  51029. var getTotalLengthBetweenNodes = function (edge, seriesModel) {
  51030. var len = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node1, edge.node2, seriesModel), seriesModel);
  51031. var lenV = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node2, edge.node1, seriesModel), seriesModel);
  51032. return len + lenV;
  51033. };
  51034. /**
  51035. *
  51036. * @param key
  51037. */
  51038. var getEdgeMapLengthWithKey = function (key, seriesModel) {
  51039. var edgeMap = seriesModel.__edgeMap;
  51040. return edgeMap[key] ? edgeMap[key].length : 0;
  51041. };
  51042. /**
  51043. * Count the number of edges between the same two points, used to obtain the curvature table and the parity of the edge
  51044. * @see /graph/GraphSeries.js@getInitialData
  51045. * @param {module:echarts/model/SeriesModel} seriesModel
  51046. */
  51047. function initCurvenessList(seriesModel) {
  51048. if (!getAutoCurvenessParams(seriesModel)) {
  51049. return;
  51050. }
  51051. seriesModel.__curvenessList = [];
  51052. seriesModel.__edgeMap = {}; // calc the array of curveness List
  51053. createCurveness(seriesModel);
  51054. }
  51055. /**
  51056. * set edgeMap with key
  51057. * @param {number|string|module:echarts/data/Graph.Node} n1
  51058. * @param {number|string|module:echarts/data/Graph.Node} n2
  51059. * @param {module:echarts/model/SeriesModel} seriesModel
  51060. * @param {number} index
  51061. */
  51062. function createEdgeMapForCurveness(n1, n2, seriesModel, index) {
  51063. if (!getAutoCurvenessParams(seriesModel)) {
  51064. return;
  51065. }
  51066. var key = getKeyOfEdges(n1, n2, seriesModel);
  51067. var edgeMap = seriesModel.__edgeMap;
  51068. var oppositeEdges = edgeMap[getOppositeKey(key)]; // set direction
  51069. if (edgeMap[key] && !oppositeEdges) {
  51070. edgeMap[key].isForward = true;
  51071. } else if (oppositeEdges && edgeMap[key]) {
  51072. oppositeEdges.isForward = true;
  51073. edgeMap[key].isForward = false;
  51074. }
  51075. edgeMap[key] = edgeMap[key] || [];
  51076. edgeMap[key].push(index);
  51077. }
  51078. /**
  51079. * get curvature for edge
  51080. * @param edge
  51081. * @param {module:echarts/model/SeriesModel} seriesModel
  51082. * @param index
  51083. */
  51084. function getCurvenessForEdge(edge, seriesModel, index, needReverse) {
  51085. var autoCurvenessParams = getAutoCurvenessParams(seriesModel);
  51086. var isArrayParam = isArray(autoCurvenessParams);
  51087. if (!autoCurvenessParams) {
  51088. return null;
  51089. }
  51090. var edgeArray = getEdgeFromMap(edge, seriesModel);
  51091. if (!edgeArray) {
  51092. return null;
  51093. }
  51094. var edgeIndex = -1;
  51095. for (var i = 0; i < edgeArray.length; i++) {
  51096. if (edgeArray[i] === index) {
  51097. edgeIndex = i;
  51098. break;
  51099. }
  51100. } // if totalLen is Longer createCurveness
  51101. var totalLen = getTotalLengthBetweenNodes(edge, seriesModel);
  51102. createCurveness(seriesModel, totalLen);
  51103. edge.lineStyle = edge.lineStyle || {}; // if is opposite edge, must set curvenss to opposite number
  51104. var curKey = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  51105. var curvenessList = seriesModel.__curvenessList; // if pass array no need parity
  51106. var parityCorrection = isArrayParam ? 0 : totalLen % 2 ? 0 : 1;
  51107. if (!edgeArray.isForward) {
  51108. // the opposite edge show outside
  51109. var oppositeKey = getOppositeKey(curKey);
  51110. var len = getEdgeMapLengthWithKey(oppositeKey, seriesModel);
  51111. var resValue = curvenessList[edgeIndex + len + parityCorrection]; // isNeedReverse, simple, force type need reverse the curveness in the junction of the forword and the opposite
  51112. if (needReverse) {
  51113. // set as array may make the parity handle with the len of opposite
  51114. if (isArrayParam) {
  51115. if (autoCurvenessParams && autoCurvenessParams[0] === 0) {
  51116. return (len + parityCorrection) % 2 ? resValue : -resValue;
  51117. } else {
  51118. return ((len % 2 ? 0 : 1) + parityCorrection) % 2 ? resValue : -resValue;
  51119. }
  51120. } else {
  51121. return (len + parityCorrection) % 2 ? resValue : -resValue;
  51122. }
  51123. } else {
  51124. return curvenessList[edgeIndex + len + parityCorrection];
  51125. }
  51126. } else {
  51127. return curvenessList[parityCorrection + edgeIndex];
  51128. }
  51129. }
  51130. function simpleLayout(seriesModel) {
  51131. var coordSys = seriesModel.coordinateSystem;
  51132. if (coordSys && coordSys.type !== 'view') {
  51133. return;
  51134. }
  51135. var graph = seriesModel.getGraph();
  51136. graph.eachNode(function (node) {
  51137. var model = node.getModel();
  51138. node.setLayout([+model.get('x'), +model.get('y')]);
  51139. });
  51140. simpleLayoutEdge(graph, seriesModel);
  51141. }
  51142. function simpleLayoutEdge(graph, seriesModel) {
  51143. graph.eachEdge(function (edge, index) {
  51144. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, seriesModel, index, true), 0);
  51145. var p1 = clone$1(edge.node1.getLayout());
  51146. var p2 = clone$1(edge.node2.getLayout());
  51147. var points = [p1, p2];
  51148. if (+curveness) {
  51149. points.push([(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness]);
  51150. }
  51151. edge.setLayout(points);
  51152. });
  51153. }
  51154. function graphSimpleLayout(ecModel, api) {
  51155. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51156. var layout = seriesModel.get('layout');
  51157. var coordSys = seriesModel.coordinateSystem;
  51158. if (coordSys && coordSys.type !== 'view') {
  51159. var data_1 = seriesModel.getData();
  51160. var dimensions_1 = [];
  51161. each(coordSys.dimensions, function (coordDim) {
  51162. dimensions_1 = dimensions_1.concat(data_1.mapDimensionsAll(coordDim));
  51163. });
  51164. for (var dataIndex = 0; dataIndex < data_1.count(); dataIndex++) {
  51165. var value = [];
  51166. var hasValue = false;
  51167. for (var i = 0; i < dimensions_1.length; i++) {
  51168. var val = data_1.get(dimensions_1[i], dataIndex);
  51169. if (!isNaN(val)) {
  51170. hasValue = true;
  51171. }
  51172. value.push(val);
  51173. }
  51174. if (hasValue) {
  51175. data_1.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  51176. } else {
  51177. // Also {Array.<number>}, not undefined to avoid if...else... statement
  51178. data_1.setItemLayout(dataIndex, [NaN, NaN]);
  51179. }
  51180. }
  51181. simpleLayoutEdge(data_1.graph, seriesModel);
  51182. } else if (!layout || layout === 'none') {
  51183. simpleLayout(seriesModel);
  51184. }
  51185. });
  51186. }
  51187. /*
  51188. * Licensed to the Apache Software Foundation (ASF) under one
  51189. * or more contributor license agreements. See the NOTICE file
  51190. * distributed with this work for additional information
  51191. * regarding copyright ownership. The ASF licenses this file
  51192. * to you under the Apache License, Version 2.0 (the
  51193. * "License"); you may not use this file except in compliance
  51194. * with the License. You may obtain a copy of the License at
  51195. *
  51196. * http://www.apache.org/licenses/LICENSE-2.0
  51197. *
  51198. * Unless required by applicable law or agreed to in writing,
  51199. * software distributed under the License is distributed on an
  51200. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51201. * KIND, either express or implied. See the License for the
  51202. * specific language governing permissions and limitations
  51203. * under the License.
  51204. */
  51205. /**
  51206. * AUTO-GENERATED FILE. DO NOT MODIFY.
  51207. */
  51208. /*
  51209. * Licensed to the Apache Software Foundation (ASF) under one
  51210. * or more contributor license agreements. See the NOTICE file
  51211. * distributed with this work for additional information
  51212. * regarding copyright ownership. The ASF licenses this file
  51213. * to you under the Apache License, Version 2.0 (the
  51214. * "License"); you may not use this file except in compliance
  51215. * with the License. You may obtain a copy of the License at
  51216. *
  51217. * http://www.apache.org/licenses/LICENSE-2.0
  51218. *
  51219. * Unless required by applicable law or agreed to in writing,
  51220. * software distributed under the License is distributed on an
  51221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51222. * KIND, either express or implied. See the License for the
  51223. * specific language governing permissions and limitations
  51224. * under the License.
  51225. */
  51226. function getNodeGlobalScale(seriesModel) {
  51227. var coordSys = seriesModel.coordinateSystem;
  51228. if (coordSys.type !== 'view') {
  51229. return 1;
  51230. }
  51231. var nodeScaleRatio = seriesModel.option.nodeScaleRatio;
  51232. var groupZoom = coordSys.scaleX; // Scale node when zoom changes
  51233. var roamZoom = coordSys.getZoom();
  51234. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  51235. return nodeScale / groupZoom;
  51236. }
  51237. function getSymbolSize(node) {
  51238. var symbolSize = node.getVisual('symbolSize');
  51239. if (symbolSize instanceof Array) {
  51240. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  51241. }
  51242. return +symbolSize;
  51243. }
  51244. var PI$6 = Math.PI;
  51245. var _symbolRadiansHalf = [];
  51246. /**
  51247. * `basedOn` can be:
  51248. * 'value':
  51249. * This layout is not accurate and have same bad case. For example,
  51250. * if the min value is very smaller than the max value, the nodes
  51251. * with the min value probably overlap even though there is enough
  51252. * space to layout them. So we only use this approach in the as the
  51253. * init layout of the force layout.
  51254. * FIXME
  51255. * Probably we do not need this method any more but use
  51256. * `basedOn: 'symbolSize'` in force layout if
  51257. * delay its init operations to GraphView.
  51258. * 'symbolSize':
  51259. * This approach work only if all of the symbol size calculated.
  51260. * That is, the progressive rendering is not applied to graph.
  51261. * FIXME
  51262. * If progressive rendering is applied to graph some day,
  51263. * probably we have to use `basedOn: 'value'`.
  51264. */
  51265. function circularLayout(seriesModel, basedOn) {
  51266. var coordSys = seriesModel.coordinateSystem;
  51267. if (coordSys && coordSys.type !== 'view') {
  51268. return;
  51269. }
  51270. var rect = coordSys.getBoundingRect();
  51271. var nodeData = seriesModel.getData();
  51272. var graph = nodeData.graph;
  51273. var cx = rect.width / 2 + rect.x;
  51274. var cy = rect.height / 2 + rect.y;
  51275. var r = Math.min(rect.width, rect.height) / 2;
  51276. var count = nodeData.count();
  51277. nodeData.setLayout({
  51278. cx: cx,
  51279. cy: cy
  51280. });
  51281. if (!count) {
  51282. return;
  51283. }
  51284. _layoutNodesBasedOn[basedOn](seriesModel, graph, nodeData, r, cx, cy, count);
  51285. graph.eachEdge(function (edge, index) {
  51286. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), getCurvenessForEdge(edge, seriesModel, index), 0);
  51287. var p1 = clone$1(edge.node1.getLayout());
  51288. var p2 = clone$1(edge.node2.getLayout());
  51289. var cp1;
  51290. var x12 = (p1[0] + p2[0]) / 2;
  51291. var y12 = (p1[1] + p2[1]) / 2;
  51292. if (+curveness) {
  51293. curveness *= 3;
  51294. cp1 = [cx * curveness + x12 * (1 - curveness), cy * curveness + y12 * (1 - curveness)];
  51295. }
  51296. edge.setLayout([p1, p2, cp1]);
  51297. });
  51298. }
  51299. var _layoutNodesBasedOn = {
  51300. value: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  51301. var angle = 0;
  51302. var sum = nodeData.getSum('value');
  51303. var unitAngle = Math.PI * 2 / (sum || count);
  51304. graph.eachNode(function (node) {
  51305. var value = node.getValue('value');
  51306. var radianHalf = unitAngle * (sum ? value : 1) / 2;
  51307. angle += radianHalf;
  51308. node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  51309. angle += radianHalf;
  51310. });
  51311. },
  51312. symbolSize: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  51313. var sumRadian = 0;
  51314. _symbolRadiansHalf.length = count;
  51315. var nodeScale = getNodeGlobalScale(seriesModel);
  51316. graph.eachNode(function (node) {
  51317. var symbolSize = getSymbolSize(node); // Normally this case will not happen, but we still add
  51318. // some the defensive code (2px is an arbitrary value).
  51319. isNaN(symbolSize) && (symbolSize = 2);
  51320. symbolSize < 0 && (symbolSize = 0);
  51321. symbolSize *= nodeScale;
  51322. var symbolRadianHalf = Math.asin(symbolSize / 2 / r); // when `symbolSize / 2` is bigger than `r`.
  51323. isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$6 / 2);
  51324. _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf;
  51325. sumRadian += symbolRadianHalf * 2;
  51326. });
  51327. var halfRemainRadian = (2 * PI$6 - sumRadian) / count / 2;
  51328. var angle = 0;
  51329. graph.eachNode(function (node) {
  51330. var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex];
  51331. angle += radianHalf;
  51332. node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  51333. angle += radianHalf;
  51334. });
  51335. }
  51336. };
  51337. function graphCircularLayout(ecModel) {
  51338. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51339. if (seriesModel.get('layout') === 'circular') {
  51340. circularLayout(seriesModel, 'symbolSize');
  51341. }
  51342. });
  51343. }
  51344. var scaleAndAdd$1 = scaleAndAdd; // function adjacentNode(n, e) {
  51345. // return e.n1 === n ? e.n2 : e.n1;
  51346. // }
  51347. function forceLayout(inNodes, inEdges, opts) {
  51348. var nodes = inNodes;
  51349. var edges = inEdges;
  51350. var rect = opts.rect;
  51351. var width = rect.width;
  51352. var height = rect.height;
  51353. var center = [rect.x + width / 2, rect.y + height / 2]; // let scale = opts.scale || 1;
  51354. var gravity = opts.gravity == null ? 0.1 : opts.gravity; // for (let i = 0; i < edges.length; i++) {
  51355. // let e = edges[i];
  51356. // let n1 = e.n1;
  51357. // let n2 = e.n2;
  51358. // n1.edges = n1.edges || [];
  51359. // n2.edges = n2.edges || [];
  51360. // n1.edges.push(e);
  51361. // n2.edges.push(e);
  51362. // }
  51363. // Init position
  51364. for (var i = 0; i < nodes.length; i++) {
  51365. var n = nodes[i];
  51366. if (!n.p) {
  51367. n.p = create(width * (Math.random() - 0.5) + center[0], height * (Math.random() - 0.5) + center[1]);
  51368. }
  51369. n.pp = clone$1(n.p);
  51370. n.edges = null;
  51371. } // Formula in 'Graph Drawing by Force-directed Placement'
  51372. // let k = scale * Math.sqrt(width * height / nodes.length);
  51373. // let k2 = k * k;
  51374. var initialFriction = opts.friction == null ? 0.6 : opts.friction;
  51375. var friction = initialFriction;
  51376. var beforeStepCallback;
  51377. var afterStepCallback;
  51378. return {
  51379. warmUp: function () {
  51380. friction = initialFriction * 0.8;
  51381. },
  51382. setFixed: function (idx) {
  51383. nodes[idx].fixed = true;
  51384. },
  51385. setUnfixed: function (idx) {
  51386. nodes[idx].fixed = false;
  51387. },
  51388. /**
  51389. * Before step hook
  51390. */
  51391. beforeStep: function (cb) {
  51392. beforeStepCallback = cb;
  51393. },
  51394. /**
  51395. * After step hook
  51396. */
  51397. afterStep: function (cb) {
  51398. afterStepCallback = cb;
  51399. },
  51400. /**
  51401. * Some formulas were originally copied from "d3.js"
  51402. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  51403. * with some modifications made for this project.
  51404. * See the license statement at the head of this file.
  51405. */
  51406. step: function (cb) {
  51407. beforeStepCallback && beforeStepCallback(nodes, edges);
  51408. var v12 = [];
  51409. var nLen = nodes.length;
  51410. for (var i = 0; i < edges.length; i++) {
  51411. var e = edges[i];
  51412. if (e.ignoreForceLayout) {
  51413. continue;
  51414. }
  51415. var n1 = e.n1;
  51416. var n2 = e.n2;
  51417. sub(v12, n2.p, n1.p);
  51418. var d = len(v12) - e.d;
  51419. var w = n2.w / (n1.w + n2.w);
  51420. if (isNaN(w)) {
  51421. w = 0;
  51422. }
  51423. normalize(v12, v12);
  51424. !n1.fixed && scaleAndAdd$1(n1.p, n1.p, v12, w * d * friction);
  51425. !n2.fixed && scaleAndAdd$1(n2.p, n2.p, v12, -(1 - w) * d * friction);
  51426. } // Gravity
  51427. for (var i = 0; i < nLen; i++) {
  51428. var n = nodes[i];
  51429. if (!n.fixed) {
  51430. sub(v12, center, n.p); // let d = vec2.len(v12);
  51431. // vec2.scale(v12, v12, 1 / d);
  51432. // let gravityFactor = gravity;
  51433. scaleAndAdd$1(n.p, n.p, v12, gravity * friction);
  51434. }
  51435. } // Repulsive
  51436. // PENDING
  51437. for (var i = 0; i < nLen; i++) {
  51438. var n1 = nodes[i];
  51439. for (var j = i + 1; j < nLen; j++) {
  51440. var n2 = nodes[j];
  51441. sub(v12, n2.p, n1.p);
  51442. var d = len(v12);
  51443. if (d === 0) {
  51444. // Random repulse
  51445. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  51446. d = 1;
  51447. }
  51448. var repFact = (n1.rep + n2.rep) / d / d;
  51449. !n1.fixed && scaleAndAdd$1(n1.pp, n1.pp, v12, repFact);
  51450. !n2.fixed && scaleAndAdd$1(n2.pp, n2.pp, v12, -repFact);
  51451. }
  51452. }
  51453. var v = [];
  51454. for (var i = 0; i < nLen; i++) {
  51455. var n = nodes[i];
  51456. if (!n.fixed) {
  51457. sub(v, n.p, n.pp);
  51458. scaleAndAdd$1(n.p, n.p, v, friction);
  51459. copy(n.pp, n.p);
  51460. }
  51461. }
  51462. friction = friction * 0.992;
  51463. var finished = friction < 0.01;
  51464. afterStepCallback && afterStepCallback(nodes, edges, finished);
  51465. cb && cb(finished);
  51466. }
  51467. };
  51468. }
  51469. function graphForceLayout(ecModel) {
  51470. ecModel.eachSeriesByType('graph', function (graphSeries) {
  51471. var coordSys = graphSeries.coordinateSystem;
  51472. if (coordSys && coordSys.type !== 'view') {
  51473. return;
  51474. }
  51475. if (graphSeries.get('layout') === 'force') {
  51476. var preservedPoints_1 = graphSeries.preservedPoints || {};
  51477. var graph_1 = graphSeries.getGraph();
  51478. var nodeData_1 = graph_1.data;
  51479. var edgeData = graph_1.edgeData;
  51480. var forceModel = graphSeries.getModel('force');
  51481. var initLayout = forceModel.get('initLayout');
  51482. if (graphSeries.preservedPoints) {
  51483. nodeData_1.each(function (idx) {
  51484. var id = nodeData_1.getId(idx);
  51485. nodeData_1.setItemLayout(idx, preservedPoints_1[id] || [NaN, NaN]);
  51486. });
  51487. } else if (!initLayout || initLayout === 'none') {
  51488. simpleLayout(graphSeries);
  51489. } else if (initLayout === 'circular') {
  51490. circularLayout(graphSeries, 'value');
  51491. }
  51492. var nodeDataExtent_1 = nodeData_1.getDataExtent('value');
  51493. var edgeDataExtent_1 = edgeData.getDataExtent('value'); // let edgeDataExtent = edgeData.getDataExtent('value');
  51494. var repulsion = forceModel.get('repulsion');
  51495. var edgeLength = forceModel.get('edgeLength');
  51496. var repulsionArr_1 = isArray(repulsion) ? repulsion : [repulsion, repulsion];
  51497. var edgeLengthArr_1 = isArray(edgeLength) ? edgeLength : [edgeLength, edgeLength]; // Larger value has smaller length
  51498. edgeLengthArr_1 = [edgeLengthArr_1[1], edgeLengthArr_1[0]];
  51499. var nodes_1 = nodeData_1.mapArray('value', function (value, idx) {
  51500. var point = nodeData_1.getItemLayout(idx);
  51501. var rep = linearMap(value, nodeDataExtent_1, repulsionArr_1);
  51502. if (isNaN(rep)) {
  51503. rep = (repulsionArr_1[0] + repulsionArr_1[1]) / 2;
  51504. }
  51505. return {
  51506. w: rep,
  51507. rep: rep,
  51508. fixed: nodeData_1.getItemModel(idx).get('fixed'),
  51509. p: !point || isNaN(point[0]) || isNaN(point[1]) ? null : point
  51510. };
  51511. });
  51512. var edges = edgeData.mapArray('value', function (value, idx) {
  51513. var edge = graph_1.getEdgeByIndex(idx);
  51514. var d = linearMap(value, edgeDataExtent_1, edgeLengthArr_1);
  51515. if (isNaN(d)) {
  51516. d = (edgeLengthArr_1[0] + edgeLengthArr_1[1]) / 2;
  51517. }
  51518. var edgeModel = edge.getModel();
  51519. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, graphSeries, idx, true), 0);
  51520. return {
  51521. n1: nodes_1[edge.node1.dataIndex],
  51522. n2: nodes_1[edge.node2.dataIndex],
  51523. d: d,
  51524. curveness: curveness,
  51525. ignoreForceLayout: edgeModel.get('ignoreForceLayout')
  51526. };
  51527. }); // let coordSys = graphSeries.coordinateSystem;
  51528. var rect = coordSys.getBoundingRect();
  51529. var forceInstance = forceLayout(nodes_1, edges, {
  51530. rect: rect,
  51531. gravity: forceModel.get('gravity'),
  51532. friction: forceModel.get('friction')
  51533. });
  51534. forceInstance.beforeStep(function (nodes, edges) {
  51535. for (var i = 0, l = nodes.length; i < l; i++) {
  51536. if (nodes[i].fixed) {
  51537. // Write back to layout instance
  51538. copy(nodes[i].p, graph_1.getNodeByIndex(i).getLayout());
  51539. }
  51540. }
  51541. });
  51542. forceInstance.afterStep(function (nodes, edges, stopped) {
  51543. for (var i = 0, l = nodes.length; i < l; i++) {
  51544. if (!nodes[i].fixed) {
  51545. graph_1.getNodeByIndex(i).setLayout(nodes[i].p);
  51546. }
  51547. preservedPoints_1[nodeData_1.getId(i)] = nodes[i].p;
  51548. }
  51549. for (var i = 0, l = edges.length; i < l; i++) {
  51550. var e = edges[i];
  51551. var edge = graph_1.getEdgeByIndex(i);
  51552. var p1 = e.n1.p;
  51553. var p2 = e.n2.p;
  51554. var points = edge.getLayout();
  51555. points = points ? points.slice() : [];
  51556. points[0] = points[0] || [];
  51557. points[1] = points[1] || [];
  51558. copy(points[0], p1);
  51559. copy(points[1], p2);
  51560. if (+e.curveness) {
  51561. points[2] = [(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness];
  51562. }
  51563. edge.setLayout(points);
  51564. }
  51565. });
  51566. graphSeries.forceLayout = forceInstance;
  51567. graphSeries.preservedPoints = preservedPoints_1; // Step to get the layout
  51568. forceInstance.step();
  51569. } else {
  51570. // Remove prev injected forceLayout instance
  51571. graphSeries.forceLayout = null;
  51572. }
  51573. });
  51574. }
  51575. function getViewRect$2(seriesModel, api, aspect) {
  51576. var option = extend(seriesModel.getBoxLayoutParams(), {
  51577. aspect: aspect
  51578. });
  51579. return getLayoutRect(option, {
  51580. width: api.getWidth(),
  51581. height: api.getHeight()
  51582. });
  51583. }
  51584. function createViewCoordSys(ecModel, api) {
  51585. var viewList = [];
  51586. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51587. var coordSysType = seriesModel.get('coordinateSystem');
  51588. if (!coordSysType || coordSysType === 'view') {
  51589. var data_1 = seriesModel.getData();
  51590. var positions = data_1.mapArray(function (idx) {
  51591. var itemModel = data_1.getItemModel(idx);
  51592. return [+itemModel.get('x'), +itemModel.get('y')];
  51593. });
  51594. var min = [];
  51595. var max = [];
  51596. fromPoints(positions, min, max); // If width or height is 0
  51597. if (max[0] - min[0] === 0) {
  51598. max[0] += 1;
  51599. min[0] -= 1;
  51600. }
  51601. if (max[1] - min[1] === 0) {
  51602. max[1] += 1;
  51603. min[1] -= 1;
  51604. }
  51605. var aspect = (max[0] - min[0]) / (max[1] - min[1]); // FIXME If get view rect after data processed?
  51606. var viewRect = getViewRect$2(seriesModel, api, aspect); // Position may be NaN, use view rect instead
  51607. if (isNaN(aspect)) {
  51608. min = [viewRect.x, viewRect.y];
  51609. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  51610. }
  51611. var bbWidth = max[0] - min[0];
  51612. var bbHeight = max[1] - min[1];
  51613. var viewWidth = viewRect.width;
  51614. var viewHeight = viewRect.height;
  51615. var viewCoordSys = seriesModel.coordinateSystem = new View();
  51616. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  51617. viewCoordSys.setBoundingRect(min[0], min[1], bbWidth, bbHeight);
  51618. viewCoordSys.setViewRect(viewRect.x, viewRect.y, viewWidth, viewHeight); // Update roam info
  51619. viewCoordSys.setCenter(seriesModel.get('center'));
  51620. viewCoordSys.setZoom(seriesModel.get('zoom'));
  51621. viewList.push(viewCoordSys);
  51622. }
  51623. });
  51624. return viewList;
  51625. }
  51626. var straightLineProto = Line.prototype;
  51627. var bezierCurveProto = BezierCurve.prototype;
  51628. var StraightLineShape =
  51629. /** @class */
  51630. function () {
  51631. function StraightLineShape() {
  51632. // Start point
  51633. this.x1 = 0;
  51634. this.y1 = 0; // End point
  51635. this.x2 = 0;
  51636. this.y2 = 0;
  51637. this.percent = 1;
  51638. }
  51639. return StraightLineShape;
  51640. }();
  51641. var CurveShape =
  51642. /** @class */
  51643. function (_super) {
  51644. __extends(CurveShape, _super);
  51645. function CurveShape() {
  51646. return _super !== null && _super.apply(this, arguments) || this;
  51647. }
  51648. return CurveShape;
  51649. }(StraightLineShape);
  51650. function isStraightLine(shape) {
  51651. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  51652. }
  51653. var ECLinePath =
  51654. /** @class */
  51655. function (_super) {
  51656. __extends(ECLinePath, _super);
  51657. function ECLinePath(opts) {
  51658. var _this = _super.call(this, opts) || this;
  51659. _this.type = 'ec-line';
  51660. return _this;
  51661. }
  51662. ECLinePath.prototype.getDefaultStyle = function () {
  51663. return {
  51664. stroke: '#000',
  51665. fill: null
  51666. };
  51667. };
  51668. ECLinePath.prototype.getDefaultShape = function () {
  51669. return new StraightLineShape();
  51670. };
  51671. ECLinePath.prototype.buildPath = function (ctx, shape) {
  51672. if (isStraightLine(shape)) {
  51673. straightLineProto.buildPath.call(this, ctx, shape);
  51674. } else {
  51675. bezierCurveProto.buildPath.call(this, ctx, shape);
  51676. }
  51677. };
  51678. ECLinePath.prototype.pointAt = function (t) {
  51679. if (isStraightLine(this.shape)) {
  51680. return straightLineProto.pointAt.call(this, t);
  51681. } else {
  51682. return bezierCurveProto.pointAt.call(this, t);
  51683. }
  51684. };
  51685. ECLinePath.prototype.tangentAt = function (t) {
  51686. var shape = this.shape;
  51687. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  51688. return normalize(p, p);
  51689. };
  51690. return ECLinePath;
  51691. }(Path);
  51692. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  51693. function makeSymbolTypeKey(symbolCategory) {
  51694. return '_' + symbolCategory + 'Type';
  51695. }
  51696. /**
  51697. * @inner
  51698. */
  51699. function createSymbol$1(name, lineData, idx) {
  51700. var symbolType = lineData.getItemVisual(idx, name);
  51701. if (!symbolType || symbolType === 'none') {
  51702. return;
  51703. }
  51704. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  51705. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  51706. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  51707. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  51708. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  51709. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  51710. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
  51711. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  51712. symbolPath.name = name;
  51713. return symbolPath;
  51714. }
  51715. function createLine(points) {
  51716. var line = new ECLinePath({
  51717. name: 'line',
  51718. subPixelOptimize: true
  51719. });
  51720. setLinePoints(line.shape, points);
  51721. return line;
  51722. }
  51723. function setLinePoints(targetShape, points) {
  51724. targetShape.x1 = points[0][0];
  51725. targetShape.y1 = points[0][1];
  51726. targetShape.x2 = points[1][0];
  51727. targetShape.y2 = points[1][1];
  51728. targetShape.percent = 1;
  51729. var cp1 = points[2];
  51730. if (cp1) {
  51731. targetShape.cpx1 = cp1[0];
  51732. targetShape.cpy1 = cp1[1];
  51733. } else {
  51734. targetShape.cpx1 = NaN;
  51735. targetShape.cpy1 = NaN;
  51736. }
  51737. }
  51738. var Line$1 =
  51739. /** @class */
  51740. function (_super) {
  51741. __extends(Line, _super);
  51742. function Line(lineData, idx, seriesScope) {
  51743. var _this = _super.call(this) || this;
  51744. _this._createLine(lineData, idx, seriesScope);
  51745. return _this;
  51746. }
  51747. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  51748. var seriesModel = lineData.hostModel;
  51749. var linePoints = lineData.getItemLayout(idx);
  51750. var line = createLine(linePoints);
  51751. line.shape.percent = 0;
  51752. initProps(line, {
  51753. shape: {
  51754. percent: 1
  51755. }
  51756. }, seriesModel, idx);
  51757. this.add(line);
  51758. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  51759. var symbol = createSymbol$1(symbolCategory, lineData, idx); // symbols must added after line to make sure
  51760. // it will be updated after line#update.
  51761. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  51762. this.add(symbol);
  51763. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  51764. }, this);
  51765. this._updateCommonStl(lineData, idx, seriesScope);
  51766. }; // TODO More strict on the List type in parameters?
  51767. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  51768. var seriesModel = lineData.hostModel;
  51769. var line = this.childOfName('line');
  51770. var linePoints = lineData.getItemLayout(idx);
  51771. var target = {
  51772. shape: {}
  51773. };
  51774. setLinePoints(target.shape, linePoints);
  51775. updateProps(line, target, seriesModel, idx);
  51776. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  51777. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  51778. var key = makeSymbolTypeKey(symbolCategory); // Symbol changed
  51779. if (this[key] !== symbolType) {
  51780. this.remove(this.childOfName(symbolCategory));
  51781. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  51782. this.add(symbol);
  51783. }
  51784. this[key] = symbolType;
  51785. }, this);
  51786. this._updateCommonStl(lineData, idx, seriesScope);
  51787. };
  51788. Line.prototype.getLinePath = function () {
  51789. return this.childAt(0);
  51790. };
  51791. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  51792. var seriesModel = lineData.hostModel;
  51793. var line = this.childOfName('line');
  51794. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  51795. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  51796. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  51797. var labelStatesModels = seriesScope && seriesScope.labelStatesModels; // Optimization for large dataset
  51798. if (!seriesScope || lineData.hasItemOption) {
  51799. var itemModel = lineData.getItemModel(idx);
  51800. emphasisLineStyle = itemModel.getModel(['emphasis', 'lineStyle']).getLineStyle();
  51801. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  51802. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  51803. labelStatesModels = getLabelStatesModels(itemModel);
  51804. }
  51805. var lineStyle = lineData.getItemVisual(idx, 'style');
  51806. var visualColor = lineStyle.stroke;
  51807. line.useStyle(lineStyle);
  51808. line.style.fill = null;
  51809. line.style.strokeNoScale = true;
  51810. line.ensureState('emphasis').style = emphasisLineStyle;
  51811. line.ensureState('blur').style = blurLineStyle;
  51812. line.ensureState('select').style = selectLineStyle; // Update symbol
  51813. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  51814. var symbol = this.childOfName(symbolCategory);
  51815. if (symbol) {
  51816. // Share opacity and color with line.
  51817. symbol.setColor(visualColor);
  51818. symbol.style.opacity = lineStyle.opacity;
  51819. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  51820. var stateName = SPECIAL_STATES[i];
  51821. var lineState = line.getState(stateName);
  51822. if (lineState) {
  51823. var lineStateStyle = lineState.style || {};
  51824. var state = symbol.ensureState(stateName);
  51825. var stateStyle = state.style || (state.style = {});
  51826. if (lineStateStyle.stroke != null) {
  51827. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  51828. }
  51829. if (lineStateStyle.opacity != null) {
  51830. stateStyle.opacity = lineStateStyle.opacity;
  51831. }
  51832. }
  51833. }
  51834. symbol.markRedraw();
  51835. }
  51836. }, this);
  51837. var rawVal = seriesModel.getRawValue(idx);
  51838. setLabelStyle(this, labelStatesModels, {
  51839. labelDataIndex: idx,
  51840. labelFetcher: {
  51841. getFormattedLabel: function (dataIndex, stateName) {
  51842. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  51843. }
  51844. },
  51845. inheritColor: visualColor || '#000',
  51846. defaultOpacity: lineStyle.opacity,
  51847. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  51848. });
  51849. var label = this.getTextContent(); // Always set `textStyle` even if `normalStyle.text` is null, because default
  51850. // values have to be set on `normalStyle`.
  51851. if (label) {
  51852. var labelNormalModel = labelStatesModels.normal;
  51853. label.__align = label.style.align;
  51854. label.__verticalAlign = label.style.verticalAlign; // 'start', 'middle', 'end'
  51855. label.__position = labelNormalModel.get('position') || 'middle';
  51856. var distance = labelNormalModel.get('distance');
  51857. if (!isArray(distance)) {
  51858. distance = [distance, distance];
  51859. }
  51860. label.__labelDistance = distance;
  51861. }
  51862. this.setTextConfig({
  51863. position: null,
  51864. local: true,
  51865. inside: false // Can't be inside for stroke element.
  51866. });
  51867. enableHoverEmphasis(this);
  51868. };
  51869. Line.prototype.highlight = function () {
  51870. enterEmphasis(this);
  51871. };
  51872. Line.prototype.downplay = function () {
  51873. leaveEmphasis(this);
  51874. };
  51875. Line.prototype.updateLayout = function (lineData, idx) {
  51876. this.setLinePoints(lineData.getItemLayout(idx));
  51877. };
  51878. Line.prototype.setLinePoints = function (points) {
  51879. var linePath = this.childOfName('line');
  51880. setLinePoints(linePath.shape, points);
  51881. linePath.dirty();
  51882. };
  51883. Line.prototype.beforeUpdate = function () {
  51884. var lineGroup = this;
  51885. var symbolFrom = lineGroup.childOfName('fromSymbol');
  51886. var symbolTo = lineGroup.childOfName('toSymbol');
  51887. var label = lineGroup.getTextContent(); // Quick reject
  51888. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  51889. return;
  51890. }
  51891. var invScale = 1;
  51892. var parentNode = this.parent;
  51893. while (parentNode) {
  51894. if (parentNode.scaleX) {
  51895. invScale /= parentNode.scaleX;
  51896. }
  51897. parentNode = parentNode.parent;
  51898. }
  51899. var line = lineGroup.childOfName('line'); // If line not changed
  51900. // FIXME Parent scale changed
  51901. if (!this.__dirty && !line.__dirty) {
  51902. return;
  51903. }
  51904. var percent = line.shape.percent;
  51905. var fromPos = line.pointAt(0);
  51906. var toPos = line.pointAt(percent);
  51907. var d = sub([], toPos, fromPos);
  51908. normalize(d, d);
  51909. function setSymbolRotation(symbol, percent) {
  51910. // Fix #12388
  51911. // when symbol is set to be 'arrow' in markLine,
  51912. // symbolRotate value will be ignored, and compulsively use tangent angle.
  51913. // rotate by default if symbol rotation is not specified
  51914. var specifiedRotation = symbol.__specifiedRotation;
  51915. if (specifiedRotation == null) {
  51916. var tangent = line.tangentAt(percent);
  51917. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  51918. } else {
  51919. symbol.attr('rotation', specifiedRotation);
  51920. }
  51921. }
  51922. if (symbolFrom) {
  51923. symbolFrom.setPosition(fromPos);
  51924. setSymbolRotation(symbolFrom, 0);
  51925. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  51926. symbolFrom.markRedraw();
  51927. }
  51928. if (symbolTo) {
  51929. symbolTo.setPosition(toPos);
  51930. setSymbolRotation(symbolTo, 1);
  51931. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  51932. symbolTo.markRedraw();
  51933. }
  51934. if (label && !label.ignore) {
  51935. label.x = label.y = 0;
  51936. label.originX = label.originY = 0;
  51937. var textAlign = void 0;
  51938. var textVerticalAlign = void 0;
  51939. var distance = label.__labelDistance;
  51940. var distanceX = distance[0] * invScale;
  51941. var distanceY = distance[1] * invScale;
  51942. var halfPercent = percent / 2;
  51943. var tangent = line.tangentAt(halfPercent);
  51944. var n = [tangent[1], -tangent[0]];
  51945. var cp = line.pointAt(halfPercent);
  51946. if (n[1] > 0) {
  51947. n[0] = -n[0];
  51948. n[1] = -n[1];
  51949. }
  51950. var dir = tangent[0] < 0 ? -1 : 1;
  51951. if (label.__position !== 'start' && label.__position !== 'end') {
  51952. var rotation = -Math.atan2(tangent[1], tangent[0]);
  51953. if (toPos[0] < fromPos[0]) {
  51954. rotation = Math.PI + rotation;
  51955. }
  51956. label.rotation = rotation;
  51957. }
  51958. var dy = void 0;
  51959. switch (label.__position) {
  51960. case 'insideStartTop':
  51961. case 'insideMiddleTop':
  51962. case 'insideEndTop':
  51963. case 'middle':
  51964. dy = -distanceY;
  51965. textVerticalAlign = 'bottom';
  51966. break;
  51967. case 'insideStartBottom':
  51968. case 'insideMiddleBottom':
  51969. case 'insideEndBottom':
  51970. dy = distanceY;
  51971. textVerticalAlign = 'top';
  51972. break;
  51973. default:
  51974. dy = 0;
  51975. textVerticalAlign = 'middle';
  51976. }
  51977. switch (label.__position) {
  51978. case 'end':
  51979. label.x = d[0] * distanceX + toPos[0];
  51980. label.y = d[1] * distanceY + toPos[1];
  51981. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  51982. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  51983. break;
  51984. case 'start':
  51985. label.x = -d[0] * distanceX + fromPos[0];
  51986. label.y = -d[1] * distanceY + fromPos[1];
  51987. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  51988. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  51989. break;
  51990. case 'insideStartTop':
  51991. case 'insideStart':
  51992. case 'insideStartBottom':
  51993. label.x = distanceX * dir + fromPos[0];
  51994. label.y = fromPos[1] + dy;
  51995. textAlign = tangent[0] < 0 ? 'right' : 'left';
  51996. label.originX = -distanceX * dir;
  51997. label.originY = -dy;
  51998. break;
  51999. case 'insideMiddleTop':
  52000. case 'insideMiddle':
  52001. case 'insideMiddleBottom':
  52002. case 'middle':
  52003. label.x = cp[0];
  52004. label.y = cp[1] + dy;
  52005. textAlign = 'center';
  52006. label.originY = -dy;
  52007. break;
  52008. case 'insideEndTop':
  52009. case 'insideEnd':
  52010. case 'insideEndBottom':
  52011. label.x = -distanceX * dir + toPos[0];
  52012. label.y = toPos[1] + dy;
  52013. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  52014. label.originX = distanceX * dir;
  52015. label.originY = -dy;
  52016. break;
  52017. }
  52018. label.scaleX = label.scaleY = invScale;
  52019. label.setStyle({
  52020. // Use the user specified text align and baseline first
  52021. verticalAlign: label.__verticalAlign || textVerticalAlign,
  52022. align: label.__align || textAlign
  52023. });
  52024. }
  52025. };
  52026. return Line;
  52027. }(Group);
  52028. var LineDraw =
  52029. /** @class */
  52030. function () {
  52031. function LineDraw(LineCtor) {
  52032. this.group = new Group();
  52033. this._LineCtor = LineCtor || Line$1;
  52034. }
  52035. LineDraw.prototype.isPersistent = function () {
  52036. return true;
  52037. };
  52038. LineDraw.prototype.updateData = function (lineData) {
  52039. var _this = this;
  52040. var lineDraw = this;
  52041. var group = lineDraw.group;
  52042. var oldLineData = lineDraw._lineData;
  52043. lineDraw._lineData = lineData; // There is no oldLineData only when first rendering or switching from
  52044. // stream mode to normal mode, where previous elements should be removed.
  52045. if (!oldLineData) {
  52046. group.removeAll();
  52047. }
  52048. var seriesScope = makeSeriesScope$1(lineData);
  52049. lineData.diff(oldLineData).add(function (idx) {
  52050. _this._doAdd(lineData, idx, seriesScope);
  52051. }).update(function (newIdx, oldIdx) {
  52052. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  52053. }).remove(function (idx) {
  52054. group.remove(oldLineData.getItemGraphicEl(idx));
  52055. }).execute();
  52056. };
  52057. LineDraw.prototype.updateLayout = function () {
  52058. var lineData = this._lineData; // Do not support update layout in incremental mode.
  52059. if (!lineData) {
  52060. return;
  52061. }
  52062. lineData.eachItemGraphicEl(function (el, idx) {
  52063. el.updateLayout(lineData, idx);
  52064. }, this);
  52065. };
  52066. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  52067. this._seriesScope = makeSeriesScope$1(lineData);
  52068. this._lineData = null;
  52069. this.group.removeAll();
  52070. };
  52071. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  52072. function updateIncrementalAndHover(el) {
  52073. if (!el.isGroup && !isEffectObject(el)) {
  52074. el.incremental = true;
  52075. el.ensureState('emphasis').hoverLayer = true;
  52076. }
  52077. }
  52078. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  52079. var itemLayout = lineData.getItemLayout(idx);
  52080. if (lineNeedsDraw(itemLayout)) {
  52081. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  52082. el.traverse(updateIncrementalAndHover);
  52083. this.group.add(el);
  52084. lineData.setItemGraphicEl(idx, el);
  52085. }
  52086. }
  52087. };
  52088. LineDraw.prototype.remove = function () {
  52089. this.group.removeAll();
  52090. };
  52091. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  52092. var itemLayout = lineData.getItemLayout(idx);
  52093. if (!lineNeedsDraw(itemLayout)) {
  52094. return;
  52095. }
  52096. var el = new this._LineCtor(lineData, idx, seriesScope);
  52097. lineData.setItemGraphicEl(idx, el);
  52098. this.group.add(el);
  52099. };
  52100. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  52101. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  52102. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  52103. this.group.remove(itemEl);
  52104. return;
  52105. }
  52106. if (!itemEl) {
  52107. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  52108. } else {
  52109. itemEl.updateData(newLineData, newIdx, seriesScope);
  52110. }
  52111. newLineData.setItemGraphicEl(newIdx, itemEl);
  52112. this.group.add(itemEl);
  52113. };
  52114. return LineDraw;
  52115. }();
  52116. function isEffectObject(el) {
  52117. return el.animators && el.animators.length > 0;
  52118. }
  52119. function makeSeriesScope$1(lineData) {
  52120. var hostModel = lineData.hostModel;
  52121. return {
  52122. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  52123. emphasisLineStyle: hostModel.getModel(['emphasis', 'lineStyle']).getLineStyle(),
  52124. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  52125. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  52126. labelStatesModels: getLabelStatesModels(hostModel)
  52127. };
  52128. }
  52129. function isPointNaN(pt) {
  52130. return isNaN(pt[0]) || isNaN(pt[1]);
  52131. }
  52132. function lineNeedsDraw(pts) {
  52133. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  52134. }
  52135. var v1 = [];
  52136. var v2 = [];
  52137. var v3 = [];
  52138. var quadraticAt$1 = quadraticAt;
  52139. var v2DistSquare = distSquare;
  52140. var mathAbs$2 = Math.abs;
  52141. function intersectCurveCircle(curvePoints, center, radius) {
  52142. var p0 = curvePoints[0];
  52143. var p1 = curvePoints[1];
  52144. var p2 = curvePoints[2];
  52145. var d = Infinity;
  52146. var t;
  52147. var radiusSquare = radius * radius;
  52148. var interval = 0.1;
  52149. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  52150. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  52151. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  52152. var diff = mathAbs$2(v2DistSquare(v1, center) - radiusSquare);
  52153. if (diff < d) {
  52154. d = diff;
  52155. t = _t;
  52156. }
  52157. } // Assume the segment is monotone,Find root through Bisection method
  52158. // At most 32 iteration
  52159. for (var i = 0; i < 32; i++) {
  52160. // let prev = t - interval;
  52161. var next = t + interval; // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  52162. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  52163. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  52164. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  52165. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  52166. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  52167. var diff = v2DistSquare(v2, center) - radiusSquare;
  52168. if (mathAbs$2(diff) < 1e-2) {
  52169. break;
  52170. } // let prevDiff = v2DistSquare(v1, center) - radiusSquare;
  52171. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  52172. interval /= 2;
  52173. if (diff < 0) {
  52174. if (nextDiff >= 0) {
  52175. t = t + interval;
  52176. } else {
  52177. t = t - interval;
  52178. }
  52179. } else {
  52180. if (nextDiff >= 0) {
  52181. t = t - interval;
  52182. } else {
  52183. t = t + interval;
  52184. }
  52185. }
  52186. }
  52187. return t;
  52188. } // Adjust edge to avoid
  52189. function adjustEdge(graph, scale) {
  52190. var tmp0 = [];
  52191. var quadraticSubdivide$1 = quadraticSubdivide;
  52192. var pts = [[], [], []];
  52193. var pts2 = [[], []];
  52194. var v = [];
  52195. scale /= 2;
  52196. graph.eachEdge(function (edge, idx) {
  52197. var linePoints = edge.getLayout();
  52198. var fromSymbol = edge.getVisual('fromSymbol');
  52199. var toSymbol = edge.getVisual('toSymbol');
  52200. if (!linePoints.__original) {
  52201. linePoints.__original = [clone$1(linePoints[0]), clone$1(linePoints[1])];
  52202. if (linePoints[2]) {
  52203. linePoints.__original.push(clone$1(linePoints[2]));
  52204. }
  52205. }
  52206. var originalPoints = linePoints.__original; // Quadratic curve
  52207. if (linePoints[2] != null) {
  52208. copy(pts[0], originalPoints[0]);
  52209. copy(pts[1], originalPoints[2]);
  52210. copy(pts[2], originalPoints[1]);
  52211. if (fromSymbol && fromSymbol !== 'none') {
  52212. var symbolSize = getSymbolSize(edge.node1);
  52213. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale); // Subdivide and get the second
  52214. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  52215. pts[0][0] = tmp0[3];
  52216. pts[1][0] = tmp0[4];
  52217. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  52218. pts[0][1] = tmp0[3];
  52219. pts[1][1] = tmp0[4];
  52220. }
  52221. if (toSymbol && toSymbol !== 'none') {
  52222. var symbolSize = getSymbolSize(edge.node2);
  52223. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale); // Subdivide and get the first
  52224. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  52225. pts[1][0] = tmp0[1];
  52226. pts[2][0] = tmp0[2];
  52227. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  52228. pts[1][1] = tmp0[1];
  52229. pts[2][1] = tmp0[2];
  52230. } // Copy back to layout
  52231. copy(linePoints[0], pts[0]);
  52232. copy(linePoints[1], pts[2]);
  52233. copy(linePoints[2], pts[1]);
  52234. } // Line
  52235. else {
  52236. copy(pts2[0], originalPoints[0]);
  52237. copy(pts2[1], originalPoints[1]);
  52238. sub(v, pts2[1], pts2[0]);
  52239. normalize(v, v);
  52240. if (fromSymbol && fromSymbol !== 'none') {
  52241. var symbolSize = getSymbolSize(edge.node1);
  52242. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale);
  52243. }
  52244. if (toSymbol && toSymbol !== 'none') {
  52245. var symbolSize = getSymbolSize(edge.node2);
  52246. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale);
  52247. }
  52248. copy(linePoints[0], pts2[0]);
  52249. copy(linePoints[1], pts2[1]);
  52250. }
  52251. });
  52252. }
  52253. function isViewCoordSys(coordSys) {
  52254. return coordSys.type === 'view';
  52255. }
  52256. var GraphView =
  52257. /** @class */
  52258. function (_super) {
  52259. __extends(GraphView, _super);
  52260. function GraphView() {
  52261. var _this = _super !== null && _super.apply(this, arguments) || this;
  52262. _this.type = GraphView.type;
  52263. return _this;
  52264. }
  52265. GraphView.prototype.init = function (ecModel, api) {
  52266. var symbolDraw = new SymbolDraw();
  52267. var lineDraw = new LineDraw();
  52268. var group = this.group;
  52269. this._controller = new RoamController(api.getZr());
  52270. this._controllerHost = {
  52271. target: group
  52272. };
  52273. group.add(symbolDraw.group);
  52274. group.add(lineDraw.group);
  52275. this._symbolDraw = symbolDraw;
  52276. this._lineDraw = lineDraw;
  52277. this._firstRender = true;
  52278. };
  52279. GraphView.prototype.render = function (seriesModel, ecModel, api) {
  52280. var _this = this;
  52281. var coordSys = seriesModel.coordinateSystem;
  52282. this._model = seriesModel;
  52283. var symbolDraw = this._symbolDraw;
  52284. var lineDraw = this._lineDraw;
  52285. var group = this.group;
  52286. if (isViewCoordSys(coordSys)) {
  52287. var groupNewProp = {
  52288. x: coordSys.x,
  52289. y: coordSys.y,
  52290. scaleX: coordSys.scaleX,
  52291. scaleY: coordSys.scaleY
  52292. };
  52293. if (this._firstRender) {
  52294. group.attr(groupNewProp);
  52295. } else {
  52296. updateProps(group, groupNewProp, seriesModel);
  52297. }
  52298. } // Fix edge contact point with node
  52299. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  52300. var data = seriesModel.getData();
  52301. symbolDraw.updateData(data);
  52302. var edgeData = seriesModel.getEdgeData(); // TODO: TYPE
  52303. lineDraw.updateData(edgeData);
  52304. this._updateNodeAndLinkScale();
  52305. this._updateController(seriesModel, ecModel, api);
  52306. clearTimeout(this._layoutTimeout);
  52307. var forceLayout = seriesModel.forceLayout;
  52308. var layoutAnimation = seriesModel.get(['force', 'layoutAnimation']);
  52309. if (forceLayout) {
  52310. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  52311. }
  52312. data.graph.eachNode(function (node) {
  52313. var idx = node.dataIndex;
  52314. var el = node.getGraphicEl();
  52315. var itemModel = node.getModel(); // Update draggable
  52316. el.off('drag').off('dragend');
  52317. var draggable = itemModel.get('draggable');
  52318. if (draggable) {
  52319. el.on('drag', function () {
  52320. if (forceLayout) {
  52321. forceLayout.warmUp();
  52322. !_this._layouting && _this._startForceLayoutIteration(forceLayout, layoutAnimation);
  52323. forceLayout.setFixed(idx); // Write position back to layout
  52324. data.setItemLayout(idx, [el.x, el.y]);
  52325. }
  52326. }).on('dragend', function () {
  52327. if (forceLayout) {
  52328. forceLayout.setUnfixed(idx);
  52329. }
  52330. });
  52331. }
  52332. el.setDraggable(draggable && !!forceLayout);
  52333. var focus = itemModel.get(['emphasis', 'focus']);
  52334. if (focus === 'adjacency') {
  52335. getECData(el).focus = node.getAdjacentDataIndices();
  52336. }
  52337. });
  52338. data.graph.eachEdge(function (edge) {
  52339. var el = edge.getGraphicEl();
  52340. var focus = edge.getModel().get(['emphasis', 'focus']);
  52341. if (focus === 'adjacency') {
  52342. getECData(el).focus = {
  52343. edge: [edge.dataIndex],
  52344. node: [edge.node1.dataIndex, edge.node2.dataIndex]
  52345. };
  52346. }
  52347. });
  52348. var circularRotateLabel = seriesModel.get('layout') === 'circular' && seriesModel.get(['circular', 'rotateLabel']);
  52349. var cx = data.getLayout('cx');
  52350. var cy = data.getLayout('cy');
  52351. data.eachItemGraphicEl(function (el, idx) {
  52352. var itemModel = data.getItemModel(idx);
  52353. var labelRotate = itemModel.get(['label', 'rotate']) || 0;
  52354. var symbolPath = el.getSymbolPath();
  52355. if (circularRotateLabel) {
  52356. var pos = data.getItemLayout(idx);
  52357. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  52358. if (rad < 0) {
  52359. rad = Math.PI * 2 + rad;
  52360. }
  52361. var isLeft = pos[0] < cx;
  52362. if (isLeft) {
  52363. rad = rad - Math.PI;
  52364. }
  52365. var textPosition = isLeft ? 'left' : 'right';
  52366. symbolPath.setTextConfig({
  52367. rotation: -rad,
  52368. position: textPosition,
  52369. origin: 'center'
  52370. });
  52371. var emphasisState = symbolPath.ensureState('emphasis');
  52372. extend(emphasisState.textConfig || (emphasisState.textConfig = {}), {
  52373. position: textPosition
  52374. });
  52375. } else {
  52376. symbolPath.setTextConfig({
  52377. rotation: labelRotate *= Math.PI / 180
  52378. });
  52379. }
  52380. });
  52381. this._firstRender = false;
  52382. };
  52383. GraphView.prototype.dispose = function () {
  52384. this._controller && this._controller.dispose();
  52385. this._controllerHost = null;
  52386. };
  52387. GraphView.prototype._startForceLayoutIteration = function (forceLayout, layoutAnimation) {
  52388. var self = this;
  52389. (function step() {
  52390. forceLayout.step(function (stopped) {
  52391. self.updateLayout(self._model);
  52392. (self._layouting = !stopped) && (layoutAnimation ? self._layoutTimeout = setTimeout(step, 16) : step());
  52393. });
  52394. })();
  52395. };
  52396. GraphView.prototype._updateController = function (seriesModel, ecModel, api) {
  52397. var _this = this;
  52398. var controller = this._controller;
  52399. var controllerHost = this._controllerHost;
  52400. var group = this.group;
  52401. controller.setPointerChecker(function (e, x, y) {
  52402. var rect = group.getBoundingRect();
  52403. rect.applyTransform(group.transform);
  52404. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  52405. });
  52406. if (!isViewCoordSys(seriesModel.coordinateSystem)) {
  52407. controller.disable();
  52408. return;
  52409. }
  52410. controller.enable(seriesModel.get('roam'));
  52411. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  52412. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  52413. controller.off('pan').off('zoom').on('pan', function (e) {
  52414. updateViewOnPan(controllerHost, e.dx, e.dy);
  52415. api.dispatchAction({
  52416. seriesId: seriesModel.id,
  52417. type: 'graphRoam',
  52418. dx: e.dx,
  52419. dy: e.dy
  52420. });
  52421. }).on('zoom', function (e) {
  52422. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  52423. api.dispatchAction({
  52424. seriesId: seriesModel.id,
  52425. type: 'graphRoam',
  52426. zoom: e.scale,
  52427. originX: e.originX,
  52428. originY: e.originY
  52429. });
  52430. _this._updateNodeAndLinkScale();
  52431. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  52432. _this._lineDraw.updateLayout(); // Only update label layout on zoom
  52433. api.updateLabelLayout();
  52434. });
  52435. };
  52436. GraphView.prototype._updateNodeAndLinkScale = function () {
  52437. var seriesModel = this._model;
  52438. var data = seriesModel.getData();
  52439. var nodeScale = getNodeGlobalScale(seriesModel);
  52440. data.eachItemGraphicEl(function (el, idx) {
  52441. el.setSymbolScale(nodeScale);
  52442. });
  52443. };
  52444. GraphView.prototype.updateLayout = function (seriesModel) {
  52445. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  52446. this._symbolDraw.updateLayout();
  52447. this._lineDraw.updateLayout();
  52448. };
  52449. GraphView.prototype.remove = function (ecModel, api) {
  52450. this._symbolDraw && this._symbolDraw.remove();
  52451. this._lineDraw && this._lineDraw.remove();
  52452. };
  52453. GraphView.type = 'graph';
  52454. return GraphView;
  52455. }(ChartView);
  52456. function generateNodeKey(id) {
  52457. return '_EC_' + id;
  52458. }
  52459. var Graph =
  52460. /** @class */
  52461. function () {
  52462. function Graph(directed) {
  52463. this.type = 'graph';
  52464. this.nodes = [];
  52465. this.edges = [];
  52466. this._nodesMap = {};
  52467. /**
  52468. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  52469. * @private
  52470. */
  52471. this._edgesMap = {};
  52472. this._directed = directed || false;
  52473. }
  52474. /**
  52475. * If is directed graph
  52476. */
  52477. Graph.prototype.isDirected = function () {
  52478. return this._directed;
  52479. };
  52480. /**
  52481. * Add a new node
  52482. */
  52483. Graph.prototype.addNode = function (id, dataIndex) {
  52484. id = id == null ? '' + dataIndex : '' + id;
  52485. var nodesMap = this._nodesMap;
  52486. if (nodesMap[generateNodeKey(id)]) {
  52487. if ("development" !== 'production') {
  52488. console.error('Graph nodes have duplicate name or id');
  52489. }
  52490. return;
  52491. }
  52492. var node = new GraphNode(id, dataIndex);
  52493. node.hostGraph = this;
  52494. this.nodes.push(node);
  52495. nodesMap[generateNodeKey(id)] = node;
  52496. return node;
  52497. };
  52498. /**
  52499. * Get node by data index
  52500. */
  52501. Graph.prototype.getNodeByIndex = function (dataIndex) {
  52502. var rawIdx = this.data.getRawIndex(dataIndex);
  52503. return this.nodes[rawIdx];
  52504. };
  52505. /**
  52506. * Get node by id
  52507. */
  52508. Graph.prototype.getNodeById = function (id) {
  52509. return this._nodesMap[generateNodeKey(id)];
  52510. };
  52511. /**
  52512. * Add a new edge
  52513. */
  52514. Graph.prototype.addEdge = function (n1, n2, dataIndex) {
  52515. var nodesMap = this._nodesMap;
  52516. var edgesMap = this._edgesMap; // PNEDING
  52517. if (typeof n1 === 'number') {
  52518. n1 = this.nodes[n1];
  52519. }
  52520. if (typeof n2 === 'number') {
  52521. n2 = this.nodes[n2];
  52522. }
  52523. if (!(n1 instanceof GraphNode)) {
  52524. n1 = nodesMap[generateNodeKey(n1)];
  52525. }
  52526. if (!(n2 instanceof GraphNode)) {
  52527. n2 = nodesMap[generateNodeKey(n2)];
  52528. }
  52529. if (!n1 || !n2) {
  52530. return;
  52531. }
  52532. var key = n1.id + '-' + n2.id;
  52533. var edge = new GraphEdge(n1, n2, dataIndex);
  52534. edge.hostGraph = this;
  52535. if (this._directed) {
  52536. n1.outEdges.push(edge);
  52537. n2.inEdges.push(edge);
  52538. }
  52539. n1.edges.push(edge);
  52540. if (n1 !== n2) {
  52541. n2.edges.push(edge);
  52542. }
  52543. this.edges.push(edge);
  52544. edgesMap[key] = edge;
  52545. return edge;
  52546. };
  52547. /**
  52548. * Get edge by data index
  52549. */
  52550. Graph.prototype.getEdgeByIndex = function (dataIndex) {
  52551. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  52552. return this.edges[rawIdx];
  52553. };
  52554. /**
  52555. * Get edge by two linked nodes
  52556. */
  52557. Graph.prototype.getEdge = function (n1, n2) {
  52558. if (n1 instanceof GraphNode) {
  52559. n1 = n1.id;
  52560. }
  52561. if (n2 instanceof GraphNode) {
  52562. n2 = n2.id;
  52563. }
  52564. var edgesMap = this._edgesMap;
  52565. if (this._directed) {
  52566. return edgesMap[n1 + '-' + n2];
  52567. } else {
  52568. return edgesMap[n1 + '-' + n2] || edgesMap[n2 + '-' + n1];
  52569. }
  52570. };
  52571. /**
  52572. * Iterate all nodes
  52573. */
  52574. Graph.prototype.eachNode = function (cb, context) {
  52575. var nodes = this.nodes;
  52576. var len = nodes.length;
  52577. for (var i = 0; i < len; i++) {
  52578. if (nodes[i].dataIndex >= 0) {
  52579. cb.call(context, nodes[i], i);
  52580. }
  52581. }
  52582. };
  52583. /**
  52584. * Iterate all edges
  52585. */
  52586. Graph.prototype.eachEdge = function (cb, context) {
  52587. var edges = this.edges;
  52588. var len = edges.length;
  52589. for (var i = 0; i < len; i++) {
  52590. if (edges[i].dataIndex >= 0 && edges[i].node1.dataIndex >= 0 && edges[i].node2.dataIndex >= 0) {
  52591. cb.call(context, edges[i], i);
  52592. }
  52593. }
  52594. };
  52595. /**
  52596. * Breadth first traverse
  52597. * Return true to stop traversing
  52598. */
  52599. Graph.prototype.breadthFirstTraverse = function (cb, startNode, direction, context) {
  52600. if (!(startNode instanceof GraphNode)) {
  52601. startNode = this._nodesMap[generateNodeKey(startNode)];
  52602. }
  52603. if (!startNode) {
  52604. return;
  52605. }
  52606. var edgeType = direction === 'out' ? 'outEdges' : direction === 'in' ? 'inEdges' : 'edges';
  52607. for (var i = 0; i < this.nodes.length; i++) {
  52608. this.nodes[i].__visited = false;
  52609. }
  52610. if (cb.call(context, startNode, null)) {
  52611. return;
  52612. }
  52613. var queue = [startNode];
  52614. while (queue.length) {
  52615. var currentNode = queue.shift();
  52616. var edges = currentNode[edgeType];
  52617. for (var i = 0; i < edges.length; i++) {
  52618. var e = edges[i];
  52619. var otherNode = e.node1 === currentNode ? e.node2 : e.node1;
  52620. if (!otherNode.__visited) {
  52621. if (cb.call(context, otherNode, currentNode)) {
  52622. // Stop traversing
  52623. return;
  52624. }
  52625. queue.push(otherNode);
  52626. otherNode.__visited = true;
  52627. }
  52628. }
  52629. }
  52630. };
  52631. // depthFirstTraverse(
  52632. // cb, startNode, direction, context
  52633. // ) {
  52634. // };
  52635. // Filter update
  52636. Graph.prototype.update = function () {
  52637. var data = this.data;
  52638. var edgeData = this.edgeData;
  52639. var nodes = this.nodes;
  52640. var edges = this.edges;
  52641. for (var i = 0, len = nodes.length; i < len; i++) {
  52642. nodes[i].dataIndex = -1;
  52643. }
  52644. for (var i = 0, len = data.count(); i < len; i++) {
  52645. nodes[data.getRawIndex(i)].dataIndex = i;
  52646. }
  52647. edgeData.filterSelf(function (idx) {
  52648. var edge = edges[edgeData.getRawIndex(idx)];
  52649. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  52650. }); // Update edge
  52651. for (var i = 0, len = edges.length; i < len; i++) {
  52652. edges[i].dataIndex = -1;
  52653. }
  52654. for (var i = 0, len = edgeData.count(); i < len; i++) {
  52655. edges[edgeData.getRawIndex(i)].dataIndex = i;
  52656. }
  52657. };
  52658. /**
  52659. * @return {module:echarts/data/Graph}
  52660. */
  52661. Graph.prototype.clone = function () {
  52662. var graph = new Graph(this._directed);
  52663. var nodes = this.nodes;
  52664. var edges = this.edges;
  52665. for (var i = 0; i < nodes.length; i++) {
  52666. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  52667. }
  52668. for (var i = 0; i < edges.length; i++) {
  52669. var e = edges[i];
  52670. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  52671. }
  52672. return graph;
  52673. };
  52674. return Graph;
  52675. }();
  52676. var GraphNode =
  52677. /** @class */
  52678. function () {
  52679. function GraphNode(id, dataIndex) {
  52680. this.inEdges = [];
  52681. this.outEdges = [];
  52682. this.edges = [];
  52683. this.dataIndex = -1;
  52684. this.id = id == null ? '' : id;
  52685. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  52686. }
  52687. /**
  52688. * @return {number}
  52689. */
  52690. GraphNode.prototype.degree = function () {
  52691. return this.edges.length;
  52692. };
  52693. /**
  52694. * @return {number}
  52695. */
  52696. GraphNode.prototype.inDegree = function () {
  52697. return this.inEdges.length;
  52698. };
  52699. /**
  52700. * @return {number}
  52701. */
  52702. GraphNode.prototype.outDegree = function () {
  52703. return this.outEdges.length;
  52704. };
  52705. GraphNode.prototype.getModel = function (path) {
  52706. if (this.dataIndex < 0) {
  52707. return;
  52708. }
  52709. var graph = this.hostGraph;
  52710. var itemModel = graph.data.getItemModel(this.dataIndex);
  52711. return itemModel.getModel(path);
  52712. };
  52713. GraphNode.prototype.getAdjacentDataIndices = function () {
  52714. var dataIndices = {
  52715. edge: [],
  52716. node: []
  52717. };
  52718. for (var i = 0; i < this.edges.length; i++) {
  52719. var adjacentEdge = this.edges[i];
  52720. if (adjacentEdge.dataIndex < 0) {
  52721. continue;
  52722. }
  52723. dataIndices.edge.push(adjacentEdge.dataIndex);
  52724. dataIndices.node.push(adjacentEdge.node1.dataIndex, adjacentEdge.node2.dataIndex);
  52725. }
  52726. return dataIndices;
  52727. };
  52728. return GraphNode;
  52729. }();
  52730. var GraphEdge =
  52731. /** @class */
  52732. function () {
  52733. function GraphEdge(n1, n2, dataIndex) {
  52734. this.dataIndex = -1;
  52735. this.node1 = n1;
  52736. this.node2 = n2;
  52737. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  52738. } // eslint-disable-next-line @typescript-eslint/no-unused-vars
  52739. GraphEdge.prototype.getModel = function (path) {
  52740. if (this.dataIndex < 0) {
  52741. return;
  52742. }
  52743. var graph = this.hostGraph;
  52744. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  52745. return itemModel.getModel(path);
  52746. };
  52747. GraphEdge.prototype.getAdjacentDataIndices = function () {
  52748. return {
  52749. edge: [this.dataIndex],
  52750. node: [this.node1.dataIndex, this.node2.dataIndex]
  52751. };
  52752. };
  52753. return GraphEdge;
  52754. }();
  52755. function createGraphDataProxyMixin(hostName, dataName) {
  52756. return {
  52757. /**
  52758. * @param Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  52759. */
  52760. getValue: function (dimension) {
  52761. var data = this[hostName][dataName];
  52762. return data.getStore().get(data.getDimensionIndex(dimension || 'value'), this.dataIndex);
  52763. },
  52764. // TODO: TYPE stricter type.
  52765. setVisual: function (key, value) {
  52766. this.dataIndex >= 0 && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  52767. },
  52768. getVisual: function (key) {
  52769. return this[hostName][dataName].getItemVisual(this.dataIndex, key);
  52770. },
  52771. setLayout: function (layout, merge) {
  52772. this.dataIndex >= 0 && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge);
  52773. },
  52774. getLayout: function () {
  52775. return this[hostName][dataName].getItemLayout(this.dataIndex);
  52776. },
  52777. getGraphicEl: function () {
  52778. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  52779. },
  52780. getRawIndex: function () {
  52781. return this[hostName][dataName].getRawIndex(this.dataIndex);
  52782. }
  52783. };
  52784. }
  52785. mixin(GraphNode, createGraphDataProxyMixin('hostGraph', 'data'));
  52786. mixin(GraphEdge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  52787. function createGraphFromNodeEdge(nodes, edges, seriesModel, directed, beforeLink) {
  52788. // ??? TODO
  52789. // support dataset?
  52790. var graph = new Graph(directed);
  52791. for (var i = 0; i < nodes.length; i++) {
  52792. graph.addNode(retrieve( // Id, name, dataIndex
  52793. nodes[i].id, nodes[i].name, i), i);
  52794. }
  52795. var linkNameList = [];
  52796. var validEdges = [];
  52797. var linkCount = 0;
  52798. for (var i = 0; i < edges.length; i++) {
  52799. var link = edges[i];
  52800. var source = link.source;
  52801. var target = link.target; // addEdge may fail when source or target not exists
  52802. if (graph.addEdge(source, target, linkCount)) {
  52803. validEdges.push(link);
  52804. linkNameList.push(retrieve(convertOptionIdName(link.id, null), source + ' > ' + target));
  52805. linkCount++;
  52806. }
  52807. }
  52808. var coordSys = seriesModel.get('coordinateSystem');
  52809. var nodeData;
  52810. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  52811. nodeData = createSeriesData(nodes, seriesModel);
  52812. } else {
  52813. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  52814. var coordDimensions = coordSysCtor ? coordSysCtor.dimensions || [] : []; // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  52815. // `value` dimension, but graph need `value` dimension. It's better to
  52816. // uniform this behavior.
  52817. if (indexOf(coordDimensions, 'value') < 0) {
  52818. coordDimensions.concat(['value']);
  52819. }
  52820. var dimensions = prepareSeriesDataSchema(nodes, {
  52821. coordDimensions: coordDimensions,
  52822. encodeDefine: seriesModel.getEncode()
  52823. }).dimensions;
  52824. nodeData = new SeriesData(dimensions, seriesModel);
  52825. nodeData.initData(nodes);
  52826. }
  52827. var edgeData = new SeriesData(['value'], seriesModel);
  52828. edgeData.initData(validEdges, linkNameList);
  52829. beforeLink && beforeLink(nodeData, edgeData);
  52830. linkSeriesData({
  52831. mainData: nodeData,
  52832. struct: graph,
  52833. structAttr: 'graph',
  52834. datas: {
  52835. node: nodeData,
  52836. edge: edgeData
  52837. },
  52838. datasAttr: {
  52839. node: 'data',
  52840. edge: 'edgeData'
  52841. }
  52842. }); // Update dataIndex of nodes and edges because invalid edge may be removed
  52843. graph.update();
  52844. return graph;
  52845. }
  52846. var GraphSeriesModel =
  52847. /** @class */
  52848. function (_super) {
  52849. __extends(GraphSeriesModel, _super);
  52850. function GraphSeriesModel() {
  52851. var _this = _super !== null && _super.apply(this, arguments) || this;
  52852. _this.type = GraphSeriesModel.type;
  52853. _this.hasSymbolVisual = true;
  52854. return _this;
  52855. }
  52856. GraphSeriesModel.prototype.init = function (option) {
  52857. _super.prototype.init.apply(this, arguments);
  52858. var self = this;
  52859. function getCategoriesData() {
  52860. return self._categoriesData;
  52861. } // Provide data for legend select
  52862. this.legendVisualProvider = new LegendVisualProvider(getCategoriesData, getCategoriesData);
  52863. this.fillDataTextStyle(option.edges || option.links);
  52864. this._updateCategoriesData();
  52865. };
  52866. GraphSeriesModel.prototype.mergeOption = function (option) {
  52867. _super.prototype.mergeOption.apply(this, arguments);
  52868. this.fillDataTextStyle(option.edges || option.links);
  52869. this._updateCategoriesData();
  52870. };
  52871. GraphSeriesModel.prototype.mergeDefaultAndTheme = function (option) {
  52872. _super.prototype.mergeDefaultAndTheme.apply(this, arguments);
  52873. defaultEmphasis(option, 'edgeLabel', ['show']);
  52874. };
  52875. GraphSeriesModel.prototype.getInitialData = function (option, ecModel) {
  52876. var edges = option.edges || option.links || [];
  52877. var nodes = option.data || option.nodes || [];
  52878. var self = this;
  52879. if (nodes && edges) {
  52880. // auto curveness
  52881. initCurvenessList(this);
  52882. var graph = createGraphFromNodeEdge(nodes, edges, this, true, beforeLink);
  52883. each(graph.edges, function (edge) {
  52884. createEdgeMapForCurveness(edge.node1, edge.node2, this, edge.dataIndex);
  52885. }, this);
  52886. return graph.data;
  52887. }
  52888. function beforeLink(nodeData, edgeData) {
  52889. // Overwrite nodeData.getItemModel to
  52890. nodeData.wrapMethod('getItemModel', function (model) {
  52891. var categoriesModels = self._categoriesModels;
  52892. var categoryIdx = model.getShallow('category');
  52893. var categoryModel = categoriesModels[categoryIdx];
  52894. if (categoryModel) {
  52895. categoryModel.parentModel = model.parentModel;
  52896. model.parentModel = categoryModel;
  52897. }
  52898. return model;
  52899. }); // TODO Inherit resolveParentPath by default in Model#getModel?
  52900. var oldGetModel = Model.prototype.getModel;
  52901. function newGetModel(path, parentModel) {
  52902. var model = oldGetModel.call(this, path, parentModel);
  52903. model.resolveParentPath = resolveParentPath;
  52904. return model;
  52905. }
  52906. edgeData.wrapMethod('getItemModel', function (model) {
  52907. model.resolveParentPath = resolveParentPath;
  52908. model.getModel = newGetModel;
  52909. return model;
  52910. });
  52911. function resolveParentPath(pathArr) {
  52912. if (pathArr && (pathArr[0] === 'label' || pathArr[1] === 'label')) {
  52913. var newPathArr = pathArr.slice();
  52914. if (pathArr[0] === 'label') {
  52915. newPathArr[0] = 'edgeLabel';
  52916. } else if (pathArr[1] === 'label') {
  52917. newPathArr[1] = 'edgeLabel';
  52918. }
  52919. return newPathArr;
  52920. }
  52921. return pathArr;
  52922. }
  52923. }
  52924. };
  52925. GraphSeriesModel.prototype.getGraph = function () {
  52926. return this.getData().graph;
  52927. };
  52928. GraphSeriesModel.prototype.getEdgeData = function () {
  52929. return this.getGraph().edgeData;
  52930. };
  52931. GraphSeriesModel.prototype.getCategoriesData = function () {
  52932. return this._categoriesData;
  52933. };
  52934. GraphSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  52935. if (dataType === 'edge') {
  52936. var nodeData = this.getData();
  52937. var params = this.getDataParams(dataIndex, dataType);
  52938. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  52939. var sourceName = nodeData.getName(edge.node1.dataIndex);
  52940. var targetName = nodeData.getName(edge.node2.dataIndex);
  52941. var nameArr = [];
  52942. sourceName != null && nameArr.push(sourceName);
  52943. targetName != null && nameArr.push(targetName);
  52944. return createTooltipMarkup('nameValue', {
  52945. name: nameArr.join(' > '),
  52946. value: params.value,
  52947. noValue: params.value == null
  52948. });
  52949. } // dataType === 'node' or empty
  52950. var nodeMarkup = defaultSeriesFormatTooltip({
  52951. series: this,
  52952. dataIndex: dataIndex,
  52953. multipleSeries: multipleSeries
  52954. });
  52955. return nodeMarkup;
  52956. };
  52957. GraphSeriesModel.prototype._updateCategoriesData = function () {
  52958. var categories = map(this.option.categories || [], function (category) {
  52959. // Data must has value
  52960. return category.value != null ? category : extend({
  52961. value: 0
  52962. }, category);
  52963. });
  52964. var categoriesData = new SeriesData(['value'], this);
  52965. categoriesData.initData(categories);
  52966. this._categoriesData = categoriesData;
  52967. this._categoriesModels = categoriesData.mapArray(function (idx) {
  52968. return categoriesData.getItemModel(idx);
  52969. });
  52970. };
  52971. GraphSeriesModel.prototype.setZoom = function (zoom) {
  52972. this.option.zoom = zoom;
  52973. };
  52974. GraphSeriesModel.prototype.setCenter = function (center) {
  52975. this.option.center = center;
  52976. };
  52977. GraphSeriesModel.prototype.isAnimationEnabled = function () {
  52978. return _super.prototype.isAnimationEnabled.call(this) // Not enable animation when do force layout
  52979. && !(this.get('layout') === 'force' && this.get(['force', 'layoutAnimation']));
  52980. };
  52981. GraphSeriesModel.type = 'series.graph';
  52982. GraphSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  52983. GraphSeriesModel.defaultOption = {
  52984. zlevel: 0,
  52985. z: 2,
  52986. coordinateSystem: 'view',
  52987. // Default option for all coordinate systems
  52988. // xAxisIndex: 0,
  52989. // yAxisIndex: 0,
  52990. // polarIndex: 0,
  52991. // geoIndex: 0,
  52992. legendHoverLink: true,
  52993. layout: null,
  52994. // Configuration of circular layout
  52995. circular: {
  52996. rotateLabel: false
  52997. },
  52998. // Configuration of force directed layout
  52999. force: {
  53000. initLayout: null,
  53001. // Node repulsion. Can be an array to represent range.
  53002. repulsion: [0, 50],
  53003. gravity: 0.1,
  53004. // Initial friction
  53005. friction: 0.6,
  53006. // Edge length. Can be an array to represent range.
  53007. edgeLength: 30,
  53008. layoutAnimation: true
  53009. },
  53010. left: 'center',
  53011. top: 'center',
  53012. // right: null,
  53013. // bottom: null,
  53014. // width: '80%',
  53015. // height: '80%',
  53016. symbol: 'circle',
  53017. symbolSize: 10,
  53018. edgeSymbol: ['none', 'none'],
  53019. edgeSymbolSize: 10,
  53020. edgeLabel: {
  53021. position: 'middle',
  53022. distance: 5
  53023. },
  53024. draggable: false,
  53025. roam: false,
  53026. // Default on center of graph
  53027. center: null,
  53028. zoom: 1,
  53029. // Symbol size scale ratio in roam
  53030. nodeScaleRatio: 0.6,
  53031. // cursor: null,
  53032. // categories: [],
  53033. // data: []
  53034. // Or
  53035. // nodes: []
  53036. //
  53037. // links: []
  53038. // Or
  53039. // edges: []
  53040. label: {
  53041. show: false,
  53042. formatter: '{b}'
  53043. },
  53044. itemStyle: {},
  53045. lineStyle: {
  53046. color: '#aaa',
  53047. width: 1,
  53048. opacity: 0.5
  53049. },
  53050. emphasis: {
  53051. scale: true,
  53052. label: {
  53053. show: true
  53054. }
  53055. },
  53056. select: {
  53057. itemStyle: {
  53058. borderColor: '#212121'
  53059. }
  53060. }
  53061. };
  53062. return GraphSeriesModel;
  53063. }(SeriesModel);
  53064. var actionInfo = {
  53065. type: 'graphRoam',
  53066. event: 'graphRoam',
  53067. update: 'none'
  53068. };
  53069. function install$d(registers) {
  53070. registers.registerChartView(GraphView);
  53071. registers.registerSeriesModel(GraphSeriesModel);
  53072. registers.registerProcessor(categoryFilter);
  53073. registers.registerVisual(categoryVisual);
  53074. registers.registerVisual(graphEdgeVisual);
  53075. registers.registerLayout(graphSimpleLayout);
  53076. registers.registerLayout(registers.PRIORITY.VISUAL.POST_CHART_LAYOUT, graphCircularLayout);
  53077. registers.registerLayout(graphForceLayout);
  53078. registers.registerCoordinateSystem('graphView', {
  53079. dimensions: View.dimensions,
  53080. create: createViewCoordSys
  53081. }); // Register legacy focus actions
  53082. registers.registerAction({
  53083. type: 'focusNodeAdjacency',
  53084. event: 'focusNodeAdjacency',
  53085. update: 'series:focusNodeAdjacency'
  53086. }, function () {});
  53087. registers.registerAction({
  53088. type: 'unfocusNodeAdjacency',
  53089. event: 'unfocusNodeAdjacency',
  53090. update: 'series:unfocusNodeAdjacency'
  53091. }, function () {}); // Register roam action.
  53092. registers.registerAction(actionInfo, function (payload, ecModel) {
  53093. ecModel.eachComponent({
  53094. mainType: 'series',
  53095. query: payload
  53096. }, function (seriesModel) {
  53097. var coordSys = seriesModel.coordinateSystem;
  53098. var res = updateCenterAndZoom(coordSys, payload);
  53099. seriesModel.setCenter && seriesModel.setCenter(res.center);
  53100. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  53101. });
  53102. });
  53103. }
  53104. var PointerShape =
  53105. /** @class */
  53106. function () {
  53107. function PointerShape() {
  53108. this.angle = 0;
  53109. this.width = 10;
  53110. this.r = 10;
  53111. this.x = 0;
  53112. this.y = 0;
  53113. }
  53114. return PointerShape;
  53115. }();
  53116. var PointerPath =
  53117. /** @class */
  53118. function (_super) {
  53119. __extends(PointerPath, _super);
  53120. function PointerPath(opts) {
  53121. var _this = _super.call(this, opts) || this;
  53122. _this.type = 'pointer';
  53123. return _this;
  53124. }
  53125. PointerPath.prototype.getDefaultShape = function () {
  53126. return new PointerShape();
  53127. };
  53128. PointerPath.prototype.buildPath = function (ctx, shape) {
  53129. var mathCos = Math.cos;
  53130. var mathSin = Math.sin;
  53131. var r = shape.r;
  53132. var width = shape.width;
  53133. var angle = shape.angle;
  53134. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  53135. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  53136. angle = shape.angle - Math.PI / 2;
  53137. ctx.moveTo(x, y);
  53138. ctx.lineTo(shape.x + mathCos(angle) * width, shape.y + mathSin(angle) * width);
  53139. ctx.lineTo(shape.x + mathCos(shape.angle) * r, shape.y + mathSin(shape.angle) * r);
  53140. ctx.lineTo(shape.x - mathCos(angle) * width, shape.y - mathSin(angle) * width);
  53141. ctx.lineTo(x, y);
  53142. };
  53143. return PointerPath;
  53144. }(Path);
  53145. function parsePosition(seriesModel, api) {
  53146. var center = seriesModel.get('center');
  53147. var width = api.getWidth();
  53148. var height = api.getHeight();
  53149. var size = Math.min(width, height);
  53150. var cx = parsePercent$1(center[0], api.getWidth());
  53151. var cy = parsePercent$1(center[1], api.getHeight());
  53152. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  53153. return {
  53154. cx: cx,
  53155. cy: cy,
  53156. r: r
  53157. };
  53158. }
  53159. function formatLabel(value, labelFormatter) {
  53160. var label = value == null ? '' : value + '';
  53161. if (labelFormatter) {
  53162. if (typeof labelFormatter === 'string') {
  53163. label = labelFormatter.replace('{value}', label);
  53164. } else if (typeof labelFormatter === 'function') {
  53165. label = labelFormatter(value);
  53166. }
  53167. }
  53168. return label;
  53169. }
  53170. var PI2$9 = Math.PI * 2;
  53171. var GaugeView =
  53172. /** @class */
  53173. function (_super) {
  53174. __extends(GaugeView, _super);
  53175. function GaugeView() {
  53176. var _this = _super !== null && _super.apply(this, arguments) || this;
  53177. _this.type = GaugeView.type;
  53178. return _this;
  53179. }
  53180. GaugeView.prototype.render = function (seriesModel, ecModel, api) {
  53181. this.group.removeAll();
  53182. var colorList = seriesModel.get(['axisLine', 'lineStyle', 'color']);
  53183. var posInfo = parsePosition(seriesModel, api);
  53184. this._renderMain(seriesModel, ecModel, api, colorList, posInfo);
  53185. this._data = seriesModel.getData();
  53186. };
  53187. GaugeView.prototype.dispose = function () {};
  53188. GaugeView.prototype._renderMain = function (seriesModel, ecModel, api, colorList, posInfo) {
  53189. var group = this.group;
  53190. var clockwise = seriesModel.get('clockwise');
  53191. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  53192. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  53193. var axisLineModel = seriesModel.getModel('axisLine');
  53194. var roundCap = axisLineModel.get('roundCap');
  53195. var MainPath = roundCap ? SausagePath : Sector;
  53196. var showAxis = axisLineModel.get('show');
  53197. var lineStyleModel = axisLineModel.getModel('lineStyle');
  53198. var axisLineWidth = lineStyleModel.get('width');
  53199. var angleRangeSpan = !((endAngle - startAngle) % PI2$9) && endAngle !== startAngle ? PI2$9 : (endAngle - startAngle) % PI2$9;
  53200. var prevEndAngle = startAngle;
  53201. for (var i = 0; showAxis && i < colorList.length; i++) {
  53202. // Clamp
  53203. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  53204. endAngle = startAngle + angleRangeSpan * percent;
  53205. var sector = new MainPath({
  53206. shape: {
  53207. startAngle: prevEndAngle,
  53208. endAngle: endAngle,
  53209. cx: posInfo.cx,
  53210. cy: posInfo.cy,
  53211. clockwise: clockwise,
  53212. r0: posInfo.r - axisLineWidth,
  53213. r: posInfo.r
  53214. },
  53215. silent: true
  53216. });
  53217. sector.setStyle({
  53218. fill: colorList[i][1]
  53219. });
  53220. sector.setStyle(lineStyleModel.getLineStyle( // Because we use sector to simulate arc
  53221. // so the properties for stroking are useless
  53222. ['color', 'width']));
  53223. group.add(sector);
  53224. prevEndAngle = endAngle;
  53225. }
  53226. var getColor = function (percent) {
  53227. // Less than 0
  53228. if (percent <= 0) {
  53229. return colorList[0][1];
  53230. }
  53231. var i;
  53232. for (i = 0; i < colorList.length; i++) {
  53233. if (colorList[i][0] >= percent && (i === 0 ? 0 : colorList[i - 1][0]) < percent) {
  53234. return colorList[i][1];
  53235. }
  53236. } // More than 1
  53237. return colorList[i - 1][1];
  53238. };
  53239. if (!clockwise) {
  53240. var tmp = startAngle;
  53241. startAngle = endAngle;
  53242. endAngle = tmp;
  53243. }
  53244. this._renderTicks(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  53245. this._renderTitleAndDetail(seriesModel, ecModel, api, getColor, posInfo);
  53246. this._renderAnchor(seriesModel, posInfo);
  53247. this._renderPointer(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  53248. };
  53249. GaugeView.prototype._renderTicks = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  53250. var group = this.group;
  53251. var cx = posInfo.cx;
  53252. var cy = posInfo.cy;
  53253. var r = posInfo.r;
  53254. var minVal = +seriesModel.get('min');
  53255. var maxVal = +seriesModel.get('max');
  53256. var splitLineModel = seriesModel.getModel('splitLine');
  53257. var tickModel = seriesModel.getModel('axisTick');
  53258. var labelModel = seriesModel.getModel('axisLabel');
  53259. var splitNumber = seriesModel.get('splitNumber');
  53260. var subSplitNumber = tickModel.get('splitNumber');
  53261. var splitLineLen = parsePercent$1(splitLineModel.get('length'), r);
  53262. var tickLen = parsePercent$1(tickModel.get('length'), r);
  53263. var angle = startAngle;
  53264. var step = (endAngle - startAngle) / splitNumber;
  53265. var subStep = step / subSplitNumber;
  53266. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  53267. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  53268. var splitLineDistance = splitLineModel.get('distance');
  53269. var unitX;
  53270. var unitY;
  53271. for (var i = 0; i <= splitNumber; i++) {
  53272. unitX = Math.cos(angle);
  53273. unitY = Math.sin(angle); // Split line
  53274. if (splitLineModel.get('show')) {
  53275. var distance = splitLineDistance ? splitLineDistance + axisLineWidth : axisLineWidth;
  53276. var splitLine = new Line({
  53277. shape: {
  53278. x1: unitX * (r - distance) + cx,
  53279. y1: unitY * (r - distance) + cy,
  53280. x2: unitX * (r - splitLineLen - distance) + cx,
  53281. y2: unitY * (r - splitLineLen - distance) + cy
  53282. },
  53283. style: splitLineStyle,
  53284. silent: true
  53285. });
  53286. if (splitLineStyle.stroke === 'auto') {
  53287. splitLine.setStyle({
  53288. stroke: getColor(i / splitNumber)
  53289. });
  53290. }
  53291. group.add(splitLine);
  53292. } // Label
  53293. if (labelModel.get('show')) {
  53294. var distance = labelModel.get('distance') + splitLineDistance;
  53295. var label = formatLabel(round(i / splitNumber * (maxVal - minVal) + minVal), labelModel.get('formatter'));
  53296. var autoColor = getColor(i / splitNumber);
  53297. group.add(new ZRText({
  53298. style: createTextStyle(labelModel, {
  53299. text: label,
  53300. x: unitX * (r - splitLineLen - distance) + cx,
  53301. y: unitY * (r - splitLineLen - distance) + cy,
  53302. verticalAlign: unitY < -0.8 ? 'top' : unitY > 0.8 ? 'bottom' : 'middle',
  53303. align: unitX < -0.4 ? 'left' : unitX > 0.4 ? 'right' : 'center'
  53304. }, {
  53305. inheritColor: autoColor
  53306. }),
  53307. silent: true
  53308. }));
  53309. } // Axis tick
  53310. if (tickModel.get('show') && i !== splitNumber) {
  53311. var distance = tickModel.get('distance');
  53312. distance = distance ? distance + axisLineWidth : axisLineWidth;
  53313. for (var j = 0; j <= subSplitNumber; j++) {
  53314. unitX = Math.cos(angle);
  53315. unitY = Math.sin(angle);
  53316. var tickLine = new Line({
  53317. shape: {
  53318. x1: unitX * (r - distance) + cx,
  53319. y1: unitY * (r - distance) + cy,
  53320. x2: unitX * (r - tickLen - distance) + cx,
  53321. y2: unitY * (r - tickLen - distance) + cy
  53322. },
  53323. silent: true,
  53324. style: tickLineStyle
  53325. });
  53326. if (tickLineStyle.stroke === 'auto') {
  53327. tickLine.setStyle({
  53328. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  53329. });
  53330. }
  53331. group.add(tickLine);
  53332. angle += subStep;
  53333. }
  53334. angle -= subStep;
  53335. } else {
  53336. angle += step;
  53337. }
  53338. }
  53339. };
  53340. GaugeView.prototype._renderPointer = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  53341. var group = this.group;
  53342. var oldData = this._data;
  53343. var oldProgressData = this._progressEls;
  53344. var progressList = [];
  53345. var showPointer = seriesModel.get(['pointer', 'show']);
  53346. var progressModel = seriesModel.getModel('progress');
  53347. var showProgress = progressModel.get('show');
  53348. var data = seriesModel.getData();
  53349. var valueDim = data.mapDimension('value');
  53350. var minVal = +seriesModel.get('min');
  53351. var maxVal = +seriesModel.get('max');
  53352. var valueExtent = [minVal, maxVal];
  53353. var angleExtent = [startAngle, endAngle];
  53354. function createPointer(idx, angle) {
  53355. var itemModel = data.getItemModel(idx);
  53356. var pointerModel = itemModel.getModel('pointer');
  53357. var pointerWidth = parsePercent$1(pointerModel.get('width'), posInfo.r);
  53358. var pointerLength = parsePercent$1(pointerModel.get('length'), posInfo.r);
  53359. var pointerStr = seriesModel.get(['pointer', 'icon']);
  53360. var pointerOffset = pointerModel.get('offsetCenter');
  53361. var pointerOffsetX = parsePercent$1(pointerOffset[0], posInfo.r);
  53362. var pointerOffsetY = parsePercent$1(pointerOffset[1], posInfo.r);
  53363. var pointerKeepAspect = pointerModel.get('keepAspect');
  53364. var pointer; // not exist icon type will be set 'rect'
  53365. if (pointerStr) {
  53366. pointer = createSymbol(pointerStr, pointerOffsetX - pointerWidth / 2, pointerOffsetY - pointerLength, pointerWidth, pointerLength, null, pointerKeepAspect);
  53367. } else {
  53368. pointer = new PointerPath({
  53369. shape: {
  53370. angle: -Math.PI / 2,
  53371. width: pointerWidth,
  53372. r: pointerLength,
  53373. x: pointerOffsetX,
  53374. y: pointerOffsetY
  53375. }
  53376. });
  53377. }
  53378. pointer.rotation = -(angle + Math.PI / 2);
  53379. pointer.x = posInfo.cx;
  53380. pointer.y = posInfo.cy;
  53381. return pointer;
  53382. }
  53383. function createProgress(idx, endAngle) {
  53384. var roundCap = progressModel.get('roundCap');
  53385. var ProgressPath = roundCap ? SausagePath : Sector;
  53386. var isOverlap = progressModel.get('overlap');
  53387. var progressWidth = isOverlap ? progressModel.get('width') : axisLineWidth / data.count();
  53388. var r0 = isOverlap ? posInfo.r - progressWidth : posInfo.r - (idx + 1) * progressWidth;
  53389. var r = isOverlap ? posInfo.r : posInfo.r - idx * progressWidth;
  53390. var progress = new ProgressPath({
  53391. shape: {
  53392. startAngle: startAngle,
  53393. endAngle: endAngle,
  53394. cx: posInfo.cx,
  53395. cy: posInfo.cy,
  53396. clockwise: clockwise,
  53397. r0: r0,
  53398. r: r
  53399. }
  53400. });
  53401. isOverlap && (progress.z2 = maxVal - data.get(valueDim, idx) % maxVal);
  53402. return progress;
  53403. }
  53404. if (showProgress || showPointer) {
  53405. data.diff(oldData).add(function (idx) {
  53406. if (showPointer) {
  53407. var pointer = createPointer(idx, startAngle);
  53408. initProps(pointer, {
  53409. rotation: -(linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true) + Math.PI / 2)
  53410. }, seriesModel);
  53411. group.add(pointer);
  53412. data.setItemGraphicEl(idx, pointer);
  53413. }
  53414. if (showProgress) {
  53415. var progress = createProgress(idx, startAngle);
  53416. var isClip = progressModel.get('clip');
  53417. initProps(progress, {
  53418. shape: {
  53419. endAngle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, isClip)
  53420. }
  53421. }, seriesModel);
  53422. group.add(progress); // Add data index and series index for indexing the data by element
  53423. // Useful in tooltip
  53424. setCommonECData(seriesModel.seriesIndex, data.dataType, idx, progress);
  53425. progressList[idx] = progress;
  53426. }
  53427. }).update(function (newIdx, oldIdx) {
  53428. if (showPointer) {
  53429. var previousPointer = oldData.getItemGraphicEl(oldIdx);
  53430. var previousRotate = previousPointer ? previousPointer.rotation : startAngle;
  53431. var pointer = createPointer(newIdx, previousRotate);
  53432. pointer.rotation = previousRotate;
  53433. updateProps(pointer, {
  53434. rotation: -(linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true) + Math.PI / 2)
  53435. }, seriesModel);
  53436. group.add(pointer);
  53437. data.setItemGraphicEl(newIdx, pointer);
  53438. }
  53439. if (showProgress) {
  53440. var previousProgress = oldProgressData[oldIdx];
  53441. var previousEndAngle = previousProgress ? previousProgress.shape.endAngle : startAngle;
  53442. var progress = createProgress(newIdx, previousEndAngle);
  53443. var isClip = progressModel.get('clip');
  53444. updateProps(progress, {
  53445. shape: {
  53446. endAngle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, isClip)
  53447. }
  53448. }, seriesModel);
  53449. group.add(progress); // Add data index and series index for indexing the data by element
  53450. // Useful in tooltip
  53451. setCommonECData(seriesModel.seriesIndex, data.dataType, newIdx, progress);
  53452. progressList[newIdx] = progress;
  53453. }
  53454. }).execute();
  53455. data.each(function (idx) {
  53456. var itemModel = data.getItemModel(idx);
  53457. var emphasisModel = itemModel.getModel('emphasis');
  53458. if (showPointer) {
  53459. var pointer = data.getItemGraphicEl(idx);
  53460. var symbolStyle = data.getItemVisual(idx, 'style');
  53461. var visualColor = symbolStyle.fill;
  53462. if (pointer instanceof ZRImage) {
  53463. var pathStyle = pointer.style;
  53464. pointer.useStyle(extend({
  53465. image: pathStyle.image,
  53466. x: pathStyle.x,
  53467. y: pathStyle.y,
  53468. width: pathStyle.width,
  53469. height: pathStyle.height
  53470. }, symbolStyle));
  53471. } else {
  53472. pointer.useStyle(symbolStyle);
  53473. pointer.type !== 'pointer' && pointer.setColor(visualColor);
  53474. }
  53475. pointer.setStyle(itemModel.getModel(['pointer', 'itemStyle']).getItemStyle());
  53476. if (pointer.style.fill === 'auto') {
  53477. pointer.setStyle('fill', getColor(linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)));
  53478. }
  53479. pointer.z2EmphasisLift = 0;
  53480. setStatesStylesFromModel(pointer, itemModel);
  53481. enableHoverEmphasis(pointer, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  53482. }
  53483. if (showProgress) {
  53484. var progress = progressList[idx];
  53485. progress.useStyle(data.getItemVisual(idx, 'style'));
  53486. progress.setStyle(itemModel.getModel(['progress', 'itemStyle']).getItemStyle());
  53487. progress.z2EmphasisLift = 0;
  53488. setStatesStylesFromModel(progress, itemModel);
  53489. enableHoverEmphasis(progress, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  53490. }
  53491. });
  53492. this._progressEls = progressList;
  53493. }
  53494. };
  53495. GaugeView.prototype._renderAnchor = function (seriesModel, posInfo) {
  53496. var anchorModel = seriesModel.getModel('anchor');
  53497. var showAnchor = anchorModel.get('show');
  53498. if (showAnchor) {
  53499. var anchorSize = anchorModel.get('size');
  53500. var anchorType = anchorModel.get('icon');
  53501. var offsetCenter = anchorModel.get('offsetCenter');
  53502. var anchorKeepAspect = anchorModel.get('keepAspect');
  53503. 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);
  53504. anchor.z2 = anchorModel.get('showAbove') ? 1 : 0;
  53505. anchor.setStyle(anchorModel.getModel('itemStyle').getItemStyle());
  53506. this.group.add(anchor);
  53507. }
  53508. };
  53509. GaugeView.prototype._renderTitleAndDetail = function (seriesModel, ecModel, api, getColor, posInfo) {
  53510. var _this = this;
  53511. var data = seriesModel.getData();
  53512. var valueDim = data.mapDimension('value');
  53513. var minVal = +seriesModel.get('min');
  53514. var maxVal = +seriesModel.get('max');
  53515. var contentGroup = new Group();
  53516. var newTitleEls = [];
  53517. var newDetailEls = [];
  53518. var hasAnimation = seriesModel.isAnimationEnabled();
  53519. var showPointerAbove = seriesModel.get(['pointer', 'showAbove']);
  53520. data.diff(this._data).add(function (idx) {
  53521. newTitleEls[idx] = new ZRText({
  53522. silent: true
  53523. });
  53524. newDetailEls[idx] = new ZRText({
  53525. silent: true
  53526. });
  53527. }).update(function (idx, oldIdx) {
  53528. newTitleEls[idx] = _this._titleEls[oldIdx];
  53529. newDetailEls[idx] = _this._detailEls[oldIdx];
  53530. }).execute();
  53531. data.each(function (idx) {
  53532. var itemModel = data.getItemModel(idx);
  53533. var value = data.get(valueDim, idx);
  53534. var itemGroup = new Group();
  53535. var autoColor = getColor(linearMap(value, [minVal, maxVal], [0, 1], true));
  53536. var itemTitleModel = itemModel.getModel('title');
  53537. if (itemTitleModel.get('show')) {
  53538. var titleOffsetCenter = itemTitleModel.get('offsetCenter');
  53539. var titleX = posInfo.cx + parsePercent$1(titleOffsetCenter[0], posInfo.r);
  53540. var titleY = posInfo.cy + parsePercent$1(titleOffsetCenter[1], posInfo.r);
  53541. var labelEl = newTitleEls[idx];
  53542. labelEl.attr({
  53543. z2: showPointerAbove ? 0 : 2,
  53544. style: createTextStyle(itemTitleModel, {
  53545. x: titleX,
  53546. y: titleY,
  53547. text: data.getName(idx),
  53548. align: 'center',
  53549. verticalAlign: 'middle'
  53550. }, {
  53551. inheritColor: autoColor
  53552. })
  53553. });
  53554. itemGroup.add(labelEl);
  53555. }
  53556. var itemDetailModel = itemModel.getModel('detail');
  53557. if (itemDetailModel.get('show')) {
  53558. var detailOffsetCenter = itemDetailModel.get('offsetCenter');
  53559. var detailX = posInfo.cx + parsePercent$1(detailOffsetCenter[0], posInfo.r);
  53560. var detailY = posInfo.cy + parsePercent$1(detailOffsetCenter[1], posInfo.r);
  53561. var width = parsePercent$1(itemDetailModel.get('width'), posInfo.r);
  53562. var height = parsePercent$1(itemDetailModel.get('height'), posInfo.r);
  53563. var detailColor = seriesModel.get(['progress', 'show']) ? data.getItemVisual(idx, 'style').fill : autoColor;
  53564. var labelEl = newDetailEls[idx];
  53565. var formatter_1 = itemDetailModel.get('formatter');
  53566. labelEl.attr({
  53567. z2: showPointerAbove ? 0 : 2,
  53568. style: createTextStyle(itemDetailModel, {
  53569. x: detailX,
  53570. y: detailY,
  53571. text: formatLabel(value, formatter_1),
  53572. width: isNaN(width) ? null : width,
  53573. height: isNaN(height) ? null : height,
  53574. align: 'center',
  53575. verticalAlign: 'middle'
  53576. }, {
  53577. inheritColor: detailColor
  53578. })
  53579. });
  53580. setLabelValueAnimation(labelEl, {
  53581. normal: itemDetailModel
  53582. }, value, function (value) {
  53583. return formatLabel(value, formatter_1);
  53584. });
  53585. hasAnimation && animateLabelValue(labelEl, idx, data, seriesModel, {
  53586. getFormattedLabel: function (labelDataIndex, status, dataType, labelDimIndex, fmt, extendParams) {
  53587. return formatLabel(extendParams ? extendParams.interpolatedValue : value, formatter_1);
  53588. }
  53589. });
  53590. itemGroup.add(labelEl);
  53591. }
  53592. contentGroup.add(itemGroup);
  53593. });
  53594. this.group.add(contentGroup);
  53595. this._titleEls = newTitleEls;
  53596. this._detailEls = newDetailEls;
  53597. };
  53598. GaugeView.type = 'gauge';
  53599. return GaugeView;
  53600. }(ChartView);
  53601. var GaugeSeriesModel =
  53602. /** @class */
  53603. function (_super) {
  53604. __extends(GaugeSeriesModel, _super);
  53605. function GaugeSeriesModel() {
  53606. var _this = _super !== null && _super.apply(this, arguments) || this;
  53607. _this.type = GaugeSeriesModel.type;
  53608. _this.visualStyleAccessPath = 'itemStyle';
  53609. return _this;
  53610. }
  53611. GaugeSeriesModel.prototype.getInitialData = function (option, ecModel) {
  53612. return createSeriesDataSimply(this, ['value']);
  53613. };
  53614. GaugeSeriesModel.type = 'series.gauge';
  53615. GaugeSeriesModel.defaultOption = {
  53616. zlevel: 0,
  53617. z: 2,
  53618. colorBy: 'data',
  53619. // 默认全局居中
  53620. center: ['50%', '50%'],
  53621. legendHoverLink: true,
  53622. radius: '75%',
  53623. startAngle: 225,
  53624. endAngle: -45,
  53625. clockwise: true,
  53626. // 最小值
  53627. min: 0,
  53628. // 最大值
  53629. max: 100,
  53630. // 分割段数,默认为10
  53631. splitNumber: 10,
  53632. // 坐标轴线
  53633. axisLine: {
  53634. // 默认显示,属性show控制显示与否
  53635. show: true,
  53636. roundCap: false,
  53637. lineStyle: {
  53638. color: [[1, '#E6EBF8']],
  53639. width: 10
  53640. }
  53641. },
  53642. // 坐标轴线
  53643. progress: {
  53644. // 默认显示,属性show控制显示与否
  53645. show: false,
  53646. overlap: true,
  53647. width: 10,
  53648. roundCap: false,
  53649. clip: true
  53650. },
  53651. // 分隔线
  53652. splitLine: {
  53653. // 默认显示,属性show控制显示与否
  53654. show: true,
  53655. // 属性length控制线长
  53656. length: 10,
  53657. distance: 10,
  53658. // 属性lineStyle(详见lineStyle)控制线条样式
  53659. lineStyle: {
  53660. color: '#63677A',
  53661. width: 3,
  53662. type: 'solid'
  53663. }
  53664. },
  53665. // 坐标轴小标记
  53666. axisTick: {
  53667. // 属性show控制显示与否,默认不显示
  53668. show: true,
  53669. // 每份split细分多少段
  53670. splitNumber: 5,
  53671. // 属性length控制线长
  53672. length: 6,
  53673. distance: 10,
  53674. // 属性lineStyle控制线条样式
  53675. lineStyle: {
  53676. color: '#63677A',
  53677. width: 1,
  53678. type: 'solid'
  53679. }
  53680. },
  53681. axisLabel: {
  53682. show: true,
  53683. distance: 15,
  53684. // formatter: null,
  53685. color: '#464646',
  53686. fontSize: 12
  53687. },
  53688. pointer: {
  53689. icon: null,
  53690. offsetCenter: [0, 0],
  53691. show: true,
  53692. showAbove: true,
  53693. length: '60%',
  53694. width: 6,
  53695. keepAspect: false
  53696. },
  53697. anchor: {
  53698. show: false,
  53699. showAbove: false,
  53700. size: 6,
  53701. icon: 'circle',
  53702. offsetCenter: [0, 0],
  53703. keepAspect: false,
  53704. itemStyle: {
  53705. color: '#fff',
  53706. borderWidth: 0,
  53707. borderColor: '#5470c6'
  53708. }
  53709. },
  53710. title: {
  53711. show: true,
  53712. // x, y,单位px
  53713. offsetCenter: [0, '20%'],
  53714. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  53715. color: '#464646',
  53716. fontSize: 16,
  53717. valueAnimation: false
  53718. },
  53719. detail: {
  53720. show: true,
  53721. backgroundColor: 'rgba(0,0,0,0)',
  53722. borderWidth: 0,
  53723. borderColor: '#ccc',
  53724. width: 100,
  53725. height: null,
  53726. padding: [5, 10],
  53727. // x, y,单位px
  53728. offsetCenter: [0, '40%'],
  53729. // formatter: null,
  53730. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  53731. color: '#464646',
  53732. fontSize: 30,
  53733. fontWeight: 'bold',
  53734. lineHeight: 30,
  53735. valueAnimation: false
  53736. }
  53737. };
  53738. return GaugeSeriesModel;
  53739. }(SeriesModel);
  53740. function install$e(registers) {
  53741. registers.registerChartView(GaugeView);
  53742. registers.registerSeriesModel(GaugeSeriesModel);
  53743. }
  53744. var opacityAccessPath = ['itemStyle', 'opacity'];
  53745. /**
  53746. * Piece of pie including Sector, Label, LabelLine
  53747. */
  53748. var FunnelPiece =
  53749. /** @class */
  53750. function (_super) {
  53751. __extends(FunnelPiece, _super);
  53752. function FunnelPiece(data, idx) {
  53753. var _this = _super.call(this) || this;
  53754. var polygon = _this;
  53755. var labelLine = new Polyline();
  53756. var text = new ZRText();
  53757. polygon.setTextContent(text);
  53758. _this.setTextGuideLine(labelLine);
  53759. _this.updateData(data, idx, true);
  53760. return _this;
  53761. }
  53762. FunnelPiece.prototype.updateData = function (data, idx, firstCreate) {
  53763. var polygon = this;
  53764. var seriesModel = data.hostModel;
  53765. var itemModel = data.getItemModel(idx);
  53766. var layout = data.getItemLayout(idx);
  53767. var emphasisModel = itemModel.getModel('emphasis');
  53768. var opacity = itemModel.get(opacityAccessPath);
  53769. opacity = opacity == null ? 1 : opacity;
  53770. if (!firstCreate) {
  53771. saveOldStyle(polygon);
  53772. } // Update common style
  53773. polygon.useStyle(data.getItemVisual(idx, 'style'));
  53774. polygon.style.lineJoin = 'round';
  53775. if (firstCreate) {
  53776. polygon.setShape({
  53777. points: layout.points
  53778. });
  53779. polygon.style.opacity = 0;
  53780. initProps(polygon, {
  53781. style: {
  53782. opacity: opacity
  53783. }
  53784. }, seriesModel, idx);
  53785. } else {
  53786. updateProps(polygon, {
  53787. style: {
  53788. opacity: opacity
  53789. },
  53790. shape: {
  53791. points: layout.points
  53792. }
  53793. }, seriesModel, idx);
  53794. }
  53795. setStatesStylesFromModel(polygon, itemModel);
  53796. this._updateLabel(data, idx);
  53797. enableHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  53798. };
  53799. FunnelPiece.prototype._updateLabel = function (data, idx) {
  53800. var polygon = this;
  53801. var labelLine = this.getTextGuideLine();
  53802. var labelText = polygon.getTextContent();
  53803. var seriesModel = data.hostModel;
  53804. var itemModel = data.getItemModel(idx);
  53805. var layout = data.getItemLayout(idx);
  53806. var labelLayout = layout.label;
  53807. var style = data.getItemVisual(idx, 'style');
  53808. var visualColor = style.fill;
  53809. setLabelStyle( // position will not be used in setLabelStyle
  53810. labelText, getLabelStatesModels(itemModel), {
  53811. labelFetcher: data.hostModel,
  53812. labelDataIndex: idx,
  53813. defaultOpacity: style.opacity,
  53814. defaultText: data.getName(idx)
  53815. }, {
  53816. normal: {
  53817. align: labelLayout.textAlign,
  53818. verticalAlign: labelLayout.verticalAlign
  53819. }
  53820. });
  53821. polygon.setTextConfig({
  53822. local: true,
  53823. inside: !!labelLayout.inside,
  53824. insideStroke: visualColor,
  53825. // insideFill: 'auto',
  53826. outsideFill: visualColor
  53827. });
  53828. var linePoints = labelLayout.linePoints;
  53829. labelLine.setShape({
  53830. points: linePoints
  53831. });
  53832. polygon.textGuideLineConfig = {
  53833. anchor: linePoints ? new Point(linePoints[0][0], linePoints[0][1]) : null
  53834. }; // Make sure update style on labelText after setLabelStyle.
  53835. // Because setLabelStyle will replace a new style on it.
  53836. updateProps(labelText, {
  53837. style: {
  53838. x: labelLayout.x,
  53839. y: labelLayout.y
  53840. }
  53841. }, seriesModel, idx);
  53842. labelText.attr({
  53843. rotation: labelLayout.rotation,
  53844. originX: labelLayout.x,
  53845. originY: labelLayout.y,
  53846. z2: 10
  53847. });
  53848. setLabelLineStyle(polygon, getLabelLineStatesModels(itemModel), {
  53849. // Default use item visual color
  53850. stroke: visualColor
  53851. });
  53852. };
  53853. return FunnelPiece;
  53854. }(Polygon);
  53855. var FunnelView =
  53856. /** @class */
  53857. function (_super) {
  53858. __extends(FunnelView, _super);
  53859. function FunnelView() {
  53860. var _this = _super !== null && _super.apply(this, arguments) || this;
  53861. _this.type = FunnelView.type;
  53862. _this.ignoreLabelLineUpdate = true;
  53863. return _this;
  53864. }
  53865. FunnelView.prototype.render = function (seriesModel, ecModel, api) {
  53866. var data = seriesModel.getData();
  53867. var oldData = this._data;
  53868. var group = this.group;
  53869. data.diff(oldData).add(function (idx) {
  53870. var funnelPiece = new FunnelPiece(data, idx);
  53871. data.setItemGraphicEl(idx, funnelPiece);
  53872. group.add(funnelPiece);
  53873. }).update(function (newIdx, oldIdx) {
  53874. var piece = oldData.getItemGraphicEl(oldIdx);
  53875. piece.updateData(data, newIdx);
  53876. group.add(piece);
  53877. data.setItemGraphicEl(newIdx, piece);
  53878. }).remove(function (idx) {
  53879. var piece = oldData.getItemGraphicEl(idx);
  53880. removeElementWithFadeOut(piece, seriesModel, idx);
  53881. }).execute();
  53882. this._data = data;
  53883. };
  53884. FunnelView.prototype.remove = function () {
  53885. this.group.removeAll();
  53886. this._data = null;
  53887. };
  53888. FunnelView.prototype.dispose = function () {};
  53889. FunnelView.type = 'funnel';
  53890. return FunnelView;
  53891. }(ChartView);
  53892. var FunnelSeriesModel =
  53893. /** @class */
  53894. function (_super) {
  53895. __extends(FunnelSeriesModel, _super);
  53896. function FunnelSeriesModel() {
  53897. var _this = _super !== null && _super.apply(this, arguments) || this;
  53898. _this.type = FunnelSeriesModel.type;
  53899. return _this;
  53900. }
  53901. FunnelSeriesModel.prototype.init = function (option) {
  53902. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  53903. // Use a function instead of direct access because data reference may changed
  53904. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)); // Extend labelLine emphasis
  53905. this._defaultLabelLine(option);
  53906. };
  53907. FunnelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  53908. return createSeriesDataSimply(this, {
  53909. coordDimensions: ['value'],
  53910. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  53911. });
  53912. };
  53913. FunnelSeriesModel.prototype._defaultLabelLine = function (option) {
  53914. // Extend labelLine emphasis
  53915. defaultEmphasis(option, 'labelLine', ['show']);
  53916. var labelLineNormalOpt = option.labelLine;
  53917. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  53918. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  53919. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  53920. }; // Overwrite
  53921. FunnelSeriesModel.prototype.getDataParams = function (dataIndex) {
  53922. var data = this.getData();
  53923. var params = _super.prototype.getDataParams.call(this, dataIndex);
  53924. var valueDim = data.mapDimension('value');
  53925. var sum = data.getSum(valueDim); // Percent is 0 if sum is 0
  53926. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  53927. params.$vars.push('percent');
  53928. return params;
  53929. };
  53930. FunnelSeriesModel.type = 'series.funnel';
  53931. FunnelSeriesModel.defaultOption = {
  53932. zlevel: 0,
  53933. z: 2,
  53934. legendHoverLink: true,
  53935. colorBy: 'data',
  53936. left: 80,
  53937. top: 60,
  53938. right: 80,
  53939. bottom: 60,
  53940. // width: {totalWidth} - left - right,
  53941. // height: {totalHeight} - top - bottom,
  53942. // 默认取数据最小最大值
  53943. // min: 0,
  53944. // max: 100,
  53945. minSize: '0%',
  53946. maxSize: '100%',
  53947. sort: 'descending',
  53948. orient: 'vertical',
  53949. gap: 0,
  53950. funnelAlign: 'center',
  53951. label: {
  53952. show: true,
  53953. position: 'outer' // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  53954. },
  53955. labelLine: {
  53956. show: true,
  53957. length: 20,
  53958. lineStyle: {
  53959. // color: 各异,
  53960. width: 1
  53961. }
  53962. },
  53963. itemStyle: {
  53964. // color: 各异,
  53965. borderColor: '#fff',
  53966. borderWidth: 1
  53967. },
  53968. emphasis: {
  53969. label: {
  53970. show: true
  53971. }
  53972. },
  53973. select: {
  53974. itemStyle: {
  53975. borderColor: '#212121'
  53976. }
  53977. }
  53978. };
  53979. return FunnelSeriesModel;
  53980. }(SeriesModel);
  53981. function getViewRect$3(seriesModel, api) {
  53982. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  53983. width: api.getWidth(),
  53984. height: api.getHeight()
  53985. });
  53986. }
  53987. function getSortedIndices(data, sort) {
  53988. var valueDim = data.mapDimension('value');
  53989. var valueArr = data.mapArray(valueDim, function (val) {
  53990. return val;
  53991. });
  53992. var indices = [];
  53993. var isAscending = sort === 'ascending';
  53994. for (var i = 0, len = data.count(); i < len; i++) {
  53995. indices[i] = i;
  53996. } // Add custom sortable function & none sortable opetion by "options.sort"
  53997. if (typeof sort === 'function') {
  53998. indices.sort(sort);
  53999. } else if (sort !== 'none') {
  54000. indices.sort(function (a, b) {
  54001. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  54002. });
  54003. }
  54004. return indices;
  54005. }
  54006. function labelLayout(data) {
  54007. var seriesModel = data.hostModel;
  54008. var orient = seriesModel.get('orient');
  54009. data.each(function (idx) {
  54010. var itemModel = data.getItemModel(idx);
  54011. var labelModel = itemModel.getModel('label');
  54012. var labelPosition = labelModel.get('position');
  54013. var labelLineModel = itemModel.getModel('labelLine');
  54014. var layout = data.getItemLayout(idx);
  54015. var points = layout.points;
  54016. var isLabelInside = labelPosition === 'inner' || labelPosition === 'inside' || labelPosition === 'center' || labelPosition === 'insideLeft' || labelPosition === 'insideRight';
  54017. var textAlign;
  54018. var textX;
  54019. var textY;
  54020. var linePoints;
  54021. if (isLabelInside) {
  54022. if (labelPosition === 'insideLeft') {
  54023. textX = (points[0][0] + points[3][0]) / 2 + 5;
  54024. textY = (points[0][1] + points[3][1]) / 2;
  54025. textAlign = 'left';
  54026. } else if (labelPosition === 'insideRight') {
  54027. textX = (points[1][0] + points[2][0]) / 2 - 5;
  54028. textY = (points[1][1] + points[2][1]) / 2;
  54029. textAlign = 'right';
  54030. } else {
  54031. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  54032. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  54033. textAlign = 'center';
  54034. }
  54035. linePoints = [[textX, textY], [textX, textY]];
  54036. } else {
  54037. var x1 = void 0;
  54038. var y1 = void 0;
  54039. var x2 = void 0;
  54040. var y2 = void 0;
  54041. var labelLineLen = labelLineModel.get('length');
  54042. if ("development" !== 'production') {
  54043. if (orient === 'vertical' && ['top', 'bottom'].indexOf(labelPosition) > -1) {
  54044. labelPosition = 'left';
  54045. console.warn('Position error: Funnel chart on vertical orient dose not support top and bottom.');
  54046. }
  54047. if (orient === 'horizontal' && ['left', 'right'].indexOf(labelPosition) > -1) {
  54048. labelPosition = 'bottom';
  54049. console.warn('Position error: Funnel chart on horizontal orient dose not support left and right.');
  54050. }
  54051. }
  54052. if (labelPosition === 'left') {
  54053. // Left side
  54054. x1 = (points[3][0] + points[0][0]) / 2;
  54055. y1 = (points[3][1] + points[0][1]) / 2;
  54056. x2 = x1 - labelLineLen;
  54057. textX = x2 - 5;
  54058. textAlign = 'right';
  54059. } else if (labelPosition === 'right') {
  54060. // Right side
  54061. x1 = (points[1][0] + points[2][0]) / 2;
  54062. y1 = (points[1][1] + points[2][1]) / 2;
  54063. x2 = x1 + labelLineLen;
  54064. textX = x2 + 5;
  54065. textAlign = 'left';
  54066. } else if (labelPosition === 'top') {
  54067. // Top side
  54068. x1 = (points[3][0] + points[0][0]) / 2;
  54069. y1 = (points[3][1] + points[0][1]) / 2;
  54070. y2 = y1 - labelLineLen;
  54071. textY = y2 - 5;
  54072. textAlign = 'center';
  54073. } else if (labelPosition === 'bottom') {
  54074. // Bottom side
  54075. x1 = (points[1][0] + points[2][0]) / 2;
  54076. y1 = (points[1][1] + points[2][1]) / 2;
  54077. y2 = y1 + labelLineLen;
  54078. textY = y2 + 5;
  54079. textAlign = 'center';
  54080. } else if (labelPosition === 'rightTop') {
  54081. // RightTop side
  54082. x1 = orient === 'horizontal' ? points[3][0] : points[1][0];
  54083. y1 = orient === 'horizontal' ? points[3][1] : points[1][1];
  54084. if (orient === 'horizontal') {
  54085. y2 = y1 - labelLineLen;
  54086. textY = y2 - 5;
  54087. textAlign = 'center';
  54088. } else {
  54089. x2 = x1 + labelLineLen;
  54090. textX = x2 + 5;
  54091. textAlign = 'top';
  54092. }
  54093. } else if (labelPosition === 'rightBottom') {
  54094. // RightBottom side
  54095. x1 = points[2][0];
  54096. y1 = points[2][1];
  54097. if (orient === 'horizontal') {
  54098. y2 = y1 + labelLineLen;
  54099. textY = y2 + 5;
  54100. textAlign = 'center';
  54101. } else {
  54102. x2 = x1 + labelLineLen;
  54103. textX = x2 + 5;
  54104. textAlign = 'bottom';
  54105. }
  54106. } else if (labelPosition === 'leftTop') {
  54107. // LeftTop side
  54108. x1 = points[0][0];
  54109. y1 = orient === 'horizontal' ? points[0][1] : points[1][1];
  54110. if (orient === 'horizontal') {
  54111. y2 = y1 - labelLineLen;
  54112. textY = y2 - 5;
  54113. textAlign = 'center';
  54114. } else {
  54115. x2 = x1 - labelLineLen;
  54116. textX = x2 - 5;
  54117. textAlign = 'right';
  54118. }
  54119. } else if (labelPosition === 'leftBottom') {
  54120. // LeftBottom side
  54121. x1 = orient === 'horizontal' ? points[1][0] : points[3][0];
  54122. y1 = orient === 'horizontal' ? points[1][1] : points[2][1];
  54123. if (orient === 'horizontal') {
  54124. y2 = y1 + labelLineLen;
  54125. textY = y2 + 5;
  54126. textAlign = 'center';
  54127. } else {
  54128. x2 = x1 - labelLineLen;
  54129. textX = x2 - 5;
  54130. textAlign = 'right';
  54131. }
  54132. } else {
  54133. // Right side or Bottom side
  54134. x1 = (points[1][0] + points[2][0]) / 2;
  54135. y1 = (points[1][1] + points[2][1]) / 2;
  54136. if (orient === 'horizontal') {
  54137. y2 = y1 + labelLineLen;
  54138. textY = y2 + 5;
  54139. textAlign = 'center';
  54140. } else {
  54141. x2 = x1 + labelLineLen;
  54142. textX = x2 + 5;
  54143. textAlign = 'left';
  54144. }
  54145. }
  54146. if (orient === 'horizontal') {
  54147. x2 = x1;
  54148. textX = x2;
  54149. } else {
  54150. y2 = y1;
  54151. textY = y2;
  54152. }
  54153. linePoints = [[x1, y1], [x2, y2]];
  54154. }
  54155. layout.label = {
  54156. linePoints: linePoints,
  54157. x: textX,
  54158. y: textY,
  54159. verticalAlign: 'middle',
  54160. textAlign: textAlign,
  54161. inside: isLabelInside
  54162. };
  54163. });
  54164. }
  54165. function funnelLayout(ecModel, api) {
  54166. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  54167. var data = seriesModel.getData();
  54168. var valueDim = data.mapDimension('value');
  54169. var sort = seriesModel.get('sort');
  54170. var viewRect = getViewRect$3(seriesModel, api);
  54171. var orient = seriesModel.get('orient');
  54172. var viewWidth = viewRect.width;
  54173. var viewHeight = viewRect.height;
  54174. var indices = getSortedIndices(data, sort);
  54175. var x = viewRect.x;
  54176. var y = viewRect.y;
  54177. 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)];
  54178. var dataExtent = data.getDataExtent(valueDim);
  54179. var min = seriesModel.get('min');
  54180. var max = seriesModel.get('max');
  54181. if (min == null) {
  54182. min = Math.min(dataExtent[0], 0);
  54183. }
  54184. if (max == null) {
  54185. max = dataExtent[1];
  54186. }
  54187. var funnelAlign = seriesModel.get('funnelAlign');
  54188. var gap = seriesModel.get('gap');
  54189. var viewSize = orient === 'horizontal' ? viewWidth : viewHeight;
  54190. var itemSize = (viewSize - gap * (data.count() - 1)) / data.count();
  54191. var getLinePoints = function (idx, offset) {
  54192. // End point index is data.count() and we assign it 0
  54193. if (orient === 'horizontal') {
  54194. var val_1 = data.get(valueDim, idx) || 0;
  54195. var itemHeight = linearMap(val_1, [min, max], sizeExtent, true);
  54196. var y0 = void 0;
  54197. switch (funnelAlign) {
  54198. case 'top':
  54199. y0 = y;
  54200. break;
  54201. case 'center':
  54202. y0 = y + (viewHeight - itemHeight) / 2;
  54203. break;
  54204. case 'bottom':
  54205. y0 = y + (viewHeight - itemHeight);
  54206. break;
  54207. }
  54208. return [[offset, y0], [offset, y0 + itemHeight]];
  54209. }
  54210. var val = data.get(valueDim, idx) || 0;
  54211. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  54212. var x0;
  54213. switch (funnelAlign) {
  54214. case 'left':
  54215. x0 = x;
  54216. break;
  54217. case 'center':
  54218. x0 = x + (viewWidth - itemWidth) / 2;
  54219. break;
  54220. case 'right':
  54221. x0 = x + viewWidth - itemWidth;
  54222. break;
  54223. }
  54224. return [[x0, offset], [x0 + itemWidth, offset]];
  54225. };
  54226. if (sort === 'ascending') {
  54227. // From bottom to top
  54228. itemSize = -itemSize;
  54229. gap = -gap;
  54230. if (orient === 'horizontal') {
  54231. x += viewWidth;
  54232. } else {
  54233. y += viewHeight;
  54234. }
  54235. indices = indices.reverse();
  54236. }
  54237. for (var i = 0; i < indices.length; i++) {
  54238. var idx = indices[i];
  54239. var nextIdx = indices[i + 1];
  54240. var itemModel = data.getItemModel(idx);
  54241. if (orient === 'horizontal') {
  54242. var width = itemModel.get(['itemStyle', 'width']);
  54243. if (width == null) {
  54244. width = itemSize;
  54245. } else {
  54246. width = parsePercent$1(width, viewWidth);
  54247. if (sort === 'ascending') {
  54248. width = -width;
  54249. }
  54250. }
  54251. var start = getLinePoints(idx, x);
  54252. var end = getLinePoints(nextIdx, x + width);
  54253. x += width + gap;
  54254. data.setItemLayout(idx, {
  54255. points: start.concat(end.slice().reverse())
  54256. });
  54257. } else {
  54258. var height = itemModel.get(['itemStyle', 'height']);
  54259. if (height == null) {
  54260. height = itemSize;
  54261. } else {
  54262. height = parsePercent$1(height, viewHeight);
  54263. if (sort === 'ascending') {
  54264. height = -height;
  54265. }
  54266. }
  54267. var start = getLinePoints(idx, y);
  54268. var end = getLinePoints(nextIdx, y + height);
  54269. y += height + gap;
  54270. data.setItemLayout(idx, {
  54271. points: start.concat(end.slice().reverse())
  54272. });
  54273. }
  54274. }
  54275. labelLayout(data);
  54276. });
  54277. }
  54278. function install$f(registers) {
  54279. registers.registerChartView(FunnelView);
  54280. registers.registerSeriesModel(FunnelSeriesModel);
  54281. registers.registerLayout(funnelLayout);
  54282. registers.registerProcessor(dataFilter('funnel'));
  54283. }
  54284. var DEFAULT_SMOOTH = 0.3;
  54285. var ParallelView =
  54286. /** @class */
  54287. function (_super) {
  54288. __extends(ParallelView, _super);
  54289. function ParallelView() {
  54290. var _this = _super !== null && _super.apply(this, arguments) || this;
  54291. _this.type = ParallelView.type;
  54292. _this._dataGroup = new Group();
  54293. _this._initialized = false;
  54294. return _this;
  54295. }
  54296. ParallelView.prototype.init = function () {
  54297. this.group.add(this._dataGroup);
  54298. };
  54299. /**
  54300. * @override
  54301. */
  54302. ParallelView.prototype.render = function (seriesModel, ecModel, api, payload) {
  54303. var dataGroup = this._dataGroup;
  54304. var data = seriesModel.getData();
  54305. var oldData = this._data;
  54306. var coordSys = seriesModel.coordinateSystem;
  54307. var dimensions = coordSys.dimensions;
  54308. var seriesScope = makeSeriesScope$2(seriesModel);
  54309. data.diff(oldData).add(add).update(update).remove(remove).execute();
  54310. function add(newDataIndex) {
  54311. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  54312. updateElCommon(line, data, newDataIndex, seriesScope);
  54313. }
  54314. function update(newDataIndex, oldDataIndex) {
  54315. var line = oldData.getItemGraphicEl(oldDataIndex);
  54316. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  54317. data.setItemGraphicEl(newDataIndex, line);
  54318. updateProps(line, {
  54319. shape: {
  54320. points: points
  54321. }
  54322. }, seriesModel, newDataIndex);
  54323. saveOldStyle(line);
  54324. updateElCommon(line, data, newDataIndex, seriesScope);
  54325. }
  54326. function remove(oldDataIndex) {
  54327. var line = oldData.getItemGraphicEl(oldDataIndex);
  54328. dataGroup.remove(line);
  54329. } // First create
  54330. if (!this._initialized) {
  54331. this._initialized = true;
  54332. var clipPath = createGridClipShape(coordSys, seriesModel, function () {
  54333. // Callback will be invoked immediately if there is no animation
  54334. setTimeout(function () {
  54335. dataGroup.removeClipPath();
  54336. });
  54337. });
  54338. dataGroup.setClipPath(clipPath);
  54339. }
  54340. this._data = data;
  54341. };
  54342. ParallelView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  54343. this._initialized = true;
  54344. this._data = null;
  54345. this._dataGroup.removeAll();
  54346. };
  54347. ParallelView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  54348. var data = seriesModel.getData();
  54349. var coordSys = seriesModel.coordinateSystem;
  54350. var dimensions = coordSys.dimensions;
  54351. var seriesScope = makeSeriesScope$2(seriesModel);
  54352. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  54353. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  54354. line.incremental = true;
  54355. updateElCommon(line, data, dataIndex, seriesScope);
  54356. }
  54357. };
  54358. ParallelView.prototype.remove = function () {
  54359. this._dataGroup && this._dataGroup.removeAll();
  54360. this._data = null;
  54361. };
  54362. ParallelView.type = 'parallel';
  54363. return ParallelView;
  54364. }(ChartView);
  54365. function createGridClipShape(coordSys, seriesModel, cb) {
  54366. var parallelModel = coordSys.model;
  54367. var rect = coordSys.getRect();
  54368. var rectEl = new Rect({
  54369. shape: {
  54370. x: rect.x,
  54371. y: rect.y,
  54372. width: rect.width,
  54373. height: rect.height
  54374. }
  54375. });
  54376. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  54377. rectEl.setShape(dim, 0);
  54378. initProps(rectEl, {
  54379. shape: {
  54380. width: rect.width,
  54381. height: rect.height
  54382. }
  54383. }, seriesModel, cb);
  54384. return rectEl;
  54385. }
  54386. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  54387. var points = [];
  54388. for (var i = 0; i < dimensions.length; i++) {
  54389. var dimName = dimensions[i];
  54390. var value = data.get(data.mapDimension(dimName), dataIndex);
  54391. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  54392. points.push(coordSys.dataToPoint(value, dimName));
  54393. }
  54394. }
  54395. return points;
  54396. }
  54397. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  54398. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  54399. var line = new Polyline({
  54400. shape: {
  54401. points: points
  54402. },
  54403. // silent: true,
  54404. z2: 10
  54405. });
  54406. dataGroup.add(line);
  54407. data.setItemGraphicEl(dataIndex, line);
  54408. return line;
  54409. }
  54410. function makeSeriesScope$2(seriesModel) {
  54411. var smooth = seriesModel.get('smooth', true);
  54412. smooth === true && (smooth = DEFAULT_SMOOTH);
  54413. smooth = numericToNumber(smooth);
  54414. eqNaN(smooth) && (smooth = 0);
  54415. return {
  54416. smooth: smooth
  54417. };
  54418. }
  54419. function updateElCommon(el, data, dataIndex, seriesScope) {
  54420. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  54421. el.style.fill = null;
  54422. el.setShape('smooth', seriesScope.smooth);
  54423. var itemModel = data.getItemModel(dataIndex);
  54424. var emphasisModel = itemModel.getModel('emphasis');
  54425. setStatesStylesFromModel(el, itemModel, 'lineStyle');
  54426. enableHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  54427. } // function simpleDiff(oldData, newData, dimensions) {
  54428. // let oldLen;
  54429. // if (!oldData
  54430. // || !oldData.__plProgressive
  54431. // || (oldLen = oldData.count()) !== newData.count()
  54432. // ) {
  54433. // return true;
  54434. // }
  54435. // let dimLen = dimensions.length;
  54436. // for (let i = 0; i < oldLen; i++) {
  54437. // for (let j = 0; j < dimLen; j++) {
  54438. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  54439. // return true;
  54440. // }
  54441. // }
  54442. // }
  54443. // return false;
  54444. // }
  54445. // FIXME put in common util?
  54446. function isEmptyValue(val, axisType) {
  54447. return axisType === 'category' ? val == null : val == null || isNaN(val); // axisType === 'value'
  54448. }
  54449. var ParallelSeriesModel =
  54450. /** @class */
  54451. function (_super) {
  54452. __extends(ParallelSeriesModel, _super);
  54453. function ParallelSeriesModel() {
  54454. var _this = _super !== null && _super.apply(this, arguments) || this;
  54455. _this.type = ParallelSeriesModel.type;
  54456. _this.visualStyleAccessPath = 'lineStyle';
  54457. _this.visualDrawType = 'stroke';
  54458. return _this;
  54459. }
  54460. ParallelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  54461. return createSeriesData(null, this, {
  54462. useEncodeDefaulter: bind(makeDefaultEncode, null, this)
  54463. });
  54464. };
  54465. /**
  54466. * User can get data raw indices on 'axisAreaSelected' event received.
  54467. *
  54468. * @return Raw indices
  54469. */
  54470. ParallelSeriesModel.prototype.getRawIndicesByActiveState = function (activeState) {
  54471. var coordSys = this.coordinateSystem;
  54472. var data = this.getData();
  54473. var indices = [];
  54474. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  54475. if (activeState === theActiveState) {
  54476. indices.push(data.getRawIndex(dataIndex));
  54477. }
  54478. });
  54479. return indices;
  54480. };
  54481. ParallelSeriesModel.type = 'series.parallel';
  54482. ParallelSeriesModel.dependencies = ['parallel'];
  54483. ParallelSeriesModel.defaultOption = {
  54484. zlevel: 0,
  54485. z: 2,
  54486. coordinateSystem: 'parallel',
  54487. parallelIndex: 0,
  54488. label: {
  54489. show: false
  54490. },
  54491. inactiveOpacity: 0.05,
  54492. activeOpacity: 1,
  54493. lineStyle: {
  54494. width: 1,
  54495. opacity: 0.45,
  54496. type: 'solid'
  54497. },
  54498. emphasis: {
  54499. label: {
  54500. show: false
  54501. }
  54502. },
  54503. progressive: 500,
  54504. smooth: false,
  54505. animationEasing: 'linear'
  54506. };
  54507. return ParallelSeriesModel;
  54508. }(SeriesModel);
  54509. function makeDefaultEncode(seriesModel) {
  54510. // The mapping of parallelAxis dimension to data dimension can
  54511. // be specified in parallelAxis.option.dim. For example, if
  54512. // parallelAxis.option.dim is 'dim3', it mapping to the third
  54513. // dimension of data. But `data.encode` has higher priority.
  54514. // Moreover, parallelModel.dimension should not be regarded as data
  54515. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  54516. var parallelModel = seriesModel.ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  54517. if (!parallelModel) {
  54518. return;
  54519. }
  54520. var encodeDefine = {};
  54521. each(parallelModel.dimensions, function (axisDim) {
  54522. var dataDimIndex = convertDimNameToNumber(axisDim);
  54523. encodeDefine[axisDim] = dataDimIndex;
  54524. });
  54525. return encodeDefine;
  54526. }
  54527. function convertDimNameToNumber(dimName) {
  54528. return +dimName.replace('dim', '');
  54529. }
  54530. /*
  54531. * Licensed to the Apache Software Foundation (ASF) under one
  54532. * or more contributor license agreements. See the NOTICE file
  54533. * distributed with this work for additional information
  54534. * regarding copyright ownership. The ASF licenses this file
  54535. * to you under the Apache License, Version 2.0 (the
  54536. * "License"); you may not use this file except in compliance
  54537. * with the License. You may obtain a copy of the License at
  54538. *
  54539. * http://www.apache.org/licenses/LICENSE-2.0
  54540. *
  54541. * Unless required by applicable law or agreed to in writing,
  54542. * software distributed under the License is distributed on an
  54543. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54544. * KIND, either express or implied. See the License for the
  54545. * specific language governing permissions and limitations
  54546. * under the License.
  54547. */
  54548. /**
  54549. * AUTO-GENERATED FILE. DO NOT MODIFY.
  54550. */
  54551. /*
  54552. * Licensed to the Apache Software Foundation (ASF) under one
  54553. * or more contributor license agreements. See the NOTICE file
  54554. * distributed with this work for additional information
  54555. * regarding copyright ownership. The ASF licenses this file
  54556. * to you under the Apache License, Version 2.0 (the
  54557. * "License"); you may not use this file except in compliance
  54558. * with the License. You may obtain a copy of the License at
  54559. *
  54560. * http://www.apache.org/licenses/LICENSE-2.0
  54561. *
  54562. * Unless required by applicable law or agreed to in writing,
  54563. * software distributed under the License is distributed on an
  54564. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54565. * KIND, either express or implied. See the License for the
  54566. * specific language governing permissions and limitations
  54567. * under the License.
  54568. */
  54569. var opacityAccessPath$1 = ['lineStyle', 'opacity'];
  54570. var parallelVisual = {
  54571. seriesType: 'parallel',
  54572. reset: function (seriesModel, ecModel) {
  54573. var coordSys = seriesModel.coordinateSystem;
  54574. var opacityMap = {
  54575. normal: seriesModel.get(['lineStyle', 'opacity']),
  54576. active: seriesModel.get('activeOpacity'),
  54577. inactive: seriesModel.get('inactiveOpacity')
  54578. };
  54579. return {
  54580. progress: function (params, data) {
  54581. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  54582. var opacity = opacityMap[activeState];
  54583. if (activeState === 'normal' && data.hasItemOption) {
  54584. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  54585. itemOpacity != null && (opacity = itemOpacity);
  54586. }
  54587. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  54588. existsStyle.opacity = opacity;
  54589. }, params.start, params.end);
  54590. }
  54591. };
  54592. }
  54593. };
  54594. function parallelPreprocessor(option) {
  54595. createParallelIfNeeded(option);
  54596. mergeAxisOptionFromParallel(option);
  54597. }
  54598. /**
  54599. * Create a parallel coordinate if not exists.
  54600. * @inner
  54601. */
  54602. function createParallelIfNeeded(option) {
  54603. if (option.parallel) {
  54604. return;
  54605. }
  54606. var hasParallelSeries = false;
  54607. each(option.series, function (seriesOpt) {
  54608. if (seriesOpt && seriesOpt.type === 'parallel') {
  54609. hasParallelSeries = true;
  54610. }
  54611. });
  54612. if (hasParallelSeries) {
  54613. option.parallel = [{}];
  54614. }
  54615. }
  54616. /**
  54617. * Merge aixs definition from parallel option (if exists) to axis option.
  54618. * @inner
  54619. */
  54620. function mergeAxisOptionFromParallel(option) {
  54621. var axes = normalizeToArray(option.parallelAxis);
  54622. each(axes, function (axisOption) {
  54623. if (!isObject(axisOption)) {
  54624. return;
  54625. }
  54626. var parallelIndex = axisOption.parallelIndex || 0;
  54627. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  54628. if (parallelOption && parallelOption.parallelAxisDefault) {
  54629. merge(axisOption, parallelOption.parallelAxisDefault, false);
  54630. }
  54631. });
  54632. }
  54633. var CLICK_THRESHOLD = 5; // > 4
  54634. var ParallelView$1 =
  54635. /** @class */
  54636. function (_super) {
  54637. __extends(ParallelView, _super);
  54638. function ParallelView() {
  54639. var _this = _super !== null && _super.apply(this, arguments) || this;
  54640. _this.type = ParallelView.type;
  54641. return _this;
  54642. }
  54643. ParallelView.prototype.render = function (parallelModel, ecModel, api) {
  54644. this._model = parallelModel;
  54645. this._api = api;
  54646. if (!this._handlers) {
  54647. this._handlers = {};
  54648. each(handlers, function (handler, eventName) {
  54649. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  54650. }, this);
  54651. }
  54652. createOrUpdate(this, '_throttledDispatchExpand', parallelModel.get('axisExpandRate'), 'fixRate');
  54653. };
  54654. ParallelView.prototype.dispose = function (ecModel, api) {
  54655. each(this._handlers, function (handler, eventName) {
  54656. api.getZr().off(eventName, handler);
  54657. });
  54658. this._handlers = null;
  54659. };
  54660. /**
  54661. * @internal
  54662. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  54663. */
  54664. ParallelView.prototype._throttledDispatchExpand = function (opt) {
  54665. this._dispatchExpand(opt);
  54666. };
  54667. /**
  54668. * @internal
  54669. */
  54670. ParallelView.prototype._dispatchExpand = function (opt) {
  54671. opt && this._api.dispatchAction(extend({
  54672. type: 'parallelAxisExpand'
  54673. }, opt));
  54674. };
  54675. ParallelView.type = 'parallel';
  54676. return ParallelView;
  54677. }(ComponentView);
  54678. var handlers = {
  54679. mousedown: function (e) {
  54680. if (checkTrigger(this, 'click')) {
  54681. this._mouseDownPoint = [e.offsetX, e.offsetY];
  54682. }
  54683. },
  54684. mouseup: function (e) {
  54685. var mouseDownPoint = this._mouseDownPoint;
  54686. if (checkTrigger(this, 'click') && mouseDownPoint) {
  54687. var point = [e.offsetX, e.offsetY];
  54688. var dist = Math.pow(mouseDownPoint[0] - point[0], 2) + Math.pow(mouseDownPoint[1] - point[1], 2);
  54689. if (dist > CLICK_THRESHOLD) {
  54690. return;
  54691. }
  54692. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  54693. result.behavior !== 'none' && this._dispatchExpand({
  54694. axisExpandWindow: result.axisExpandWindow
  54695. });
  54696. }
  54697. this._mouseDownPoint = null;
  54698. },
  54699. mousemove: function (e) {
  54700. // Should do nothing when brushing.
  54701. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  54702. return;
  54703. }
  54704. var model = this._model;
  54705. var result = model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  54706. var behavior = result.behavior;
  54707. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  54708. this._throttledDispatchExpand(behavior === 'none' ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  54709. : {
  54710. axisExpandWindow: result.axisExpandWindow,
  54711. // Jumping uses animation, and sliding suppresses animation.
  54712. animation: behavior === 'jump' ? null : {
  54713. duration: 0 // Disable animation.
  54714. }
  54715. });
  54716. }
  54717. };
  54718. function checkTrigger(view, triggerOn) {
  54719. var model = view._model;
  54720. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  54721. }
  54722. var ParallelModel =
  54723. /** @class */
  54724. function (_super) {
  54725. __extends(ParallelModel, _super);
  54726. function ParallelModel() {
  54727. var _this = _super !== null && _super.apply(this, arguments) || this;
  54728. _this.type = ParallelModel.type;
  54729. return _this;
  54730. }
  54731. ParallelModel.prototype.init = function () {
  54732. _super.prototype.init.apply(this, arguments);
  54733. this.mergeOption({});
  54734. };
  54735. ParallelModel.prototype.mergeOption = function (newOption) {
  54736. var thisOption = this.option;
  54737. newOption && merge(thisOption, newOption, true);
  54738. this._initDimensions();
  54739. };
  54740. /**
  54741. * Whether series or axis is in this coordinate system.
  54742. */
  54743. ParallelModel.prototype.contains = function (model, ecModel) {
  54744. var parallelIndex = model.get('parallelIndex');
  54745. return parallelIndex != null && ecModel.getComponent('parallel', parallelIndex) === this;
  54746. };
  54747. ParallelModel.prototype.setAxisExpand = function (opt) {
  54748. each(['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'], function (name) {
  54749. if (opt.hasOwnProperty(name)) {
  54750. // @ts-ignore FIXME: why "never" inferred in this.option[name]?
  54751. this.option[name] = opt[name];
  54752. }
  54753. }, this);
  54754. };
  54755. ParallelModel.prototype._initDimensions = function () {
  54756. var dimensions = this.dimensions = [];
  54757. var parallelAxisIndex = this.parallelAxisIndex = [];
  54758. var axisModels = filter(this.ecModel.queryComponents({
  54759. mainType: 'parallelAxis'
  54760. }), function (axisModel) {
  54761. // Can not use this.contains here, because
  54762. // initialization has not been completed yet.
  54763. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  54764. }, this);
  54765. each(axisModels, function (axisModel) {
  54766. dimensions.push('dim' + axisModel.get('dim'));
  54767. parallelAxisIndex.push(axisModel.componentIndex);
  54768. });
  54769. };
  54770. ParallelModel.type = 'parallel';
  54771. ParallelModel.dependencies = ['parallelAxis'];
  54772. ParallelModel.layoutMode = 'box';
  54773. ParallelModel.defaultOption = {
  54774. zlevel: 0,
  54775. z: 0,
  54776. left: 80,
  54777. top: 60,
  54778. right: 80,
  54779. bottom: 60,
  54780. // width: {totalWidth} - left - right,
  54781. // height: {totalHeight} - top - bottom,
  54782. layout: 'horizontal',
  54783. // FIXME
  54784. // naming?
  54785. axisExpandable: false,
  54786. axisExpandCenter: null,
  54787. axisExpandCount: 0,
  54788. axisExpandWidth: 50,
  54789. axisExpandRate: 17,
  54790. axisExpandDebounce: 50,
  54791. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  54792. // Do not doc to user until necessary.
  54793. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  54794. axisExpandTriggerOn: 'click',
  54795. parallelAxisDefault: null
  54796. };
  54797. return ParallelModel;
  54798. }(ComponentModel);
  54799. var ParallelAxis =
  54800. /** @class */
  54801. function (_super) {
  54802. __extends(ParallelAxis, _super);
  54803. function ParallelAxis(dim, scale, coordExtent, axisType, axisIndex) {
  54804. var _this = _super.call(this, dim, scale, coordExtent) || this;
  54805. _this.type = axisType || 'value';
  54806. _this.axisIndex = axisIndex;
  54807. return _this;
  54808. }
  54809. ParallelAxis.prototype.isHorizontal = function () {
  54810. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  54811. };
  54812. return ParallelAxis;
  54813. }(Axis);
  54814. /*
  54815. * Licensed to the Apache Software Foundation (ASF) under one
  54816. * or more contributor license agreements. See the NOTICE file
  54817. * distributed with this work for additional information
  54818. * regarding copyright ownership. The ASF licenses this file
  54819. * to you under the Apache License, Version 2.0 (the
  54820. * "License"); you may not use this file except in compliance
  54821. * with the License. You may obtain a copy of the License at
  54822. *
  54823. * http://www.apache.org/licenses/LICENSE-2.0
  54824. *
  54825. * Unless required by applicable law or agreed to in writing,
  54826. * software distributed under the License is distributed on an
  54827. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54828. * KIND, either express or implied. See the License for the
  54829. * specific language governing permissions and limitations
  54830. * under the License.
  54831. */
  54832. /**
  54833. * AUTO-GENERATED FILE. DO NOT MODIFY.
  54834. */
  54835. /*
  54836. * Licensed to the Apache Software Foundation (ASF) under one
  54837. * or more contributor license agreements. See the NOTICE file
  54838. * distributed with this work for additional information
  54839. * regarding copyright ownership. The ASF licenses this file
  54840. * to you under the Apache License, Version 2.0 (the
  54841. * "License"); you may not use this file except in compliance
  54842. * with the License. You may obtain a copy of the License at
  54843. *
  54844. * http://www.apache.org/licenses/LICENSE-2.0
  54845. *
  54846. * Unless required by applicable law or agreed to in writing,
  54847. * software distributed under the License is distributed on an
  54848. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54849. * KIND, either express or implied. See the License for the
  54850. * specific language governing permissions and limitations
  54851. * under the License.
  54852. */
  54853. /**
  54854. * Calculate slider move result.
  54855. * Usage:
  54856. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  54857. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  54858. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  54859. *
  54860. * @param delta Move length.
  54861. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  54862. * handleEnds will be modified in this method.
  54863. * @param extent handleEnds is restricted by extent.
  54864. * extent[0] should less or equals than extent[1].
  54865. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  54866. * @param minSpan The range of dataZoom can not be smaller than that.
  54867. * If not set, handle0 and cross handle1. If set as a non-negative
  54868. * number (including `0`), handles will push each other when reaching
  54869. * the minSpan.
  54870. * @param maxSpan The range of dataZoom can not be larger than that.
  54871. * @return The input handleEnds.
  54872. */
  54873. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  54874. delta = delta || 0;
  54875. var extentSpan = extent[1] - extent[0]; // Notice maxSpan and minSpan can be null/undefined.
  54876. if (minSpan != null) {
  54877. minSpan = restrict(minSpan, [0, extentSpan]);
  54878. }
  54879. if (maxSpan != null) {
  54880. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  54881. }
  54882. if (handleIndex === 'all') {
  54883. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  54884. handleSpan = restrict(handleSpan, [0, extentSpan]);
  54885. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  54886. handleIndex = 0;
  54887. }
  54888. handleEnds[0] = restrict(handleEnds[0], extent);
  54889. handleEnds[1] = restrict(handleEnds[1], extent);
  54890. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  54891. handleEnds[handleIndex] += delta; // Restrict in extent.
  54892. var extentMinSpan = minSpan || 0;
  54893. var realExtent = extent.slice();
  54894. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  54895. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent); // Expand span.
  54896. var currDistSign;
  54897. currDistSign = getSpanSign(handleEnds, handleIndex);
  54898. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  54899. // If minSpan exists, 'cross' is forbidden.
  54900. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  54901. } // Shrink span.
  54902. currDistSign = getSpanSign(handleEnds, handleIndex);
  54903. if (maxSpan != null && currDistSign.span > maxSpan) {
  54904. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  54905. }
  54906. return handleEnds;
  54907. }
  54908. function getSpanSign(handleEnds, handleIndex) {
  54909. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  54910. // is at left of handleEnds[1] for non-cross case.
  54911. return {
  54912. span: Math.abs(dist),
  54913. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  54914. };
  54915. }
  54916. function restrict(value, extend) {
  54917. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  54918. }
  54919. var each$5 = each;
  54920. var mathMin$8 = Math.min;
  54921. var mathMax$8 = Math.max;
  54922. var mathFloor$1 = Math.floor;
  54923. var mathCeil$1 = Math.ceil;
  54924. var round$2 = round;
  54925. var PI$7 = Math.PI;
  54926. var Parallel =
  54927. /** @class */
  54928. function () {
  54929. function Parallel(parallelModel, ecModel, api) {
  54930. this.type = 'parallel';
  54931. /**
  54932. * key: dimension
  54933. */
  54934. this._axesMap = createHashMap();
  54935. /**
  54936. * key: dimension
  54937. * value: {position: [], rotation, }
  54938. */
  54939. this._axesLayout = {};
  54940. this.dimensions = parallelModel.dimensions;
  54941. this._model = parallelModel;
  54942. this._init(parallelModel, ecModel, api);
  54943. }
  54944. Parallel.prototype._init = function (parallelModel, ecModel, api) {
  54945. var dimensions = parallelModel.dimensions;
  54946. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  54947. each$5(dimensions, function (dim, idx) {
  54948. var axisIndex = parallelAxisIndex[idx];
  54949. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  54950. var axis = this._axesMap.set(dim, new ParallelAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisIndex));
  54951. var isCategory = axis.type === 'category';
  54952. axis.onBand = isCategory && axisModel.get('boundaryGap');
  54953. axis.inverse = axisModel.get('inverse'); // Injection
  54954. axisModel.axis = axis;
  54955. axis.model = axisModel;
  54956. axis.coordinateSystem = axisModel.coordinateSystem = this;
  54957. }, this);
  54958. };
  54959. /**
  54960. * Update axis scale after data processed
  54961. */
  54962. Parallel.prototype.update = function (ecModel, api) {
  54963. this._updateAxesFromSeries(this._model, ecModel);
  54964. };
  54965. Parallel.prototype.containPoint = function (point) {
  54966. var layoutInfo = this._makeLayoutInfo();
  54967. var axisBase = layoutInfo.axisBase;
  54968. var layoutBase = layoutInfo.layoutBase;
  54969. var pixelDimIndex = layoutInfo.pixelDimIndex;
  54970. var pAxis = point[1 - pixelDimIndex];
  54971. var pLayout = point[pixelDimIndex];
  54972. return pAxis >= axisBase && pAxis <= axisBase + layoutInfo.axisLength && pLayout >= layoutBase && pLayout <= layoutBase + layoutInfo.layoutLength;
  54973. };
  54974. Parallel.prototype.getModel = function () {
  54975. return this._model;
  54976. };
  54977. /**
  54978. * Update properties from series
  54979. */
  54980. Parallel.prototype._updateAxesFromSeries = function (parallelModel, ecModel) {
  54981. ecModel.eachSeries(function (seriesModel) {
  54982. if (!parallelModel.contains(seriesModel, ecModel)) {
  54983. return;
  54984. }
  54985. var data = seriesModel.getData();
  54986. each$5(this.dimensions, function (dim) {
  54987. var axis = this._axesMap.get(dim);
  54988. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  54989. niceScaleExtent(axis.scale, axis.model);
  54990. }, this);
  54991. }, this);
  54992. };
  54993. /**
  54994. * Resize the parallel coordinate system.
  54995. */
  54996. Parallel.prototype.resize = function (parallelModel, api) {
  54997. this._rect = getLayoutRect(parallelModel.getBoxLayoutParams(), {
  54998. width: api.getWidth(),
  54999. height: api.getHeight()
  55000. });
  55001. this._layoutAxes();
  55002. };
  55003. Parallel.prototype.getRect = function () {
  55004. return this._rect;
  55005. };
  55006. Parallel.prototype._makeLayoutInfo = function () {
  55007. var parallelModel = this._model;
  55008. var rect = this._rect;
  55009. var xy = ['x', 'y'];
  55010. var wh = ['width', 'height'];
  55011. var layout = parallelModel.get('layout');
  55012. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  55013. var layoutLength = rect[wh[pixelDimIndex]];
  55014. var layoutExtent = [0, layoutLength];
  55015. var axisCount = this.dimensions.length;
  55016. var axisExpandWidth = restrict$1(parallelModel.get('axisExpandWidth'), layoutExtent);
  55017. var axisExpandCount = restrict$1(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  55018. var axisExpandable = parallelModel.get('axisExpandable') && axisCount > 3 && axisCount > axisExpandCount && axisExpandCount > 1 && axisExpandWidth > 0 && layoutLength > 0; // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  55019. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  55020. // where collapsed axes should be overlapped.
  55021. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  55022. var winSize;
  55023. if (!axisExpandWindow) {
  55024. winSize = restrict$1(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  55025. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$1(axisCount / 2);
  55026. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  55027. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  55028. } else {
  55029. winSize = restrict$1(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  55030. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  55031. }
  55032. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount); // Avoid axisCollapseWidth is too small.
  55033. axisCollapseWidth < 3 && (axisCollapseWidth = 0); // Find the first and last indices > ewin[0] and < ewin[1].
  55034. var winInnerIndices = [mathFloor$1(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1, mathCeil$1(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1]; // Pos in ec coordinates.
  55035. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  55036. return {
  55037. layout: layout,
  55038. pixelDimIndex: pixelDimIndex,
  55039. layoutBase: rect[xy[pixelDimIndex]],
  55040. layoutLength: layoutLength,
  55041. axisBase: rect[xy[1 - pixelDimIndex]],
  55042. axisLength: rect[wh[1 - pixelDimIndex]],
  55043. axisExpandable: axisExpandable,
  55044. axisExpandWidth: axisExpandWidth,
  55045. axisCollapseWidth: axisCollapseWidth,
  55046. axisExpandWindow: axisExpandWindow,
  55047. axisCount: axisCount,
  55048. winInnerIndices: winInnerIndices,
  55049. axisExpandWindow0Pos: axisExpandWindow0Pos
  55050. };
  55051. };
  55052. Parallel.prototype._layoutAxes = function () {
  55053. var rect = this._rect;
  55054. var axes = this._axesMap;
  55055. var dimensions = this.dimensions;
  55056. var layoutInfo = this._makeLayoutInfo();
  55057. var layout = layoutInfo.layout;
  55058. axes.each(function (axis) {
  55059. var axisExtent = [0, layoutInfo.axisLength];
  55060. var idx = axis.inverse ? 1 : 0;
  55061. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  55062. });
  55063. each$5(dimensions, function (dim, idx) {
  55064. var posInfo = (layoutInfo.axisExpandable ? layoutAxisWithExpand : layoutAxisWithoutExpand)(idx, layoutInfo);
  55065. var positionTable = {
  55066. horizontal: {
  55067. x: posInfo.position,
  55068. y: layoutInfo.axisLength
  55069. },
  55070. vertical: {
  55071. x: 0,
  55072. y: posInfo.position
  55073. }
  55074. };
  55075. var rotationTable = {
  55076. horizontal: PI$7 / 2,
  55077. vertical: 0
  55078. };
  55079. var position = [positionTable[layout].x + rect.x, positionTable[layout].y + rect.y];
  55080. var rotation = rotationTable[layout];
  55081. var transform = create$1();
  55082. rotate(transform, transform, rotation);
  55083. translate(transform, transform, position); // TODO
  55084. // tick layout info
  55085. // TODO
  55086. // update dimensions info based on axis order.
  55087. this._axesLayout[dim] = {
  55088. position: position,
  55089. rotation: rotation,
  55090. transform: transform,
  55091. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  55092. axisLabelShow: posInfo.axisLabelShow,
  55093. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  55094. tickDirection: 1,
  55095. labelDirection: 1
  55096. };
  55097. }, this);
  55098. };
  55099. /**
  55100. * Get axis by dim.
  55101. */
  55102. Parallel.prototype.getAxis = function (dim) {
  55103. return this._axesMap.get(dim);
  55104. };
  55105. /**
  55106. * Convert a dim value of a single item of series data to Point.
  55107. */
  55108. Parallel.prototype.dataToPoint = function (value, dim) {
  55109. return this.axisCoordToPoint(this._axesMap.get(dim).dataToCoord(value), dim);
  55110. };
  55111. /**
  55112. * Travel data for one time, get activeState of each data item.
  55113. * @param start the start dataIndex that travel from.
  55114. * @param end the next dataIndex of the last dataIndex will be travel.
  55115. */
  55116. Parallel.prototype.eachActiveState = function (data, callback, start, end) {
  55117. start == null && (start = 0);
  55118. end == null && (end = data.count());
  55119. var axesMap = this._axesMap;
  55120. var dimensions = this.dimensions;
  55121. var dataDimensions = [];
  55122. var axisModels = [];
  55123. each(dimensions, function (axisDim) {
  55124. dataDimensions.push(data.mapDimension(axisDim));
  55125. axisModels.push(axesMap.get(axisDim).model);
  55126. });
  55127. var hasActiveSet = this.hasAxisBrushed();
  55128. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  55129. var activeState = void 0;
  55130. if (!hasActiveSet) {
  55131. activeState = 'normal';
  55132. } else {
  55133. activeState = 'active';
  55134. var values = data.getValues(dataDimensions, dataIndex);
  55135. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  55136. var state = axisModels[j].getActiveState(values[j]);
  55137. if (state === 'inactive') {
  55138. activeState = 'inactive';
  55139. break;
  55140. }
  55141. }
  55142. }
  55143. callback(activeState, dataIndex);
  55144. }
  55145. };
  55146. /**
  55147. * Whether has any activeSet.
  55148. */
  55149. Parallel.prototype.hasAxisBrushed = function () {
  55150. var dimensions = this.dimensions;
  55151. var axesMap = this._axesMap;
  55152. var hasActiveSet = false;
  55153. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  55154. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  55155. hasActiveSet = true;
  55156. }
  55157. }
  55158. return hasActiveSet;
  55159. };
  55160. /**
  55161. * Convert coords of each axis to Point.
  55162. * Return point. For example: [10, 20]
  55163. */
  55164. Parallel.prototype.axisCoordToPoint = function (coord, dim) {
  55165. var axisLayout = this._axesLayout[dim];
  55166. return applyTransform$1([coord, 0], axisLayout.transform);
  55167. };
  55168. /**
  55169. * Get axis layout.
  55170. */
  55171. Parallel.prototype.getAxisLayout = function (dim) {
  55172. return clone(this._axesLayout[dim]);
  55173. };
  55174. /**
  55175. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  55176. */
  55177. Parallel.prototype.getSlidedAxisExpandWindow = function (point) {
  55178. var layoutInfo = this._makeLayoutInfo();
  55179. var pixelDimIndex = layoutInfo.pixelDimIndex;
  55180. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  55181. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  55182. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)]; // Out of the area of coordinate system.
  55183. if (!this.containPoint(point)) {
  55184. return {
  55185. behavior: 'none',
  55186. axisExpandWindow: axisExpandWindow
  55187. };
  55188. } // Conver the point from global to expand coordinates.
  55189. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos; // For dragging operation convenience, the window should not be
  55190. // slided when mouse is the center area of the window.
  55191. var delta;
  55192. var behavior = 'slide';
  55193. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  55194. var triggerArea = this._model.get('axisExpandSlideTriggerArea'); // But consider touch device, jump is necessary.
  55195. var useJump = triggerArea[0] != null;
  55196. if (axisCollapseWidth) {
  55197. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  55198. behavior = 'jump';
  55199. delta = pointCoord - winSize * triggerArea[2];
  55200. } else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  55201. behavior = 'jump';
  55202. delta = pointCoord - winSize * (1 - triggerArea[2]);
  55203. } else {
  55204. (delta = pointCoord - winSize * triggerArea[1]) >= 0 && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0 && (delta = 0);
  55205. }
  55206. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  55207. delta ? sliderMove(delta, axisExpandWindow, extent, 'all') // Avoid nonsense triger on mousemove.
  55208. : behavior = 'none';
  55209. } // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  55210. else {
  55211. var winSize2 = axisExpandWindow[1] - axisExpandWindow[0];
  55212. var pos = extent[1] * pointCoord / winSize2;
  55213. axisExpandWindow = [mathMax$8(0, pos - winSize2 / 2)];
  55214. axisExpandWindow[1] = mathMin$8(extent[1], axisExpandWindow[0] + winSize2);
  55215. axisExpandWindow[0] = axisExpandWindow[1] - winSize2;
  55216. }
  55217. return {
  55218. axisExpandWindow: axisExpandWindow,
  55219. behavior: behavior
  55220. };
  55221. };
  55222. return Parallel;
  55223. }();
  55224. function restrict$1(len, extent) {
  55225. return mathMin$8(mathMax$8(len, extent[0]), extent[1]);
  55226. }
  55227. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  55228. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  55229. return {
  55230. position: step * axisIndex,
  55231. axisNameAvailableWidth: step,
  55232. axisLabelShow: true
  55233. };
  55234. }
  55235. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  55236. var layoutLength = layoutInfo.layoutLength;
  55237. var axisExpandWidth = layoutInfo.axisExpandWidth;
  55238. var axisCount = layoutInfo.axisCount;
  55239. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  55240. var winInnerIndices = layoutInfo.winInnerIndices;
  55241. var position;
  55242. var axisNameAvailableWidth = axisCollapseWidth;
  55243. var axisLabelShow = false;
  55244. var nameTruncateMaxWidth;
  55245. if (axisIndex < winInnerIndices[0]) {
  55246. position = axisIndex * axisCollapseWidth;
  55247. nameTruncateMaxWidth = axisCollapseWidth;
  55248. } else if (axisIndex <= winInnerIndices[1]) {
  55249. position = layoutInfo.axisExpandWindow0Pos + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  55250. axisNameAvailableWidth = axisExpandWidth;
  55251. axisLabelShow = true;
  55252. } else {
  55253. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  55254. nameTruncateMaxWidth = axisCollapseWidth;
  55255. }
  55256. return {
  55257. position: position,
  55258. axisNameAvailableWidth: axisNameAvailableWidth,
  55259. axisLabelShow: axisLabelShow,
  55260. nameTruncateMaxWidth: nameTruncateMaxWidth
  55261. };
  55262. }
  55263. function createParallelCoordSys(ecModel, api) {
  55264. var coordSysList = [];
  55265. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  55266. var coordSys = new Parallel(parallelModel, ecModel, api);
  55267. coordSys.name = 'parallel_' + idx;
  55268. coordSys.resize(parallelModel, api);
  55269. parallelModel.coordinateSystem = coordSys;
  55270. coordSys.model = parallelModel;
  55271. coordSysList.push(coordSys);
  55272. }); // Inject the coordinateSystems into seriesModel
  55273. ecModel.eachSeries(function (seriesModel) {
  55274. if (seriesModel.get('coordinateSystem') === 'parallel') {
  55275. var parallelModel = seriesModel.getReferringComponents('parallel', SINGLE_REFERRING).models[0];
  55276. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  55277. }
  55278. });
  55279. return coordSysList;
  55280. }
  55281. var parallelCoordSysCreator = {
  55282. create: createParallelCoordSys
  55283. };
  55284. var ParallelAxisModel =
  55285. /** @class */
  55286. function (_super) {
  55287. __extends(ParallelAxisModel, _super);
  55288. function ParallelAxisModel() {
  55289. var _this = _super !== null && _super.apply(this, arguments) || this;
  55290. _this.type = ParallelAxisModel.type;
  55291. /**
  55292. * @readOnly
  55293. */
  55294. _this.activeIntervals = [];
  55295. return _this;
  55296. }
  55297. ParallelAxisModel.prototype.getAreaSelectStyle = function () {
  55298. return makeStyleMapper([['fill', 'color'], ['lineWidth', 'borderWidth'], ['stroke', 'borderColor'], ['width', 'width'], ['opacity', 'opacity'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  55299. // So do not transfer decal directly.
  55300. ])(this.getModel('areaSelectStyle'));
  55301. };
  55302. /**
  55303. * The code of this feature is put on AxisModel but not ParallelAxis,
  55304. * because axisModel can be alive after echarts updating but instance of
  55305. * ParallelAxis having been disposed. this._activeInterval should be kept
  55306. * when action dispatched (i.e. legend click).
  55307. *
  55308. * @param intervals `interval.length === 0` means set all active.
  55309. */
  55310. ParallelAxisModel.prototype.setActiveIntervals = function (intervals) {
  55311. var activeIntervals = this.activeIntervals = clone(intervals); // Normalize
  55312. if (activeIntervals) {
  55313. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  55314. asc(activeIntervals[i]);
  55315. }
  55316. }
  55317. };
  55318. /**
  55319. * @param value When only attempting detect whether 'no activeIntervals set',
  55320. * `value` is not needed to be input.
  55321. */
  55322. ParallelAxisModel.prototype.getActiveState = function (value) {
  55323. var activeIntervals = this.activeIntervals;
  55324. if (!activeIntervals.length) {
  55325. return 'normal';
  55326. }
  55327. if (value == null || isNaN(+value)) {
  55328. return 'inactive';
  55329. } // Simple optimization
  55330. if (activeIntervals.length === 1) {
  55331. var interval = activeIntervals[0];
  55332. if (interval[0] <= value && value <= interval[1]) {
  55333. return 'active';
  55334. }
  55335. } else {
  55336. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  55337. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  55338. return 'active';
  55339. }
  55340. }
  55341. }
  55342. return 'inactive';
  55343. };
  55344. return ParallelAxisModel;
  55345. }(ComponentModel);
  55346. mixin(ParallelAxisModel, AxisModelCommonMixin);
  55347. var BRUSH_PANEL_GLOBAL = true;
  55348. var mathMin$9 = Math.min;
  55349. var mathMax$9 = Math.max;
  55350. var mathPow$2 = Math.pow;
  55351. var COVER_Z = 10000;
  55352. var UNSELECT_THRESHOLD = 6;
  55353. var MIN_RESIZE_LINE_WIDTH = 6;
  55354. var MUTEX_RESOURCE_KEY = 'globalPan';
  55355. var DIRECTION_MAP = {
  55356. w: [0, 0],
  55357. e: [0, 1],
  55358. n: [1, 0],
  55359. s: [1, 1]
  55360. };
  55361. var CURSOR_MAP = {
  55362. w: 'ew',
  55363. e: 'ew',
  55364. n: 'ns',
  55365. s: 'ns',
  55366. ne: 'nesw',
  55367. sw: 'nesw',
  55368. nw: 'nwse',
  55369. se: 'nwse'
  55370. };
  55371. var DEFAULT_BRUSH_OPT = {
  55372. brushStyle: {
  55373. lineWidth: 2,
  55374. stroke: 'rgba(210,219,238,0.3)',
  55375. fill: '#D2DBEE'
  55376. },
  55377. transformable: true,
  55378. brushMode: 'single',
  55379. removeOnClick: false
  55380. };
  55381. var baseUID = 0;
  55382. /**
  55383. * params:
  55384. * areas: Array.<Array>, coord relates to container group,
  55385. * If no container specified, to global.
  55386. * opt {
  55387. * isEnd: boolean,
  55388. * removeOnClick: boolean
  55389. * }
  55390. */
  55391. var BrushController =
  55392. /** @class */
  55393. function (_super) {
  55394. __extends(BrushController, _super);
  55395. function BrushController(zr) {
  55396. var _this = _super.call(this) || this;
  55397. /**
  55398. * @internal
  55399. */
  55400. _this._track = [];
  55401. /**
  55402. * @internal
  55403. */
  55404. _this._covers = [];
  55405. _this._handlers = {};
  55406. if ("development" !== 'production') {
  55407. assert(zr);
  55408. }
  55409. _this._zr = zr;
  55410. _this.group = new Group();
  55411. _this._uid = 'brushController_' + baseUID++;
  55412. each(pointerHandlers, function (handler, eventName) {
  55413. this._handlers[eventName] = bind(handler, this);
  55414. }, _this);
  55415. return _this;
  55416. }
  55417. /**
  55418. * If set to `false`, select disabled.
  55419. */
  55420. BrushController.prototype.enableBrush = function (brushOption) {
  55421. if ("development" !== 'production') {
  55422. assert(this._mounted);
  55423. }
  55424. this._brushType && this._doDisableBrush();
  55425. brushOption.brushType && this._doEnableBrush(brushOption);
  55426. return this;
  55427. };
  55428. BrushController.prototype._doEnableBrush = function (brushOption) {
  55429. var zr = this._zr; // Consider roam, which takes globalPan too.
  55430. if (!this._enableGlobalPan) {
  55431. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  55432. }
  55433. each(this._handlers, function (handler, eventName) {
  55434. zr.on(eventName, handler);
  55435. });
  55436. this._brushType = brushOption.brushType;
  55437. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  55438. };
  55439. BrushController.prototype._doDisableBrush = function () {
  55440. var zr = this._zr;
  55441. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  55442. each(this._handlers, function (handler, eventName) {
  55443. zr.off(eventName, handler);
  55444. });
  55445. this._brushType = this._brushOption = null;
  55446. };
  55447. /**
  55448. * @param panelOpts If not pass, it is global brush.
  55449. */
  55450. BrushController.prototype.setPanels = function (panelOpts) {
  55451. if (panelOpts && panelOpts.length) {
  55452. var panels_1 = this._panels = {};
  55453. each(panelOpts, function (panelOpts) {
  55454. panels_1[panelOpts.panelId] = clone(panelOpts);
  55455. });
  55456. } else {
  55457. this._panels = null;
  55458. }
  55459. return this;
  55460. };
  55461. BrushController.prototype.mount = function (opt) {
  55462. opt = opt || {};
  55463. if ("development" !== 'production') {
  55464. this._mounted = true; // should be at first.
  55465. }
  55466. this._enableGlobalPan = opt.enableGlobalPan;
  55467. var thisGroup = this.group;
  55468. this._zr.add(thisGroup);
  55469. thisGroup.attr({
  55470. x: opt.x || 0,
  55471. y: opt.y || 0,
  55472. rotation: opt.rotation || 0,
  55473. scaleX: opt.scaleX || 1,
  55474. scaleY: opt.scaleY || 1
  55475. });
  55476. this._transform = thisGroup.getLocalTransform();
  55477. return this;
  55478. }; // eachCover(cb, context): void {
  55479. // each(this._covers, cb, context);
  55480. // }
  55481. /**
  55482. * Update covers.
  55483. * @param coverConfigList
  55484. * If coverConfigList is null/undefined, all covers removed.
  55485. */
  55486. BrushController.prototype.updateCovers = function (coverConfigList) {
  55487. if ("development" !== 'production') {
  55488. assert(this._mounted);
  55489. }
  55490. coverConfigList = map(coverConfigList, function (coverConfig) {
  55491. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  55492. });
  55493. var tmpIdPrefix = '\0-brush-index-';
  55494. var oldCovers = this._covers;
  55495. var newCovers = this._covers = [];
  55496. var controller = this;
  55497. var creatingCover = this._creatingCover;
  55498. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  55499. return this;
  55500. function getKey(brushOption, index) {
  55501. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  55502. }
  55503. function oldGetKey(cover, index) {
  55504. return getKey(cover.__brushOption, index);
  55505. }
  55506. function addOrUpdate(newIndex, oldIndex) {
  55507. var newBrushInternal = coverConfigList[newIndex]; // Consider setOption in event listener of brushSelect,
  55508. // where updating cover when creating should be forbiden.
  55509. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  55510. newCovers[newIndex] = oldCovers[oldIndex];
  55511. } else {
  55512. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  55513. updateCoverAfterCreation(controller, cover);
  55514. }
  55515. }
  55516. function remove(oldIndex) {
  55517. if (oldCovers[oldIndex] !== creatingCover) {
  55518. controller.group.remove(oldCovers[oldIndex]);
  55519. }
  55520. }
  55521. };
  55522. BrushController.prototype.unmount = function () {
  55523. if ("development" !== 'production') {
  55524. if (!this._mounted) {
  55525. return;
  55526. }
  55527. }
  55528. this.enableBrush(false); // container may 'removeAll' outside.
  55529. clearCovers(this);
  55530. this._zr.remove(this.group);
  55531. if ("development" !== 'production') {
  55532. this._mounted = false; // should be at last.
  55533. }
  55534. return this;
  55535. };
  55536. BrushController.prototype.dispose = function () {
  55537. this.unmount();
  55538. this.off();
  55539. };
  55540. return BrushController;
  55541. }(Eventful);
  55542. function createCover(controller, brushOption) {
  55543. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  55544. cover.__brushOption = brushOption;
  55545. updateZ(cover, brushOption);
  55546. controller.group.add(cover);
  55547. return cover;
  55548. }
  55549. function endCreating(controller, creatingCover) {
  55550. var coverRenderer = getCoverRenderer(creatingCover);
  55551. if (coverRenderer.endCreating) {
  55552. coverRenderer.endCreating(controller, creatingCover);
  55553. updateZ(creatingCover, creatingCover.__brushOption);
  55554. }
  55555. return creatingCover;
  55556. }
  55557. function updateCoverShape(controller, cover) {
  55558. var brushOption = cover.__brushOption;
  55559. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  55560. }
  55561. function updateZ(cover, brushOption) {
  55562. var z = brushOption.z;
  55563. z == null && (z = COVER_Z);
  55564. cover.traverse(function (el) {
  55565. el.z = z;
  55566. el.z2 = z; // Consider in given container.
  55567. });
  55568. }
  55569. function updateCoverAfterCreation(controller, cover) {
  55570. getCoverRenderer(cover).updateCommon(controller, cover);
  55571. updateCoverShape(controller, cover);
  55572. }
  55573. function getCoverRenderer(cover) {
  55574. return coverRenderers[cover.__brushOption.brushType];
  55575. } // return target panel or `true` (means global panel)
  55576. function getPanelByPoint(controller, e, localCursorPoint) {
  55577. var panels = controller._panels;
  55578. if (!panels) {
  55579. return BRUSH_PANEL_GLOBAL; // Global panel
  55580. }
  55581. var panel;
  55582. var transform = controller._transform;
  55583. each(panels, function (pn) {
  55584. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  55585. });
  55586. return panel;
  55587. } // Return a panel or true
  55588. function getPanelByCover(controller, cover) {
  55589. var panels = controller._panels;
  55590. if (!panels) {
  55591. return BRUSH_PANEL_GLOBAL; // Global panel
  55592. }
  55593. var panelId = cover.__brushOption.panelId; // User may give cover without coord sys info,
  55594. // which is then treated as global panel.
  55595. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  55596. }
  55597. function clearCovers(controller) {
  55598. var covers = controller._covers;
  55599. var originalLength = covers.length;
  55600. each(covers, function (cover) {
  55601. controller.group.remove(cover);
  55602. }, controller);
  55603. covers.length = 0;
  55604. return !!originalLength;
  55605. }
  55606. function trigger$1(controller, opt) {
  55607. var areas = map(controller._covers, function (cover) {
  55608. var brushOption = cover.__brushOption;
  55609. var range = clone(brushOption.range);
  55610. return {
  55611. brushType: brushOption.brushType,
  55612. panelId: brushOption.panelId,
  55613. range: range
  55614. };
  55615. });
  55616. controller.trigger('brush', {
  55617. areas: areas,
  55618. isEnd: !!opt.isEnd,
  55619. removeOnClick: !!opt.removeOnClick
  55620. });
  55621. }
  55622. function shouldShowCover(controller) {
  55623. var track = controller._track;
  55624. if (!track.length) {
  55625. return false;
  55626. }
  55627. var p2 = track[track.length - 1];
  55628. var p1 = track[0];
  55629. var dx = p2[0] - p1[0];
  55630. var dy = p2[1] - p1[1];
  55631. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  55632. return dist > UNSELECT_THRESHOLD;
  55633. }
  55634. function getTrackEnds(track) {
  55635. var tail = track.length - 1;
  55636. tail < 0 && (tail = 0);
  55637. return [track[0], track[tail]];
  55638. }
  55639. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  55640. var cover = new Group();
  55641. cover.add(new Rect({
  55642. name: 'main',
  55643. style: makeStyle(brushOption),
  55644. silent: true,
  55645. draggable: true,
  55646. cursor: 'move',
  55647. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  55648. ondragend: curry(trigger$1, controller, {
  55649. isEnd: true
  55650. })
  55651. }));
  55652. each(edgeNameSequences, function (nameSequence) {
  55653. cover.add(new Rect({
  55654. name: nameSequence.join(''),
  55655. style: {
  55656. opacity: 0
  55657. },
  55658. draggable: true,
  55659. silent: true,
  55660. invisible: true,
  55661. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  55662. ondragend: curry(trigger$1, controller, {
  55663. isEnd: true
  55664. })
  55665. }));
  55666. });
  55667. return cover;
  55668. }
  55669. function updateBaseRect(controller, cover, localRange, brushOption) {
  55670. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  55671. var handleSize = mathMax$9(lineWidth, MIN_RESIZE_LINE_WIDTH);
  55672. var x = localRange[0][0];
  55673. var y = localRange[1][0];
  55674. var xa = x - lineWidth / 2;
  55675. var ya = y - lineWidth / 2;
  55676. var x2 = localRange[0][1];
  55677. var y2 = localRange[1][1];
  55678. var x2a = x2 - handleSize + lineWidth / 2;
  55679. var y2a = y2 - handleSize + lineWidth / 2;
  55680. var width = x2 - x;
  55681. var height = y2 - y;
  55682. var widtha = width + lineWidth;
  55683. var heighta = height + lineWidth;
  55684. updateRectShape(controller, cover, 'main', x, y, width, height);
  55685. if (brushOption.transformable) {
  55686. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  55687. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  55688. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  55689. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  55690. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  55691. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  55692. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  55693. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  55694. }
  55695. }
  55696. function updateCommon(controller, cover) {
  55697. var brushOption = cover.__brushOption;
  55698. var transformable = brushOption.transformable;
  55699. var mainEl = cover.childAt(0);
  55700. mainEl.useStyle(makeStyle(brushOption));
  55701. mainEl.attr({
  55702. silent: !transformable,
  55703. cursor: transformable ? 'move' : 'default'
  55704. });
  55705. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  55706. var el = cover.childOfName(nameSequence.join(''));
  55707. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  55708. el && el.attr({
  55709. silent: !transformable,
  55710. invisible: !transformable,
  55711. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  55712. });
  55713. });
  55714. }
  55715. function updateRectShape(controller, cover, name, x, y, w, h) {
  55716. var el = cover.childOfName(name);
  55717. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  55718. }
  55719. function makeStyle(brushOption) {
  55720. return defaults({
  55721. strokeNoScale: true
  55722. }, brushOption.brushStyle);
  55723. }
  55724. function formatRectRange(x, y, x2, y2) {
  55725. var min = [mathMin$9(x, x2), mathMin$9(y, y2)];
  55726. var max = [mathMax$9(x, x2), mathMax$9(y, y2)];
  55727. return [[min[0], max[0]], [min[1], max[1]] // y range
  55728. ];
  55729. }
  55730. function getTransform$1(controller) {
  55731. return getTransform(controller.group);
  55732. }
  55733. function getGlobalDirection1(controller, localDirName) {
  55734. var map = {
  55735. w: 'left',
  55736. e: 'right',
  55737. n: 'top',
  55738. s: 'bottom'
  55739. };
  55740. var inverseMap = {
  55741. left: 'w',
  55742. right: 'e',
  55743. top: 'n',
  55744. bottom: 's'
  55745. };
  55746. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  55747. return inverseMap[dir];
  55748. }
  55749. function getGlobalDirection2(controller, localDirNameSeq) {
  55750. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  55751. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  55752. return globalDir.join('');
  55753. }
  55754. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  55755. var brushOption = cover.__brushOption;
  55756. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  55757. var localDelta = toLocalDelta(controller, dx, dy);
  55758. each(dirNameSequence, function (dirName) {
  55759. var ind = DIRECTION_MAP[dirName];
  55760. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  55761. });
  55762. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  55763. updateCoverAfterCreation(controller, cover);
  55764. trigger$1(controller, {
  55765. isEnd: false
  55766. });
  55767. }
  55768. function driftPolygon(controller, cover, dx, dy) {
  55769. var range = cover.__brushOption.range;
  55770. var localDelta = toLocalDelta(controller, dx, dy);
  55771. each(range, function (point) {
  55772. point[0] += localDelta[0];
  55773. point[1] += localDelta[1];
  55774. });
  55775. updateCoverAfterCreation(controller, cover);
  55776. trigger$1(controller, {
  55777. isEnd: false
  55778. });
  55779. }
  55780. function toLocalDelta(controller, dx, dy) {
  55781. var thisGroup = controller.group;
  55782. var localD = thisGroup.transformCoordToLocal(dx, dy);
  55783. var localZero = thisGroup.transformCoordToLocal(0, 0);
  55784. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  55785. }
  55786. function clipByPanel(controller, cover, data) {
  55787. var panel = getPanelByCover(controller, cover);
  55788. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  55789. }
  55790. function pointsToRect(points) {
  55791. var xmin = mathMin$9(points[0][0], points[1][0]);
  55792. var ymin = mathMin$9(points[0][1], points[1][1]);
  55793. var xmax = mathMax$9(points[0][0], points[1][0]);
  55794. var ymax = mathMax$9(points[0][1], points[1][1]);
  55795. return {
  55796. x: xmin,
  55797. y: ymin,
  55798. width: xmax - xmin,
  55799. height: ymax - ymin
  55800. };
  55801. }
  55802. function resetCursor(controller, e, localCursorPoint) {
  55803. if ( // Check active
  55804. !controller._brushType // resetCursor should be always called when mouse is in zr area,
  55805. // but not called when mouse is out of zr area to avoid bad influence
  55806. // if `mousemove`, `mouseup` are triggered from `document` event.
  55807. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  55808. return;
  55809. }
  55810. var zr = controller._zr;
  55811. var covers = controller._covers;
  55812. var currPanel = getPanelByPoint(controller, e, localCursorPoint); // Check whether in covers.
  55813. if (!controller._dragging) {
  55814. for (var i = 0; i < covers.length; i++) {
  55815. var brushOption = covers[i].__brushOption;
  55816. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  55817. // Use cursor style set on cover.
  55818. return;
  55819. }
  55820. }
  55821. }
  55822. currPanel && zr.setCursorStyle('crosshair');
  55823. }
  55824. function preventDefault(e) {
  55825. var rawE = e.event;
  55826. rawE.preventDefault && rawE.preventDefault();
  55827. }
  55828. function mainShapeContain(cover, x, y) {
  55829. return cover.childOfName('main').contain(x, y);
  55830. }
  55831. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  55832. var creatingCover = controller._creatingCover;
  55833. var panel = controller._creatingPanel;
  55834. var thisBrushOption = controller._brushOption;
  55835. var eventParams;
  55836. controller._track.push(localCursorPoint.slice());
  55837. if (shouldShowCover(controller) || creatingCover) {
  55838. if (panel && !creatingCover) {
  55839. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  55840. var brushOption = clone(thisBrushOption);
  55841. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  55842. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  55843. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  55844. controller._covers.push(creatingCover);
  55845. }
  55846. if (creatingCover) {
  55847. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  55848. var coverBrushOption = creatingCover.__brushOption;
  55849. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  55850. if (isEnd) {
  55851. endCreating(controller, creatingCover);
  55852. coverRenderer.updateCommon(controller, creatingCover);
  55853. }
  55854. updateCoverShape(controller, creatingCover);
  55855. eventParams = {
  55856. isEnd: isEnd
  55857. };
  55858. }
  55859. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  55860. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  55861. // But a single click do not clear covers, because user may have casual
  55862. // clicks (for example, click on other component and do not expect covers
  55863. // disappear).
  55864. // Only some cover removed, trigger action, but not every click trigger action.
  55865. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  55866. eventParams = {
  55867. isEnd: isEnd,
  55868. removeOnClick: true
  55869. };
  55870. }
  55871. }
  55872. return eventParams;
  55873. }
  55874. function determineBrushType(brushType, panel) {
  55875. if (brushType === 'auto') {
  55876. if ("development" !== 'production') {
  55877. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  55878. }
  55879. return panel.defaultBrushType;
  55880. }
  55881. return brushType;
  55882. }
  55883. var pointerHandlers = {
  55884. mousedown: function (e) {
  55885. if (this._dragging) {
  55886. // In case some browser do not support globalOut,
  55887. // and release mouse out side the browser.
  55888. handleDragEnd(this, e);
  55889. } else if (!e.target || !e.target.draggable) {
  55890. preventDefault(e);
  55891. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  55892. this._creatingCover = null;
  55893. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  55894. if (panel) {
  55895. this._dragging = true;
  55896. this._track = [localCursorPoint.slice()];
  55897. }
  55898. }
  55899. },
  55900. mousemove: function (e) {
  55901. var x = e.offsetX;
  55902. var y = e.offsetY;
  55903. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  55904. resetCursor(this, e, localCursorPoint);
  55905. if (this._dragging) {
  55906. preventDefault(e);
  55907. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  55908. eventParams && trigger$1(this, eventParams);
  55909. }
  55910. },
  55911. mouseup: function (e) {
  55912. handleDragEnd(this, e);
  55913. }
  55914. };
  55915. function handleDragEnd(controller, e) {
  55916. if (controller._dragging) {
  55917. preventDefault(e);
  55918. var x = e.offsetX;
  55919. var y = e.offsetY;
  55920. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  55921. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  55922. controller._dragging = false;
  55923. controller._track = [];
  55924. controller._creatingCover = null; // trigger event shoule be at final, after procedure will be nested.
  55925. eventParams && trigger$1(controller, eventParams);
  55926. }
  55927. }
  55928. function isOutsideZrArea(controller, x, y) {
  55929. var zr = controller._zr;
  55930. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  55931. }
  55932. /**
  55933. * key: brushType
  55934. */
  55935. var coverRenderers = {
  55936. lineX: getLineRenderer(0),
  55937. lineY: getLineRenderer(1),
  55938. rect: {
  55939. createCover: function (controller, brushOption) {
  55940. function returnInput(range) {
  55941. return range;
  55942. }
  55943. return createBaseRectCover({
  55944. toRectRange: returnInput,
  55945. fromRectRange: returnInput
  55946. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  55947. },
  55948. getCreatingRange: function (localTrack) {
  55949. var ends = getTrackEnds(localTrack);
  55950. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  55951. },
  55952. updateCoverShape: function (controller, cover, localRange, brushOption) {
  55953. updateBaseRect(controller, cover, localRange, brushOption);
  55954. },
  55955. updateCommon: updateCommon,
  55956. contain: mainShapeContain
  55957. },
  55958. polygon: {
  55959. createCover: function (controller, brushOption) {
  55960. var cover = new Group(); // Do not use graphic.Polygon because graphic.Polyline do not close the
  55961. // border of the shape when drawing, which is a better experience for user.
  55962. cover.add(new Polyline({
  55963. name: 'main',
  55964. style: makeStyle(brushOption),
  55965. silent: true
  55966. }));
  55967. return cover;
  55968. },
  55969. getCreatingRange: function (localTrack) {
  55970. return localTrack;
  55971. },
  55972. endCreating: function (controller, cover) {
  55973. cover.remove(cover.childAt(0)); // Use graphic.Polygon close the shape.
  55974. cover.add(new Polygon({
  55975. name: 'main',
  55976. draggable: true,
  55977. drift: curry(driftPolygon, controller, cover),
  55978. ondragend: curry(trigger$1, controller, {
  55979. isEnd: true
  55980. })
  55981. }));
  55982. },
  55983. updateCoverShape: function (controller, cover, localRange, brushOption) {
  55984. cover.childAt(0).setShape({
  55985. points: clipByPanel(controller, cover, localRange)
  55986. });
  55987. },
  55988. updateCommon: updateCommon,
  55989. contain: mainShapeContain
  55990. }
  55991. };
  55992. function getLineRenderer(xyIndex) {
  55993. return {
  55994. createCover: function (controller, brushOption) {
  55995. return createBaseRectCover({
  55996. toRectRange: function (range) {
  55997. var rectRange = [range, [0, 100]];
  55998. xyIndex && rectRange.reverse();
  55999. return rectRange;
  56000. },
  56001. fromRectRange: function (rectRange) {
  56002. return rectRange[xyIndex];
  56003. }
  56004. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  56005. },
  56006. getCreatingRange: function (localTrack) {
  56007. var ends = getTrackEnds(localTrack);
  56008. var min = mathMin$9(ends[0][xyIndex], ends[1][xyIndex]);
  56009. var max = mathMax$9(ends[0][xyIndex], ends[1][xyIndex]);
  56010. return [min, max];
  56011. },
  56012. updateCoverShape: function (controller, cover, localRange, brushOption) {
  56013. var otherExtent; // If brushWidth not specified, fit the panel.
  56014. var panel = getPanelByCover(controller, cover);
  56015. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  56016. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  56017. } else {
  56018. var zr = controller._zr;
  56019. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  56020. }
  56021. var rectRange = [localRange, otherExtent];
  56022. xyIndex && rectRange.reverse();
  56023. updateBaseRect(controller, cover, rectRange, brushOption);
  56024. },
  56025. updateCommon: updateCommon,
  56026. contain: mainShapeContain
  56027. };
  56028. }
  56029. function makeRectPanelClipPath(rect) {
  56030. rect = normalizeRect(rect);
  56031. return function (localPoints) {
  56032. return clipPointsByRect(localPoints, rect);
  56033. };
  56034. }
  56035. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  56036. rect = normalizeRect(rect);
  56037. return function (xyIndex) {
  56038. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  56039. var brushWidth = idx ? rect.width : rect.height;
  56040. var base = idx ? rect.x : rect.y;
  56041. return [base, base + (brushWidth || 0)];
  56042. };
  56043. }
  56044. function makeRectIsTargetByCursor(rect, api, targetModel) {
  56045. var boundingRect = normalizeRect(rect);
  56046. return function (e, localCursorPoint) {
  56047. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  56048. };
  56049. } // Consider width/height is negative.
  56050. function normalizeRect(rect) {
  56051. return BoundingRect.create(rect);
  56052. }
  56053. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  56054. var ParallelAxisView =
  56055. /** @class */
  56056. function (_super) {
  56057. __extends(ParallelAxisView, _super);
  56058. function ParallelAxisView() {
  56059. var _this = _super !== null && _super.apply(this, arguments) || this;
  56060. _this.type = ParallelAxisView.type;
  56061. return _this;
  56062. }
  56063. ParallelAxisView.prototype.init = function (ecModel, api) {
  56064. _super.prototype.init.apply(this, arguments);
  56065. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this));
  56066. };
  56067. ParallelAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  56068. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  56069. return;
  56070. }
  56071. this.axisModel = axisModel;
  56072. this.api = api;
  56073. this.group.removeAll();
  56074. var oldAxisGroup = this._axisGroup;
  56075. this._axisGroup = new Group();
  56076. this.group.add(this._axisGroup);
  56077. if (!axisModel.get('show')) {
  56078. return;
  56079. }
  56080. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  56081. var coordSys = coordSysModel.coordinateSystem;
  56082. var areaSelectStyle = axisModel.getAreaSelectStyle();
  56083. var areaWidth = areaSelectStyle.width;
  56084. var dim = axisModel.axis.dim;
  56085. var axisLayout = coordSys.getAxisLayout(dim);
  56086. var builderOpt = extend({
  56087. strokeContainThreshold: areaWidth
  56088. }, axisLayout);
  56089. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  56090. each(elementList, axisBuilder.add, axisBuilder);
  56091. this._axisGroup.add(axisBuilder.getGroup());
  56092. this._refreshBrushController(builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api);
  56093. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  56094. }; // /**
  56095. // * @override
  56096. // */
  56097. // updateVisual(axisModel, ecModel, api, payload) {
  56098. // this._brushController && this._brushController
  56099. // .updateCovers(getCoverInfoList(axisModel));
  56100. // }
  56101. ParallelAxisView.prototype._refreshBrushController = function (builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api) {
  56102. // After filtering, axis may change, select area needs to be update.
  56103. var extent = axisModel.axis.getExtent();
  56104. var extentLen = extent[1] - extent[0];
  56105. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  56106. // width/height might be negative, which will be
  56107. // normalized in BoundingRect.
  56108. var rect = BoundingRect.create({
  56109. x: extent[0],
  56110. y: -areaWidth / 2,
  56111. width: extentLen,
  56112. height: areaWidth
  56113. });
  56114. rect.x -= extra;
  56115. rect.width += 2 * extra;
  56116. this._brushController.mount({
  56117. enableGlobalPan: true,
  56118. rotation: builderOpt.rotation,
  56119. x: builderOpt.position[0],
  56120. y: builderOpt.position[1]
  56121. }).setPanels([{
  56122. panelId: 'pl',
  56123. clipPath: makeRectPanelClipPath(rect),
  56124. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  56125. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  56126. }]).enableBrush({
  56127. brushType: 'lineX',
  56128. brushStyle: areaSelectStyle,
  56129. removeOnClick: true
  56130. }).updateCovers(getCoverInfoList(axisModel));
  56131. };
  56132. ParallelAxisView.prototype._onBrush = function (eventParam) {
  56133. var coverInfoList = eventParam.areas; // Do not cache these object, because the mey be changed.
  56134. var axisModel = this.axisModel;
  56135. var axis = axisModel.axis;
  56136. var intervals = map(coverInfoList, function (coverInfo) {
  56137. return [axis.coordToData(coverInfo.range[0], true), axis.coordToData(coverInfo.range[1], true)];
  56138. }); // If realtime is true, action is not dispatched on drag end, because
  56139. // the drag end emits the same params with the last drag move event,
  56140. // and may have some delay when using touch pad.
  56141. if (!axisModel.option.realtime === eventParam.isEnd || eventParam.removeOnClick) {
  56142. // jshint ignore:line
  56143. this.api.dispatchAction({
  56144. type: 'axisAreaSelect',
  56145. parallelAxisId: axisModel.id,
  56146. intervals: intervals
  56147. });
  56148. }
  56149. };
  56150. ParallelAxisView.prototype.dispose = function () {
  56151. this._brushController.dispose();
  56152. };
  56153. ParallelAxisView.type = 'parallelAxis';
  56154. return ParallelAxisView;
  56155. }(ComponentView);
  56156. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  56157. return payload && payload.type === 'axisAreaSelect' && ecModel.findComponents({
  56158. mainType: 'parallelAxis',
  56159. query: payload
  56160. })[0] === axisModel;
  56161. }
  56162. function getCoverInfoList(axisModel) {
  56163. var axis = axisModel.axis;
  56164. return map(axisModel.activeIntervals, function (interval) {
  56165. return {
  56166. brushType: 'lineX',
  56167. panelId: 'pl',
  56168. range: [axis.dataToCoord(interval[0], true), axis.dataToCoord(interval[1], true)]
  56169. };
  56170. });
  56171. }
  56172. function getCoordSysModel(axisModel, ecModel) {
  56173. return ecModel.getComponent('parallel', axisModel.get('parallelIndex'));
  56174. }
  56175. /*
  56176. * Licensed to the Apache Software Foundation (ASF) under one
  56177. * or more contributor license agreements. See the NOTICE file
  56178. * distributed with this work for additional information
  56179. * regarding copyright ownership. The ASF licenses this file
  56180. * to you under the Apache License, Version 2.0 (the
  56181. * "License"); you may not use this file except in compliance
  56182. * with the License. You may obtain a copy of the License at
  56183. *
  56184. * http://www.apache.org/licenses/LICENSE-2.0
  56185. *
  56186. * Unless required by applicable law or agreed to in writing,
  56187. * software distributed under the License is distributed on an
  56188. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56189. * KIND, either express or implied. See the License for the
  56190. * specific language governing permissions and limitations
  56191. * under the License.
  56192. */
  56193. /**
  56194. * AUTO-GENERATED FILE. DO NOT MODIFY.
  56195. */
  56196. /*
  56197. * Licensed to the Apache Software Foundation (ASF) under one
  56198. * or more contributor license agreements. See the NOTICE file
  56199. * distributed with this work for additional information
  56200. * regarding copyright ownership. The ASF licenses this file
  56201. * to you under the Apache License, Version 2.0 (the
  56202. * "License"); you may not use this file except in compliance
  56203. * with the License. You may obtain a copy of the License at
  56204. *
  56205. * http://www.apache.org/licenses/LICENSE-2.0
  56206. *
  56207. * Unless required by applicable law or agreed to in writing,
  56208. * software distributed under the License is distributed on an
  56209. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56210. * KIND, either express or implied. See the License for the
  56211. * specific language governing permissions and limitations
  56212. * under the License.
  56213. */
  56214. var actionInfo$1 = {
  56215. type: 'axisAreaSelect',
  56216. event: 'axisAreaSelected' // update: 'updateVisual'
  56217. };
  56218. function installParallelActions(registers) {
  56219. registers.registerAction(actionInfo$1, function (payload, ecModel) {
  56220. ecModel.eachComponent({
  56221. mainType: 'parallelAxis',
  56222. query: payload
  56223. }, function (parallelAxisModel) {
  56224. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  56225. });
  56226. });
  56227. /**
  56228. * @payload
  56229. */
  56230. registers.registerAction('parallelAxisExpand', function (payload, ecModel) {
  56231. ecModel.eachComponent({
  56232. mainType: 'parallel',
  56233. query: payload
  56234. }, function (parallelModel) {
  56235. parallelModel.setAxisExpand(payload);
  56236. });
  56237. });
  56238. }
  56239. var defaultAxisOption = {
  56240. type: 'value',
  56241. areaSelectStyle: {
  56242. width: 20,
  56243. borderWidth: 1,
  56244. borderColor: 'rgba(160,197,232)',
  56245. color: 'rgba(160,197,232)',
  56246. opacity: 0.3
  56247. },
  56248. realtime: true,
  56249. z: 10
  56250. };
  56251. function install$g(registers) {
  56252. registers.registerComponentView(ParallelView$1);
  56253. registers.registerComponentModel(ParallelModel);
  56254. registers.registerCoordinateSystem('parallel', parallelCoordSysCreator);
  56255. registers.registerPreprocessor(parallelPreprocessor);
  56256. registers.registerComponentModel(ParallelAxisModel);
  56257. registers.registerComponentView(ParallelAxisView);
  56258. axisModelCreator(registers, 'parallel', ParallelAxisModel, defaultAxisOption);
  56259. installParallelActions(registers);
  56260. }
  56261. function install$h(registers) {
  56262. use(install$g);
  56263. registers.registerChartView(ParallelView);
  56264. registers.registerSeriesModel(ParallelSeriesModel);
  56265. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, parallelVisual);
  56266. }
  56267. var SankeyPathShape =
  56268. /** @class */
  56269. function () {
  56270. function SankeyPathShape() {
  56271. this.x1 = 0;
  56272. this.y1 = 0;
  56273. this.x2 = 0;
  56274. this.y2 = 0;
  56275. this.cpx1 = 0;
  56276. this.cpy1 = 0;
  56277. this.cpx2 = 0;
  56278. this.cpy2 = 0;
  56279. this.extent = 0;
  56280. }
  56281. return SankeyPathShape;
  56282. }();
  56283. var SankeyPath =
  56284. /** @class */
  56285. function (_super) {
  56286. __extends(SankeyPath, _super);
  56287. function SankeyPath(opts) {
  56288. return _super.call(this, opts) || this;
  56289. }
  56290. SankeyPath.prototype.getDefaultShape = function () {
  56291. return new SankeyPathShape();
  56292. };
  56293. SankeyPath.prototype.buildPath = function (ctx, shape) {
  56294. var extent = shape.extent;
  56295. ctx.moveTo(shape.x1, shape.y1);
  56296. ctx.bezierCurveTo(shape.cpx1, shape.cpy1, shape.cpx2, shape.cpy2, shape.x2, shape.y2);
  56297. if (shape.orient === 'vertical') {
  56298. ctx.lineTo(shape.x2 + extent, shape.y2);
  56299. ctx.bezierCurveTo(shape.cpx2 + extent, shape.cpy2, shape.cpx1 + extent, shape.cpy1, shape.x1 + extent, shape.y1);
  56300. } else {
  56301. ctx.lineTo(shape.x2, shape.y2 + extent);
  56302. ctx.bezierCurveTo(shape.cpx2, shape.cpy2 + extent, shape.cpx1, shape.cpy1 + extent, shape.x1, shape.y1 + extent);
  56303. }
  56304. ctx.closePath();
  56305. };
  56306. SankeyPath.prototype.highlight = function () {
  56307. enterEmphasis(this);
  56308. };
  56309. SankeyPath.prototype.downplay = function () {
  56310. leaveEmphasis(this);
  56311. };
  56312. return SankeyPath;
  56313. }(Path);
  56314. var SankeyView =
  56315. /** @class */
  56316. function (_super) {
  56317. __extends(SankeyView, _super);
  56318. function SankeyView() {
  56319. var _this = _super !== null && _super.apply(this, arguments) || this;
  56320. _this.type = SankeyView.type;
  56321. _this._focusAdjacencyDisabled = false;
  56322. return _this;
  56323. }
  56324. SankeyView.prototype.render = function (seriesModel, ecModel, api) {
  56325. var sankeyView = this;
  56326. var graph = seriesModel.getGraph();
  56327. var group = this.group;
  56328. var layoutInfo = seriesModel.layoutInfo; // view width
  56329. var width = layoutInfo.width; // view height
  56330. var height = layoutInfo.height;
  56331. var nodeData = seriesModel.getData();
  56332. var edgeData = seriesModel.getData('edge');
  56333. var orient = seriesModel.get('orient');
  56334. this._model = seriesModel;
  56335. group.removeAll();
  56336. group.x = layoutInfo.x;
  56337. group.y = layoutInfo.y; // generate a bezire Curve for each edge
  56338. graph.eachEdge(function (edge) {
  56339. var curve = new SankeyPath();
  56340. var ecData = getECData(curve);
  56341. ecData.dataIndex = edge.dataIndex;
  56342. ecData.seriesIndex = seriesModel.seriesIndex;
  56343. ecData.dataType = 'edge';
  56344. var edgeModel = edge.getModel();
  56345. var lineStyleModel = edgeModel.getModel('lineStyle');
  56346. var curvature = lineStyleModel.get('curveness');
  56347. var n1Layout = edge.node1.getLayout();
  56348. var node1Model = edge.node1.getModel();
  56349. var dragX1 = node1Model.get('localX');
  56350. var dragY1 = node1Model.get('localY');
  56351. var n2Layout = edge.node2.getLayout();
  56352. var node2Model = edge.node2.getModel();
  56353. var dragX2 = node2Model.get('localX');
  56354. var dragY2 = node2Model.get('localY');
  56355. var edgeLayout = edge.getLayout();
  56356. var x1;
  56357. var y1;
  56358. var x2;
  56359. var y2;
  56360. var cpx1;
  56361. var cpy1;
  56362. var cpx2;
  56363. var cpy2;
  56364. curve.shape.extent = Math.max(1, edgeLayout.dy);
  56365. curve.shape.orient = orient;
  56366. if (orient === 'vertical') {
  56367. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  56368. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  56369. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  56370. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  56371. cpx1 = x1;
  56372. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  56373. cpx2 = x2;
  56374. cpy2 = y1 * curvature + y2 * (1 - curvature);
  56375. } else {
  56376. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  56377. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  56378. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  56379. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  56380. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  56381. cpy1 = y1;
  56382. cpx2 = x1 * curvature + x2 * (1 - curvature);
  56383. cpy2 = y2;
  56384. }
  56385. curve.setShape({
  56386. x1: x1,
  56387. y1: y1,
  56388. x2: x2,
  56389. y2: y2,
  56390. cpx1: cpx1,
  56391. cpy1: cpy1,
  56392. cpx2: cpx2,
  56393. cpy2: cpy2
  56394. });
  56395. curve.useStyle(lineStyleModel.getItemStyle()); // Special color, use source node color or target node color
  56396. switch (curve.style.fill) {
  56397. case 'source':
  56398. curve.style.fill = edge.node1.getVisual('color');
  56399. curve.style.decal = edge.node1.getVisual('style').decal;
  56400. break;
  56401. case 'target':
  56402. curve.style.fill = edge.node2.getVisual('color');
  56403. curve.style.decal = edge.node2.getVisual('style').decal;
  56404. break;
  56405. case 'gradient':
  56406. var sourceColor = edge.node1.getVisual('color');
  56407. var targetColor = edge.node2.getVisual('color');
  56408. if (typeof sourceColor === 'string' && typeof targetColor === 'string') {
  56409. curve.style.fill = new LinearGradient(0, 0, +(orient === 'horizontal'), +(orient === 'vertical'), [{
  56410. color: sourceColor,
  56411. offset: 0
  56412. }, {
  56413. color: targetColor,
  56414. offset: 1
  56415. }]);
  56416. }
  56417. }
  56418. var emphasisModel = edgeModel.getModel('emphasis');
  56419. setStatesStylesFromModel(curve, edgeModel, 'lineStyle', function (model) {
  56420. return model.getItemStyle();
  56421. });
  56422. group.add(curve);
  56423. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  56424. var focus = emphasisModel.get('focus');
  56425. enableHoverEmphasis(curve, focus === 'adjacency' ? edge.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope'));
  56426. getECData(curve).dataType = 'edge';
  56427. }); // Generate a rect for each node
  56428. graph.eachNode(function (node) {
  56429. var layout = node.getLayout();
  56430. var itemModel = node.getModel();
  56431. var dragX = itemModel.get('localX');
  56432. var dragY = itemModel.get('localY');
  56433. var emphasisModel = itemModel.getModel('emphasis');
  56434. var rect = new Rect({
  56435. shape: {
  56436. x: dragX != null ? dragX * width : layout.x,
  56437. y: dragY != null ? dragY * height : layout.y,
  56438. width: layout.dx,
  56439. height: layout.dy
  56440. },
  56441. style: itemModel.getModel('itemStyle').getItemStyle(),
  56442. z2: 10
  56443. });
  56444. setLabelStyle(rect, getLabelStatesModels(itemModel), {
  56445. labelFetcher: seriesModel,
  56446. labelDataIndex: node.dataIndex,
  56447. defaultText: node.id
  56448. });
  56449. rect.disableLabelAnimation = true;
  56450. rect.setStyle('fill', node.getVisual('color'));
  56451. rect.setStyle('decal', node.getVisual('style').decal);
  56452. setStatesStylesFromModel(rect, itemModel);
  56453. group.add(rect);
  56454. nodeData.setItemGraphicEl(node.dataIndex, rect);
  56455. getECData(rect).dataType = 'node';
  56456. var focus = emphasisModel.get('focus');
  56457. enableHoverEmphasis(rect, focus === 'adjacency' ? node.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope'));
  56458. });
  56459. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  56460. var itemModel = nodeData.getItemModel(dataIndex);
  56461. if (itemModel.get('draggable')) {
  56462. el.drift = function (dx, dy) {
  56463. sankeyView._focusAdjacencyDisabled = true;
  56464. this.shape.x += dx;
  56465. this.shape.y += dy;
  56466. this.dirty();
  56467. api.dispatchAction({
  56468. type: 'dragNode',
  56469. seriesId: seriesModel.id,
  56470. dataIndex: nodeData.getRawIndex(dataIndex),
  56471. localX: this.shape.x / width,
  56472. localY: this.shape.y / height
  56473. });
  56474. };
  56475. el.ondragend = function () {
  56476. sankeyView._focusAdjacencyDisabled = false;
  56477. };
  56478. el.draggable = true;
  56479. el.cursor = 'move';
  56480. }
  56481. });
  56482. if (!this._data && seriesModel.isAnimationEnabled()) {
  56483. group.setClipPath(createGridClipShape$1(group.getBoundingRect(), seriesModel, function () {
  56484. group.removeClipPath();
  56485. }));
  56486. }
  56487. this._data = seriesModel.getData();
  56488. };
  56489. SankeyView.prototype.dispose = function () {};
  56490. SankeyView.type = 'sankey';
  56491. return SankeyView;
  56492. }(ChartView); // Add animation to the view
  56493. function createGridClipShape$1(rect, seriesModel, cb) {
  56494. var rectEl = new Rect({
  56495. shape: {
  56496. x: rect.x - 10,
  56497. y: rect.y - 10,
  56498. width: 0,
  56499. height: rect.height + 20
  56500. }
  56501. });
  56502. initProps(rectEl, {
  56503. shape: {
  56504. width: rect.width + 20
  56505. }
  56506. }, seriesModel, cb);
  56507. return rectEl;
  56508. }
  56509. var SankeySeriesModel =
  56510. /** @class */
  56511. function (_super) {
  56512. __extends(SankeySeriesModel, _super);
  56513. function SankeySeriesModel() {
  56514. var _this = _super !== null && _super.apply(this, arguments) || this;
  56515. _this.type = SankeySeriesModel.type;
  56516. return _this;
  56517. }
  56518. /**
  56519. * Init a graph data structure from data in option series
  56520. */
  56521. SankeySeriesModel.prototype.getInitialData = function (option, ecModel) {
  56522. var links = option.edges || option.links;
  56523. var nodes = option.data || option.nodes;
  56524. var levels = option.levels;
  56525. this.levelModels = [];
  56526. var levelModels = this.levelModels;
  56527. for (var i = 0; i < levels.length; i++) {
  56528. if (levels[i].depth != null && levels[i].depth >= 0) {
  56529. levelModels[levels[i].depth] = new Model(levels[i], this, ecModel);
  56530. } else {
  56531. if ("development" !== 'production') {
  56532. throw new Error('levels[i].depth is mandatory and should be natural number');
  56533. }
  56534. }
  56535. }
  56536. if (nodes && links) {
  56537. var graph = createGraphFromNodeEdge(nodes, links, this, true, beforeLink);
  56538. return graph.data;
  56539. }
  56540. function beforeLink(nodeData, edgeData) {
  56541. nodeData.wrapMethod('getItemModel', function (model, idx) {
  56542. var seriesModel = model.parentModel;
  56543. var layout = seriesModel.getData().getItemLayout(idx);
  56544. if (layout) {
  56545. var nodeDepth = layout.depth;
  56546. var levelModel = seriesModel.levelModels[nodeDepth];
  56547. if (levelModel) {
  56548. model.parentModel = levelModel;
  56549. }
  56550. }
  56551. return model;
  56552. });
  56553. edgeData.wrapMethod('getItemModel', function (model, idx) {
  56554. var seriesModel = model.parentModel;
  56555. var edge = seriesModel.getGraph().getEdgeByIndex(idx);
  56556. var layout = edge.node1.getLayout();
  56557. if (layout) {
  56558. var depth = layout.depth;
  56559. var levelModel = seriesModel.levelModels[depth];
  56560. if (levelModel) {
  56561. model.parentModel = levelModel;
  56562. }
  56563. }
  56564. return model;
  56565. });
  56566. }
  56567. };
  56568. SankeySeriesModel.prototype.setNodePosition = function (dataIndex, localPosition) {
  56569. var nodes = this.option.data || this.option.nodes;
  56570. var dataItem = nodes[dataIndex];
  56571. dataItem.localX = localPosition[0];
  56572. dataItem.localY = localPosition[1];
  56573. };
  56574. /**
  56575. * Return the graphic data structure
  56576. *
  56577. * @return graphic data structure
  56578. */
  56579. SankeySeriesModel.prototype.getGraph = function () {
  56580. return this.getData().graph;
  56581. };
  56582. /**
  56583. * Get edge data of graphic data structure
  56584. *
  56585. * @return data structure of list
  56586. */
  56587. SankeySeriesModel.prototype.getEdgeData = function () {
  56588. return this.getGraph().edgeData;
  56589. };
  56590. SankeySeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  56591. function noValue(val) {
  56592. return isNaN(val) || val == null;
  56593. } // dataType === 'node' or empty do not show tooltip by default
  56594. if (dataType === 'edge') {
  56595. var params = this.getDataParams(dataIndex, dataType);
  56596. var rawDataOpt = params.data;
  56597. var edgeValue = params.value;
  56598. var edgeName = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  56599. return createTooltipMarkup('nameValue', {
  56600. name: edgeName,
  56601. value: edgeValue,
  56602. noValue: noValue(edgeValue)
  56603. });
  56604. } // dataType === 'node'
  56605. else {
  56606. var node = this.getGraph().getNodeByIndex(dataIndex);
  56607. var value = node.getLayout().value;
  56608. var name_1 = this.getDataParams(dataIndex, dataType).data.name;
  56609. return createTooltipMarkup('nameValue', {
  56610. name: name_1 != null ? name_1 + '' : null,
  56611. value: value,
  56612. noValue: noValue(value)
  56613. });
  56614. }
  56615. };
  56616. SankeySeriesModel.prototype.optionUpdated = function () {}; // Override Series.getDataParams()
  56617. SankeySeriesModel.prototype.getDataParams = function (dataIndex, dataType) {
  56618. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  56619. if (params.value == null && dataType === 'node') {
  56620. var node = this.getGraph().getNodeByIndex(dataIndex);
  56621. var nodeValue = node.getLayout().value;
  56622. params.value = nodeValue;
  56623. }
  56624. return params;
  56625. };
  56626. SankeySeriesModel.type = 'series.sankey';
  56627. SankeySeriesModel.defaultOption = {
  56628. zlevel: 0,
  56629. z: 2,
  56630. coordinateSystem: 'view',
  56631. left: '5%',
  56632. top: '5%',
  56633. right: '20%',
  56634. bottom: '5%',
  56635. orient: 'horizontal',
  56636. nodeWidth: 20,
  56637. nodeGap: 8,
  56638. draggable: true,
  56639. layoutIterations: 32,
  56640. label: {
  56641. show: true,
  56642. position: 'right',
  56643. fontSize: 12
  56644. },
  56645. levels: [],
  56646. nodeAlign: 'justify',
  56647. lineStyle: {
  56648. color: '#314656',
  56649. opacity: 0.2,
  56650. curveness: 0.5
  56651. },
  56652. emphasis: {
  56653. label: {
  56654. show: true
  56655. },
  56656. lineStyle: {
  56657. opacity: 0.5
  56658. }
  56659. },
  56660. select: {
  56661. itemStyle: {
  56662. borderColor: '#212121'
  56663. }
  56664. },
  56665. animationEasing: 'linear',
  56666. animationDuration: 1000
  56667. };
  56668. return SankeySeriesModel;
  56669. }(SeriesModel);
  56670. function sankeyLayout(ecModel, api) {
  56671. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  56672. var nodeWidth = seriesModel.get('nodeWidth');
  56673. var nodeGap = seriesModel.get('nodeGap');
  56674. var layoutInfo = getViewRect$4(seriesModel, api);
  56675. seriesModel.layoutInfo = layoutInfo;
  56676. var width = layoutInfo.width;
  56677. var height = layoutInfo.height;
  56678. var graph = seriesModel.getGraph();
  56679. var nodes = graph.nodes;
  56680. var edges = graph.edges;
  56681. computeNodeValues(nodes);
  56682. var filteredNodes = filter(nodes, function (node) {
  56683. return node.getLayout().value === 0;
  56684. });
  56685. var iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations');
  56686. var orient = seriesModel.get('orient');
  56687. var nodeAlign = seriesModel.get('nodeAlign');
  56688. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign);
  56689. });
  56690. }
  56691. /**
  56692. * Get the layout position of the whole view
  56693. */
  56694. function getViewRect$4(seriesModel, api) {
  56695. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  56696. width: api.getWidth(),
  56697. height: api.getHeight()
  56698. });
  56699. }
  56700. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign) {
  56701. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign);
  56702. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  56703. computeEdgeDepths(nodes, orient);
  56704. }
  56705. /**
  56706. * Compute the value of each node by summing the associated edge's value
  56707. */
  56708. function computeNodeValues(nodes) {
  56709. each(nodes, function (node) {
  56710. var value1 = sum(node.outEdges, getEdgeValue);
  56711. var value2 = sum(node.inEdges, getEdgeValue);
  56712. var nodeRawValue = node.getValue() || 0;
  56713. var value = Math.max(value1, value2, nodeRawValue);
  56714. node.setLayout({
  56715. value: value
  56716. }, true);
  56717. });
  56718. }
  56719. /**
  56720. * Compute the x-position for each node.
  56721. *
  56722. * Here we use Kahn algorithm to detect cycle when we traverse
  56723. * the node to computer the initial x position.
  56724. */
  56725. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
  56726. // Used to mark whether the edge is deleted. if it is deleted,
  56727. // the value is 0, otherwise it is 1.
  56728. var remainEdges = []; // Storage each node's indegree.
  56729. var indegreeArr = []; //Used to storage the node with indegree is equal to 0.
  56730. var zeroIndegrees = [];
  56731. var nextTargetNode = [];
  56732. var x = 0; // let kx = 0;
  56733. for (var i = 0; i < edges.length; i++) {
  56734. remainEdges[i] = 1;
  56735. }
  56736. for (var i = 0; i < nodes.length; i++) {
  56737. indegreeArr[i] = nodes[i].inEdges.length;
  56738. if (indegreeArr[i] === 0) {
  56739. zeroIndegrees.push(nodes[i]);
  56740. }
  56741. }
  56742. var maxNodeDepth = -1; // Traversing nodes using topological sorting to calculate the
  56743. // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
  56744. // position of the nodes.
  56745. while (zeroIndegrees.length) {
  56746. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  56747. var node = zeroIndegrees[idx];
  56748. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  56749. var isItemDepth = item.depth != null && item.depth >= 0;
  56750. if (isItemDepth && item.depth > maxNodeDepth) {
  56751. maxNodeDepth = item.depth;
  56752. }
  56753. node.setLayout({
  56754. depth: isItemDepth ? item.depth : x
  56755. }, true);
  56756. orient === 'vertical' ? node.setLayout({
  56757. dy: nodeWidth
  56758. }, true) : node.setLayout({
  56759. dx: nodeWidth
  56760. }, true);
  56761. for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
  56762. var edge = node.outEdges[edgeIdx];
  56763. var indexEdge = edges.indexOf(edge);
  56764. remainEdges[indexEdge] = 0;
  56765. var targetNode = edge.node2;
  56766. var nodeIndex = nodes.indexOf(targetNode);
  56767. if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
  56768. nextTargetNode.push(targetNode);
  56769. }
  56770. }
  56771. }
  56772. ++x;
  56773. zeroIndegrees = nextTargetNode;
  56774. nextTargetNode = [];
  56775. }
  56776. for (var i = 0; i < remainEdges.length; i++) {
  56777. if (remainEdges[i] === 1) {
  56778. throw new Error('Sankey is a DAG, the original data has cycle!');
  56779. }
  56780. }
  56781. var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
  56782. if (nodeAlign && nodeAlign !== 'left') {
  56783. adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
  56784. }
  56785. var kx = orient === 'vertical' ? (height - nodeWidth) / maxDepth : (width - nodeWidth) / maxDepth;
  56786. scaleNodeBreadths(nodes, kx, orient);
  56787. }
  56788. function isNodeDepth(node) {
  56789. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  56790. return item.depth != null && item.depth >= 0;
  56791. }
  56792. function adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth) {
  56793. if (nodeAlign === 'right') {
  56794. var nextSourceNode = [];
  56795. var remainNodes = nodes;
  56796. var nodeHeight = 0;
  56797. while (remainNodes.length) {
  56798. for (var i = 0; i < remainNodes.length; i++) {
  56799. var node = remainNodes[i];
  56800. node.setLayout({
  56801. skNodeHeight: nodeHeight
  56802. }, true);
  56803. for (var j = 0; j < node.inEdges.length; j++) {
  56804. var edge = node.inEdges[j];
  56805. if (nextSourceNode.indexOf(edge.node1) < 0) {
  56806. nextSourceNode.push(edge.node1);
  56807. }
  56808. }
  56809. }
  56810. remainNodes = nextSourceNode;
  56811. nextSourceNode = [];
  56812. ++nodeHeight;
  56813. }
  56814. each(nodes, function (node) {
  56815. if (!isNodeDepth(node)) {
  56816. node.setLayout({
  56817. depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)
  56818. }, true);
  56819. }
  56820. });
  56821. } else if (nodeAlign === 'justify') {
  56822. moveSinksRight(nodes, maxDepth);
  56823. }
  56824. }
  56825. /**
  56826. * All the node without outEgdes are assigned maximum x-position and
  56827. * be aligned in the last column.
  56828. *
  56829. * @param nodes. node of sankey view.
  56830. * @param maxDepth. use to assign to node without outEdges as x-position.
  56831. */
  56832. function moveSinksRight(nodes, maxDepth) {
  56833. each(nodes, function (node) {
  56834. if (!isNodeDepth(node) && !node.outEdges.length) {
  56835. node.setLayout({
  56836. depth: maxDepth
  56837. }, true);
  56838. }
  56839. });
  56840. }
  56841. /**
  56842. * Scale node x-position to the width
  56843. *
  56844. * @param nodes node of sankey view
  56845. * @param kx multiple used to scale nodes
  56846. */
  56847. function scaleNodeBreadths(nodes, kx, orient) {
  56848. each(nodes, function (node) {
  56849. var nodeDepth = node.getLayout().depth * kx;
  56850. orient === 'vertical' ? node.setLayout({
  56851. y: nodeDepth
  56852. }, true) : node.setLayout({
  56853. x: nodeDepth
  56854. }, true);
  56855. });
  56856. }
  56857. /**
  56858. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  56859. *
  56860. * @param nodes node of sankey view
  56861. * @param edges edge of sankey view
  56862. * @param height the whole height of the area to draw the view
  56863. * @param nodeGap the vertical distance between two nodes
  56864. * in the same column.
  56865. * @param iterations the number of iterations for the algorithm
  56866. */
  56867. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  56868. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  56869. initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient);
  56870. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  56871. for (var alpha = 1; iterations > 0; iterations--) {
  56872. // 0.99 is a experience parameter, ensure that each iterations of
  56873. // changes as small as possible.
  56874. alpha *= 0.99;
  56875. relaxRightToLeft(nodesByBreadth, alpha, orient);
  56876. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  56877. relaxLeftToRight(nodesByBreadth, alpha, orient);
  56878. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  56879. }
  56880. }
  56881. function prepareNodesByBreadth(nodes, orient) {
  56882. var nodesByBreadth = [];
  56883. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  56884. var groupResult = groupData(nodes, function (node) {
  56885. return node.getLayout()[keyAttr];
  56886. });
  56887. groupResult.keys.sort(function (a, b) {
  56888. return a - b;
  56889. });
  56890. each(groupResult.keys, function (key) {
  56891. nodesByBreadth.push(groupResult.buckets.get(key));
  56892. });
  56893. return nodesByBreadth;
  56894. }
  56895. /**
  56896. * Compute the original y-position for each node
  56897. */
  56898. function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
  56899. var minKy = Infinity;
  56900. each(nodesByBreadth, function (nodes) {
  56901. var n = nodes.length;
  56902. var sum = 0;
  56903. each(nodes, function (node) {
  56904. sum += node.getLayout().value;
  56905. });
  56906. var ky = orient === 'vertical' ? (width - (n - 1) * nodeGap) / sum : (height - (n - 1) * nodeGap) / sum;
  56907. if (ky < minKy) {
  56908. minKy = ky;
  56909. }
  56910. });
  56911. each(nodesByBreadth, function (nodes) {
  56912. each(nodes, function (node, i) {
  56913. var nodeDy = node.getLayout().value * minKy;
  56914. if (orient === 'vertical') {
  56915. node.setLayout({
  56916. x: i
  56917. }, true);
  56918. node.setLayout({
  56919. dx: nodeDy
  56920. }, true);
  56921. } else {
  56922. node.setLayout({
  56923. y: i
  56924. }, true);
  56925. node.setLayout({
  56926. dy: nodeDy
  56927. }, true);
  56928. }
  56929. });
  56930. });
  56931. each(edges, function (edge) {
  56932. var edgeDy = +edge.getValue() * minKy;
  56933. edge.setLayout({
  56934. dy: edgeDy
  56935. }, true);
  56936. });
  56937. }
  56938. /**
  56939. * Resolve the collision of initialized depth (y-position)
  56940. */
  56941. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  56942. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  56943. each(nodesByBreadth, function (nodes) {
  56944. nodes.sort(function (a, b) {
  56945. return a.getLayout()[keyAttr] - b.getLayout()[keyAttr];
  56946. });
  56947. var nodeX;
  56948. var node;
  56949. var dy;
  56950. var y0 = 0;
  56951. var n = nodes.length;
  56952. var nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy';
  56953. for (var i = 0; i < n; i++) {
  56954. node = nodes[i];
  56955. dy = y0 - node.getLayout()[keyAttr];
  56956. if (dy > 0) {
  56957. nodeX = node.getLayout()[keyAttr] + dy;
  56958. orient === 'vertical' ? node.setLayout({
  56959. x: nodeX
  56960. }, true) : node.setLayout({
  56961. y: nodeX
  56962. }, true);
  56963. }
  56964. y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap;
  56965. }
  56966. var viewWidth = orient === 'vertical' ? width : height; // If the bottommost node goes outside the bounds, push it back up
  56967. dy = y0 - nodeGap - viewWidth;
  56968. if (dy > 0) {
  56969. nodeX = node.getLayout()[keyAttr] - dy;
  56970. orient === 'vertical' ? node.setLayout({
  56971. x: nodeX
  56972. }, true) : node.setLayout({
  56973. y: nodeX
  56974. }, true);
  56975. y0 = nodeX;
  56976. for (var i = n - 2; i >= 0; --i) {
  56977. node = nodes[i];
  56978. dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0;
  56979. if (dy > 0) {
  56980. nodeX = node.getLayout()[keyAttr] - dy;
  56981. orient === 'vertical' ? node.setLayout({
  56982. x: nodeX
  56983. }, true) : node.setLayout({
  56984. y: nodeX
  56985. }, true);
  56986. }
  56987. y0 = node.getLayout()[keyAttr];
  56988. }
  56989. }
  56990. });
  56991. }
  56992. /**
  56993. * Change the y-position of the nodes, except most the right side nodes
  56994. * @param nodesByBreadth
  56995. * @param alpha parameter used to adjust the nodes y-position
  56996. */
  56997. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  56998. each(nodesByBreadth.slice().reverse(), function (nodes) {
  56999. each(nodes, function (node) {
  57000. if (node.outEdges.length) {
  57001. var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue);
  57002. if (isNaN(y)) {
  57003. var len = node.outEdges.length;
  57004. y = len ? sum(node.outEdges, centerTarget, orient) / len : 0;
  57005. }
  57006. if (orient === 'vertical') {
  57007. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  57008. node.setLayout({
  57009. x: nodeX
  57010. }, true);
  57011. } else {
  57012. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  57013. node.setLayout({
  57014. y: nodeY
  57015. }, true);
  57016. }
  57017. }
  57018. });
  57019. });
  57020. }
  57021. function weightedTarget(edge, orient) {
  57022. return center$1(edge.node2, orient) * edge.getValue();
  57023. }
  57024. function centerTarget(edge, orient) {
  57025. return center$1(edge.node2, orient);
  57026. }
  57027. function weightedSource(edge, orient) {
  57028. return center$1(edge.node1, orient) * edge.getValue();
  57029. }
  57030. function centerSource(edge, orient) {
  57031. return center$1(edge.node1, orient);
  57032. }
  57033. function center$1(node, orient) {
  57034. return orient === 'vertical' ? node.getLayout().x + node.getLayout().dx / 2 : node.getLayout().y + node.getLayout().dy / 2;
  57035. }
  57036. function getEdgeValue(edge) {
  57037. return edge.getValue();
  57038. }
  57039. function sum(array, cb, orient) {
  57040. var sum = 0;
  57041. var len = array.length;
  57042. var i = -1;
  57043. while (++i < len) {
  57044. var value = +cb(array[i], orient);
  57045. if (!isNaN(value)) {
  57046. sum += value;
  57047. }
  57048. }
  57049. return sum;
  57050. }
  57051. /**
  57052. * Change the y-position of the nodes, except most the left side nodes
  57053. */
  57054. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  57055. each(nodesByBreadth, function (nodes) {
  57056. each(nodes, function (node) {
  57057. if (node.inEdges.length) {
  57058. var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue);
  57059. if (isNaN(y)) {
  57060. var len = node.inEdges.length;
  57061. y = len ? sum(node.inEdges, centerSource, orient) / len : 0;
  57062. }
  57063. if (orient === 'vertical') {
  57064. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  57065. node.setLayout({
  57066. x: nodeX
  57067. }, true);
  57068. } else {
  57069. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  57070. node.setLayout({
  57071. y: nodeY
  57072. }, true);
  57073. }
  57074. }
  57075. });
  57076. });
  57077. }
  57078. /**
  57079. * Compute the depth(y-position) of each edge
  57080. */
  57081. function computeEdgeDepths(nodes, orient) {
  57082. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  57083. each(nodes, function (node) {
  57084. node.outEdges.sort(function (a, b) {
  57085. return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr];
  57086. });
  57087. node.inEdges.sort(function (a, b) {
  57088. return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr];
  57089. });
  57090. });
  57091. each(nodes, function (node) {
  57092. var sy = 0;
  57093. var ty = 0;
  57094. each(node.outEdges, function (edge) {
  57095. edge.setLayout({
  57096. sy: sy
  57097. }, true);
  57098. sy += edge.getLayout().dy;
  57099. });
  57100. each(node.inEdges, function (edge) {
  57101. edge.setLayout({
  57102. ty: ty
  57103. }, true);
  57104. ty += edge.getLayout().dy;
  57105. });
  57106. });
  57107. }
  57108. function sankeyVisual(ecModel) {
  57109. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  57110. var graph = seriesModel.getGraph();
  57111. var nodes = graph.nodes;
  57112. if (nodes.length) {
  57113. var minValue_1 = Infinity;
  57114. var maxValue_1 = -Infinity;
  57115. each(nodes, function (node) {
  57116. var nodeValue = node.getLayout().value;
  57117. if (nodeValue < minValue_1) {
  57118. minValue_1 = nodeValue;
  57119. }
  57120. if (nodeValue > maxValue_1) {
  57121. maxValue_1 = nodeValue;
  57122. }
  57123. });
  57124. each(nodes, function (node) {
  57125. var mapping = new VisualMapping({
  57126. type: 'color',
  57127. mappingMethod: 'linear',
  57128. dataExtent: [minValue_1, maxValue_1],
  57129. visual: seriesModel.get('color')
  57130. });
  57131. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  57132. var customColor = node.getModel().get(['itemStyle', 'color']);
  57133. if (customColor != null) {
  57134. node.setVisual('color', customColor);
  57135. node.setVisual('style', {
  57136. fill: customColor
  57137. });
  57138. } else {
  57139. node.setVisual('color', mapValueToColor);
  57140. node.setVisual('style', {
  57141. fill: mapValueToColor
  57142. });
  57143. }
  57144. });
  57145. }
  57146. });
  57147. }
  57148. function install$i(registers) {
  57149. registers.registerChartView(SankeyView);
  57150. registers.registerSeriesModel(SankeySeriesModel);
  57151. registers.registerLayout(sankeyLayout);
  57152. registers.registerVisual(sankeyVisual);
  57153. registers.registerAction({
  57154. type: 'dragNode',
  57155. event: 'dragnode',
  57156. // here can only use 'update' now, other value is not support in echarts.
  57157. update: 'update'
  57158. }, function (payload, ecModel) {
  57159. ecModel.eachComponent({
  57160. mainType: 'series',
  57161. subType: 'sankey',
  57162. query: payload
  57163. }, function (seriesModel) {
  57164. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  57165. });
  57166. });
  57167. }
  57168. var WhiskerBoxCommonMixin =
  57169. /** @class */
  57170. function () {
  57171. function WhiskerBoxCommonMixin() {}
  57172. /**
  57173. * @override
  57174. */
  57175. WhiskerBoxCommonMixin.prototype.getInitialData = function (option, ecModel) {
  57176. // When both types of xAxis and yAxis are 'value', layout is
  57177. // needed to be specified by user. Otherwise, layout can be
  57178. // judged by which axis is category.
  57179. var ordinalMeta;
  57180. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  57181. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  57182. var xAxisType = xAxisModel.get('type');
  57183. var yAxisType = yAxisModel.get('type');
  57184. var addOrdinal; // FIXME
  57185. // Consider time axis.
  57186. if (xAxisType === 'category') {
  57187. option.layout = 'horizontal';
  57188. ordinalMeta = xAxisModel.getOrdinalMeta();
  57189. addOrdinal = true;
  57190. } else if (yAxisType === 'category') {
  57191. option.layout = 'vertical';
  57192. ordinalMeta = yAxisModel.getOrdinalMeta();
  57193. addOrdinal = true;
  57194. } else {
  57195. option.layout = option.layout || 'horizontal';
  57196. }
  57197. var coordDims = ['x', 'y'];
  57198. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  57199. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  57200. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  57201. var axisModels = [xAxisModel, yAxisModel];
  57202. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  57203. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  57204. var data = option.data; // Clone a new data for next setOption({}) usage.
  57205. // Avoid modifying current data will affect further update.
  57206. if (data && addOrdinal) {
  57207. var newOptionData_1 = [];
  57208. each(data, function (item, index) {
  57209. var newItem;
  57210. if (isArray(item)) {
  57211. newItem = item.slice(); // Modify current using data.
  57212. item.unshift(index);
  57213. } else if (isArray(item.value)) {
  57214. newItem = extend({}, item);
  57215. newItem.value = newItem.value.slice(); // Modify current using data.
  57216. item.value.unshift(index);
  57217. } else {
  57218. newItem = item;
  57219. }
  57220. newOptionData_1.push(newItem);
  57221. });
  57222. option.data = newOptionData_1;
  57223. }
  57224. var defaultValueDimensions = this.defaultValueDimensions;
  57225. var coordDimensions = [{
  57226. name: baseAxisDim,
  57227. type: getDimensionTypeByAxis(baseAxisType),
  57228. ordinalMeta: ordinalMeta,
  57229. otherDims: {
  57230. tooltip: false,
  57231. itemName: 0
  57232. },
  57233. dimsDef: ['base']
  57234. }, {
  57235. name: otherAxisDim,
  57236. type: getDimensionTypeByAxis(otherAxisType),
  57237. dimsDef: defaultValueDimensions.slice()
  57238. }];
  57239. return createSeriesDataSimply(this, {
  57240. coordDimensions: coordDimensions,
  57241. dimensionsCount: defaultValueDimensions.length + 1,
  57242. encodeDefaulter: curry(makeSeriesEncodeForAxisCoordSys, coordDimensions, this)
  57243. });
  57244. };
  57245. /**
  57246. * If horizontal, base axis is x, otherwise y.
  57247. * @override
  57248. */
  57249. WhiskerBoxCommonMixin.prototype.getBaseAxis = function () {
  57250. var dim = this._baseAxisDim;
  57251. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  57252. };
  57253. return WhiskerBoxCommonMixin;
  57254. }();
  57255. var BoxplotSeriesModel =
  57256. /** @class */
  57257. function (_super) {
  57258. __extends(BoxplotSeriesModel, _super);
  57259. function BoxplotSeriesModel() {
  57260. var _this = _super !== null && _super.apply(this, arguments) || this;
  57261. _this.type = BoxplotSeriesModel.type; // TODO
  57262. // box width represents group size, so dimension should have 'size'.
  57263. /**
  57264. * @see <https://en.wikipedia.org/wiki/Box_plot>
  57265. * The meanings of 'min' and 'max' depend on user,
  57266. * and echarts do not need to know it.
  57267. * @readOnly
  57268. */
  57269. _this.defaultValueDimensions = [{
  57270. name: 'min',
  57271. defaultTooltip: true
  57272. }, {
  57273. name: 'Q1',
  57274. defaultTooltip: true
  57275. }, {
  57276. name: 'median',
  57277. defaultTooltip: true
  57278. }, {
  57279. name: 'Q3',
  57280. defaultTooltip: true
  57281. }, {
  57282. name: 'max',
  57283. defaultTooltip: true
  57284. }];
  57285. _this.visualDrawType = 'stroke';
  57286. return _this;
  57287. }
  57288. BoxplotSeriesModel.type = 'series.boxplot';
  57289. BoxplotSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  57290. BoxplotSeriesModel.defaultOption = {
  57291. zlevel: 0,
  57292. z: 2,
  57293. coordinateSystem: 'cartesian2d',
  57294. legendHoverLink: true,
  57295. layout: null,
  57296. boxWidth: [7, 50],
  57297. itemStyle: {
  57298. color: '#fff',
  57299. borderWidth: 1
  57300. },
  57301. emphasis: {
  57302. scale: true,
  57303. itemStyle: {
  57304. borderWidth: 2,
  57305. shadowBlur: 5,
  57306. shadowOffsetX: 1,
  57307. shadowOffsetY: 1,
  57308. shadowColor: 'rgba(0,0,0,0.2)'
  57309. }
  57310. },
  57311. animationDuration: 800
  57312. };
  57313. return BoxplotSeriesModel;
  57314. }(SeriesModel);
  57315. mixin(BoxplotSeriesModel, WhiskerBoxCommonMixin, true);
  57316. var BoxplotView =
  57317. /** @class */
  57318. function (_super) {
  57319. __extends(BoxplotView, _super);
  57320. function BoxplotView() {
  57321. var _this = _super !== null && _super.apply(this, arguments) || this;
  57322. _this.type = BoxplotView.type;
  57323. return _this;
  57324. }
  57325. BoxplotView.prototype.render = function (seriesModel, ecModel, api) {
  57326. var data = seriesModel.getData();
  57327. var group = this.group;
  57328. var oldData = this._data; // There is no old data only when first rendering or switching from
  57329. // stream mode to normal mode, where previous elements should be removed.
  57330. if (!this._data) {
  57331. group.removeAll();
  57332. }
  57333. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  57334. data.diff(oldData).add(function (newIdx) {
  57335. if (data.hasValue(newIdx)) {
  57336. var itemLayout = data.getItemLayout(newIdx);
  57337. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  57338. data.setItemGraphicEl(newIdx, symbolEl);
  57339. group.add(symbolEl);
  57340. }
  57341. }).update(function (newIdx, oldIdx) {
  57342. var symbolEl = oldData.getItemGraphicEl(oldIdx); // Empty data
  57343. if (!data.hasValue(newIdx)) {
  57344. group.remove(symbolEl);
  57345. return;
  57346. }
  57347. var itemLayout = data.getItemLayout(newIdx);
  57348. if (!symbolEl) {
  57349. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  57350. } else {
  57351. saveOldStyle(symbolEl);
  57352. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  57353. }
  57354. group.add(symbolEl);
  57355. data.setItemGraphicEl(newIdx, symbolEl);
  57356. }).remove(function (oldIdx) {
  57357. var el = oldData.getItemGraphicEl(oldIdx);
  57358. el && group.remove(el);
  57359. }).execute();
  57360. this._data = data;
  57361. };
  57362. BoxplotView.prototype.remove = function (ecModel) {
  57363. var group = this.group;
  57364. var data = this._data;
  57365. this._data = null;
  57366. data && data.eachItemGraphicEl(function (el) {
  57367. el && group.remove(el);
  57368. });
  57369. };
  57370. BoxplotView.type = 'boxplot';
  57371. return BoxplotView;
  57372. }(ChartView);
  57373. var BoxPathShape =
  57374. /** @class */
  57375. function () {
  57376. function BoxPathShape() {}
  57377. return BoxPathShape;
  57378. }();
  57379. var BoxPath =
  57380. /** @class */
  57381. function (_super) {
  57382. __extends(BoxPath, _super);
  57383. function BoxPath(opts) {
  57384. var _this = _super.call(this, opts) || this;
  57385. _this.type = 'boxplotBoxPath';
  57386. return _this;
  57387. }
  57388. BoxPath.prototype.getDefaultShape = function () {
  57389. return new BoxPathShape();
  57390. };
  57391. BoxPath.prototype.buildPath = function (ctx, shape) {
  57392. var ends = shape.points;
  57393. var i = 0;
  57394. ctx.moveTo(ends[i][0], ends[i][1]);
  57395. i++;
  57396. for (; i < 4; i++) {
  57397. ctx.lineTo(ends[i][0], ends[i][1]);
  57398. }
  57399. ctx.closePath();
  57400. for (; i < ends.length; i++) {
  57401. ctx.moveTo(ends[i][0], ends[i][1]);
  57402. i++;
  57403. ctx.lineTo(ends[i][0], ends[i][1]);
  57404. }
  57405. };
  57406. return BoxPath;
  57407. }(Path);
  57408. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  57409. var ends = itemLayout.ends;
  57410. var el = new BoxPath({
  57411. shape: {
  57412. points: isInit ? transInit(ends, constDim, itemLayout) : ends
  57413. }
  57414. });
  57415. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  57416. return el;
  57417. }
  57418. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  57419. var seriesModel = data.hostModel;
  57420. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  57421. updateMethod(el, {
  57422. shape: {
  57423. points: itemLayout.ends
  57424. }
  57425. }, seriesModel, dataIndex);
  57426. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  57427. el.style.strokeNoScale = true;
  57428. el.z2 = 100;
  57429. var itemModel = data.getItemModel(dataIndex);
  57430. setStatesStylesFromModel(el, itemModel);
  57431. enableHoverEmphasis(el, itemModel.get(['emphasis', 'focus']), itemModel.get(['emphasis', 'blurScope']));
  57432. }
  57433. function transInit(points, dim, itemLayout) {
  57434. return map(points, function (point) {
  57435. point = point.slice();
  57436. point[dim] = itemLayout.initBaseline;
  57437. return point;
  57438. });
  57439. }
  57440. /*
  57441. * Licensed to the Apache Software Foundation (ASF) under one
  57442. * or more contributor license agreements. See the NOTICE file
  57443. * distributed with this work for additional information
  57444. * regarding copyright ownership. The ASF licenses this file
  57445. * to you under the Apache License, Version 2.0 (the
  57446. * "License"); you may not use this file except in compliance
  57447. * with the License. You may obtain a copy of the License at
  57448. *
  57449. * http://www.apache.org/licenses/LICENSE-2.0
  57450. *
  57451. * Unless required by applicable law or agreed to in writing,
  57452. * software distributed under the License is distributed on an
  57453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57454. * KIND, either express or implied. See the License for the
  57455. * specific language governing permissions and limitations
  57456. * under the License.
  57457. */
  57458. /**
  57459. * AUTO-GENERATED FILE. DO NOT MODIFY.
  57460. */
  57461. /*
  57462. * Licensed to the Apache Software Foundation (ASF) under one
  57463. * or more contributor license agreements. See the NOTICE file
  57464. * distributed with this work for additional information
  57465. * regarding copyright ownership. The ASF licenses this file
  57466. * to you under the Apache License, Version 2.0 (the
  57467. * "License"); you may not use this file except in compliance
  57468. * with the License. You may obtain a copy of the License at
  57469. *
  57470. * http://www.apache.org/licenses/LICENSE-2.0
  57471. *
  57472. * Unless required by applicable law or agreed to in writing,
  57473. * software distributed under the License is distributed on an
  57474. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57475. * KIND, either express or implied. See the License for the
  57476. * specific language governing permissions and limitations
  57477. * under the License.
  57478. */
  57479. function boxplotVisual(ecModel, api) {}
  57480. var each$6 = each;
  57481. function boxplotLayout(ecModel) {
  57482. var groupResult = groupSeriesByAxis(ecModel);
  57483. each$6(groupResult, function (groupItem) {
  57484. var seriesModels = groupItem.seriesModels;
  57485. if (!seriesModels.length) {
  57486. return;
  57487. }
  57488. calculateBase(groupItem);
  57489. each$6(seriesModels, function (seriesModel, idx) {
  57490. layoutSingleSeries(seriesModel, groupItem.boxOffsetList[idx], groupItem.boxWidthList[idx]);
  57491. });
  57492. });
  57493. }
  57494. /**
  57495. * Group series by axis.
  57496. */
  57497. function groupSeriesByAxis(ecModel) {
  57498. var result = [];
  57499. var axisList = [];
  57500. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  57501. var baseAxis = seriesModel.getBaseAxis();
  57502. var idx = indexOf(axisList, baseAxis);
  57503. if (idx < 0) {
  57504. idx = axisList.length;
  57505. axisList[idx] = baseAxis;
  57506. result[idx] = {
  57507. axis: baseAxis,
  57508. seriesModels: []
  57509. };
  57510. }
  57511. result[idx].seriesModels.push(seriesModel);
  57512. });
  57513. return result;
  57514. }
  57515. /**
  57516. * Calculate offset and box width for each series.
  57517. */
  57518. function calculateBase(groupItem) {
  57519. var extent;
  57520. var baseAxis = groupItem.axis;
  57521. var seriesModels = groupItem.seriesModels;
  57522. var seriesCount = seriesModels.length;
  57523. var boxWidthList = groupItem.boxWidthList = [];
  57524. var boxOffsetList = groupItem.boxOffsetList = [];
  57525. var boundList = [];
  57526. var bandWidth;
  57527. if (baseAxis.type === 'category') {
  57528. bandWidth = baseAxis.getBandWidth();
  57529. } else {
  57530. var maxDataCount_1 = 0;
  57531. each$6(seriesModels, function (seriesModel) {
  57532. maxDataCount_1 = Math.max(maxDataCount_1, seriesModel.getData().count());
  57533. });
  57534. extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / maxDataCount_1;
  57535. }
  57536. each$6(seriesModels, function (seriesModel) {
  57537. var boxWidthBound = seriesModel.get('boxWidth');
  57538. if (!isArray(boxWidthBound)) {
  57539. boxWidthBound = [boxWidthBound, boxWidthBound];
  57540. }
  57541. boundList.push([parsePercent$1(boxWidthBound[0], bandWidth) || 0, parsePercent$1(boxWidthBound[1], bandWidth) || 0]);
  57542. });
  57543. var availableWidth = bandWidth * 0.8 - 2;
  57544. var boxGap = availableWidth / seriesCount * 0.3;
  57545. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  57546. var base = boxWidth / 2 - availableWidth / 2;
  57547. each$6(seriesModels, function (seriesModel, idx) {
  57548. boxOffsetList.push(base);
  57549. base += boxGap + boxWidth;
  57550. boxWidthList.push(Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1]));
  57551. });
  57552. }
  57553. /**
  57554. * Calculate points location for each series.
  57555. */
  57556. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  57557. var coordSys = seriesModel.coordinateSystem;
  57558. var data = seriesModel.getData();
  57559. var halfWidth = boxWidth / 2;
  57560. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  57561. var vDimIdx = 1 - cDimIdx;
  57562. var coordDims = ['x', 'y'];
  57563. var cDim = data.mapDimension(coordDims[cDimIdx]);
  57564. var vDims = data.mapDimensionsAll(coordDims[vDimIdx]);
  57565. if (cDim == null || vDims.length < 5) {
  57566. return;
  57567. }
  57568. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  57569. var axisDimVal = data.get(cDim, dataIndex);
  57570. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  57571. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  57572. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  57573. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  57574. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  57575. var ends = [];
  57576. addBodyEnd(ends, end2, false);
  57577. addBodyEnd(ends, end4, true);
  57578. ends.push(end1, end2, end5, end4);
  57579. layEndLine(ends, end1);
  57580. layEndLine(ends, end5);
  57581. layEndLine(ends, median);
  57582. data.setItemLayout(dataIndex, {
  57583. initBaseline: median[vDimIdx],
  57584. ends: ends
  57585. });
  57586. }
  57587. function getPoint(axisDimVal, dim, dataIndex) {
  57588. var val = data.get(dim, dataIndex);
  57589. var p = [];
  57590. p[cDimIdx] = axisDimVal;
  57591. p[vDimIdx] = val;
  57592. var point;
  57593. if (isNaN(axisDimVal) || isNaN(val)) {
  57594. point = [NaN, NaN];
  57595. } else {
  57596. point = coordSys.dataToPoint(p);
  57597. point[cDimIdx] += offset;
  57598. }
  57599. return point;
  57600. }
  57601. function addBodyEnd(ends, point, start) {
  57602. var point1 = point.slice();
  57603. var point2 = point.slice();
  57604. point1[cDimIdx] += halfWidth;
  57605. point2[cDimIdx] -= halfWidth;
  57606. start ? ends.push(point1, point2) : ends.push(point2, point1);
  57607. }
  57608. function layEndLine(ends, endCenter) {
  57609. var from = endCenter.slice();
  57610. var to = endCenter.slice();
  57611. from[cDimIdx] -= halfWidth;
  57612. to[cDimIdx] += halfWidth;
  57613. ends.push(from, to);
  57614. }
  57615. }
  57616. /**
  57617. * See:
  57618. * <https://en.wikipedia.org/wiki/Box_plot#cite_note-frigge_hoaglin_iglewicz-2>
  57619. * <http://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/boxplot.stats.html>
  57620. *
  57621. * Helper method for preparing data.
  57622. *
  57623. * @param rawData like
  57624. * [
  57625. * [12,232,443], (raw data set for the first box)
  57626. * [3843,5545,1232], (raw data set for the second box)
  57627. * ...
  57628. * ]
  57629. * @param opt.boundIQR=1.5 Data less than min bound is outlier.
  57630. * default 1.5, means Q1 - 1.5 * (Q3 - Q1).
  57631. * If 'none'/0 passed, min bound will not be used.
  57632. */
  57633. function prepareBoxplotData(rawData, opt) {
  57634. opt = opt || {};
  57635. var boxData = [];
  57636. var outliers = [];
  57637. var boundIQR = opt.boundIQR;
  57638. var useExtreme = boundIQR === 'none' || boundIQR === 0;
  57639. for (var i = 0; i < rawData.length; i++) {
  57640. var ascList = asc(rawData[i].slice());
  57641. var Q1 = quantile(ascList, 0.25);
  57642. var Q2 = quantile(ascList, 0.5);
  57643. var Q3 = quantile(ascList, 0.75);
  57644. var min = ascList[0];
  57645. var max = ascList[ascList.length - 1];
  57646. var bound = (boundIQR == null ? 1.5 : boundIQR) * (Q3 - Q1);
  57647. var low = useExtreme ? min : Math.max(min, Q1 - bound);
  57648. var high = useExtreme ? max : Math.min(max, Q3 + bound);
  57649. var itemNameFormatter = opt.itemNameFormatter;
  57650. var itemName = isFunction(itemNameFormatter) ? itemNameFormatter({
  57651. value: i
  57652. }) : isString(itemNameFormatter) ? itemNameFormatter.replace('{value}', i + '') : i + '';
  57653. boxData.push([itemName, low, Q1, Q2, Q3, high]);
  57654. for (var j = 0; j < ascList.length; j++) {
  57655. var dataItem = ascList[j];
  57656. if (dataItem < low || dataItem > high) {
  57657. var outlier = [itemName, dataItem];
  57658. outliers.push(outlier);
  57659. }
  57660. }
  57661. }
  57662. return {
  57663. boxData: boxData,
  57664. outliers: outliers
  57665. };
  57666. }
  57667. var boxplotTransform = {
  57668. type: 'echarts:boxplot',
  57669. transform: function transform(params) {
  57670. var upstream = params.upstream;
  57671. if (upstream.sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS) {
  57672. var errMsg = '';
  57673. if ("development" !== 'production') {
  57674. errMsg = makePrintable('source data is not applicable for this boxplot transform. Expect number[][].');
  57675. }
  57676. throwError(errMsg);
  57677. }
  57678. var result = prepareBoxplotData(upstream.getRawData(), params.config);
  57679. return [{
  57680. dimensions: ['ItemName', 'Low', 'Q1', 'Q2', 'Q3', 'High'],
  57681. data: result.boxData
  57682. }, {
  57683. data: result.outliers
  57684. }];
  57685. }
  57686. };
  57687. function install$j(registers) {
  57688. registers.registerSeriesModel(BoxplotSeriesModel);
  57689. registers.registerChartView(BoxplotView);
  57690. registers.registerVisual(boxplotVisual);
  57691. registers.registerLayout(boxplotLayout);
  57692. registers.registerTransform(boxplotTransform);
  57693. }
  57694. var SKIP_PROPS = ['color', 'borderColor'];
  57695. var CandlestickView =
  57696. /** @class */
  57697. function (_super) {
  57698. __extends(CandlestickView, _super);
  57699. function CandlestickView() {
  57700. var _this = _super !== null && _super.apply(this, arguments) || this;
  57701. _this.type = CandlestickView.type;
  57702. return _this;
  57703. }
  57704. CandlestickView.prototype.render = function (seriesModel, ecModel, api) {
  57705. // If there is clipPath created in large mode. Remove it.
  57706. this.group.removeClipPath();
  57707. this._updateDrawMode(seriesModel);
  57708. this._isLargeDraw ? this._renderLarge(seriesModel) : this._renderNormal(seriesModel);
  57709. };
  57710. CandlestickView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  57711. this._clear();
  57712. this._updateDrawMode(seriesModel);
  57713. };
  57714. CandlestickView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  57715. this._isLargeDraw ? this._incrementalRenderLarge(params, seriesModel) : this._incrementalRenderNormal(params, seriesModel);
  57716. };
  57717. CandlestickView.prototype._updateDrawMode = function (seriesModel) {
  57718. var isLargeDraw = seriesModel.pipelineContext.large;
  57719. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  57720. this._isLargeDraw = isLargeDraw;
  57721. this._clear();
  57722. }
  57723. };
  57724. CandlestickView.prototype._renderNormal = function (seriesModel) {
  57725. var data = seriesModel.getData();
  57726. var oldData = this._data;
  57727. var group = this.group;
  57728. var isSimpleBox = data.getLayout('isSimpleBox');
  57729. var needsClip = seriesModel.get('clip', true);
  57730. var coord = seriesModel.coordinateSystem;
  57731. var clipArea = coord.getArea && coord.getArea(); // There is no old data only when first rendering or switching from
  57732. // stream mode to normal mode, where previous elements should be removed.
  57733. if (!this._data) {
  57734. group.removeAll();
  57735. }
  57736. data.diff(oldData).add(function (newIdx) {
  57737. if (data.hasValue(newIdx)) {
  57738. var itemLayout = data.getItemLayout(newIdx);
  57739. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  57740. return;
  57741. }
  57742. var el = createNormalBox$1(itemLayout, newIdx, true);
  57743. initProps(el, {
  57744. shape: {
  57745. points: itemLayout.ends
  57746. }
  57747. }, seriesModel, newIdx);
  57748. setBoxCommon(el, data, newIdx, isSimpleBox);
  57749. group.add(el);
  57750. data.setItemGraphicEl(newIdx, el);
  57751. }
  57752. }).update(function (newIdx, oldIdx) {
  57753. var el = oldData.getItemGraphicEl(oldIdx); // Empty data
  57754. if (!data.hasValue(newIdx)) {
  57755. group.remove(el);
  57756. return;
  57757. }
  57758. var itemLayout = data.getItemLayout(newIdx);
  57759. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  57760. group.remove(el);
  57761. return;
  57762. }
  57763. if (!el) {
  57764. el = createNormalBox$1(itemLayout);
  57765. } else {
  57766. updateProps(el, {
  57767. shape: {
  57768. points: itemLayout.ends
  57769. }
  57770. }, seriesModel, newIdx);
  57771. saveOldStyle(el);
  57772. }
  57773. setBoxCommon(el, data, newIdx, isSimpleBox);
  57774. group.add(el);
  57775. data.setItemGraphicEl(newIdx, el);
  57776. }).remove(function (oldIdx) {
  57777. var el = oldData.getItemGraphicEl(oldIdx);
  57778. el && group.remove(el);
  57779. }).execute();
  57780. this._data = data;
  57781. };
  57782. CandlestickView.prototype._renderLarge = function (seriesModel) {
  57783. this._clear();
  57784. createLarge$1(seriesModel, this.group);
  57785. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  57786. if (clipPath) {
  57787. this.group.setClipPath(clipPath);
  57788. } else {
  57789. this.group.removeClipPath();
  57790. }
  57791. };
  57792. CandlestickView.prototype._incrementalRenderNormal = function (params, seriesModel) {
  57793. var data = seriesModel.getData();
  57794. var isSimpleBox = data.getLayout('isSimpleBox');
  57795. var dataIndex;
  57796. while ((dataIndex = params.next()) != null) {
  57797. var itemLayout = data.getItemLayout(dataIndex);
  57798. var el = createNormalBox$1(itemLayout);
  57799. setBoxCommon(el, data, dataIndex, isSimpleBox);
  57800. el.incremental = true;
  57801. this.group.add(el);
  57802. }
  57803. };
  57804. CandlestickView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  57805. createLarge$1(seriesModel, this.group, true);
  57806. };
  57807. CandlestickView.prototype.remove = function (ecModel) {
  57808. this._clear();
  57809. };
  57810. CandlestickView.prototype._clear = function () {
  57811. this.group.removeAll();
  57812. this._data = null;
  57813. };
  57814. CandlestickView.type = 'candlestick';
  57815. return CandlestickView;
  57816. }(ChartView);
  57817. var NormalBoxPathShape =
  57818. /** @class */
  57819. function () {
  57820. function NormalBoxPathShape() {}
  57821. return NormalBoxPathShape;
  57822. }();
  57823. var NormalBoxPath =
  57824. /** @class */
  57825. function (_super) {
  57826. __extends(NormalBoxPath, _super);
  57827. function NormalBoxPath(opts) {
  57828. var _this = _super.call(this, opts) || this;
  57829. _this.type = 'normalCandlestickBox';
  57830. return _this;
  57831. }
  57832. NormalBoxPath.prototype.getDefaultShape = function () {
  57833. return new NormalBoxPathShape();
  57834. };
  57835. NormalBoxPath.prototype.buildPath = function (ctx, shape) {
  57836. var ends = shape.points;
  57837. if (this.__simpleBox) {
  57838. ctx.moveTo(ends[4][0], ends[4][1]);
  57839. ctx.lineTo(ends[6][0], ends[6][1]);
  57840. } else {
  57841. ctx.moveTo(ends[0][0], ends[0][1]);
  57842. ctx.lineTo(ends[1][0], ends[1][1]);
  57843. ctx.lineTo(ends[2][0], ends[2][1]);
  57844. ctx.lineTo(ends[3][0], ends[3][1]);
  57845. ctx.closePath();
  57846. ctx.moveTo(ends[4][0], ends[4][1]);
  57847. ctx.lineTo(ends[5][0], ends[5][1]);
  57848. ctx.moveTo(ends[6][0], ends[6][1]);
  57849. ctx.lineTo(ends[7][0], ends[7][1]);
  57850. }
  57851. };
  57852. return NormalBoxPath;
  57853. }(Path);
  57854. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  57855. var ends = itemLayout.ends;
  57856. return new NormalBoxPath({
  57857. shape: {
  57858. points: isInit ? transInit$1(ends, itemLayout) : ends
  57859. },
  57860. z2: 100
  57861. });
  57862. }
  57863. function isNormalBoxClipped(clipArea, itemLayout) {
  57864. var clipped = true;
  57865. for (var i = 0; i < itemLayout.ends.length; i++) {
  57866. // If any point are in the region.
  57867. if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) {
  57868. clipped = false;
  57869. break;
  57870. }
  57871. }
  57872. return clipped;
  57873. }
  57874. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  57875. var itemModel = data.getItemModel(dataIndex);
  57876. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  57877. el.style.strokeNoScale = true;
  57878. el.__simpleBox = isSimpleBox;
  57879. setStatesStylesFromModel(el, itemModel);
  57880. }
  57881. function transInit$1(points, itemLayout) {
  57882. return map(points, function (point) {
  57883. point = point.slice();
  57884. point[1] = itemLayout.initBaseline;
  57885. return point;
  57886. });
  57887. }
  57888. var LargeBoxPathShape =
  57889. /** @class */
  57890. function () {
  57891. function LargeBoxPathShape() {}
  57892. return LargeBoxPathShape;
  57893. }();
  57894. var LargeBoxPath =
  57895. /** @class */
  57896. function (_super) {
  57897. __extends(LargeBoxPath, _super);
  57898. function LargeBoxPath(opts) {
  57899. var _this = _super.call(this, opts) || this;
  57900. _this.type = 'largeCandlestickBox';
  57901. return _this;
  57902. }
  57903. LargeBoxPath.prototype.getDefaultShape = function () {
  57904. return new LargeBoxPathShape();
  57905. };
  57906. LargeBoxPath.prototype.buildPath = function (ctx, shape) {
  57907. // Drawing lines is more efficient than drawing
  57908. // a whole line or drawing rects.
  57909. var points = shape.points;
  57910. for (var i = 0; i < points.length;) {
  57911. if (this.__sign === points[i++]) {
  57912. var x = points[i++];
  57913. ctx.moveTo(x, points[i++]);
  57914. ctx.lineTo(x, points[i++]);
  57915. } else {
  57916. i += 3;
  57917. }
  57918. }
  57919. };
  57920. return LargeBoxPath;
  57921. }(Path);
  57922. function createLarge$1(seriesModel, group, incremental) {
  57923. var data = seriesModel.getData();
  57924. var largePoints = data.getLayout('largePoints');
  57925. var elP = new LargeBoxPath({
  57926. shape: {
  57927. points: largePoints
  57928. },
  57929. __sign: 1
  57930. });
  57931. group.add(elP);
  57932. var elN = new LargeBoxPath({
  57933. shape: {
  57934. points: largePoints
  57935. },
  57936. __sign: -1
  57937. });
  57938. group.add(elN);
  57939. setLargeStyle$1(1, elP, seriesModel);
  57940. setLargeStyle$1(-1, elN, seriesModel);
  57941. if (incremental) {
  57942. elP.incremental = true;
  57943. elN.incremental = true;
  57944. }
  57945. }
  57946. function setLargeStyle$1(sign, el, seriesModel, data) {
  57947. // TODO put in visual?
  57948. var borderColor = seriesModel.get(['itemStyle', sign > 0 ? 'borderColor' : 'borderColor0']) || seriesModel.get(['itemStyle', sign > 0 ? 'color' : 'color0']); // Color must be excluded.
  57949. // Because symbol provide setColor individually to set fill and stroke
  57950. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(SKIP_PROPS);
  57951. el.useStyle(itemStyle);
  57952. el.style.fill = null;
  57953. el.style.stroke = borderColor;
  57954. }
  57955. var CandlestickSeriesModel =
  57956. /** @class */
  57957. function (_super) {
  57958. __extends(CandlestickSeriesModel, _super);
  57959. function CandlestickSeriesModel() {
  57960. var _this = _super !== null && _super.apply(this, arguments) || this;
  57961. _this.type = CandlestickSeriesModel.type;
  57962. _this.defaultValueDimensions = [{
  57963. name: 'open',
  57964. defaultTooltip: true
  57965. }, {
  57966. name: 'close',
  57967. defaultTooltip: true
  57968. }, {
  57969. name: 'lowest',
  57970. defaultTooltip: true
  57971. }, {
  57972. name: 'highest',
  57973. defaultTooltip: true
  57974. }];
  57975. return _this;
  57976. }
  57977. /**
  57978. * Get dimension for shadow in dataZoom
  57979. * @return dimension name
  57980. */
  57981. CandlestickSeriesModel.prototype.getShadowDim = function () {
  57982. return 'open';
  57983. };
  57984. CandlestickSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  57985. var itemLayout = data.getItemLayout(dataIndex);
  57986. return itemLayout && selectors.rect(itemLayout.brushRect);
  57987. };
  57988. CandlestickSeriesModel.type = 'series.candlestick';
  57989. CandlestickSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  57990. CandlestickSeriesModel.defaultOption = {
  57991. zlevel: 0,
  57992. z: 2,
  57993. coordinateSystem: 'cartesian2d',
  57994. legendHoverLink: true,
  57995. // xAxisIndex: 0,
  57996. // yAxisIndex: 0,
  57997. layout: null,
  57998. clip: true,
  57999. itemStyle: {
  58000. color: '#eb5454',
  58001. color0: '#47b262',
  58002. borderColor: '#eb5454',
  58003. borderColor0: '#47b262',
  58004. // borderColor: '#d24040',
  58005. // borderColor0: '#398f4f',
  58006. borderWidth: 1
  58007. },
  58008. emphasis: {
  58009. scale: true,
  58010. itemStyle: {
  58011. borderWidth: 2
  58012. }
  58013. },
  58014. barMaxWidth: null,
  58015. barMinWidth: null,
  58016. barWidth: null,
  58017. large: true,
  58018. largeThreshold: 600,
  58019. progressive: 3e3,
  58020. progressiveThreshold: 1e4,
  58021. progressiveChunkMode: 'mod',
  58022. animationEasing: 'linear',
  58023. animationDuration: 300
  58024. };
  58025. return CandlestickSeriesModel;
  58026. }(SeriesModel);
  58027. mixin(CandlestickSeriesModel, WhiskerBoxCommonMixin, true);
  58028. function candlestickPreprocessor(option) {
  58029. if (!option || !isArray(option.series)) {
  58030. return;
  58031. } // Translate 'k' to 'candlestick'.
  58032. each(option.series, function (seriesItem) {
  58033. if (isObject(seriesItem) && seriesItem.type === 'k') {
  58034. seriesItem.type = 'candlestick';
  58035. }
  58036. });
  58037. }
  58038. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  58039. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  58040. var positiveColorQuery = ['itemStyle', 'color'];
  58041. var negativeColorQuery = ['itemStyle', 'color0'];
  58042. var candlestickVisual = {
  58043. seriesType: 'candlestick',
  58044. plan: createRenderPlanner(),
  58045. // For legend.
  58046. performRawSeries: true,
  58047. reset: function (seriesModel, ecModel) {
  58048. function getColor(sign, model) {
  58049. return model.get(sign > 0 ? positiveColorQuery : negativeColorQuery);
  58050. }
  58051. function getBorderColor(sign, model) {
  58052. return model.get(sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery);
  58053. } // Only visible series has each data be visual encoded
  58054. if (ecModel.isSeriesFiltered(seriesModel)) {
  58055. return;
  58056. }
  58057. var isLargeRender = seriesModel.pipelineContext.large;
  58058. return !isLargeRender && {
  58059. progress: function (params, data) {
  58060. var dataIndex;
  58061. while ((dataIndex = params.next()) != null) {
  58062. var itemModel = data.getItemModel(dataIndex);
  58063. var sign = data.getItemLayout(dataIndex).sign;
  58064. var style = itemModel.getItemStyle();
  58065. style.fill = getColor(sign, itemModel);
  58066. style.stroke = getBorderColor(sign, itemModel) || style.fill;
  58067. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  58068. extend(existsStyle, style);
  58069. }
  58070. }
  58071. };
  58072. }
  58073. };
  58074. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  58075. var candlestickLayout = {
  58076. seriesType: 'candlestick',
  58077. plan: createRenderPlanner(),
  58078. reset: function (seriesModel) {
  58079. var coordSys = seriesModel.coordinateSystem;
  58080. var data = seriesModel.getData();
  58081. var candleWidth = calculateCandleWidth(seriesModel, data);
  58082. var cDimIdx = 0;
  58083. var vDimIdx = 1;
  58084. var coordDims = ['x', 'y'];
  58085. var cDimI = data.getDimensionIndex(data.mapDimension(coordDims[cDimIdx]));
  58086. var vDimsI = map(data.mapDimensionsAll(coordDims[vDimIdx]), data.getDimensionIndex, data);
  58087. var openDimI = vDimsI[0];
  58088. var closeDimI = vDimsI[1];
  58089. var lowestDimI = vDimsI[2];
  58090. var highestDimI = vDimsI[3];
  58091. data.setLayout({
  58092. candleWidth: candleWidth,
  58093. // The value is experimented visually.
  58094. isSimpleBox: candleWidth <= 1.3
  58095. });
  58096. if (cDimI < 0 || vDimsI.length < 4) {
  58097. return;
  58098. }
  58099. return {
  58100. progress: seriesModel.pipelineContext.large ? largeProgress : normalProgress
  58101. };
  58102. function normalProgress(params, data) {
  58103. var dataIndex;
  58104. var store = data.getStore();
  58105. while ((dataIndex = params.next()) != null) {
  58106. var axisDimVal = store.get(cDimI, dataIndex);
  58107. var openVal = store.get(openDimI, dataIndex);
  58108. var closeVal = store.get(closeDimI, dataIndex);
  58109. var lowestVal = store.get(lowestDimI, dataIndex);
  58110. var highestVal = store.get(highestDimI, dataIndex);
  58111. var ocLow = Math.min(openVal, closeVal);
  58112. var ocHigh = Math.max(openVal, closeVal);
  58113. var ocLowPoint = getPoint(ocLow, axisDimVal);
  58114. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  58115. var lowestPoint = getPoint(lowestVal, axisDimVal);
  58116. var highestPoint = getPoint(highestVal, axisDimVal);
  58117. var ends = [];
  58118. addBodyEnd(ends, ocHighPoint, 0);
  58119. addBodyEnd(ends, ocLowPoint, 1);
  58120. ends.push(subPixelOptimizePoint(highestPoint), subPixelOptimizePoint(ocHighPoint), subPixelOptimizePoint(lowestPoint), subPixelOptimizePoint(ocLowPoint));
  58121. data.setItemLayout(dataIndex, {
  58122. sign: getSign(store, dataIndex, openVal, closeVal, closeDimI),
  58123. initBaseline: openVal > closeVal ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx],
  58124. ends: ends,
  58125. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  58126. });
  58127. }
  58128. function getPoint(val, axisDimVal) {
  58129. var p = [];
  58130. p[cDimIdx] = axisDimVal;
  58131. p[vDimIdx] = val;
  58132. return isNaN(axisDimVal) || isNaN(val) ? [NaN, NaN] : coordSys.dataToPoint(p);
  58133. }
  58134. function addBodyEnd(ends, point, start) {
  58135. var point1 = point.slice();
  58136. var point2 = point.slice();
  58137. point1[cDimIdx] = subPixelOptimize$1(point1[cDimIdx] + candleWidth / 2, 1, false);
  58138. point2[cDimIdx] = subPixelOptimize$1(point2[cDimIdx] - candleWidth / 2, 1, true);
  58139. start ? ends.push(point1, point2) : ends.push(point2, point1);
  58140. }
  58141. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  58142. var pmin = getPoint(lowestVal, axisDimVal);
  58143. var pmax = getPoint(highestVal, axisDimVal);
  58144. pmin[cDimIdx] -= candleWidth / 2;
  58145. pmax[cDimIdx] -= candleWidth / 2;
  58146. return {
  58147. x: pmin[0],
  58148. y: pmin[1],
  58149. width: candleWidth ,
  58150. height: pmax[1] - pmin[1]
  58151. };
  58152. }
  58153. function subPixelOptimizePoint(point) {
  58154. point[cDimIdx] = subPixelOptimize$1(point[cDimIdx], 1);
  58155. return point;
  58156. }
  58157. }
  58158. function largeProgress(params, data) {
  58159. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  58160. var points = new LargeArr$1(params.count * 4);
  58161. var offset = 0;
  58162. var point;
  58163. var tmpIn = [];
  58164. var tmpOut = [];
  58165. var dataIndex;
  58166. var store = data.getStore();
  58167. while ((dataIndex = params.next()) != null) {
  58168. var axisDimVal = store.get(cDimI, dataIndex);
  58169. var openVal = store.get(openDimI, dataIndex);
  58170. var closeVal = store.get(closeDimI, dataIndex);
  58171. var lowestVal = store.get(lowestDimI, dataIndex);
  58172. var highestVal = store.get(highestDimI, dataIndex);
  58173. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  58174. points[offset++] = NaN;
  58175. offset += 3;
  58176. continue;
  58177. }
  58178. points[offset++] = getSign(store, dataIndex, openVal, closeVal, closeDimI);
  58179. tmpIn[cDimIdx] = axisDimVal;
  58180. tmpIn[vDimIdx] = lowestVal;
  58181. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  58182. points[offset++] = point ? point[0] : NaN;
  58183. points[offset++] = point ? point[1] : NaN;
  58184. tmpIn[vDimIdx] = highestVal;
  58185. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  58186. points[offset++] = point ? point[1] : NaN;
  58187. }
  58188. data.setLayout('largePoints', points);
  58189. }
  58190. }
  58191. };
  58192. function getSign(store, dataIndex, openVal, closeVal, closeDimI) {
  58193. var sign;
  58194. if (openVal > closeVal) {
  58195. sign = -1;
  58196. } else if (openVal < closeVal) {
  58197. sign = 1;
  58198. } else {
  58199. sign = dataIndex > 0 // If close === open, compare with close of last record
  58200. ? store.get(closeDimI, dataIndex - 1) <= closeVal ? 1 : -1 : // No record of previous, set to be positive
  58201. 1;
  58202. }
  58203. return sign;
  58204. }
  58205. function calculateCandleWidth(seriesModel, data) {
  58206. var baseAxis = seriesModel.getBaseAxis();
  58207. var extent;
  58208. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : (extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / data.count());
  58209. var barMaxWidth = parsePercent$1(retrieve2(seriesModel.get('barMaxWidth'), bandWidth), bandWidth);
  58210. var barMinWidth = parsePercent$1(retrieve2(seriesModel.get('barMinWidth'), 1), bandWidth);
  58211. var barWidth = seriesModel.get('barWidth');
  58212. return barWidth != null ? parsePercent$1(barWidth, bandWidth) // Put max outer to ensure bar visible in spite of overlap.
  58213. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  58214. }
  58215. function install$k(registers) {
  58216. registers.registerChartView(CandlestickView);
  58217. registers.registerSeriesModel(CandlestickSeriesModel);
  58218. registers.registerPreprocessor(candlestickPreprocessor);
  58219. registers.registerVisual(candlestickVisual);
  58220. registers.registerLayout(candlestickLayout);
  58221. }
  58222. function updateRipplePath(rippleGroup, effectCfg) {
  58223. var color = effectCfg.rippleEffectColor || effectCfg.color;
  58224. rippleGroup.eachChild(function (ripplePath) {
  58225. ripplePath.attr({
  58226. z: effectCfg.z,
  58227. zlevel: effectCfg.zlevel,
  58228. style: {
  58229. stroke: effectCfg.brushType === 'stroke' ? color : null,
  58230. fill: effectCfg.brushType === 'fill' ? color : null
  58231. }
  58232. });
  58233. });
  58234. }
  58235. var EffectSymbol =
  58236. /** @class */
  58237. function (_super) {
  58238. __extends(EffectSymbol, _super);
  58239. function EffectSymbol(data, idx) {
  58240. var _this = _super.call(this) || this;
  58241. var symbol = new Symbol(data, idx);
  58242. var rippleGroup = new Group();
  58243. _this.add(symbol);
  58244. _this.add(rippleGroup);
  58245. _this.updateData(data, idx);
  58246. return _this;
  58247. }
  58248. EffectSymbol.prototype.stopEffectAnimation = function () {
  58249. this.childAt(1).removeAll();
  58250. };
  58251. EffectSymbol.prototype.startEffectAnimation = function (effectCfg) {
  58252. var symbolType = effectCfg.symbolType;
  58253. var color = effectCfg.color;
  58254. var rippleNumber = effectCfg.rippleNumber;
  58255. var rippleGroup = this.childAt(1);
  58256. for (var i = 0; i < rippleNumber; i++) {
  58257. // If width/height are set too small (e.g., set to 1) on ios10
  58258. // and macOS Sierra, a circle stroke become a rect, no matter what
  58259. // the scale is set. So we set width/height as 2. See #4136.
  58260. var ripplePath = createSymbol(symbolType, -1, -1, 2, 2, color);
  58261. ripplePath.attr({
  58262. style: {
  58263. strokeNoScale: true
  58264. },
  58265. z2: 99,
  58266. silent: true,
  58267. scaleX: 0.5,
  58268. scaleY: 0.5
  58269. });
  58270. var delay = -i / rippleNumber * effectCfg.period + effectCfg.effectOffset;
  58271. ripplePath.animate('', true).when(effectCfg.period, {
  58272. scaleX: effectCfg.rippleScale / 2,
  58273. scaleY: effectCfg.rippleScale / 2
  58274. }).delay(delay).start();
  58275. ripplePath.animateStyle(true).when(effectCfg.period, {
  58276. opacity: 0
  58277. }).delay(delay).start();
  58278. rippleGroup.add(ripplePath);
  58279. }
  58280. updateRipplePath(rippleGroup, effectCfg);
  58281. };
  58282. /**
  58283. * Update effect symbol
  58284. */
  58285. EffectSymbol.prototype.updateEffectAnimation = function (effectCfg) {
  58286. var oldEffectCfg = this._effectCfg;
  58287. var rippleGroup = this.childAt(1); // Must reinitialize effect if following configuration changed
  58288. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale', 'rippleNumber'];
  58289. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  58290. var propName = DIFFICULT_PROPS[i];
  58291. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  58292. this.stopEffectAnimation();
  58293. this.startEffectAnimation(effectCfg);
  58294. return;
  58295. }
  58296. }
  58297. updateRipplePath(rippleGroup, effectCfg);
  58298. };
  58299. /**
  58300. * Highlight symbol
  58301. */
  58302. EffectSymbol.prototype.highlight = function () {
  58303. enterEmphasis(this);
  58304. };
  58305. /**
  58306. * Downplay symbol
  58307. */
  58308. EffectSymbol.prototype.downplay = function () {
  58309. leaveEmphasis(this);
  58310. };
  58311. EffectSymbol.prototype.getSymbolType = function () {
  58312. var symbol = this.childAt(0);
  58313. return symbol && symbol.getSymbolType();
  58314. };
  58315. /**
  58316. * Update symbol properties
  58317. */
  58318. EffectSymbol.prototype.updateData = function (data, idx) {
  58319. var _this = this;
  58320. var seriesModel = data.hostModel;
  58321. this.childAt(0).updateData(data, idx);
  58322. var rippleGroup = this.childAt(1);
  58323. var itemModel = data.getItemModel(idx);
  58324. var symbolType = data.getItemVisual(idx, 'symbol');
  58325. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  58326. var symbolStyle = data.getItemVisual(idx, 'style');
  58327. var color = symbolStyle && symbolStyle.fill;
  58328. rippleGroup.setScale(symbolSize);
  58329. rippleGroup.traverse(function (ripplePath) {
  58330. ripplePath.setStyle('fill', color);
  58331. });
  58332. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  58333. if (symbolOffset) {
  58334. rippleGroup.x = symbolOffset[0];
  58335. rippleGroup.y = symbolOffset[1];
  58336. }
  58337. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  58338. rippleGroup.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  58339. var effectCfg = {};
  58340. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  58341. effectCfg.rippleScale = itemModel.get(['rippleEffect', 'scale']);
  58342. effectCfg.brushType = itemModel.get(['rippleEffect', 'brushType']);
  58343. effectCfg.period = itemModel.get(['rippleEffect', 'period']) * 1000;
  58344. effectCfg.effectOffset = idx / data.count();
  58345. effectCfg.z = seriesModel.getShallow('z') || 0;
  58346. effectCfg.zlevel = seriesModel.getShallow('zlevel') || 0;
  58347. effectCfg.symbolType = symbolType;
  58348. effectCfg.color = color;
  58349. effectCfg.rippleEffectColor = itemModel.get(['rippleEffect', 'color']);
  58350. effectCfg.rippleNumber = itemModel.get(['rippleEffect', 'number']);
  58351. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  58352. if (effectCfg.showEffectOn === 'render') {
  58353. this._effectCfg ? this.updateEffectAnimation(effectCfg) : this.startEffectAnimation(effectCfg);
  58354. this._effectCfg = effectCfg;
  58355. } else {
  58356. // Not keep old effect config
  58357. this._effectCfg = null;
  58358. this.stopEffectAnimation();
  58359. this.onHoverStateChange = function (toState) {
  58360. if (toState === 'emphasis') {
  58361. if (effectCfg.showEffectOn !== 'render') {
  58362. _this.startEffectAnimation(effectCfg);
  58363. }
  58364. } else if (toState === 'normal') {
  58365. if (effectCfg.showEffectOn !== 'render') {
  58366. _this.stopEffectAnimation();
  58367. }
  58368. }
  58369. };
  58370. }
  58371. this._effectCfg = effectCfg;
  58372. enableHoverEmphasis(this);
  58373. };
  58374. EffectSymbol.prototype.fadeOut = function (cb) {
  58375. this.off('mouseover').off('mouseout');
  58376. cb && cb();
  58377. };
  58378. return EffectSymbol;
  58379. }(Group);
  58380. var EffectScatterView =
  58381. /** @class */
  58382. function (_super) {
  58383. __extends(EffectScatterView, _super);
  58384. function EffectScatterView() {
  58385. var _this = _super !== null && _super.apply(this, arguments) || this;
  58386. _this.type = EffectScatterView.type;
  58387. return _this;
  58388. }
  58389. EffectScatterView.prototype.init = function () {
  58390. this._symbolDraw = new SymbolDraw(EffectSymbol);
  58391. };
  58392. EffectScatterView.prototype.render = function (seriesModel, ecModel, api) {
  58393. var data = seriesModel.getData();
  58394. var effectSymbolDraw = this._symbolDraw;
  58395. effectSymbolDraw.updateData(data, {
  58396. clipShape: this._getClipShape(seriesModel)
  58397. });
  58398. this.group.add(effectSymbolDraw.group);
  58399. };
  58400. EffectScatterView.prototype._getClipShape = function (seriesModel) {
  58401. var coordSys = seriesModel.coordinateSystem;
  58402. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  58403. return seriesModel.get('clip', true) ? clipArea : null;
  58404. };
  58405. EffectScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  58406. var data = seriesModel.getData();
  58407. this.group.dirty();
  58408. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  58409. if (res.progress) {
  58410. res.progress({
  58411. start: 0,
  58412. end: data.count(),
  58413. count: data.count()
  58414. }, data);
  58415. }
  58416. this._symbolDraw.updateLayout();
  58417. };
  58418. EffectScatterView.prototype._updateGroupTransform = function (seriesModel) {
  58419. var coordSys = seriesModel.coordinateSystem;
  58420. if (coordSys && coordSys.getRoamTransform) {
  58421. this.group.transform = clone$2(coordSys.getRoamTransform());
  58422. this.group.decomposeTransform();
  58423. }
  58424. };
  58425. EffectScatterView.prototype.remove = function (ecModel, api) {
  58426. this._symbolDraw && this._symbolDraw.remove(true);
  58427. };
  58428. EffectScatterView.type = 'effectScatter';
  58429. return EffectScatterView;
  58430. }(ChartView);
  58431. var EffectScatterSeriesModel =
  58432. /** @class */
  58433. function (_super) {
  58434. __extends(EffectScatterSeriesModel, _super);
  58435. function EffectScatterSeriesModel() {
  58436. var _this = _super !== null && _super.apply(this, arguments) || this;
  58437. _this.type = EffectScatterSeriesModel.type;
  58438. _this.hasSymbolVisual = true;
  58439. return _this;
  58440. }
  58441. EffectScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  58442. return createSeriesData(null, this, {
  58443. useEncodeDefaulter: true
  58444. });
  58445. };
  58446. EffectScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  58447. return selectors.point(data.getItemLayout(dataIndex));
  58448. };
  58449. EffectScatterSeriesModel.type = 'series.effectScatter';
  58450. EffectScatterSeriesModel.dependencies = ['grid', 'polar'];
  58451. EffectScatterSeriesModel.defaultOption = {
  58452. coordinateSystem: 'cartesian2d',
  58453. zlevel: 0,
  58454. z: 2,
  58455. legendHoverLink: true,
  58456. effectType: 'ripple',
  58457. progressive: 0,
  58458. // When to show the effect, option: 'render'|'emphasis'
  58459. showEffectOn: 'render',
  58460. clip: true,
  58461. // Ripple effect config
  58462. rippleEffect: {
  58463. period: 4,
  58464. // Scale of ripple
  58465. scale: 2.5,
  58466. // Brush type can be fill or stroke
  58467. brushType: 'fill',
  58468. // Ripple number
  58469. number: 3
  58470. },
  58471. universalTransition: {
  58472. divideShape: 'clone'
  58473. },
  58474. // Cartesian coordinate system
  58475. // xAxisIndex: 0,
  58476. // yAxisIndex: 0,
  58477. // Polar coordinate system
  58478. // polarIndex: 0,
  58479. // Geo coordinate system
  58480. // geoIndex: 0,
  58481. // symbol: null, // 图形类型
  58482. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  58483. // symbolRotate: null, // 图形旋转控制
  58484. // itemStyle: {
  58485. // opacity: 1
  58486. // }
  58487. };
  58488. return EffectScatterSeriesModel;
  58489. }(SeriesModel);
  58490. function install$l(registers) {
  58491. registers.registerChartView(EffectScatterView);
  58492. registers.registerSeriesModel(EffectScatterSeriesModel);
  58493. registers.registerLayout(pointsLayout('effectScatter'));
  58494. }
  58495. var EffectLine =
  58496. /** @class */
  58497. function (_super) {
  58498. __extends(EffectLine, _super);
  58499. function EffectLine(lineData, idx, seriesScope) {
  58500. var _this = _super.call(this) || this;
  58501. _this.add(_this.createLine(lineData, idx, seriesScope));
  58502. _this._updateEffectSymbol(lineData, idx);
  58503. return _this;
  58504. }
  58505. EffectLine.prototype.createLine = function (lineData, idx, seriesScope) {
  58506. return new Line$1(lineData, idx, seriesScope);
  58507. };
  58508. EffectLine.prototype._updateEffectSymbol = function (lineData, idx) {
  58509. var itemModel = lineData.getItemModel(idx);
  58510. var effectModel = itemModel.getModel('effect');
  58511. var size = effectModel.get('symbolSize');
  58512. var symbolType = effectModel.get('symbol');
  58513. if (!isArray(size)) {
  58514. size = [size, size];
  58515. }
  58516. var lineStyle = lineData.getItemVisual(idx, 'style');
  58517. var color = effectModel.get('color') || lineStyle && lineStyle.stroke;
  58518. var symbol = this.childAt(1);
  58519. if (this._symbolType !== symbolType) {
  58520. // Remove previous
  58521. this.remove(symbol);
  58522. symbol = createSymbol(symbolType, -0.5, -0.5, 1, 1, color);
  58523. symbol.z2 = 100;
  58524. symbol.culling = true;
  58525. this.add(symbol);
  58526. } // Symbol may be removed if loop is false
  58527. if (!symbol) {
  58528. return;
  58529. } // Shadow color is same with color in default
  58530. symbol.setStyle('shadowColor', color);
  58531. symbol.setStyle(effectModel.getItemStyle(['color']));
  58532. symbol.scaleX = size[0];
  58533. symbol.scaleY = size[1];
  58534. symbol.setColor(color);
  58535. this._symbolType = symbolType;
  58536. this._symbolScale = size;
  58537. this._updateEffectAnimation(lineData, effectModel, idx);
  58538. };
  58539. EffectLine.prototype._updateEffectAnimation = function (lineData, effectModel, idx) {
  58540. var symbol = this.childAt(1);
  58541. if (!symbol) {
  58542. return;
  58543. }
  58544. var self = this;
  58545. var points = lineData.getItemLayout(idx);
  58546. var period = effectModel.get('period') * 1000;
  58547. var loop = effectModel.get('loop');
  58548. var constantSpeed = effectModel.get('constantSpeed');
  58549. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  58550. return idx / lineData.count() * period / 3;
  58551. }); // Ignore when updating
  58552. symbol.ignore = true;
  58553. this._updateAnimationPoints(symbol, points);
  58554. if (constantSpeed > 0) {
  58555. period = this._getLineLength(symbol) / constantSpeed * 1000;
  58556. }
  58557. if (period !== this._period || loop !== this._loop) {
  58558. symbol.stopAnimation();
  58559. if (period > 0) {
  58560. var delayNum = void 0;
  58561. if (typeof delayExpr === 'function') {
  58562. delayNum = delayExpr(idx);
  58563. } else {
  58564. delayNum = delayExpr;
  58565. }
  58566. if (symbol.__t > 0) {
  58567. delayNum = -period * symbol.__t;
  58568. }
  58569. symbol.__t = 0;
  58570. var animator = symbol.animate('', loop).when(period, {
  58571. __t: 1
  58572. }).delay(delayNum).during(function () {
  58573. self._updateSymbolPosition(symbol);
  58574. });
  58575. if (!loop) {
  58576. animator.done(function () {
  58577. self.remove(symbol);
  58578. });
  58579. }
  58580. animator.start();
  58581. }
  58582. }
  58583. this._period = period;
  58584. this._loop = loop;
  58585. };
  58586. EffectLine.prototype._getLineLength = function (symbol) {
  58587. // Not so accurate
  58588. return dist(symbol.__p1, symbol.__cp1) + dist(symbol.__cp1, symbol.__p2);
  58589. };
  58590. EffectLine.prototype._updateAnimationPoints = function (symbol, points) {
  58591. symbol.__p1 = points[0];
  58592. symbol.__p2 = points[1];
  58593. symbol.__cp1 = points[2] || [(points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2];
  58594. };
  58595. EffectLine.prototype.updateData = function (lineData, idx, seriesScope) {
  58596. this.childAt(0).updateData(lineData, idx, seriesScope);
  58597. this._updateEffectSymbol(lineData, idx);
  58598. };
  58599. EffectLine.prototype._updateSymbolPosition = function (symbol) {
  58600. var p1 = symbol.__p1;
  58601. var p2 = symbol.__p2;
  58602. var cp1 = symbol.__cp1;
  58603. var t = symbol.__t;
  58604. var pos = [symbol.x, symbol.y];
  58605. var lastPos = pos.slice();
  58606. var quadraticAt$1 = quadraticAt;
  58607. var quadraticDerivativeAt$1 = quadraticDerivativeAt;
  58608. pos[0] = quadraticAt$1(p1[0], cp1[0], p2[0], t);
  58609. pos[1] = quadraticAt$1(p1[1], cp1[1], p2[1], t); // Tangent
  58610. var tx = quadraticDerivativeAt$1(p1[0], cp1[0], p2[0], t);
  58611. var ty = quadraticDerivativeAt$1(p1[1], cp1[1], p2[1], t);
  58612. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2; // enable continuity trail for 'line', 'rect', 'roundRect' symbolType
  58613. if (this._symbolType === 'line' || this._symbolType === 'rect' || this._symbolType === 'roundRect') {
  58614. if (symbol.__lastT !== undefined && symbol.__lastT < symbol.__t) {
  58615. symbol.scaleY = dist(lastPos, pos) * 1.05; // make sure the last segment render within endPoint
  58616. if (t === 1) {
  58617. pos[0] = lastPos[0] + (pos[0] - lastPos[0]) / 2;
  58618. pos[1] = lastPos[1] + (pos[1] - lastPos[1]) / 2;
  58619. }
  58620. } else if (symbol.__lastT === 1) {
  58621. // After first loop, symbol.__t does NOT start with 0, so connect p1 to pos directly.
  58622. symbol.scaleY = 2 * dist(p1, pos);
  58623. } else {
  58624. symbol.scaleY = this._symbolScale[1];
  58625. }
  58626. }
  58627. symbol.__lastT = symbol.__t;
  58628. symbol.ignore = false;
  58629. symbol.x = pos[0];
  58630. symbol.y = pos[1];
  58631. };
  58632. EffectLine.prototype.updateLayout = function (lineData, idx) {
  58633. this.childAt(0).updateLayout(lineData, idx);
  58634. var effectModel = lineData.getItemModel(idx).getModel('effect');
  58635. this._updateEffectAnimation(lineData, effectModel, idx);
  58636. };
  58637. return EffectLine;
  58638. }(Group);
  58639. var Polyline$1 =
  58640. /** @class */
  58641. function (_super) {
  58642. __extends(Polyline$1, _super);
  58643. function Polyline$1(lineData, idx, seriesScope) {
  58644. var _this = _super.call(this) || this;
  58645. _this._createPolyline(lineData, idx, seriesScope);
  58646. return _this;
  58647. }
  58648. Polyline$1.prototype._createPolyline = function (lineData, idx, seriesScope) {
  58649. // let seriesModel = lineData.hostModel;
  58650. var points = lineData.getItemLayout(idx);
  58651. var line = new Polyline({
  58652. shape: {
  58653. points: points
  58654. }
  58655. });
  58656. this.add(line);
  58657. this._updateCommonStl(lineData, idx, seriesScope);
  58658. };
  58659. Polyline$1.prototype.updateData = function (lineData, idx, seriesScope) {
  58660. var seriesModel = lineData.hostModel;
  58661. var line = this.childAt(0);
  58662. var target = {
  58663. shape: {
  58664. points: lineData.getItemLayout(idx)
  58665. }
  58666. };
  58667. updateProps(line, target, seriesModel, idx);
  58668. this._updateCommonStl(lineData, idx, seriesScope);
  58669. };
  58670. Polyline$1.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  58671. var line = this.childAt(0);
  58672. var itemModel = lineData.getItemModel(idx);
  58673. var hoverLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  58674. if (!seriesScope || lineData.hasItemOption) {
  58675. hoverLineStyle = itemModel.getModel(['emphasis', 'lineStyle']).getLineStyle();
  58676. }
  58677. line.useStyle(lineData.getItemVisual(idx, 'style'));
  58678. line.style.fill = null;
  58679. line.style.strokeNoScale = true;
  58680. var lineEmphasisState = line.ensureState('emphasis');
  58681. lineEmphasisState.style = hoverLineStyle;
  58682. enableHoverEmphasis(this);
  58683. };
  58684. Polyline$1.prototype.updateLayout = function (lineData, idx) {
  58685. var polyline = this.childAt(0);
  58686. polyline.setShape('points', lineData.getItemLayout(idx));
  58687. };
  58688. return Polyline$1;
  58689. }(Group);
  58690. var EffectPolyline =
  58691. /** @class */
  58692. function (_super) {
  58693. __extends(EffectPolyline, _super);
  58694. function EffectPolyline() {
  58695. var _this = _super !== null && _super.apply(this, arguments) || this;
  58696. _this._lastFrame = 0;
  58697. _this._lastFramePercent = 0;
  58698. return _this;
  58699. } // Override
  58700. EffectPolyline.prototype.createLine = function (lineData, idx, seriesScope) {
  58701. return new Polyline$1(lineData, idx, seriesScope);
  58702. };
  58703. EffectPolyline.prototype._updateAnimationPoints = function (symbol, points) {
  58704. this._points = points;
  58705. var accLenArr = [0];
  58706. var len = 0;
  58707. for (var i = 1; i < points.length; i++) {
  58708. var p1 = points[i - 1];
  58709. var p2 = points[i];
  58710. len += dist(p1, p2);
  58711. accLenArr.push(len);
  58712. }
  58713. if (len === 0) {
  58714. this._length = 0;
  58715. return;
  58716. }
  58717. for (var i = 0; i < accLenArr.length; i++) {
  58718. accLenArr[i] /= len;
  58719. }
  58720. this._offsets = accLenArr;
  58721. this._length = len;
  58722. };
  58723. EffectPolyline.prototype._getLineLength = function () {
  58724. return this._length;
  58725. };
  58726. EffectPolyline.prototype._updateSymbolPosition = function (symbol) {
  58727. var t = symbol.__t;
  58728. var points = this._points;
  58729. var offsets = this._offsets;
  58730. var len = points.length;
  58731. if (!offsets) {
  58732. // Has length 0
  58733. return;
  58734. }
  58735. var lastFrame = this._lastFrame;
  58736. var frame;
  58737. if (t < this._lastFramePercent) {
  58738. // Start from the next frame
  58739. // PENDING start from lastFrame ?
  58740. var start = Math.min(lastFrame + 1, len - 1);
  58741. for (frame = start; frame >= 0; frame--) {
  58742. if (offsets[frame] <= t) {
  58743. break;
  58744. }
  58745. } // PENDING really need to do this ?
  58746. frame = Math.min(frame, len - 2);
  58747. } else {
  58748. for (frame = lastFrame; frame < len; frame++) {
  58749. if (offsets[frame] > t) {
  58750. break;
  58751. }
  58752. }
  58753. frame = Math.min(frame - 1, len - 2);
  58754. }
  58755. var p = (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame]);
  58756. var p0 = points[frame];
  58757. var p1 = points[frame + 1];
  58758. symbol.x = p0[0] * (1 - p) + p * p1[0];
  58759. symbol.y = p0[1] * (1 - p) + p * p1[1];
  58760. var tx = p1[0] - p0[0];
  58761. var ty = p1[1] - p0[1];
  58762. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  58763. this._lastFrame = frame;
  58764. this._lastFramePercent = t;
  58765. symbol.ignore = false;
  58766. };
  58767. return EffectPolyline;
  58768. }(EffectLine);
  58769. var LargeLinesPathShape =
  58770. /** @class */
  58771. function () {
  58772. function LargeLinesPathShape() {
  58773. this.polyline = false;
  58774. this.curveness = 0;
  58775. this.segs = [];
  58776. }
  58777. return LargeLinesPathShape;
  58778. }();
  58779. var LargeLinesPath =
  58780. /** @class */
  58781. function (_super) {
  58782. __extends(LargeLinesPath, _super);
  58783. function LargeLinesPath(opts) {
  58784. return _super.call(this, opts) || this;
  58785. }
  58786. LargeLinesPath.prototype.getDefaultStyle = function () {
  58787. return {
  58788. stroke: '#000',
  58789. fill: null
  58790. };
  58791. };
  58792. LargeLinesPath.prototype.getDefaultShape = function () {
  58793. return new LargeLinesPathShape();
  58794. };
  58795. LargeLinesPath.prototype.buildPath = function (ctx, shape) {
  58796. var segs = shape.segs;
  58797. var curveness = shape.curveness;
  58798. if (shape.polyline) {
  58799. for (var i = 0; i < segs.length;) {
  58800. var count = segs[i++];
  58801. if (count > 0) {
  58802. ctx.moveTo(segs[i++], segs[i++]);
  58803. for (var k = 1; k < count; k++) {
  58804. ctx.lineTo(segs[i++], segs[i++]);
  58805. }
  58806. }
  58807. }
  58808. } else {
  58809. for (var i = 0; i < segs.length;) {
  58810. var x0 = segs[i++];
  58811. var y0 = segs[i++];
  58812. var x1 = segs[i++];
  58813. var y1 = segs[i++];
  58814. ctx.moveTo(x0, y0);
  58815. if (curveness > 0) {
  58816. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  58817. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  58818. ctx.quadraticCurveTo(x2, y2, x1, y1);
  58819. } else {
  58820. ctx.lineTo(x1, y1);
  58821. }
  58822. }
  58823. }
  58824. };
  58825. LargeLinesPath.prototype.findDataIndex = function (x, y) {
  58826. var shape = this.shape;
  58827. var segs = shape.segs;
  58828. var curveness = shape.curveness;
  58829. var lineWidth = this.style.lineWidth;
  58830. if (shape.polyline) {
  58831. var dataIndex = 0;
  58832. for (var i = 0; i < segs.length;) {
  58833. var count = segs[i++];
  58834. if (count > 0) {
  58835. var x0 = segs[i++];
  58836. var y0 = segs[i++];
  58837. for (var k = 1; k < count; k++) {
  58838. var x1 = segs[i++];
  58839. var y1 = segs[i++];
  58840. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  58841. return dataIndex;
  58842. }
  58843. }
  58844. }
  58845. dataIndex++;
  58846. }
  58847. } else {
  58848. var dataIndex = 0;
  58849. for (var i = 0; i < segs.length;) {
  58850. var x0 = segs[i++];
  58851. var y0 = segs[i++];
  58852. var x1 = segs[i++];
  58853. var y1 = segs[i++];
  58854. if (curveness > 0) {
  58855. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  58856. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  58857. if (containStroke$2(x0, y0, x2, y2, x1, y1, lineWidth, x, y)) {
  58858. return dataIndex;
  58859. }
  58860. } else {
  58861. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  58862. return dataIndex;
  58863. }
  58864. }
  58865. dataIndex++;
  58866. }
  58867. }
  58868. return -1;
  58869. };
  58870. return LargeLinesPath;
  58871. }(Path);
  58872. var LargeLineDraw =
  58873. /** @class */
  58874. function () {
  58875. function LargeLineDraw() {
  58876. this.group = new Group();
  58877. }
  58878. LargeLineDraw.prototype.isPersistent = function () {
  58879. return !this._incremental;
  58880. };
  58881. /**
  58882. * Update symbols draw by new data
  58883. */
  58884. LargeLineDraw.prototype.updateData = function (data) {
  58885. this.group.removeAll();
  58886. var lineEl = new LargeLinesPath({
  58887. rectHover: true,
  58888. cursor: 'default'
  58889. });
  58890. lineEl.setShape({
  58891. segs: data.getLayout('linesPoints')
  58892. });
  58893. this._setCommon(lineEl, data); // Add back
  58894. this.group.add(lineEl);
  58895. this._incremental = null;
  58896. };
  58897. /**
  58898. * @override
  58899. */
  58900. LargeLineDraw.prototype.incrementalPrepareUpdate = function (data) {
  58901. this.group.removeAll();
  58902. this._clearIncremental();
  58903. if (data.count() > 5e5) {
  58904. if (!this._incremental) {
  58905. this._incremental = new IncrementalDisplayable({
  58906. silent: true
  58907. });
  58908. }
  58909. this.group.add(this._incremental);
  58910. } else {
  58911. this._incremental = null;
  58912. }
  58913. };
  58914. /**
  58915. * @override
  58916. */
  58917. LargeLineDraw.prototype.incrementalUpdate = function (taskParams, data) {
  58918. var lineEl = new LargeLinesPath();
  58919. lineEl.setShape({
  58920. segs: data.getLayout('linesPoints')
  58921. });
  58922. this._setCommon(lineEl, data, !!this._incremental);
  58923. if (!this._incremental) {
  58924. lineEl.rectHover = true;
  58925. lineEl.cursor = 'default';
  58926. lineEl.__startIndex = taskParams.start;
  58927. this.group.add(lineEl);
  58928. } else {
  58929. this._incremental.addDisplayable(lineEl, true);
  58930. }
  58931. };
  58932. /**
  58933. * @override
  58934. */
  58935. LargeLineDraw.prototype.remove = function () {
  58936. this._clearIncremental();
  58937. this._incremental = null;
  58938. this.group.removeAll();
  58939. };
  58940. LargeLineDraw.prototype._setCommon = function (lineEl, data, isIncremental) {
  58941. var hostModel = data.hostModel;
  58942. lineEl.setShape({
  58943. polyline: hostModel.get('polyline'),
  58944. curveness: hostModel.get(['lineStyle', 'curveness'])
  58945. });
  58946. lineEl.useStyle(hostModel.getModel('lineStyle').getLineStyle());
  58947. lineEl.style.strokeNoScale = true;
  58948. var style = data.getVisual('style');
  58949. if (style && style.stroke) {
  58950. lineEl.setStyle('stroke', style.stroke);
  58951. }
  58952. lineEl.setStyle('fill', null);
  58953. if (!isIncremental) {
  58954. var ecData_1 = getECData(lineEl); // Enable tooltip
  58955. // PENDING May have performance issue when path is extremely large
  58956. ecData_1.seriesIndex = hostModel.seriesIndex;
  58957. lineEl.on('mousemove', function (e) {
  58958. ecData_1.dataIndex = null;
  58959. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  58960. if (dataIndex > 0) {
  58961. // Provide dataIndex for tooltip
  58962. ecData_1.dataIndex = dataIndex + lineEl.__startIndex;
  58963. }
  58964. });
  58965. }
  58966. };
  58967. LargeLineDraw.prototype._clearIncremental = function () {
  58968. var incremental = this._incremental;
  58969. if (incremental) {
  58970. incremental.clearDisplaybles();
  58971. }
  58972. };
  58973. return LargeLineDraw;
  58974. }();
  58975. var linesLayout = {
  58976. seriesType: 'lines',
  58977. plan: createRenderPlanner(),
  58978. reset: function (seriesModel) {
  58979. var coordSys = seriesModel.coordinateSystem;
  58980. var isPolyline = seriesModel.get('polyline');
  58981. var isLarge = seriesModel.pipelineContext.large;
  58982. return {
  58983. progress: function (params, lineData) {
  58984. var lineCoords = [];
  58985. if (isLarge) {
  58986. var points = void 0;
  58987. var segCount = params.end - params.start;
  58988. if (isPolyline) {
  58989. var totalCoordsCount = 0;
  58990. for (var i = params.start; i < params.end; i++) {
  58991. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  58992. }
  58993. points = new Float32Array(segCount + totalCoordsCount * 2);
  58994. } else {
  58995. points = new Float32Array(segCount * 4);
  58996. }
  58997. var offset = 0;
  58998. var pt = [];
  58999. for (var i = params.start; i < params.end; i++) {
  59000. var len = seriesModel.getLineCoords(i, lineCoords);
  59001. if (isPolyline) {
  59002. points[offset++] = len;
  59003. }
  59004. for (var k = 0; k < len; k++) {
  59005. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  59006. points[offset++] = pt[0];
  59007. points[offset++] = pt[1];
  59008. }
  59009. }
  59010. lineData.setLayout('linesPoints', points);
  59011. } else {
  59012. for (var i = params.start; i < params.end; i++) {
  59013. var itemModel = lineData.getItemModel(i);
  59014. var len = seriesModel.getLineCoords(i, lineCoords);
  59015. var pts = [];
  59016. if (isPolyline) {
  59017. for (var j = 0; j < len; j++) {
  59018. pts.push(coordSys.dataToPoint(lineCoords[j]));
  59019. }
  59020. } else {
  59021. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  59022. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  59023. var curveness = itemModel.get(['lineStyle', 'curveness']);
  59024. if (+curveness) {
  59025. 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];
  59026. }
  59027. }
  59028. lineData.setItemLayout(i, pts);
  59029. }
  59030. }
  59031. }
  59032. };
  59033. }
  59034. };
  59035. var LinesView =
  59036. /** @class */
  59037. function (_super) {
  59038. __extends(LinesView, _super);
  59039. function LinesView() {
  59040. var _this = _super !== null && _super.apply(this, arguments) || this;
  59041. _this.type = LinesView.type;
  59042. return _this;
  59043. }
  59044. LinesView.prototype.render = function (seriesModel, ecModel, api) {
  59045. var data = seriesModel.getData();
  59046. var lineDraw = this._updateLineDraw(data, seriesModel);
  59047. var zlevel = seriesModel.get('zlevel');
  59048. var trailLength = seriesModel.get(['effect', 'trailLength']);
  59049. var zr = api.getZr(); // Avoid the drag cause ghost shadow
  59050. // FIXME Better way ?
  59051. // SVG doesn't support
  59052. var isSvg = zr.painter.getType() === 'svg';
  59053. if (!isSvg) {
  59054. zr.painter.getLayer(zlevel).clear(true);
  59055. } // Config layer with motion blur
  59056. if (this._lastZlevel != null && !isSvg) {
  59057. zr.configLayer(this._lastZlevel, {
  59058. motionBlur: false
  59059. });
  59060. }
  59061. if (this._showEffect(seriesModel) && trailLength) {
  59062. if ("development" !== 'production') {
  59063. var notInIndividual_1 = false;
  59064. ecModel.eachSeries(function (otherSeriesModel) {
  59065. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  59066. notInIndividual_1 = true;
  59067. }
  59068. });
  59069. notInIndividual_1 && console.warn('Lines with trail effect should have an individual zlevel');
  59070. }
  59071. if (!isSvg) {
  59072. zr.configLayer(zlevel, {
  59073. motionBlur: true,
  59074. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  59075. });
  59076. }
  59077. }
  59078. lineDraw.updateData(data);
  59079. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  59080. if (clipPath) {
  59081. this.group.setClipPath(clipPath);
  59082. } else {
  59083. this.group.removeClipPath();
  59084. }
  59085. this._lastZlevel = zlevel;
  59086. this._finished = true;
  59087. };
  59088. LinesView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  59089. var data = seriesModel.getData();
  59090. var lineDraw = this._updateLineDraw(data, seriesModel);
  59091. lineDraw.incrementalPrepareUpdate(data);
  59092. this._clearLayer(api);
  59093. this._finished = false;
  59094. };
  59095. LinesView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  59096. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  59097. this._finished = taskParams.end === seriesModel.getData().count();
  59098. };
  59099. LinesView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  59100. var data = seriesModel.getData();
  59101. var pipelineContext = seriesModel.pipelineContext;
  59102. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  59103. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  59104. return {
  59105. update: true
  59106. };
  59107. } else {
  59108. // TODO Use same logic with ScatterView.
  59109. // Manually update layout
  59110. var res = linesLayout.reset(seriesModel, ecModel, api);
  59111. if (res.progress) {
  59112. res.progress({
  59113. start: 0,
  59114. end: data.count(),
  59115. count: data.count()
  59116. }, data);
  59117. } // Not in large mode
  59118. this._lineDraw.updateLayout();
  59119. this._clearLayer(api);
  59120. }
  59121. };
  59122. LinesView.prototype._updateLineDraw = function (data, seriesModel) {
  59123. var lineDraw = this._lineDraw;
  59124. var hasEffect = this._showEffect(seriesModel);
  59125. var isPolyline = !!seriesModel.get('polyline');
  59126. var pipelineContext = seriesModel.pipelineContext;
  59127. var isLargeDraw = pipelineContext.large;
  59128. if ("development" !== 'production') {
  59129. if (hasEffect && isLargeDraw) {
  59130. console.warn('Large lines not support effect');
  59131. }
  59132. }
  59133. if (!lineDraw || hasEffect !== this._hasEffet || isPolyline !== this._isPolyline || isLargeDraw !== this._isLargeDraw) {
  59134. if (lineDraw) {
  59135. lineDraw.remove();
  59136. }
  59137. lineDraw = this._lineDraw = isLargeDraw ? new LargeLineDraw() : new LineDraw(isPolyline ? hasEffect ? EffectPolyline : Polyline$1 : hasEffect ? EffectLine : Line$1);
  59138. this._hasEffet = hasEffect;
  59139. this._isPolyline = isPolyline;
  59140. this._isLargeDraw = isLargeDraw;
  59141. }
  59142. this.group.add(lineDraw.group);
  59143. return lineDraw;
  59144. };
  59145. LinesView.prototype._showEffect = function (seriesModel) {
  59146. return !!seriesModel.get(['effect', 'show']);
  59147. };
  59148. LinesView.prototype._clearLayer = function (api) {
  59149. // Not use motion when dragging or zooming
  59150. var zr = api.getZr();
  59151. var isSvg = zr.painter.getType() === 'svg';
  59152. if (!isSvg && this._lastZlevel != null) {
  59153. zr.painter.getLayer(this._lastZlevel).clear(true);
  59154. }
  59155. };
  59156. LinesView.prototype.remove = function (ecModel, api) {
  59157. this._lineDraw && this._lineDraw.remove();
  59158. this._lineDraw = null; // Clear motion when lineDraw is removed
  59159. this._clearLayer(api);
  59160. };
  59161. LinesView.prototype.dispose = function (ecModel, api) {
  59162. this.remove(ecModel, api);
  59163. };
  59164. LinesView.type = 'lines';
  59165. return LinesView;
  59166. }(ChartView);
  59167. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  59168. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  59169. function compatEc2(seriesOpt) {
  59170. var data = seriesOpt.data;
  59171. if (data && data[0] && data[0][0] && data[0][0].coord) {
  59172. if ("development" !== 'production') {
  59173. console.warn('Lines data configuration has been changed to' + ' { coords:[[1,2],[2,3]] }');
  59174. }
  59175. seriesOpt.data = map(data, function (itemOpt) {
  59176. var coords = [itemOpt[0].coord, itemOpt[1].coord];
  59177. var target = {
  59178. coords: coords
  59179. };
  59180. if (itemOpt[0].name) {
  59181. target.fromName = itemOpt[0].name;
  59182. }
  59183. if (itemOpt[1].name) {
  59184. target.toName = itemOpt[1].name;
  59185. }
  59186. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  59187. });
  59188. }
  59189. }
  59190. var LinesSeriesModel =
  59191. /** @class */
  59192. function (_super) {
  59193. __extends(LinesSeriesModel, _super);
  59194. function LinesSeriesModel() {
  59195. var _this = _super !== null && _super.apply(this, arguments) || this;
  59196. _this.type = LinesSeriesModel.type;
  59197. _this.visualStyleAccessPath = 'lineStyle';
  59198. _this.visualDrawType = 'stroke';
  59199. return _this;
  59200. }
  59201. LinesSeriesModel.prototype.init = function (option) {
  59202. // The input data may be null/undefined.
  59203. option.data = option.data || []; // Not using preprocessor because mergeOption may not have series.type
  59204. compatEc2(option);
  59205. var result = this._processFlatCoordsArray(option.data);
  59206. this._flatCoords = result.flatCoords;
  59207. this._flatCoordsOffset = result.flatCoordsOffset;
  59208. if (result.flatCoords) {
  59209. option.data = new Float32Array(result.count);
  59210. }
  59211. _super.prototype.init.apply(this, arguments);
  59212. };
  59213. LinesSeriesModel.prototype.mergeOption = function (option) {
  59214. compatEc2(option);
  59215. if (option.data) {
  59216. // Only update when have option data to merge.
  59217. var result = this._processFlatCoordsArray(option.data);
  59218. this._flatCoords = result.flatCoords;
  59219. this._flatCoordsOffset = result.flatCoordsOffset;
  59220. if (result.flatCoords) {
  59221. option.data = new Float32Array(result.count);
  59222. }
  59223. }
  59224. _super.prototype.mergeOption.apply(this, arguments);
  59225. };
  59226. LinesSeriesModel.prototype.appendData = function (params) {
  59227. var result = this._processFlatCoordsArray(params.data);
  59228. if (result.flatCoords) {
  59229. if (!this._flatCoords) {
  59230. this._flatCoords = result.flatCoords;
  59231. this._flatCoordsOffset = result.flatCoordsOffset;
  59232. } else {
  59233. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  59234. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  59235. }
  59236. params.data = new Float32Array(result.count);
  59237. }
  59238. this.getRawData().appendData(params.data);
  59239. };
  59240. LinesSeriesModel.prototype._getCoordsFromItemModel = function (idx) {
  59241. var itemModel = this.getData().getItemModel(idx);
  59242. var coords = itemModel.option instanceof Array ? itemModel.option : itemModel.getShallow('coords');
  59243. if ("development" !== 'production') {
  59244. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  59245. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  59246. }
  59247. }
  59248. return coords;
  59249. };
  59250. LinesSeriesModel.prototype.getLineCoordsCount = function (idx) {
  59251. if (this._flatCoordsOffset) {
  59252. return this._flatCoordsOffset[idx * 2 + 1];
  59253. } else {
  59254. return this._getCoordsFromItemModel(idx).length;
  59255. }
  59256. };
  59257. LinesSeriesModel.prototype.getLineCoords = function (idx, out) {
  59258. if (this._flatCoordsOffset) {
  59259. var offset = this._flatCoordsOffset[idx * 2];
  59260. var len = this._flatCoordsOffset[idx * 2 + 1];
  59261. for (var i = 0; i < len; i++) {
  59262. out[i] = out[i] || [];
  59263. out[i][0] = this._flatCoords[offset + i * 2];
  59264. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  59265. }
  59266. return len;
  59267. } else {
  59268. var coords = this._getCoordsFromItemModel(idx);
  59269. for (var i = 0; i < coords.length; i++) {
  59270. out[i] = out[i] || [];
  59271. out[i][0] = coords[i][0];
  59272. out[i][1] = coords[i][1];
  59273. }
  59274. return coords.length;
  59275. }
  59276. };
  59277. LinesSeriesModel.prototype._processFlatCoordsArray = function (data) {
  59278. var startOffset = 0;
  59279. if (this._flatCoords) {
  59280. startOffset = this._flatCoords.length;
  59281. } // Stored as a typed array. In format
  59282. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  59283. if (typeof data[0] === 'number') {
  59284. var len = data.length; // Store offset and len of each segment
  59285. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  59286. var coordsStorage = new Float64Arr(len);
  59287. var coordsCursor = 0;
  59288. var offsetCursor = 0;
  59289. var dataCount = 0;
  59290. for (var i = 0; i < len;) {
  59291. dataCount++;
  59292. var count = data[i++]; // Offset
  59293. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset; // Len
  59294. coordsOffsetAndLenStorage[offsetCursor++] = count;
  59295. for (var k = 0; k < count; k++) {
  59296. var x = data[i++];
  59297. var y = data[i++];
  59298. coordsStorage[coordsCursor++] = x;
  59299. coordsStorage[coordsCursor++] = y;
  59300. if (i > len) {
  59301. if ("development" !== 'production') {
  59302. throw new Error('Invalid data format.');
  59303. }
  59304. }
  59305. }
  59306. }
  59307. return {
  59308. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  59309. flatCoords: coordsStorage,
  59310. count: dataCount
  59311. };
  59312. }
  59313. return {
  59314. flatCoordsOffset: null,
  59315. flatCoords: null,
  59316. count: data.length
  59317. };
  59318. };
  59319. LinesSeriesModel.prototype.getInitialData = function (option, ecModel) {
  59320. if ("development" !== 'production') {
  59321. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  59322. if (!CoordSys) {
  59323. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  59324. }
  59325. }
  59326. var lineData = new SeriesData(['value'], this);
  59327. lineData.hasItemOption = false;
  59328. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  59329. // dataItem is simply coords
  59330. if (dataItem instanceof Array) {
  59331. return NaN;
  59332. } else {
  59333. lineData.hasItemOption = true;
  59334. var value = dataItem.value;
  59335. if (value != null) {
  59336. return value instanceof Array ? value[dimIndex] : value;
  59337. }
  59338. }
  59339. });
  59340. return lineData;
  59341. };
  59342. LinesSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  59343. var data = this.getData();
  59344. var itemModel = data.getItemModel(dataIndex);
  59345. var name = itemModel.get('name');
  59346. if (name) {
  59347. return name;
  59348. }
  59349. var fromName = itemModel.get('fromName');
  59350. var toName = itemModel.get('toName');
  59351. var nameArr = [];
  59352. fromName != null && nameArr.push(fromName);
  59353. toName != null && nameArr.push(toName);
  59354. return createTooltipMarkup('nameValue', {
  59355. name: nameArr.join(' > ')
  59356. });
  59357. };
  59358. LinesSeriesModel.prototype.preventIncremental = function () {
  59359. return !!this.get(['effect', 'show']);
  59360. };
  59361. LinesSeriesModel.prototype.getProgressive = function () {
  59362. var progressive = this.option.progressive;
  59363. if (progressive == null) {
  59364. return this.option.large ? 1e4 : this.get('progressive');
  59365. }
  59366. return progressive;
  59367. };
  59368. LinesSeriesModel.prototype.getProgressiveThreshold = function () {
  59369. var progressiveThreshold = this.option.progressiveThreshold;
  59370. if (progressiveThreshold == null) {
  59371. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  59372. }
  59373. return progressiveThreshold;
  59374. };
  59375. LinesSeriesModel.type = 'series.lines';
  59376. LinesSeriesModel.dependencies = ['grid', 'polar', 'geo', 'calendar'];
  59377. LinesSeriesModel.defaultOption = {
  59378. coordinateSystem: 'geo',
  59379. zlevel: 0,
  59380. z: 2,
  59381. legendHoverLink: true,
  59382. // Cartesian coordinate system
  59383. xAxisIndex: 0,
  59384. yAxisIndex: 0,
  59385. symbol: ['none', 'none'],
  59386. symbolSize: [10, 10],
  59387. // Geo coordinate system
  59388. geoIndex: 0,
  59389. effect: {
  59390. show: false,
  59391. period: 4,
  59392. constantSpeed: 0,
  59393. symbol: 'circle',
  59394. symbolSize: 3,
  59395. loop: true,
  59396. trailLength: 0.2
  59397. },
  59398. large: false,
  59399. // Available when large is true
  59400. largeThreshold: 2000,
  59401. polyline: false,
  59402. clip: true,
  59403. label: {
  59404. show: false,
  59405. position: 'end' // distance: 5,
  59406. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  59407. },
  59408. lineStyle: {
  59409. opacity: 0.5
  59410. }
  59411. };
  59412. return LinesSeriesModel;
  59413. }(SeriesModel);
  59414. /*
  59415. * Licensed to the Apache Software Foundation (ASF) under one
  59416. * or more contributor license agreements. See the NOTICE file
  59417. * distributed with this work for additional information
  59418. * regarding copyright ownership. The ASF licenses this file
  59419. * to you under the Apache License, Version 2.0 (the
  59420. * "License"); you may not use this file except in compliance
  59421. * with the License. You may obtain a copy of the License at
  59422. *
  59423. * http://www.apache.org/licenses/LICENSE-2.0
  59424. *
  59425. * Unless required by applicable law or agreed to in writing,
  59426. * software distributed under the License is distributed on an
  59427. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59428. * KIND, either express or implied. See the License for the
  59429. * specific language governing permissions and limitations
  59430. * under the License.
  59431. */
  59432. /**
  59433. * AUTO-GENERATED FILE. DO NOT MODIFY.
  59434. */
  59435. /*
  59436. * Licensed to the Apache Software Foundation (ASF) under one
  59437. * or more contributor license agreements. See the NOTICE file
  59438. * distributed with this work for additional information
  59439. * regarding copyright ownership. The ASF licenses this file
  59440. * to you under the Apache License, Version 2.0 (the
  59441. * "License"); you may not use this file except in compliance
  59442. * with the License. You may obtain a copy of the License at
  59443. *
  59444. * http://www.apache.org/licenses/LICENSE-2.0
  59445. *
  59446. * Unless required by applicable law or agreed to in writing,
  59447. * software distributed under the License is distributed on an
  59448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59449. * KIND, either express or implied. See the License for the
  59450. * specific language governing permissions and limitations
  59451. * under the License.
  59452. */
  59453. function normalize$3(a) {
  59454. if (!(a instanceof Array)) {
  59455. a = [a, a];
  59456. }
  59457. return a;
  59458. }
  59459. var linesVisual = {
  59460. seriesType: 'lines',
  59461. reset: function (seriesModel) {
  59462. var symbolType = normalize$3(seriesModel.get('symbol'));
  59463. var symbolSize = normalize$3(seriesModel.get('symbolSize'));
  59464. var data = seriesModel.getData();
  59465. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  59466. data.setVisual('toSymbol', symbolType && symbolType[1]);
  59467. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  59468. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  59469. function dataEach(data, idx) {
  59470. var itemModel = data.getItemModel(idx);
  59471. var symbolType = normalize$3(itemModel.getShallow('symbol', true));
  59472. var symbolSize = normalize$3(itemModel.getShallow('symbolSize', true));
  59473. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  59474. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  59475. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  59476. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  59477. }
  59478. return {
  59479. dataEach: data.hasItemOption ? dataEach : null
  59480. };
  59481. }
  59482. };
  59483. function install$m(registers) {
  59484. registers.registerChartView(LinesView);
  59485. registers.registerSeriesModel(LinesSeriesModel);
  59486. registers.registerLayout(linesLayout);
  59487. registers.registerVisual(linesVisual);
  59488. }
  59489. var GRADIENT_LEVELS = 256;
  59490. var HeatmapLayer =
  59491. /** @class */
  59492. function () {
  59493. function HeatmapLayer() {
  59494. this.blurSize = 30;
  59495. this.pointSize = 20;
  59496. this.maxOpacity = 1;
  59497. this.minOpacity = 0;
  59498. this._gradientPixels = {
  59499. inRange: null,
  59500. outOfRange: null
  59501. };
  59502. var canvas = createCanvas();
  59503. this.canvas = canvas;
  59504. }
  59505. /**
  59506. * Renders Heatmap and returns the rendered canvas
  59507. * @param data array of data, each has x, y, value
  59508. * @param width canvas width
  59509. * @param height canvas height
  59510. */
  59511. HeatmapLayer.prototype.update = function (data, width, height, normalize, colorFunc, isInRange) {
  59512. var brush = this._getBrush();
  59513. var gradientInRange = this._getGradient(colorFunc, 'inRange');
  59514. var gradientOutOfRange = this._getGradient(colorFunc, 'outOfRange');
  59515. var r = this.pointSize + this.blurSize;
  59516. var canvas = this.canvas;
  59517. var ctx = canvas.getContext('2d');
  59518. var len = data.length;
  59519. canvas.width = width;
  59520. canvas.height = height;
  59521. for (var i = 0; i < len; ++i) {
  59522. var p = data[i];
  59523. var x = p[0];
  59524. var y = p[1];
  59525. var value = p[2]; // calculate alpha using value
  59526. var alpha = normalize(value); // draw with the circle brush with alpha
  59527. ctx.globalAlpha = alpha;
  59528. ctx.drawImage(brush, x - r, y - r);
  59529. }
  59530. if (!canvas.width || !canvas.height) {
  59531. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  59532. // 'CanvasRenderingContext2D': The source height is 0."
  59533. return canvas;
  59534. } // colorize the canvas using alpha value and set with gradient
  59535. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  59536. var pixels = imageData.data;
  59537. var offset = 0;
  59538. var pixelLen = pixels.length;
  59539. var minOpacity = this.minOpacity;
  59540. var maxOpacity = this.maxOpacity;
  59541. var diffOpacity = maxOpacity - minOpacity;
  59542. while (offset < pixelLen) {
  59543. var alpha = pixels[offset + 3] / 256;
  59544. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4; // Simple optimize to ignore the empty data
  59545. if (alpha > 0) {
  59546. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange; // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  59547. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  59548. pixels[offset++] = gradient[gradientOffset];
  59549. pixels[offset++] = gradient[gradientOffset + 1];
  59550. pixels[offset++] = gradient[gradientOffset + 2];
  59551. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  59552. } else {
  59553. offset += 4;
  59554. }
  59555. }
  59556. ctx.putImageData(imageData, 0, 0);
  59557. return canvas;
  59558. };
  59559. /**
  59560. * get canvas of a black circle brush used for canvas to draw later
  59561. */
  59562. HeatmapLayer.prototype._getBrush = function () {
  59563. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas()); // set brush size
  59564. var r = this.pointSize + this.blurSize;
  59565. var d = r * 2;
  59566. brushCanvas.width = d;
  59567. brushCanvas.height = d;
  59568. var ctx = brushCanvas.getContext('2d');
  59569. ctx.clearRect(0, 0, d, d); // in order to render shadow without the distinct circle,
  59570. // draw the distinct circle in an invisible place,
  59571. // and use shadowOffset to draw shadow in the center of the canvas
  59572. ctx.shadowOffsetX = d;
  59573. ctx.shadowBlur = this.blurSize; // draw the shadow in black, and use alpha and shadow blur to generate
  59574. // color in color map
  59575. ctx.shadowColor = '#000'; // draw circle in the left to the canvas
  59576. ctx.beginPath();
  59577. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  59578. ctx.closePath();
  59579. ctx.fill();
  59580. return brushCanvas;
  59581. };
  59582. /**
  59583. * get gradient color map
  59584. * @private
  59585. */
  59586. HeatmapLayer.prototype._getGradient = function (colorFunc, state) {
  59587. var gradientPixels = this._gradientPixels;
  59588. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  59589. var color = [0, 0, 0, 0];
  59590. var off = 0;
  59591. for (var i = 0; i < 256; i++) {
  59592. colorFunc[state](i / 255, true, color);
  59593. pixelsSingleState[off++] = color[0];
  59594. pixelsSingleState[off++] = color[1];
  59595. pixelsSingleState[off++] = color[2];
  59596. pixelsSingleState[off++] = color[3];
  59597. }
  59598. return pixelsSingleState;
  59599. };
  59600. return HeatmapLayer;
  59601. }();
  59602. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  59603. var dataSpan = dataExtent[1] - dataExtent[0];
  59604. pieceList = map(pieceList, function (piece) {
  59605. return {
  59606. interval: [(piece.interval[0] - dataExtent[0]) / dataSpan, (piece.interval[1] - dataExtent[0]) / dataSpan]
  59607. };
  59608. });
  59609. var len = pieceList.length;
  59610. var lastIndex = 0;
  59611. return function (val) {
  59612. var i; // Try to find in the location of the last found
  59613. for (i = lastIndex; i < len; i++) {
  59614. var interval = pieceList[i].interval;
  59615. if (interval[0] <= val && val <= interval[1]) {
  59616. lastIndex = i;
  59617. break;
  59618. }
  59619. }
  59620. if (i === len) {
  59621. // Not found, back interation
  59622. for (i = lastIndex - 1; i >= 0; i--) {
  59623. var interval = pieceList[i].interval;
  59624. if (interval[0] <= val && val <= interval[1]) {
  59625. lastIndex = i;
  59626. break;
  59627. }
  59628. }
  59629. }
  59630. return i >= 0 && i < len && selected[i];
  59631. };
  59632. }
  59633. function getIsInContinuousRange(dataExtent, range) {
  59634. var dataSpan = dataExtent[1] - dataExtent[0];
  59635. range = [(range[0] - dataExtent[0]) / dataSpan, (range[1] - dataExtent[0]) / dataSpan];
  59636. return function (val) {
  59637. return val >= range[0] && val <= range[1];
  59638. };
  59639. }
  59640. function isGeoCoordSys(coordSys) {
  59641. var dimensions = coordSys.dimensions; // Not use coorSys.type === 'geo' because coordSys maybe extended
  59642. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  59643. }
  59644. var HeatmapView =
  59645. /** @class */
  59646. function (_super) {
  59647. __extends(HeatmapView, _super);
  59648. function HeatmapView() {
  59649. var _this = _super !== null && _super.apply(this, arguments) || this;
  59650. _this.type = HeatmapView.type;
  59651. return _this;
  59652. }
  59653. HeatmapView.prototype.render = function (seriesModel, ecModel, api) {
  59654. var visualMapOfThisSeries;
  59655. ecModel.eachComponent('visualMap', function (visualMap) {
  59656. visualMap.eachTargetSeries(function (targetSeries) {
  59657. if (targetSeries === seriesModel) {
  59658. visualMapOfThisSeries = visualMap;
  59659. }
  59660. });
  59661. });
  59662. if ("development" !== 'production') {
  59663. if (!visualMapOfThisSeries) {
  59664. throw new Error('Heatmap must use with visualMap');
  59665. }
  59666. }
  59667. this.group.removeAll();
  59668. this._incrementalDisplayable = null;
  59669. var coordSys = seriesModel.coordinateSystem;
  59670. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  59671. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  59672. } else if (isGeoCoordSys(coordSys)) {
  59673. this._renderOnGeo(coordSys, seriesModel, visualMapOfThisSeries, api);
  59674. }
  59675. };
  59676. HeatmapView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  59677. this.group.removeAll();
  59678. };
  59679. HeatmapView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  59680. var coordSys = seriesModel.coordinateSystem;
  59681. if (coordSys) {
  59682. // geo does not support incremental rendering?
  59683. if (isGeoCoordSys(coordSys)) {
  59684. this.render(seriesModel, ecModel, api);
  59685. } else {
  59686. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  59687. }
  59688. }
  59689. };
  59690. HeatmapView.prototype._renderOnCartesianAndCalendar = function (seriesModel, api, start, end, incremental) {
  59691. var coordSys = seriesModel.coordinateSystem;
  59692. var width;
  59693. var height;
  59694. var xAxisExtent;
  59695. var yAxisExtent;
  59696. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  59697. var xAxis = coordSys.getAxis('x');
  59698. var yAxis = coordSys.getAxis('y');
  59699. if ("development" !== 'production') {
  59700. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  59701. throw new Error('Heatmap on cartesian must have two category axes');
  59702. }
  59703. if (!(xAxis.onBand && yAxis.onBand)) {
  59704. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  59705. }
  59706. }
  59707. width = xAxis.getBandWidth();
  59708. height = yAxis.getBandWidth();
  59709. xAxisExtent = xAxis.scale.getExtent();
  59710. yAxisExtent = yAxis.scale.getExtent();
  59711. }
  59712. var group = this.group;
  59713. var data = seriesModel.getData();
  59714. var emphasisStyle = seriesModel.getModel(['emphasis', 'itemStyle']).getItemStyle();
  59715. var blurStyle = seriesModel.getModel(['blur', 'itemStyle']).getItemStyle();
  59716. var selectStyle = seriesModel.getModel(['select', 'itemStyle']).getItemStyle();
  59717. var labelStatesModels = getLabelStatesModels(seriesModel);
  59718. var focus = seriesModel.get(['emphasis', 'focus']);
  59719. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  59720. var dataDims = isCoordinateSystemType(coordSys, 'cartesian2d') ? [data.mapDimension('x'), data.mapDimension('y'), data.mapDimension('value')] : [data.mapDimension('time'), data.mapDimension('value')];
  59721. for (var idx = start; idx < end; idx++) {
  59722. var rect = void 0;
  59723. var style = data.getItemVisual(idx, 'style');
  59724. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  59725. var dataDimX = data.get(dataDims[0], idx);
  59726. var dataDimY = data.get(dataDims[1], idx); // Ignore empty data and out of extent data
  59727. if (isNaN(data.get(dataDims[2], idx)) || dataDimX < xAxisExtent[0] || dataDimX > xAxisExtent[1] || dataDimY < yAxisExtent[0] || dataDimY > yAxisExtent[1]) {
  59728. continue;
  59729. }
  59730. var point = coordSys.dataToPoint([dataDimX, dataDimY]);
  59731. rect = new Rect({
  59732. shape: {
  59733. x: Math.floor(Math.round(point[0]) - width / 2),
  59734. y: Math.floor(Math.round(point[1]) - height / 2),
  59735. width: Math.ceil(width),
  59736. height: Math.ceil(height)
  59737. },
  59738. style: style
  59739. });
  59740. } else {
  59741. // Ignore empty data
  59742. if (isNaN(data.get(dataDims[1], idx))) {
  59743. continue;
  59744. }
  59745. rect = new Rect({
  59746. z2: 1,
  59747. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  59748. style: style
  59749. });
  59750. }
  59751. var itemModel = data.getItemModel(idx); // Optimization for large datset
  59752. if (data.hasItemOption) {
  59753. var emphasisModel = itemModel.getModel('emphasis');
  59754. emphasisStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  59755. blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  59756. selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  59757. focus = emphasisModel.get('focus');
  59758. blurScope = emphasisModel.get('blurScope');
  59759. labelStatesModels = getLabelStatesModels(itemModel);
  59760. }
  59761. var rawValue = seriesModel.getRawValue(idx);
  59762. var defaultText = '-';
  59763. if (rawValue && rawValue[2] != null) {
  59764. defaultText = rawValue[2] + '';
  59765. }
  59766. setLabelStyle(rect, labelStatesModels, {
  59767. labelFetcher: seriesModel,
  59768. labelDataIndex: idx,
  59769. defaultOpacity: style.opacity,
  59770. defaultText: defaultText
  59771. });
  59772. rect.ensureState('emphasis').style = emphasisStyle;
  59773. rect.ensureState('blur').style = blurStyle;
  59774. rect.ensureState('select').style = selectStyle;
  59775. enableHoverEmphasis(rect, focus, blurScope);
  59776. rect.incremental = incremental; // PENDING
  59777. if (incremental) {
  59778. // Rect must use hover layer if it's incremental.
  59779. rect.states.emphasis.hoverLayer = true;
  59780. }
  59781. group.add(rect);
  59782. data.setItemGraphicEl(idx, rect);
  59783. }
  59784. };
  59785. HeatmapView.prototype._renderOnGeo = function (geo, seriesModel, visualMapModel, api) {
  59786. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  59787. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange; // if (!visualMapping) {
  59788. // throw new Error('Data range must have color visuals');
  59789. // }
  59790. var data = seriesModel.getData();
  59791. var hmLayer = this._hmLayer || this._hmLayer || new HeatmapLayer();
  59792. hmLayer.blurSize = seriesModel.get('blurSize');
  59793. hmLayer.pointSize = seriesModel.get('pointSize');
  59794. hmLayer.minOpacity = seriesModel.get('minOpacity');
  59795. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  59796. var rect = geo.getViewRect().clone();
  59797. var roamTransform = geo.getRoamTransform();
  59798. rect.applyTransform(roamTransform); // Clamp on viewport
  59799. var x = Math.max(rect.x, 0);
  59800. var y = Math.max(rect.y, 0);
  59801. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  59802. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  59803. var width = x2 - x;
  59804. var height = y2 - y;
  59805. var dims = [data.mapDimension('lng'), data.mapDimension('lat'), data.mapDimension('value')];
  59806. var points = data.mapArray(dims, function (lng, lat, value) {
  59807. var pt = geo.dataToPoint([lng, lat]);
  59808. pt[0] -= x;
  59809. pt[1] -= y;
  59810. pt.push(value);
  59811. return pt;
  59812. });
  59813. var dataExtent = visualMapModel.getExtent();
  59814. var isInRange = visualMapModel.type === 'visualMap.continuous' ? getIsInContinuousRange(dataExtent, visualMapModel.option.range) : getIsInPiecewiseRange(dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected);
  59815. hmLayer.update(points, width, height, inRangeVisuals.color.getNormalizer(), {
  59816. inRange: inRangeVisuals.color.getColorMapper(),
  59817. outOfRange: outOfRangeVisuals.color.getColorMapper()
  59818. }, isInRange);
  59819. var img = new ZRImage({
  59820. style: {
  59821. width: width,
  59822. height: height,
  59823. x: x,
  59824. y: y,
  59825. image: hmLayer.canvas
  59826. },
  59827. silent: true
  59828. });
  59829. this.group.add(img);
  59830. };
  59831. HeatmapView.type = 'heatmap';
  59832. return HeatmapView;
  59833. }(ChartView);
  59834. var HeatmapSeriesModel =
  59835. /** @class */
  59836. function (_super) {
  59837. __extends(HeatmapSeriesModel, _super);
  59838. function HeatmapSeriesModel() {
  59839. var _this = _super !== null && _super.apply(this, arguments) || this;
  59840. _this.type = HeatmapSeriesModel.type;
  59841. return _this;
  59842. }
  59843. HeatmapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  59844. return createSeriesData(null, this, {
  59845. generateCoord: 'value'
  59846. });
  59847. };
  59848. HeatmapSeriesModel.prototype.preventIncremental = function () {
  59849. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  59850. if (coordSysCreator && coordSysCreator.dimensions) {
  59851. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  59852. }
  59853. };
  59854. HeatmapSeriesModel.type = 'series.heatmap';
  59855. HeatmapSeriesModel.dependencies = ['grid', 'geo', 'calendar'];
  59856. HeatmapSeriesModel.defaultOption = {
  59857. coordinateSystem: 'cartesian2d',
  59858. zlevel: 0,
  59859. z: 2,
  59860. // Cartesian coordinate system
  59861. // xAxisIndex: 0,
  59862. // yAxisIndex: 0,
  59863. // Geo coordinate system
  59864. geoIndex: 0,
  59865. blurSize: 30,
  59866. pointSize: 20,
  59867. maxOpacity: 1,
  59868. minOpacity: 0,
  59869. select: {
  59870. itemStyle: {
  59871. borderColor: '#212121'
  59872. }
  59873. }
  59874. };
  59875. return HeatmapSeriesModel;
  59876. }(SeriesModel);
  59877. function install$n(registers) {
  59878. registers.registerChartView(HeatmapView);
  59879. registers.registerSeriesModel(HeatmapSeriesModel);
  59880. }
  59881. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'borderWidth']; // index: +isHorizontal
  59882. var LAYOUT_ATTRS = [{
  59883. xy: 'x',
  59884. wh: 'width',
  59885. index: 0,
  59886. posDesc: ['left', 'right']
  59887. }, {
  59888. xy: 'y',
  59889. wh: 'height',
  59890. index: 1,
  59891. posDesc: ['top', 'bottom']
  59892. }];
  59893. var pathForLineWidth = new Circle();
  59894. var PictorialBarView =
  59895. /** @class */
  59896. function (_super) {
  59897. __extends(PictorialBarView, _super);
  59898. function PictorialBarView() {
  59899. var _this = _super !== null && _super.apply(this, arguments) || this;
  59900. _this.type = PictorialBarView.type;
  59901. return _this;
  59902. }
  59903. PictorialBarView.prototype.render = function (seriesModel, ecModel, api) {
  59904. var group = this.group;
  59905. var data = seriesModel.getData();
  59906. var oldData = this._data;
  59907. var cartesian = seriesModel.coordinateSystem;
  59908. var baseAxis = cartesian.getBaseAxis();
  59909. var isHorizontal = baseAxis.isHorizontal();
  59910. var coordSysRect = cartesian.master.getRect();
  59911. var opt = {
  59912. ecSize: {
  59913. width: api.getWidth(),
  59914. height: api.getHeight()
  59915. },
  59916. seriesModel: seriesModel,
  59917. coordSys: cartesian,
  59918. coordSysExtent: [[coordSysRect.x, coordSysRect.x + coordSysRect.width], [coordSysRect.y, coordSysRect.y + coordSysRect.height]],
  59919. isHorizontal: isHorizontal,
  59920. valueDim: LAYOUT_ATTRS[+isHorizontal],
  59921. categoryDim: LAYOUT_ATTRS[1 - +isHorizontal]
  59922. };
  59923. data.diff(oldData).add(function (dataIndex) {
  59924. if (!data.hasValue(dataIndex)) {
  59925. return;
  59926. }
  59927. var itemModel = getItemModel(data, dataIndex);
  59928. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  59929. var bar = createBar(data, opt, symbolMeta);
  59930. data.setItemGraphicEl(dataIndex, bar);
  59931. group.add(bar);
  59932. updateCommon$1(bar, opt, symbolMeta);
  59933. }).update(function (newIndex, oldIndex) {
  59934. var bar = oldData.getItemGraphicEl(oldIndex);
  59935. if (!data.hasValue(newIndex)) {
  59936. group.remove(bar);
  59937. return;
  59938. }
  59939. var itemModel = getItemModel(data, newIndex);
  59940. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  59941. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  59942. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  59943. group.remove(bar);
  59944. data.setItemGraphicEl(newIndex, null);
  59945. bar = null;
  59946. }
  59947. if (bar) {
  59948. updateBar(bar, opt, symbolMeta);
  59949. } else {
  59950. bar = createBar(data, opt, symbolMeta, true);
  59951. }
  59952. data.setItemGraphicEl(newIndex, bar);
  59953. bar.__pictorialSymbolMeta = symbolMeta; // Add back
  59954. group.add(bar);
  59955. updateCommon$1(bar, opt, symbolMeta);
  59956. }).remove(function (dataIndex) {
  59957. var bar = oldData.getItemGraphicEl(dataIndex);
  59958. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  59959. }).execute();
  59960. this._data = data;
  59961. return this.group;
  59962. };
  59963. PictorialBarView.prototype.remove = function (ecModel, api) {
  59964. var group = this.group;
  59965. var data = this._data;
  59966. if (ecModel.get('animation')) {
  59967. if (data) {
  59968. data.eachItemGraphicEl(function (bar) {
  59969. removeBar(data, getECData(bar).dataIndex, ecModel, bar);
  59970. });
  59971. }
  59972. } else {
  59973. group.removeAll();
  59974. }
  59975. };
  59976. PictorialBarView.type = 'pictorialBar';
  59977. return PictorialBarView;
  59978. }(ChartView); // Set or calculate default value about symbol, and calculate layout info.
  59979. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  59980. var layout = data.getItemLayout(dataIndex);
  59981. var symbolRepeat = itemModel.get('symbolRepeat');
  59982. var symbolClip = itemModel.get('symbolClip');
  59983. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  59984. var symbolRotate = itemModel.get('symbolRotate');
  59985. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  59986. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  59987. var isAnimationEnabled = itemModel.isAnimationEnabled();
  59988. var symbolMeta = {
  59989. dataIndex: dataIndex,
  59990. layout: layout,
  59991. itemModel: itemModel,
  59992. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  59993. style: data.getItemVisual(dataIndex, 'style'),
  59994. symbolClip: symbolClip,
  59995. symbolRepeat: symbolRepeat,
  59996. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  59997. symbolPatternSize: symbolPatternSize,
  59998. rotation: rotation,
  59999. animationModel: isAnimationEnabled ? itemModel : null,
  60000. hoverScale: isAnimationEnabled && itemModel.get(['emphasis', 'scale']),
  60001. z2: itemModel.getShallow('z', true) || 0
  60002. };
  60003. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  60004. prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength, symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta);
  60005. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  60006. var symbolSize = symbolMeta.symbolSize;
  60007. var symbolOffset = normalizeSymbolOffset(itemModel.get('symbolOffset'), symbolSize);
  60008. prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength, opt, symbolMeta);
  60009. return symbolMeta;
  60010. } // bar length can be negative.
  60011. function prepareBarLength(itemModel, symbolRepeat, layout, opt, outputSymbolMeta) {
  60012. var valueDim = opt.valueDim;
  60013. var symbolBoundingData = itemModel.get('symbolBoundingData');
  60014. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  60015. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  60016. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  60017. var boundingLength;
  60018. if (isArray(symbolBoundingData)) {
  60019. var symbolBoundingExtent = [convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx, convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx];
  60020. symbolBoundingExtent[1] < symbolBoundingExtent[0] && symbolBoundingExtent.reverse();
  60021. boundingLength = symbolBoundingExtent[pxSignIdx];
  60022. } else if (symbolBoundingData != null) {
  60023. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  60024. } else if (symbolRepeat) {
  60025. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  60026. } else {
  60027. boundingLength = layout[valueDim.wh];
  60028. }
  60029. outputSymbolMeta.boundingLength = boundingLength;
  60030. if (symbolRepeat) {
  60031. outputSymbolMeta.repeatCutLength = layout[valueDim.wh];
  60032. }
  60033. outputSymbolMeta.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  60034. }
  60035. function convertToCoordOnAxis(axis, value) {
  60036. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  60037. } // Support ['100%', '100%']
  60038. function prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength, pxSign, symbolPatternSize, opt, outputSymbolMeta) {
  60039. var valueDim = opt.valueDim;
  60040. var categoryDim = opt.categoryDim;
  60041. var categorySize = Math.abs(layout[categoryDim.wh]);
  60042. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  60043. var parsedSymbolSize;
  60044. if (isArray(symbolSize)) {
  60045. parsedSymbolSize = symbolSize.slice();
  60046. } else {
  60047. if (symbolSize == null) {
  60048. // will parse to number below
  60049. parsedSymbolSize = ['100%', '100%'];
  60050. } else {
  60051. parsedSymbolSize = [symbolSize, symbolSize];
  60052. }
  60053. } // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  60054. // to complicated to calculate real percent value if considering scaled lineWidth.
  60055. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  60056. // which can be tolerated in pictorial chart.
  60057. parsedSymbolSize[categoryDim.index] = parsePercent$1(parsedSymbolSize[categoryDim.index], categorySize);
  60058. parsedSymbolSize[valueDim.index] = parsePercent$1(parsedSymbolSize[valueDim.index], symbolRepeat ? categorySize : Math.abs(boundingLength));
  60059. outputSymbolMeta.symbolSize = parsedSymbolSize; // If x or y is less than zero, show reversed shape.
  60060. var symbolScale = outputSymbolMeta.symbolScale = [parsedSymbolSize[0] / symbolPatternSize, parsedSymbolSize[1] / symbolPatternSize]; // Follow convention, 'right' and 'top' is the normal scale.
  60061. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  60062. }
  60063. function prepareLineWidth(itemModel, symbolScale, rotation, opt, outputSymbolMeta) {
  60064. // In symbols are drawn with scale, so do not need to care about the case that width
  60065. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  60066. // be calculated.
  60067. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  60068. if (valueLineWidth) {
  60069. pathForLineWidth.attr({
  60070. scaleX: symbolScale[0],
  60071. scaleY: symbolScale[1],
  60072. rotation: rotation
  60073. });
  60074. pathForLineWidth.updateTransform();
  60075. valueLineWidth /= pathForLineWidth.getLineScale();
  60076. valueLineWidth *= symbolScale[opt.valueDim.index];
  60077. }
  60078. outputSymbolMeta.valueLineWidth = valueLineWidth;
  60079. }
  60080. function prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, outputSymbolMeta) {
  60081. var categoryDim = opt.categoryDim;
  60082. var valueDim = opt.valueDim;
  60083. var pxSign = outputSymbolMeta.pxSign;
  60084. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  60085. var pathLen = unitLength; // Note: rotation will not effect the layout of symbols, because user may
  60086. // want symbols to rotate on its center, which should not be translated
  60087. // when rotating.
  60088. if (symbolRepeat) {
  60089. var absBoundingLength = Math.abs(boundingLength);
  60090. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  60091. var hasEndGap = false;
  60092. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  60093. hasEndGap = true;
  60094. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  60095. }
  60096. var symbolMarginNumeric = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  60097. var uLenWithMargin = Math.max(unitLength + symbolMarginNumeric * 2, 0); // When symbol margin is less than 0, margin at both ends will be subtracted
  60098. // to ensure that all of the symbols will not be overflow the given area.
  60099. var endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Both final repeatTimes and final symbolMarginNumeric area calculated based on
  60100. // boundingLength.
  60101. var repeatSpecified = isNumeric(symbolRepeat);
  60102. var repeatTimes = repeatSpecified ? symbolRepeat : toIntTimes((absBoundingLength + endFix) / uLenWithMargin); // Adjust calculate margin, to ensure each symbol is displayed
  60103. // entirely in the given layout area.
  60104. var mDiff = absBoundingLength - repeatTimes * unitLength;
  60105. symbolMarginNumeric = mDiff / 2 / (hasEndGap ? repeatTimes : Math.max(repeatTimes - 1, 1));
  60106. uLenWithMargin = unitLength + symbolMarginNumeric * 2;
  60107. endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Update repeatTimes when not all symbol will be shown.
  60108. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  60109. repeatTimes = repeatCutLength ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin) : 0;
  60110. }
  60111. pathLen = repeatTimes * uLenWithMargin - endFix;
  60112. outputSymbolMeta.repeatTimes = repeatTimes;
  60113. outputSymbolMeta.symbolMargin = symbolMarginNumeric;
  60114. }
  60115. var sizeFix = pxSign * (pathLen / 2);
  60116. var pathPosition = outputSymbolMeta.pathPosition = [];
  60117. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  60118. pathPosition[valueDim.index] = symbolPosition === 'start' ? sizeFix : symbolPosition === 'end' ? boundingLength - sizeFix : boundingLength / 2; // 'center'
  60119. if (symbolOffset) {
  60120. pathPosition[0] += symbolOffset[0];
  60121. pathPosition[1] += symbolOffset[1];
  60122. }
  60123. var bundlePosition = outputSymbolMeta.bundlePosition = [];
  60124. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  60125. bundlePosition[valueDim.index] = layout[valueDim.xy];
  60126. var barRectShape = outputSymbolMeta.barRectShape = extend({}, layout);
  60127. barRectShape[valueDim.wh] = pxSign * Math.max(Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix));
  60128. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  60129. var clipShape = outputSymbolMeta.clipShape = {}; // Consider that symbol may be overflow layout rect.
  60130. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  60131. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  60132. clipShape[valueDim.xy] = 0;
  60133. clipShape[valueDim.wh] = layout[valueDim.wh];
  60134. }
  60135. function createPath(symbolMeta) {
  60136. var symbolPatternSize = symbolMeta.symbolPatternSize;
  60137. var path = createSymbol( // Consider texture img, make a big size.
  60138. symbolMeta.symbolType, -symbolPatternSize / 2, -symbolPatternSize / 2, symbolPatternSize, symbolPatternSize);
  60139. path.attr({
  60140. culling: true
  60141. });
  60142. path.type !== 'image' && path.setStyle({
  60143. strokeNoScale: true
  60144. });
  60145. return path;
  60146. }
  60147. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  60148. var bundle = bar.__pictorialBundle;
  60149. var symbolSize = symbolMeta.symbolSize;
  60150. var valueLineWidth = symbolMeta.valueLineWidth;
  60151. var pathPosition = symbolMeta.pathPosition;
  60152. var valueDim = opt.valueDim;
  60153. var repeatTimes = symbolMeta.repeatTimes || 0;
  60154. var index = 0;
  60155. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  60156. eachPath(bar, function (path) {
  60157. path.__pictorialAnimationIndex = index;
  60158. path.__pictorialRepeatTimes = repeatTimes;
  60159. if (index < repeatTimes) {
  60160. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  60161. } else {
  60162. updateAttr(path, null, {
  60163. scaleX: 0,
  60164. scaleY: 0
  60165. }, symbolMeta, isUpdate, function () {
  60166. bundle.remove(path);
  60167. });
  60168. } // updateHoverAnimation(path, symbolMeta);
  60169. index++;
  60170. });
  60171. for (; index < repeatTimes; index++) {
  60172. var path = createPath(symbolMeta);
  60173. path.__pictorialAnimationIndex = index;
  60174. path.__pictorialRepeatTimes = repeatTimes;
  60175. bundle.add(path);
  60176. var target = makeTarget(index);
  60177. updateAttr(path, {
  60178. x: target.x,
  60179. y: target.y,
  60180. scaleX: 0,
  60181. scaleY: 0
  60182. }, {
  60183. scaleX: target.scaleX,
  60184. scaleY: target.scaleY,
  60185. rotation: target.rotation
  60186. }, symbolMeta, isUpdate);
  60187. }
  60188. function makeTarget(index) {
  60189. var position = pathPosition.slice(); // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  60190. // Otherwise: i = index;
  60191. var pxSign = symbolMeta.pxSign;
  60192. var i = index;
  60193. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  60194. i = repeatTimes - 1 - index;
  60195. }
  60196. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  60197. return {
  60198. x: position[0],
  60199. y: position[1],
  60200. scaleX: symbolMeta.symbolScale[0],
  60201. scaleY: symbolMeta.symbolScale[1],
  60202. rotation: symbolMeta.rotation
  60203. };
  60204. }
  60205. }
  60206. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  60207. var bundle = bar.__pictorialBundle;
  60208. var mainPath = bar.__pictorialMainPath;
  60209. if (!mainPath) {
  60210. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  60211. bundle.add(mainPath);
  60212. updateAttr(mainPath, {
  60213. x: symbolMeta.pathPosition[0],
  60214. y: symbolMeta.pathPosition[1],
  60215. scaleX: 0,
  60216. scaleY: 0,
  60217. rotation: symbolMeta.rotation
  60218. }, {
  60219. scaleX: symbolMeta.symbolScale[0],
  60220. scaleY: symbolMeta.symbolScale[1]
  60221. }, symbolMeta, isUpdate);
  60222. } else {
  60223. updateAttr(mainPath, null, {
  60224. x: symbolMeta.pathPosition[0],
  60225. y: symbolMeta.pathPosition[1],
  60226. scaleX: symbolMeta.symbolScale[0],
  60227. scaleY: symbolMeta.symbolScale[1],
  60228. rotation: symbolMeta.rotation
  60229. }, symbolMeta, isUpdate);
  60230. }
  60231. } // bar rect is used for label.
  60232. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  60233. var rectShape = extend({}, symbolMeta.barRectShape);
  60234. var barRect = bar.__pictorialBarRect;
  60235. if (!barRect) {
  60236. barRect = bar.__pictorialBarRect = new Rect({
  60237. z2: 2,
  60238. shape: rectShape,
  60239. silent: true,
  60240. style: {
  60241. stroke: 'transparent',
  60242. fill: 'transparent',
  60243. lineWidth: 0
  60244. }
  60245. });
  60246. barRect.disableMorphing = true;
  60247. bar.add(barRect);
  60248. } else {
  60249. updateAttr(barRect, null, {
  60250. shape: rectShape
  60251. }, symbolMeta, isUpdate);
  60252. }
  60253. }
  60254. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  60255. // If not clip, symbol will be remove and rebuilt.
  60256. if (symbolMeta.symbolClip) {
  60257. var clipPath = bar.__pictorialClipPath;
  60258. var clipShape = extend({}, symbolMeta.clipShape);
  60259. var valueDim = opt.valueDim;
  60260. var animationModel = symbolMeta.animationModel;
  60261. var dataIndex = symbolMeta.dataIndex;
  60262. if (clipPath) {
  60263. updateProps(clipPath, {
  60264. shape: clipShape
  60265. }, animationModel, dataIndex);
  60266. } else {
  60267. clipShape[valueDim.wh] = 0;
  60268. clipPath = new Rect({
  60269. shape: clipShape
  60270. });
  60271. bar.__pictorialBundle.setClipPath(clipPath);
  60272. bar.__pictorialClipPath = clipPath;
  60273. var target = {};
  60274. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  60275. graphic[isUpdate ? 'updateProps' : 'initProps'](clipPath, {
  60276. shape: target
  60277. }, animationModel, dataIndex);
  60278. }
  60279. }
  60280. }
  60281. function getItemModel(data, dataIndex) {
  60282. var itemModel = data.getItemModel(dataIndex);
  60283. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  60284. itemModel.isAnimationEnabled = isAnimationEnabled;
  60285. return itemModel;
  60286. }
  60287. function getAnimationDelayParams(path) {
  60288. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  60289. return {
  60290. index: path.__pictorialAnimationIndex,
  60291. count: path.__pictorialRepeatTimes
  60292. };
  60293. }
  60294. function isAnimationEnabled() {
  60295. // `animation` prop can be set on itemModel in pictorial bar chart.
  60296. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  60297. }
  60298. function createBar(data, opt, symbolMeta, isUpdate) {
  60299. // bar is the main element for each data.
  60300. var bar = new Group(); // bundle is used for location and clip.
  60301. var bundle = new Group();
  60302. bar.add(bundle);
  60303. bar.__pictorialBundle = bundle;
  60304. bundle.x = symbolMeta.bundlePosition[0];
  60305. bundle.y = symbolMeta.bundlePosition[1];
  60306. if (symbolMeta.symbolRepeat) {
  60307. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  60308. } else {
  60309. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  60310. }
  60311. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  60312. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  60313. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  60314. bar.__pictorialSymbolMeta = symbolMeta;
  60315. return bar;
  60316. }
  60317. function updateBar(bar, opt, symbolMeta) {
  60318. var animationModel = symbolMeta.animationModel;
  60319. var dataIndex = symbolMeta.dataIndex;
  60320. var bundle = bar.__pictorialBundle;
  60321. updateProps(bundle, {
  60322. x: symbolMeta.bundlePosition[0],
  60323. y: symbolMeta.bundlePosition[1]
  60324. }, animationModel, dataIndex);
  60325. if (symbolMeta.symbolRepeat) {
  60326. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  60327. } else {
  60328. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  60329. }
  60330. createOrUpdateBarRect(bar, symbolMeta, true);
  60331. createOrUpdateClip(bar, opt, symbolMeta, true);
  60332. }
  60333. function removeBar(data, dataIndex, animationModel, bar) {
  60334. // Not show text when animating
  60335. var labelRect = bar.__pictorialBarRect;
  60336. labelRect && labelRect.removeTextContent();
  60337. var pathes = [];
  60338. eachPath(bar, function (path) {
  60339. pathes.push(path);
  60340. });
  60341. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath); // I do not find proper remove animation for clip yet.
  60342. bar.__pictorialClipPath && (animationModel = null);
  60343. each(pathes, function (path) {
  60344. removeElement(path, {
  60345. scaleX: 0,
  60346. scaleY: 0
  60347. }, animationModel, dataIndex, function () {
  60348. bar.parent && bar.parent.remove(bar);
  60349. });
  60350. });
  60351. data.setItemGraphicEl(dataIndex, null);
  60352. }
  60353. function getShapeStr(data, symbolMeta) {
  60354. return [data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none', !!symbolMeta.symbolRepeat, !!symbolMeta.symbolClip].join(':');
  60355. }
  60356. function eachPath(bar, cb, context) {
  60357. // Do not use Group#eachChild, because it do not support remove.
  60358. each(bar.__pictorialBundle.children(), function (el) {
  60359. el !== bar.__pictorialBarRect && cb.call(context, el);
  60360. });
  60361. }
  60362. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  60363. immediateAttrs && el.attr(immediateAttrs); // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  60364. if (symbolMeta.symbolClip && !isUpdate) {
  60365. animationAttrs && el.attr(animationAttrs);
  60366. } else {
  60367. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb);
  60368. }
  60369. }
  60370. function updateCommon$1(bar, opt, symbolMeta) {
  60371. var dataIndex = symbolMeta.dataIndex;
  60372. var itemModel = symbolMeta.itemModel; // Color must be excluded.
  60373. // Because symbol provide setColor individually to set fill and stroke
  60374. var emphasisModel = itemModel.getModel('emphasis');
  60375. var emphasisStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  60376. var blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  60377. var selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  60378. var cursorStyle = itemModel.getShallow('cursor');
  60379. var focus = emphasisModel.get('focus');
  60380. var blurScope = emphasisModel.get('blurScope');
  60381. var hoverScale = emphasisModel.get('scale');
  60382. eachPath(bar, function (path) {
  60383. if (path instanceof ZRImage) {
  60384. var pathStyle = path.style;
  60385. path.useStyle(extend({
  60386. // TODO other properties like dx, dy ?
  60387. image: pathStyle.image,
  60388. x: pathStyle.x,
  60389. y: pathStyle.y,
  60390. width: pathStyle.width,
  60391. height: pathStyle.height
  60392. }, symbolMeta.style));
  60393. } else {
  60394. path.useStyle(symbolMeta.style);
  60395. }
  60396. var emphasisState = path.ensureState('emphasis');
  60397. emphasisState.style = emphasisStyle;
  60398. if (hoverScale) {
  60399. // NOTE: Must after scale is set after updateAttr
  60400. emphasisState.scaleX = path.scaleX * 1.1;
  60401. emphasisState.scaleY = path.scaleY * 1.1;
  60402. }
  60403. path.ensureState('blur').style = blurStyle;
  60404. path.ensureState('select').style = selectStyle;
  60405. cursorStyle && (path.cursor = cursorStyle);
  60406. path.z2 = symbolMeta.z2;
  60407. });
  60408. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  60409. var barRect = bar.__pictorialBarRect;
  60410. setLabelStyle(barRect, getLabelStatesModels(itemModel), {
  60411. labelFetcher: opt.seriesModel,
  60412. labelDataIndex: dataIndex,
  60413. defaultText: getDefaultLabel(opt.seriesModel.getData(), dataIndex),
  60414. inheritColor: symbolMeta.style.fill,
  60415. defaultOpacity: symbolMeta.style.opacity,
  60416. defaultOutsidePosition: barPositionOutside
  60417. });
  60418. enableHoverEmphasis(bar, focus, blurScope);
  60419. }
  60420. function toIntTimes(times) {
  60421. var roundedTimes = Math.round(times); // Escapse accurate error
  60422. return Math.abs(times - roundedTimes) < 1e-4 ? roundedTimes : Math.ceil(times);
  60423. }
  60424. var PictorialBarSeriesModel =
  60425. /** @class */
  60426. function (_super) {
  60427. __extends(PictorialBarSeriesModel, _super);
  60428. function PictorialBarSeriesModel() {
  60429. var _this = _super !== null && _super.apply(this, arguments) || this;
  60430. _this.type = PictorialBarSeriesModel.type;
  60431. _this.hasSymbolVisual = true;
  60432. _this.defaultSymbol = 'roundRect';
  60433. return _this;
  60434. }
  60435. PictorialBarSeriesModel.prototype.getInitialData = function (option) {
  60436. // Disable stack.
  60437. option.stack = null;
  60438. return _super.prototype.getInitialData.apply(this, arguments);
  60439. };
  60440. PictorialBarSeriesModel.type = 'series.pictorialBar';
  60441. PictorialBarSeriesModel.dependencies = ['grid'];
  60442. PictorialBarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  60443. symbol: 'circle',
  60444. symbolSize: null,
  60445. symbolRotate: null,
  60446. symbolPosition: null,
  60447. symbolOffset: null,
  60448. symbolMargin: null,
  60449. symbolRepeat: false,
  60450. symbolRepeatDirection: 'end',
  60451. symbolClip: false,
  60452. symbolBoundingData: null,
  60453. symbolPatternSize: 400,
  60454. barGap: '-100%',
  60455. // z can be set in data item, which is z2 actually.
  60456. // Disable progressive
  60457. progressive: 0,
  60458. emphasis: {
  60459. // By default pictorialBar do not hover scale. Hover scale is not suitable
  60460. // for the case that both has foreground and background.
  60461. scale: false
  60462. },
  60463. select: {
  60464. itemStyle: {
  60465. borderColor: '#212121'
  60466. }
  60467. }
  60468. });
  60469. return PictorialBarSeriesModel;
  60470. }(BaseBarSeriesModel);
  60471. function install$o(registers) {
  60472. registers.registerChartView(PictorialBarView);
  60473. registers.registerSeriesModel(PictorialBarSeriesModel);
  60474. registers.registerLayout(curry(layout, 'pictorialBar'));
  60475. }
  60476. var ThemeRiverView =
  60477. /** @class */
  60478. function (_super) {
  60479. __extends(ThemeRiverView, _super);
  60480. function ThemeRiverView() {
  60481. var _this = _super !== null && _super.apply(this, arguments) || this;
  60482. _this.type = ThemeRiverView.type;
  60483. _this._layers = [];
  60484. return _this;
  60485. }
  60486. ThemeRiverView.prototype.render = function (seriesModel, ecModel, api) {
  60487. var data = seriesModel.getData();
  60488. var self = this;
  60489. var group = this.group;
  60490. var layersSeries = seriesModel.getLayerSeries();
  60491. var layoutInfo = data.getLayout('layoutInfo');
  60492. var rect = layoutInfo.rect;
  60493. var boundaryGap = layoutInfo.boundaryGap;
  60494. group.x = 0;
  60495. group.y = rect.y + boundaryGap[0];
  60496. function keyGetter(item) {
  60497. return item.name;
  60498. }
  60499. var dataDiffer = new DataDiffer(this._layersSeries || [], layersSeries, keyGetter, keyGetter);
  60500. var newLayersGroups = [];
  60501. dataDiffer.add(bind(process, this, 'add')).update(bind(process, this, 'update')).remove(bind(process, this, 'remove')).execute();
  60502. function process(status, idx, oldIdx) {
  60503. var oldLayersGroups = self._layers;
  60504. if (status === 'remove') {
  60505. group.remove(oldLayersGroups[idx]);
  60506. return;
  60507. }
  60508. var points0 = [];
  60509. var points1 = [];
  60510. var style;
  60511. var indices = layersSeries[idx].indices;
  60512. var j = 0;
  60513. for (; j < indices.length; j++) {
  60514. var layout = data.getItemLayout(indices[j]);
  60515. var x = layout.x;
  60516. var y0 = layout.y0;
  60517. var y = layout.y;
  60518. points0.push(x, y0);
  60519. points1.push(x, y0 + y);
  60520. style = data.getItemVisual(indices[j], 'style');
  60521. }
  60522. var polygon;
  60523. var textLayout = data.getItemLayout(indices[0]);
  60524. var labelModel = seriesModel.getModel('label');
  60525. var margin = labelModel.get('margin');
  60526. var emphasisModel = seriesModel.getModel('emphasis');
  60527. if (status === 'add') {
  60528. var layerGroup = newLayersGroups[idx] = new Group();
  60529. polygon = new ECPolygon({
  60530. shape: {
  60531. points: points0,
  60532. stackedOnPoints: points1,
  60533. smooth: 0.4,
  60534. stackedOnSmooth: 0.4,
  60535. smoothConstraint: false
  60536. },
  60537. z2: 0
  60538. });
  60539. layerGroup.add(polygon);
  60540. group.add(layerGroup);
  60541. if (seriesModel.isAnimationEnabled()) {
  60542. polygon.setClipPath(createGridClipShape$2(polygon.getBoundingRect(), seriesModel, function () {
  60543. polygon.removeClipPath();
  60544. }));
  60545. }
  60546. } else {
  60547. var layerGroup = oldLayersGroups[oldIdx];
  60548. polygon = layerGroup.childAt(0);
  60549. group.add(layerGroup);
  60550. newLayersGroups[idx] = layerGroup;
  60551. updateProps(polygon, {
  60552. shape: {
  60553. points: points0,
  60554. stackedOnPoints: points1
  60555. }
  60556. }, seriesModel);
  60557. saveOldStyle(polygon);
  60558. }
  60559. setLabelStyle(polygon, getLabelStatesModels(seriesModel), {
  60560. labelDataIndex: indices[j - 1],
  60561. defaultText: data.getName(indices[j - 1]),
  60562. inheritColor: style.fill
  60563. }, {
  60564. normal: {
  60565. verticalAlign: 'middle' // align: 'right'
  60566. }
  60567. });
  60568. polygon.setTextConfig({
  60569. position: null,
  60570. local: true
  60571. });
  60572. var labelEl = polygon.getTextContent(); // TODO More label position options.
  60573. if (labelEl) {
  60574. labelEl.x = textLayout.x - margin;
  60575. labelEl.y = textLayout.y0 + textLayout.y / 2;
  60576. }
  60577. polygon.useStyle(style);
  60578. data.setItemGraphicEl(idx, polygon);
  60579. setStatesStylesFromModel(polygon, seriesModel);
  60580. enableHoverEmphasis(polygon, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  60581. }
  60582. this._layersSeries = layersSeries;
  60583. this._layers = newLayersGroups;
  60584. };
  60585. ThemeRiverView.type = 'themeRiver';
  60586. return ThemeRiverView;
  60587. }(ChartView);
  60588. function createGridClipShape$2(rect, seriesModel, cb) {
  60589. var rectEl = new Rect({
  60590. shape: {
  60591. x: rect.x - 10,
  60592. y: rect.y - 10,
  60593. width: 0,
  60594. height: rect.height + 20
  60595. }
  60596. });
  60597. initProps(rectEl, {
  60598. shape: {
  60599. x: rect.x - 50,
  60600. width: rect.width + 100,
  60601. height: rect.height + 20
  60602. }
  60603. }, seriesModel, cb);
  60604. return rectEl;
  60605. }
  60606. var DATA_NAME_INDEX = 2;
  60607. var ThemeRiverSeriesModel =
  60608. /** @class */
  60609. function (_super) {
  60610. __extends(ThemeRiverSeriesModel, _super);
  60611. function ThemeRiverSeriesModel() {
  60612. var _this = _super !== null && _super.apply(this, arguments) || this;
  60613. _this.type = ThemeRiverSeriesModel.type;
  60614. return _this;
  60615. }
  60616. /**
  60617. * @override
  60618. */
  60619. ThemeRiverSeriesModel.prototype.init = function (option) {
  60620. // eslint-disable-next-line
  60621. _super.prototype.init.apply(this, arguments); // Put this function here is for the sake of consistency of code style.
  60622. // Enable legend selection for each data item
  60623. // Use a function instead of direct access because data reference may changed
  60624. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  60625. };
  60626. /**
  60627. * If there is no value of a certain point in the time for some event,set it value to 0.
  60628. *
  60629. * @param {Array} data initial data in the option
  60630. * @return {Array}
  60631. */
  60632. ThemeRiverSeriesModel.prototype.fixData = function (data) {
  60633. var rawDataLength = data.length;
  60634. /**
  60635. * Make sure every layer data get the same keys.
  60636. * The value index tells which layer has visited.
  60637. * {
  60638. * 2014/01/01: -1
  60639. * }
  60640. */
  60641. var timeValueKeys = {}; // grouped data by name
  60642. var groupResult = groupData(data, function (item) {
  60643. if (!timeValueKeys.hasOwnProperty(item[0] + '')) {
  60644. timeValueKeys[item[0] + ''] = -1;
  60645. }
  60646. return item[2];
  60647. });
  60648. var layerData = [];
  60649. groupResult.buckets.each(function (items, key) {
  60650. layerData.push({
  60651. name: key,
  60652. dataList: items
  60653. });
  60654. });
  60655. var layerNum = layerData.length;
  60656. for (var k = 0; k < layerNum; ++k) {
  60657. var name_1 = layerData[k].name;
  60658. for (var j = 0; j < layerData[k].dataList.length; ++j) {
  60659. var timeValue = layerData[k].dataList[j][0] + '';
  60660. timeValueKeys[timeValue] = k;
  60661. }
  60662. for (var timeValue in timeValueKeys) {
  60663. if (timeValueKeys.hasOwnProperty(timeValue) && timeValueKeys[timeValue] !== k) {
  60664. timeValueKeys[timeValue] = k;
  60665. data[rawDataLength] = [timeValue, 0, name_1];
  60666. rawDataLength++;
  60667. }
  60668. }
  60669. }
  60670. return data;
  60671. };
  60672. /**
  60673. * @override
  60674. * @param option the initial option that user gived
  60675. * @param ecModel the model object for themeRiver option
  60676. */
  60677. ThemeRiverSeriesModel.prototype.getInitialData = function (option, ecModel) {
  60678. var singleAxisModel = this.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  60679. var axisType = singleAxisModel.get('type'); // filter the data item with the value of label is undefined
  60680. var filterData = filter(option.data, function (dataItem) {
  60681. return dataItem[2] !== undefined;
  60682. }); // ??? TODO design a stage to transfer data for themeRiver and lines?
  60683. var data = this.fixData(filterData || []);
  60684. var nameList = [];
  60685. var nameMap = this.nameMap = createHashMap();
  60686. var count = 0;
  60687. for (var i = 0; i < data.length; ++i) {
  60688. nameList.push(data[i][DATA_NAME_INDEX]);
  60689. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  60690. nameMap.set(data[i][DATA_NAME_INDEX], count);
  60691. count++;
  60692. }
  60693. }
  60694. var dimensions = prepareSeriesDataSchema(data, {
  60695. coordDimensions: ['single'],
  60696. dimensionsDefine: [{
  60697. name: 'time',
  60698. type: getDimensionTypeByAxis(axisType)
  60699. }, {
  60700. name: 'value',
  60701. type: 'float'
  60702. }, {
  60703. name: 'name',
  60704. type: 'ordinal'
  60705. }],
  60706. encodeDefine: {
  60707. single: 0,
  60708. value: 1,
  60709. itemName: 2
  60710. }
  60711. }).dimensions;
  60712. var list = new SeriesData(dimensions, this);
  60713. list.initData(data);
  60714. return list;
  60715. };
  60716. /**
  60717. * The raw data is divided into multiple layers and each layer
  60718. * has same name.
  60719. */
  60720. ThemeRiverSeriesModel.prototype.getLayerSeries = function () {
  60721. var data = this.getData();
  60722. var lenCount = data.count();
  60723. var indexArr = [];
  60724. for (var i = 0; i < lenCount; ++i) {
  60725. indexArr[i] = i;
  60726. }
  60727. var timeDim = data.mapDimension('single'); // data group by name
  60728. var groupResult = groupData(indexArr, function (index) {
  60729. return data.get('name', index);
  60730. });
  60731. var layerSeries = [];
  60732. groupResult.buckets.each(function (items, key) {
  60733. items.sort(function (index1, index2) {
  60734. return data.get(timeDim, index1) - data.get(timeDim, index2);
  60735. });
  60736. layerSeries.push({
  60737. name: key,
  60738. indices: items
  60739. });
  60740. });
  60741. return layerSeries;
  60742. };
  60743. /**
  60744. * Get data indices for show tooltip content
  60745. */
  60746. ThemeRiverSeriesModel.prototype.getAxisTooltipData = function (dim, value, baseAxis) {
  60747. if (!isArray(dim)) {
  60748. dim = dim ? [dim] : [];
  60749. }
  60750. var data = this.getData();
  60751. var layerSeries = this.getLayerSeries();
  60752. var indices = [];
  60753. var layerNum = layerSeries.length;
  60754. var nestestValue;
  60755. for (var i = 0; i < layerNum; ++i) {
  60756. var minDist = Number.MAX_VALUE;
  60757. var nearestIdx = -1;
  60758. var pointNum = layerSeries[i].indices.length;
  60759. for (var j = 0; j < pointNum; ++j) {
  60760. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  60761. var dist = Math.abs(theValue - value);
  60762. if (dist <= minDist) {
  60763. nestestValue = theValue;
  60764. minDist = dist;
  60765. nearestIdx = layerSeries[i].indices[j];
  60766. }
  60767. }
  60768. indices.push(nearestIdx);
  60769. }
  60770. return {
  60771. dataIndices: indices,
  60772. nestestValue: nestestValue
  60773. };
  60774. };
  60775. ThemeRiverSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  60776. var data = this.getData();
  60777. var name = data.getName(dataIndex);
  60778. var value = data.get(data.mapDimension('value'), dataIndex);
  60779. return createTooltipMarkup('nameValue', {
  60780. name: name,
  60781. value: value
  60782. });
  60783. };
  60784. ThemeRiverSeriesModel.type = 'series.themeRiver';
  60785. ThemeRiverSeriesModel.dependencies = ['singleAxis'];
  60786. ThemeRiverSeriesModel.defaultOption = {
  60787. zlevel: 0,
  60788. z: 2,
  60789. colorBy: 'data',
  60790. coordinateSystem: 'singleAxis',
  60791. // gap in axis's orthogonal orientation
  60792. boundaryGap: ['10%', '10%'],
  60793. // legendHoverLink: true,
  60794. singleAxisIndex: 0,
  60795. animationEasing: 'linear',
  60796. label: {
  60797. margin: 4,
  60798. show: true,
  60799. position: 'left',
  60800. fontSize: 11
  60801. },
  60802. emphasis: {
  60803. label: {
  60804. show: true
  60805. }
  60806. }
  60807. };
  60808. return ThemeRiverSeriesModel;
  60809. }(SeriesModel);
  60810. function themeRiverLayout(ecModel, api) {
  60811. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  60812. var data = seriesModel.getData();
  60813. var single = seriesModel.coordinateSystem;
  60814. var layoutInfo = {}; // use the axis boundingRect for view
  60815. var rect = single.getRect();
  60816. layoutInfo.rect = rect;
  60817. var boundaryGap = seriesModel.get('boundaryGap');
  60818. var axis = single.getAxis();
  60819. layoutInfo.boundaryGap = boundaryGap;
  60820. if (axis.orient === 'horizontal') {
  60821. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  60822. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  60823. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  60824. doThemeRiverLayout(data, seriesModel, height);
  60825. } else {
  60826. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  60827. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  60828. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  60829. doThemeRiverLayout(data, seriesModel, width);
  60830. }
  60831. data.setLayout('layoutInfo', layoutInfo);
  60832. });
  60833. }
  60834. /**
  60835. * The layout information about themeriver
  60836. *
  60837. * @param data data in the series
  60838. * @param seriesModel the model object of themeRiver series
  60839. * @param height value used to compute every series height
  60840. */
  60841. function doThemeRiverLayout(data, seriesModel, height) {
  60842. if (!data.count()) {
  60843. return;
  60844. }
  60845. var coordSys = seriesModel.coordinateSystem; // the data in each layer are organized into a series.
  60846. var layerSeries = seriesModel.getLayerSeries(); // the points in each layer.
  60847. var timeDim = data.mapDimension('single');
  60848. var valueDim = data.mapDimension('value');
  60849. var layerPoints = map(layerSeries, function (singleLayer) {
  60850. return map(singleLayer.indices, function (idx) {
  60851. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  60852. pt[1] = data.get(valueDim, idx);
  60853. return pt;
  60854. });
  60855. });
  60856. var base = computeBaseline(layerPoints);
  60857. var baseLine = base.y0;
  60858. var ky = height / base.max; // set layout information for each item.
  60859. var n = layerSeries.length;
  60860. var m = layerSeries[0].indices.length;
  60861. var baseY0;
  60862. for (var j = 0; j < m; ++j) {
  60863. baseY0 = baseLine[j] * ky;
  60864. data.setItemLayout(layerSeries[0].indices[j], {
  60865. layerIndex: 0,
  60866. x: layerPoints[0][j][0],
  60867. y0: baseY0,
  60868. y: layerPoints[0][j][1] * ky
  60869. });
  60870. for (var i = 1; i < n; ++i) {
  60871. baseY0 += layerPoints[i - 1][j][1] * ky;
  60872. data.setItemLayout(layerSeries[i].indices[j], {
  60873. layerIndex: i,
  60874. x: layerPoints[i][j][0],
  60875. y0: baseY0,
  60876. y: layerPoints[i][j][1] * ky
  60877. });
  60878. }
  60879. }
  60880. }
  60881. /**
  60882. * Compute the baseLine of the rawdata
  60883. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  60884. *
  60885. * @param data the points in each layer
  60886. */
  60887. function computeBaseline(data) {
  60888. var layerNum = data.length;
  60889. var pointNum = data[0].length;
  60890. var sums = [];
  60891. var y0 = [];
  60892. var max = 0;
  60893. for (var i = 0; i < pointNum; ++i) {
  60894. var temp = 0;
  60895. for (var j = 0; j < layerNum; ++j) {
  60896. temp += data[j][i][1];
  60897. }
  60898. if (temp > max) {
  60899. max = temp;
  60900. }
  60901. sums.push(temp);
  60902. }
  60903. for (var k = 0; k < pointNum; ++k) {
  60904. y0[k] = (max - sums[k]) / 2;
  60905. }
  60906. max = 0;
  60907. for (var l = 0; l < pointNum; ++l) {
  60908. var sum = sums[l] + y0[l];
  60909. if (sum > max) {
  60910. max = sum;
  60911. }
  60912. }
  60913. return {
  60914. y0: y0,
  60915. max: max
  60916. };
  60917. }
  60918. function install$p(registers) {
  60919. registers.registerChartView(ThemeRiverView);
  60920. registers.registerSeriesModel(ThemeRiverSeriesModel);
  60921. registers.registerLayout(themeRiverLayout);
  60922. registers.registerProcessor(dataFilter('themeRiver'));
  60923. }
  60924. var DEFAULT_SECTOR_Z = 2;
  60925. var DEFAULT_TEXT_Z = 4;
  60926. /**
  60927. * Sunburstce of Sunburst including Sector, Label, LabelLine
  60928. */
  60929. var SunburstPiece =
  60930. /** @class */
  60931. function (_super) {
  60932. __extends(SunburstPiece, _super);
  60933. function SunburstPiece(node, seriesModel, ecModel, api) {
  60934. var _this = _super.call(this) || this;
  60935. _this.z2 = DEFAULT_SECTOR_Z;
  60936. _this.textConfig = {
  60937. inside: true
  60938. };
  60939. getECData(_this).seriesIndex = seriesModel.seriesIndex;
  60940. var text = new ZRText({
  60941. z2: DEFAULT_TEXT_Z,
  60942. silent: node.getModel().get(['label', 'silent'])
  60943. });
  60944. _this.setTextContent(text);
  60945. _this.updateData(true, node, seriesModel, ecModel, api);
  60946. return _this;
  60947. }
  60948. SunburstPiece.prototype.updateData = function (firstCreate, node, // state: 'emphasis' | 'normal' | 'highlight' | 'downplay',
  60949. seriesModel, ecModel, api) {
  60950. this.node = node;
  60951. node.piece = this;
  60952. seriesModel = seriesModel || this._seriesModel;
  60953. ecModel = ecModel || this._ecModel;
  60954. var sector = this;
  60955. getECData(sector).dataIndex = node.dataIndex;
  60956. var itemModel = node.getModel();
  60957. var emphasisModel = itemModel.getModel('emphasis');
  60958. var layout = node.getLayout();
  60959. var sectorShape = extend({}, layout);
  60960. sectorShape.label = null;
  60961. var normalStyle = node.getVisual('style');
  60962. normalStyle.lineJoin = 'bevel';
  60963. var decal = node.getVisual('decal');
  60964. if (decal) {
  60965. normalStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  60966. }
  60967. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  60968. extend(sectorShape, cornerRadius);
  60969. each(SPECIAL_STATES, function (stateName) {
  60970. var state = sector.ensureState(stateName);
  60971. var itemStyleModel = itemModel.getModel([stateName, 'itemStyle']);
  60972. state.style = itemStyleModel.getItemStyle(); // border radius
  60973. var cornerRadius = getSectorCornerRadius(itemStyleModel, sectorShape);
  60974. if (cornerRadius) {
  60975. state.shape = cornerRadius;
  60976. }
  60977. });
  60978. if (firstCreate) {
  60979. sector.setShape(sectorShape);
  60980. sector.shape.r = layout.r0;
  60981. updateProps(sector, {
  60982. shape: {
  60983. r: layout.r
  60984. }
  60985. }, seriesModel, node.dataIndex);
  60986. } else {
  60987. // Disable animation for gradient since no interpolation method
  60988. // is supported for gradient
  60989. updateProps(sector, {
  60990. shape: sectorShape
  60991. }, seriesModel);
  60992. saveOldStyle(sector);
  60993. }
  60994. sector.useStyle(normalStyle);
  60995. this._updateLabel(seriesModel);
  60996. var cursorStyle = itemModel.getShallow('cursor');
  60997. cursorStyle && sector.attr('cursor', cursorStyle);
  60998. this._seriesModel = seriesModel || this._seriesModel;
  60999. this._ecModel = ecModel || this._ecModel;
  61000. var focus = emphasisModel.get('focus');
  61001. var focusOrIndices = focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : focus;
  61002. enableHoverEmphasis(this, focusOrIndices, emphasisModel.get('blurScope'));
  61003. };
  61004. SunburstPiece.prototype._updateLabel = function (seriesModel) {
  61005. var _this = this;
  61006. var itemModel = this.node.getModel();
  61007. var normalLabelModel = itemModel.getModel('label');
  61008. var layout = this.node.getLayout();
  61009. var angle = layout.endAngle - layout.startAngle;
  61010. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  61011. var dx = Math.cos(midAngle);
  61012. var dy = Math.sin(midAngle);
  61013. var sector = this;
  61014. var label = sector.getTextContent();
  61015. var dataIndex = this.node.dataIndex;
  61016. var labelMinAngle = normalLabelModel.get('minAngle') / 180 * Math.PI;
  61017. var isNormalShown = normalLabelModel.get('show') && !(labelMinAngle != null && Math.abs(angle) < labelMinAngle);
  61018. label.ignore = !isNormalShown; // TODO use setLabelStyle
  61019. each(DISPLAY_STATES, function (stateName) {
  61020. var labelStateModel = stateName === 'normal' ? itemModel.getModel('label') : itemModel.getModel([stateName, 'label']);
  61021. var isNormal = stateName === 'normal';
  61022. var state = isNormal ? label : label.ensureState(stateName);
  61023. var text = seriesModel.getFormattedLabel(dataIndex, stateName);
  61024. if (isNormal) {
  61025. text = text || _this.node.name;
  61026. }
  61027. state.style = createTextStyle(labelStateModel, {}, null, stateName !== 'normal', true);
  61028. if (text) {
  61029. state.style.text = text;
  61030. } // Not displaying text when angle is too small
  61031. var isShown = labelStateModel.get('show');
  61032. if (isShown != null && !isNormal) {
  61033. state.ignore = !isShown;
  61034. }
  61035. var labelPosition = getLabelAttr(labelStateModel, 'position');
  61036. var sectorState = isNormal ? sector : sector.states[stateName];
  61037. var labelColor = sectorState.style.fill;
  61038. sectorState.textConfig = {
  61039. outsideFill: labelStateModel.get('color') === 'inherit' ? labelColor : null,
  61040. inside: labelPosition !== 'outside'
  61041. };
  61042. var r;
  61043. var labelPadding = getLabelAttr(labelStateModel, 'distance') || 0;
  61044. var textAlign = getLabelAttr(labelStateModel, 'align');
  61045. if (labelPosition === 'outside') {
  61046. r = layout.r + labelPadding;
  61047. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  61048. } else {
  61049. if (!textAlign || textAlign === 'center') {
  61050. r = (layout.r + layout.r0) / 2;
  61051. textAlign = 'center';
  61052. } else if (textAlign === 'left') {
  61053. r = layout.r0 + labelPadding;
  61054. if (midAngle > Math.PI / 2) {
  61055. textAlign = 'right';
  61056. }
  61057. } else if (textAlign === 'right') {
  61058. r = layout.r - labelPadding;
  61059. if (midAngle > Math.PI / 2) {
  61060. textAlign = 'left';
  61061. }
  61062. }
  61063. }
  61064. state.style.align = textAlign;
  61065. state.style.verticalAlign = getLabelAttr(labelStateModel, 'verticalAlign') || 'middle';
  61066. state.x = r * dx + layout.cx;
  61067. state.y = r * dy + layout.cy;
  61068. var rotateType = getLabelAttr(labelStateModel, 'rotate');
  61069. var rotate = 0;
  61070. if (rotateType === 'radial') {
  61071. rotate = -midAngle;
  61072. if (rotate < -Math.PI / 2) {
  61073. rotate += Math.PI;
  61074. }
  61075. } else if (rotateType === 'tangential') {
  61076. rotate = Math.PI / 2 - midAngle;
  61077. if (rotate > Math.PI / 2) {
  61078. rotate -= Math.PI;
  61079. } else if (rotate < -Math.PI / 2) {
  61080. rotate += Math.PI;
  61081. }
  61082. } else if (typeof rotateType === 'number') {
  61083. rotate = rotateType * Math.PI / 180;
  61084. }
  61085. state.rotation = rotate;
  61086. });
  61087. function getLabelAttr(model, name) {
  61088. var stateAttr = model.get(name);
  61089. if (stateAttr == null) {
  61090. return normalLabelModel.get(name);
  61091. }
  61092. return stateAttr;
  61093. }
  61094. label.dirtyStyle();
  61095. };
  61096. return SunburstPiece;
  61097. }(Sector);
  61098. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  61099. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  61100. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  61101. function installSunburstAction(registers) {
  61102. registers.registerAction({
  61103. type: ROOT_TO_NODE_ACTION,
  61104. update: 'updateView'
  61105. }, function (payload, ecModel) {
  61106. ecModel.eachComponent({
  61107. mainType: 'series',
  61108. subType: 'sunburst',
  61109. query: payload
  61110. }, handleRootToNode);
  61111. function handleRootToNode(model, index) {
  61112. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION], model);
  61113. if (targetInfo) {
  61114. var originViewRoot = model.getViewRoot();
  61115. if (originViewRoot) {
  61116. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  61117. }
  61118. model.resetViewRoot(targetInfo.node);
  61119. }
  61120. }
  61121. });
  61122. registers.registerAction({
  61123. type: HIGHLIGHT_ACTION,
  61124. update: 'none'
  61125. }, function (payload, ecModel, api) {
  61126. // Clone
  61127. payload = extend({}, payload);
  61128. ecModel.eachComponent({
  61129. mainType: 'series',
  61130. subType: 'sunburst',
  61131. query: payload
  61132. }, handleHighlight);
  61133. function handleHighlight(model) {
  61134. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  61135. if (targetInfo) {
  61136. payload.dataIndex = targetInfo.node.dataIndex;
  61137. }
  61138. }
  61139. if ("development" !== 'production') {
  61140. deprecateReplaceLog('highlight', 'sunburstHighlight');
  61141. } // Fast forward action
  61142. api.dispatchAction(extend(payload, {
  61143. type: 'highlight'
  61144. }));
  61145. });
  61146. registers.registerAction({
  61147. type: UNHIGHLIGHT_ACTION,
  61148. update: 'updateView'
  61149. }, function (payload, ecModel, api) {
  61150. payload = extend({}, payload);
  61151. if ("development" !== 'production') {
  61152. deprecateReplaceLog('downplay', 'sunburstUnhighlight');
  61153. }
  61154. api.dispatchAction(extend(payload, {
  61155. type: 'downplay'
  61156. }));
  61157. });
  61158. }
  61159. var SunburstView =
  61160. /** @class */
  61161. function (_super) {
  61162. __extends(SunburstView, _super);
  61163. function SunburstView() {
  61164. var _this = _super !== null && _super.apply(this, arguments) || this;
  61165. _this.type = SunburstView.type;
  61166. return _this;
  61167. }
  61168. SunburstView.prototype.render = function (seriesModel, ecModel, api, // @ts-ignore
  61169. payload) {
  61170. var self = this;
  61171. this.seriesModel = seriesModel;
  61172. this.api = api;
  61173. this.ecModel = ecModel;
  61174. var data = seriesModel.getData();
  61175. var virtualRoot = data.tree.root;
  61176. var newRoot = seriesModel.getViewRoot();
  61177. var group = this.group;
  61178. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  61179. var newChildren = [];
  61180. newRoot.eachNode(function (node) {
  61181. newChildren.push(node);
  61182. });
  61183. var oldChildren = this._oldChildren || [];
  61184. dualTravel(newChildren, oldChildren);
  61185. renderRollUp(virtualRoot, newRoot);
  61186. this._initEvents();
  61187. this._oldChildren = newChildren;
  61188. function dualTravel(newChildren, oldChildren) {
  61189. if (newChildren.length === 0 && oldChildren.length === 0) {
  61190. return;
  61191. }
  61192. new DataDiffer(oldChildren, newChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  61193. function getKey(node) {
  61194. return node.getId();
  61195. }
  61196. function processNode(newIdx, oldIdx) {
  61197. var newNode = newIdx == null ? null : newChildren[newIdx];
  61198. var oldNode = oldIdx == null ? null : oldChildren[oldIdx];
  61199. doRenderNode(newNode, oldNode);
  61200. }
  61201. }
  61202. function doRenderNode(newNode, oldNode) {
  61203. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  61204. // Not render data with value 0
  61205. newNode = null;
  61206. }
  61207. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  61208. if (oldNode && oldNode.piece) {
  61209. if (newNode) {
  61210. // Update
  61211. oldNode.piece.updateData(false, newNode, seriesModel, ecModel, api); // For tooltip
  61212. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  61213. } else {
  61214. // Remove
  61215. removeNode(oldNode);
  61216. }
  61217. } else if (newNode) {
  61218. // Add
  61219. var piece = new SunburstPiece(newNode, seriesModel, ecModel, api);
  61220. group.add(piece); // For tooltip
  61221. data.setItemGraphicEl(newNode.dataIndex, piece);
  61222. }
  61223. }
  61224. }
  61225. function removeNode(node) {
  61226. if (!node) {
  61227. return;
  61228. }
  61229. if (node.piece) {
  61230. group.remove(node.piece);
  61231. node.piece = null;
  61232. }
  61233. }
  61234. function renderRollUp(virtualRoot, viewRoot) {
  61235. if (viewRoot.depth > 0) {
  61236. // Render
  61237. if (self.virtualPiece) {
  61238. // Update
  61239. self.virtualPiece.updateData(false, virtualRoot, seriesModel, ecModel, api);
  61240. } else {
  61241. // Add
  61242. self.virtualPiece = new SunburstPiece(virtualRoot, seriesModel, ecModel, api);
  61243. group.add(self.virtualPiece);
  61244. } // TODO event scope
  61245. viewRoot.piece.off('click');
  61246. self.virtualPiece.on('click', function (e) {
  61247. self._rootToNode(viewRoot.parentNode);
  61248. });
  61249. } else if (self.virtualPiece) {
  61250. // Remove
  61251. group.remove(self.virtualPiece);
  61252. self.virtualPiece = null;
  61253. }
  61254. }
  61255. };
  61256. /**
  61257. * @private
  61258. */
  61259. SunburstView.prototype._initEvents = function () {
  61260. var _this = this;
  61261. this.group.off('click');
  61262. this.group.on('click', function (e) {
  61263. var targetFound = false;
  61264. var viewRoot = _this.seriesModel.getViewRoot();
  61265. viewRoot.eachNode(function (node) {
  61266. if (!targetFound && node.piece && node.piece === e.target) {
  61267. var nodeClick = node.getModel().get('nodeClick');
  61268. if (nodeClick === 'rootToNode') {
  61269. _this._rootToNode(node);
  61270. } else if (nodeClick === 'link') {
  61271. var itemModel = node.getModel();
  61272. var link = itemModel.get('link');
  61273. if (link) {
  61274. var linkTarget = itemModel.get('target', true) || '_blank';
  61275. windowOpen(link, linkTarget);
  61276. }
  61277. }
  61278. targetFound = true;
  61279. }
  61280. });
  61281. });
  61282. };
  61283. /**
  61284. * @private
  61285. */
  61286. SunburstView.prototype._rootToNode = function (node) {
  61287. if (node !== this.seriesModel.getViewRoot()) {
  61288. this.api.dispatchAction({
  61289. type: ROOT_TO_NODE_ACTION,
  61290. from: this.uid,
  61291. seriesId: this.seriesModel.id,
  61292. targetNode: node
  61293. });
  61294. }
  61295. };
  61296. /**
  61297. * @implement
  61298. */
  61299. SunburstView.prototype.containPoint = function (point, seriesModel) {
  61300. var treeRoot = seriesModel.getData();
  61301. var itemLayout = treeRoot.getItemLayout(0);
  61302. if (itemLayout) {
  61303. var dx = point[0] - itemLayout.cx;
  61304. var dy = point[1] - itemLayout.cy;
  61305. var radius = Math.sqrt(dx * dx + dy * dy);
  61306. return radius <= itemLayout.r && radius >= itemLayout.r0;
  61307. }
  61308. };
  61309. SunburstView.type = 'sunburst';
  61310. return SunburstView;
  61311. }(ChartView);
  61312. var SunburstSeriesModel =
  61313. /** @class */
  61314. function (_super) {
  61315. __extends(SunburstSeriesModel, _super);
  61316. function SunburstSeriesModel() {
  61317. var _this = _super !== null && _super.apply(this, arguments) || this;
  61318. _this.type = SunburstSeriesModel.type;
  61319. _this.ignoreStyleOnData = true;
  61320. return _this;
  61321. }
  61322. SunburstSeriesModel.prototype.getInitialData = function (option, ecModel) {
  61323. // Create a virtual root.
  61324. var root = {
  61325. name: option.name,
  61326. children: option.data
  61327. };
  61328. completeTreeValue$1(root);
  61329. var levelModels = map(option.levels || [], function (levelDefine) {
  61330. return new Model(levelDefine, this, ecModel);
  61331. }, this); // Make sure always a new tree is created when setOption,
  61332. // in TreemapView, we check whether oldTree === newTree
  61333. // to choose mappings approach among old shapes and new shapes.
  61334. var tree = Tree.createTree(root, this, beforeLink);
  61335. function beforeLink(nodeData) {
  61336. nodeData.wrapMethod('getItemModel', function (model, idx) {
  61337. var node = tree.getNodeByDataIndex(idx);
  61338. var levelModel = levelModels[node.depth];
  61339. levelModel && (model.parentModel = levelModel);
  61340. return model;
  61341. });
  61342. }
  61343. return tree.data;
  61344. };
  61345. SunburstSeriesModel.prototype.optionUpdated = function () {
  61346. this.resetViewRoot();
  61347. };
  61348. /*
  61349. * @override
  61350. */
  61351. SunburstSeriesModel.prototype.getDataParams = function (dataIndex) {
  61352. var params = _super.prototype.getDataParams.apply(this, arguments);
  61353. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  61354. params.treePathInfo = wrapTreePathInfo(node, this);
  61355. return params;
  61356. };
  61357. SunburstSeriesModel.prototype.getViewRoot = function () {
  61358. return this._viewRoot;
  61359. };
  61360. SunburstSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  61361. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  61362. var root = this.getRawData().tree.root;
  61363. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  61364. this._viewRoot = root;
  61365. }
  61366. };
  61367. SunburstSeriesModel.prototype.enableAriaDecal = function () {
  61368. enableAriaDecalForTree(this);
  61369. };
  61370. SunburstSeriesModel.type = 'series.sunburst';
  61371. SunburstSeriesModel.defaultOption = {
  61372. zlevel: 0,
  61373. z: 2,
  61374. // 默认全局居中
  61375. center: ['50%', '50%'],
  61376. radius: [0, '75%'],
  61377. // 默认顺时针
  61378. clockwise: true,
  61379. startAngle: 90,
  61380. // 最小角度改为0
  61381. minAngle: 0,
  61382. // If still show when all data zero.
  61383. stillShowZeroSum: true,
  61384. // 'rootToNode', 'link', or false
  61385. nodeClick: 'rootToNode',
  61386. renderLabelForZeroData: false,
  61387. label: {
  61388. // could be: 'radial', 'tangential', or 'none'
  61389. rotate: 'radial',
  61390. show: true,
  61391. opacity: 1,
  61392. // 'left' is for inner side of inside, and 'right' is for outter
  61393. // side for inside
  61394. align: 'center',
  61395. position: 'inside',
  61396. distance: 5,
  61397. silent: true
  61398. },
  61399. itemStyle: {
  61400. borderWidth: 1,
  61401. borderColor: 'white',
  61402. borderType: 'solid',
  61403. shadowBlur: 0,
  61404. shadowColor: 'rgba(0, 0, 0, 0.2)',
  61405. shadowOffsetX: 0,
  61406. shadowOffsetY: 0,
  61407. opacity: 1
  61408. },
  61409. emphasis: {
  61410. focus: 'descendant'
  61411. },
  61412. blur: {
  61413. itemStyle: {
  61414. opacity: 0.2
  61415. },
  61416. label: {
  61417. opacity: 0.1
  61418. }
  61419. },
  61420. // Animation type canbe expansion, scale
  61421. animationType: 'expansion',
  61422. animationDuration: 1000,
  61423. animationDurationUpdate: 500,
  61424. data: [],
  61425. /**
  61426. * Sort order.
  61427. *
  61428. * Valid values: 'desc', 'asc', null, or callback function.
  61429. * 'desc' and 'asc' for descend and ascendant order;
  61430. * null for not sorting;
  61431. * example of callback function:
  61432. * function(nodeA, nodeB) {
  61433. * return nodeA.getValue() - nodeB.getValue();
  61434. * }
  61435. */
  61436. sort: 'desc'
  61437. };
  61438. return SunburstSeriesModel;
  61439. }(SeriesModel);
  61440. function completeTreeValue$1(dataNode) {
  61441. // Postorder travel tree.
  61442. // If value of none-leaf node is not set,
  61443. // calculate it by suming up the value of all children.
  61444. var sum = 0;
  61445. each(dataNode.children, function (child) {
  61446. completeTreeValue$1(child);
  61447. var childValue = child.value; // TODO First value of array must be a number
  61448. isArray(childValue) && (childValue = childValue[0]);
  61449. sum += childValue;
  61450. });
  61451. var thisValue = dataNode.value;
  61452. if (isArray(thisValue)) {
  61453. thisValue = thisValue[0];
  61454. }
  61455. if (thisValue == null || isNaN(thisValue)) {
  61456. thisValue = sum;
  61457. } // Value should not less than 0.
  61458. if (thisValue < 0) {
  61459. thisValue = 0;
  61460. }
  61461. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  61462. }
  61463. var RADIAN$2 = Math.PI / 180;
  61464. function sunburstLayout(seriesType, ecModel, api) {
  61465. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  61466. var center = seriesModel.get('center');
  61467. var radius = seriesModel.get('radius');
  61468. if (!isArray(radius)) {
  61469. radius = [0, radius];
  61470. }
  61471. if (!isArray(center)) {
  61472. center = [center, center];
  61473. }
  61474. var width = api.getWidth();
  61475. var height = api.getHeight();
  61476. var size = Math.min(width, height);
  61477. var cx = parsePercent$1(center[0], width);
  61478. var cy = parsePercent$1(center[1], height);
  61479. var r0 = parsePercent$1(radius[0], size / 2);
  61480. var r = parsePercent$1(radius[1], size / 2);
  61481. var startAngle = -seriesModel.get('startAngle') * RADIAN$2;
  61482. var minAngle = seriesModel.get('minAngle') * RADIAN$2;
  61483. var virtualRoot = seriesModel.getData().tree.root;
  61484. var treeRoot = seriesModel.getViewRoot();
  61485. var rootDepth = treeRoot.depth;
  61486. var sort = seriesModel.get('sort');
  61487. if (sort != null) {
  61488. initChildren$1(treeRoot, sort);
  61489. }
  61490. var validDataCount = 0;
  61491. each(treeRoot.children, function (child) {
  61492. !isNaN(child.getValue()) && validDataCount++;
  61493. });
  61494. var sum = treeRoot.getValue(); // Sum may be 0
  61495. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  61496. var renderRollupNode = treeRoot.depth > 0;
  61497. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  61498. var rPerLevel = (r - r0) / (levels || 1);
  61499. var clockwise = seriesModel.get('clockwise');
  61500. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // In the case some sector angle is smaller than minAngle
  61501. // let restAngle = PI2;
  61502. // let valueSumLargerThanMinAngle = 0;
  61503. var dir = clockwise ? 1 : -1;
  61504. /**
  61505. * Render a tree
  61506. * @return increased angle
  61507. */
  61508. var renderNode = function (node, startAngle) {
  61509. if (!node) {
  61510. return;
  61511. }
  61512. var endAngle = startAngle; // Render self
  61513. if (node !== virtualRoot) {
  61514. // Tree node is virtual, so it doesn't need to be drawn
  61515. var value = node.getValue();
  61516. var angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  61517. if (angle < minAngle) {
  61518. angle = minAngle; // restAngle -= minAngle;
  61519. } // else {
  61520. // valueSumLargerThanMinAngle += value;
  61521. // }
  61522. endAngle = startAngle + dir * angle;
  61523. var depth = node.depth - rootDepth - (renderRollupNode ? -1 : 1);
  61524. var rStart = r0 + rPerLevel * depth;
  61525. var rEnd = r0 + rPerLevel * (depth + 1);
  61526. var itemModel = node.getModel(); // @ts-ignore. TODO this is not provided to developer yet. Rename it.
  61527. if (itemModel.get('r0') != null) {
  61528. // @ts-ignore
  61529. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  61530. } // @ts-ignore
  61531. if (itemModel.get('r') != null) {
  61532. // @ts-ignore
  61533. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  61534. }
  61535. node.setLayout({
  61536. angle: angle,
  61537. startAngle: startAngle,
  61538. endAngle: endAngle,
  61539. clockwise: clockwise,
  61540. cx: cx,
  61541. cy: cy,
  61542. r0: rStart,
  61543. r: rEnd
  61544. });
  61545. } // Render children
  61546. if (node.children && node.children.length) {
  61547. // currentAngle = startAngle;
  61548. var siblingAngle_1 = 0;
  61549. each(node.children, function (node) {
  61550. siblingAngle_1 += renderNode(node, startAngle + siblingAngle_1);
  61551. });
  61552. }
  61553. return endAngle - startAngle;
  61554. }; // Virtual root node for roll up
  61555. if (renderRollupNode) {
  61556. var rStart = r0;
  61557. var rEnd = r0 + rPerLevel;
  61558. var angle = Math.PI * 2;
  61559. virtualRoot.setLayout({
  61560. angle: angle,
  61561. startAngle: startAngle,
  61562. endAngle: startAngle + angle,
  61563. clockwise: clockwise,
  61564. cx: cx,
  61565. cy: cy,
  61566. r0: rStart,
  61567. r: rEnd
  61568. });
  61569. }
  61570. renderNode(treeRoot, startAngle);
  61571. });
  61572. }
  61573. /**
  61574. * Init node children by order and update visual
  61575. */
  61576. function initChildren$1(node, sortOrder) {
  61577. var children = node.children || [];
  61578. node.children = sort$2(children, sortOrder); // Init children recursively
  61579. if (children.length) {
  61580. each(node.children, function (child) {
  61581. initChildren$1(child, sortOrder);
  61582. });
  61583. }
  61584. }
  61585. /**
  61586. * Sort children nodes
  61587. *
  61588. * @param {TreeNode[]} children children of node to be sorted
  61589. * @param {string | function | null} sort sort method
  61590. * See SunburstSeries.js for details.
  61591. */
  61592. function sort$2(children, sortOrder) {
  61593. if (typeof sortOrder === 'function') {
  61594. var sortTargets = map(children, function (child, idx) {
  61595. var value = child.getValue();
  61596. return {
  61597. params: {
  61598. depth: child.depth,
  61599. height: child.height,
  61600. dataIndex: child.dataIndex,
  61601. getValue: function () {
  61602. return value;
  61603. }
  61604. },
  61605. index: idx
  61606. };
  61607. });
  61608. sortTargets.sort(function (a, b) {
  61609. return sortOrder(a.params, b.params);
  61610. });
  61611. return map(sortTargets, function (target) {
  61612. return children[target.index];
  61613. });
  61614. } else {
  61615. var isAsc_1 = sortOrder === 'asc';
  61616. return children.sort(function (a, b) {
  61617. var diff = (a.getValue() - b.getValue()) * (isAsc_1 ? 1 : -1);
  61618. return diff === 0 ? (a.dataIndex - b.dataIndex) * (isAsc_1 ? -1 : 1) : diff;
  61619. });
  61620. }
  61621. }
  61622. function sunburstVisual(ecModel) {
  61623. var paletteScope = {}; // Default color strategy
  61624. function pickColor(node, seriesModel, treeHeight) {
  61625. // Choose color from palette based on the first level.
  61626. var current = node;
  61627. while (current && current.depth > 1) {
  61628. current = current.parentNode;
  61629. }
  61630. var color = seriesModel.getColorFromPalette(current.name || current.dataIndex + '', paletteScope);
  61631. if (node.depth > 1 && typeof color === 'string') {
  61632. // Lighter on the deeper level.
  61633. color = lift(color, (node.depth - 1) / (treeHeight - 1) * 0.5);
  61634. }
  61635. return color;
  61636. }
  61637. ecModel.eachSeriesByType('sunburst', function (seriesModel) {
  61638. var data = seriesModel.getData();
  61639. var tree = data.tree;
  61640. tree.eachNode(function (node) {
  61641. var model = node.getModel();
  61642. var style = model.getModel('itemStyle').getItemStyle();
  61643. if (!style.fill) {
  61644. style.fill = pickColor(node, seriesModel, tree.root.height);
  61645. }
  61646. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  61647. extend(existsStyle, style);
  61648. });
  61649. });
  61650. }
  61651. function install$q(registers) {
  61652. registers.registerChartView(SunburstView);
  61653. registers.registerSeriesModel(SunburstSeriesModel);
  61654. registers.registerLayout(curry(sunburstLayout, 'sunburst'));
  61655. registers.registerProcessor(curry(dataFilter, 'sunburst'));
  61656. registers.registerVisual(sunburstVisual);
  61657. installSunburstAction(registers);
  61658. }
  61659. var TRANSFORM_PROPS = {
  61660. x: 1,
  61661. y: 1,
  61662. scaleX: 1,
  61663. scaleY: 1,
  61664. originX: 1,
  61665. originY: 1,
  61666. rotation: 1
  61667. }; // Also compat with ec4, where
  61668. // `visual('color') visual('borderColor')` is supported.
  61669. var STYLE_VISUAL_TYPE = {
  61670. color: 'fill',
  61671. borderColor: 'stroke'
  61672. };
  61673. var NON_STYLE_VISUAL_PROPS = {
  61674. symbol: 1,
  61675. symbolSize: 1,
  61676. symbolKeepAspect: 1,
  61677. legendIcon: 1,
  61678. visualMeta: 1,
  61679. liftZ: 1,
  61680. decal: 1
  61681. };
  61682. var customInnerStore = makeInner();
  61683. var CustomSeriesModel =
  61684. /** @class */
  61685. function (_super) {
  61686. __extends(CustomSeriesModel, _super);
  61687. function CustomSeriesModel() {
  61688. var _this = _super !== null && _super.apply(this, arguments) || this;
  61689. _this.type = CustomSeriesModel.type;
  61690. return _this;
  61691. }
  61692. CustomSeriesModel.prototype.optionUpdated = function () {
  61693. this.currentZLevel = this.get('zlevel', true);
  61694. this.currentZ = this.get('z', true);
  61695. };
  61696. CustomSeriesModel.prototype.getInitialData = function (option, ecModel) {
  61697. return createSeriesData(null, this);
  61698. };
  61699. CustomSeriesModel.prototype.getDataParams = function (dataIndex, dataType, el) {
  61700. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  61701. el && (params.info = customInnerStore(el).info);
  61702. return params;
  61703. };
  61704. CustomSeriesModel.type = 'series.custom';
  61705. CustomSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  61706. CustomSeriesModel.defaultOption = {
  61707. coordinateSystem: 'cartesian2d',
  61708. zlevel: 0,
  61709. z: 2,
  61710. legendHoverLink: true,
  61711. // Custom series will not clip by default.
  61712. // Some case will use custom series to draw label
  61713. // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
  61714. clip: false // Cartesian coordinate system
  61715. // xAxisIndex: 0,
  61716. // yAxisIndex: 0,
  61717. // Polar coordinate system
  61718. // polarIndex: 0,
  61719. // Geo coordinate system
  61720. // geoIndex: 0,
  61721. };
  61722. return CustomSeriesModel;
  61723. }(SeriesModel);
  61724. function dataToCoordSize(dataSize, dataItem) {
  61725. // dataItem is necessary in log axis.
  61726. dataItem = dataItem || [0, 0];
  61727. return map(['x', 'y'], function (dim, dimIdx) {
  61728. var axis = this.getAxis(dim);
  61729. var val = dataItem[dimIdx];
  61730. var halfSize = dataSize[dimIdx] / 2;
  61731. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  61732. }, this);
  61733. }
  61734. function cartesianPrepareCustom(coordSys) {
  61735. var rect = coordSys.master.getRect();
  61736. return {
  61737. coordSys: {
  61738. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  61739. type: 'cartesian2d',
  61740. x: rect.x,
  61741. y: rect.y,
  61742. width: rect.width,
  61743. height: rect.height
  61744. },
  61745. api: {
  61746. coord: function (data) {
  61747. // do not provide "out" param
  61748. return coordSys.dataToPoint(data);
  61749. },
  61750. size: bind(dataToCoordSize, coordSys)
  61751. }
  61752. };
  61753. }
  61754. function dataToCoordSize$1(dataSize, dataItem) {
  61755. dataItem = dataItem || [0, 0];
  61756. return map([0, 1], function (dimIdx) {
  61757. var val = dataItem[dimIdx];
  61758. var halfSize = dataSize[dimIdx] / 2;
  61759. var p1 = [];
  61760. var p2 = [];
  61761. p1[dimIdx] = val - halfSize;
  61762. p2[dimIdx] = val + halfSize;
  61763. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  61764. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  61765. }, this);
  61766. }
  61767. function geoPrepareCustom(coordSys) {
  61768. var rect = coordSys.getBoundingRect();
  61769. return {
  61770. coordSys: {
  61771. type: 'geo',
  61772. x: rect.x,
  61773. y: rect.y,
  61774. width: rect.width,
  61775. height: rect.height,
  61776. zoom: coordSys.getZoom()
  61777. },
  61778. api: {
  61779. coord: function (data) {
  61780. // do not provide "out" and noRoam param,
  61781. // Compatible with this usage:
  61782. // echarts.util.map(item.points, api.coord)
  61783. return coordSys.dataToPoint(data);
  61784. },
  61785. size: bind(dataToCoordSize$1, coordSys)
  61786. }
  61787. };
  61788. }
  61789. function dataToCoordSize$2(dataSize, dataItem) {
  61790. // dataItem is necessary in log axis.
  61791. var axis = this.getAxis();
  61792. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  61793. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  61794. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  61795. }
  61796. function singlePrepareCustom(coordSys) {
  61797. var rect = coordSys.getRect();
  61798. return {
  61799. coordSys: {
  61800. type: 'singleAxis',
  61801. x: rect.x,
  61802. y: rect.y,
  61803. width: rect.width,
  61804. height: rect.height
  61805. },
  61806. api: {
  61807. coord: function (val) {
  61808. // do not provide "out" param
  61809. return coordSys.dataToPoint(val);
  61810. },
  61811. size: bind(dataToCoordSize$2, coordSys)
  61812. }
  61813. };
  61814. }
  61815. function dataToCoordSize$3(dataSize, dataItem) {
  61816. // dataItem is necessary in log axis.
  61817. dataItem = dataItem || [0, 0];
  61818. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  61819. var getterName = 'get' + dim + 'Axis'; // TODO: TYPE Check Angle Axis
  61820. var axis = this[getterName]();
  61821. var val = dataItem[dimIdx];
  61822. var halfSize = dataSize[dimIdx] / 2;
  61823. var result = axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  61824. if (dim === 'Angle') {
  61825. result = result * Math.PI / 180;
  61826. }
  61827. return result;
  61828. }, this);
  61829. }
  61830. function polarPrepareCustom(coordSys) {
  61831. var radiusAxis = coordSys.getRadiusAxis();
  61832. var angleAxis = coordSys.getAngleAxis();
  61833. var radius = radiusAxis.getExtent();
  61834. radius[0] > radius[1] && radius.reverse();
  61835. return {
  61836. coordSys: {
  61837. type: 'polar',
  61838. cx: coordSys.cx,
  61839. cy: coordSys.cy,
  61840. r: radius[1],
  61841. r0: radius[0]
  61842. },
  61843. api: {
  61844. coord: function (data) {
  61845. var radius = radiusAxis.dataToRadius(data[0]);
  61846. var angle = angleAxis.dataToAngle(data[1]);
  61847. var coord = coordSys.coordToPoint([radius, angle]);
  61848. coord.push(radius, angle * Math.PI / 180);
  61849. return coord;
  61850. },
  61851. size: bind(dataToCoordSize$3, coordSys)
  61852. }
  61853. };
  61854. }
  61855. /*
  61856. * Licensed to the Apache Software Foundation (ASF) under one
  61857. * or more contributor license agreements. See the NOTICE file
  61858. * distributed with this work for additional information
  61859. * regarding copyright ownership. The ASF licenses this file
  61860. * to you under the Apache License, Version 2.0 (the
  61861. * "License"); you may not use this file except in compliance
  61862. * with the License. You may obtain a copy of the License at
  61863. *
  61864. * http://www.apache.org/licenses/LICENSE-2.0
  61865. *
  61866. * Unless required by applicable law or agreed to in writing,
  61867. * software distributed under the License is distributed on an
  61868. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61869. * KIND, either express or implied. See the License for the
  61870. * specific language governing permissions and limitations
  61871. * under the License.
  61872. */
  61873. /**
  61874. * AUTO-GENERATED FILE. DO NOT MODIFY.
  61875. */
  61876. /*
  61877. * Licensed to the Apache Software Foundation (ASF) under one
  61878. * or more contributor license agreements. See the NOTICE file
  61879. * distributed with this work for additional information
  61880. * regarding copyright ownership. The ASF licenses this file
  61881. * to you under the Apache License, Version 2.0 (the
  61882. * "License"); you may not use this file except in compliance
  61883. * with the License. You may obtain a copy of the License at
  61884. *
  61885. * http://www.apache.org/licenses/LICENSE-2.0
  61886. *
  61887. * Unless required by applicable law or agreed to in writing,
  61888. * software distributed under the License is distributed on an
  61889. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61890. * KIND, either express or implied. See the License for the
  61891. * specific language governing permissions and limitations
  61892. * under the License.
  61893. */
  61894. function calendarPrepareCustom(coordSys) {
  61895. var rect = coordSys.getRect();
  61896. var rangeInfo = coordSys.getRangeInfo();
  61897. return {
  61898. coordSys: {
  61899. type: 'calendar',
  61900. x: rect.x,
  61901. y: rect.y,
  61902. width: rect.width,
  61903. height: rect.height,
  61904. cellWidth: coordSys.getCellWidth(),
  61905. cellHeight: coordSys.getCellHeight(),
  61906. rangeInfo: {
  61907. start: rangeInfo.start,
  61908. end: rangeInfo.end,
  61909. weeks: rangeInfo.weeks,
  61910. dayCount: rangeInfo.allDay
  61911. }
  61912. },
  61913. api: {
  61914. coord: function (data, clamp) {
  61915. return coordSys.dataToPoint(data, clamp);
  61916. }
  61917. }
  61918. };
  61919. }
  61920. var deprecatedLogs = {};
  61921. /**
  61922. * Whether need to call `convertEC4CompatibleStyle`.
  61923. */
  61924. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  61925. // Since echarts5, `RectText` is separated from its host element and style.text
  61926. // does not exist any more. The compat work brings some extra burden on performance.
  61927. // So we provide:
  61928. // `legacy: true` force make compat.
  61929. // `legacy: false`, force do not compat.
  61930. // `legacy` not set: auto detect wheter legacy.
  61931. // But in this case we do not compat (difficult to detect and rare case):
  61932. // Becuse custom series and graphic component support "merge", users may firstly
  61933. // only set `textStrokeWidth` style or secondly only set `text`.
  61934. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan' // Difficult to detect whether legacy for a "text" el.
  61935. && (elType === 'text' || hasOwn(style, 'text')));
  61936. }
  61937. /**
  61938. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  61939. * @param hostStyle The properties might be modified.
  61940. * @return If be text el, `textContentStyle` and `textConfig` will not be retured.
  61941. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  61942. * retried from the `hostStyle`.
  61943. */
  61944. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  61945. var srcStyle = hostStyle;
  61946. var textConfig;
  61947. var textContent;
  61948. var textContentStyle;
  61949. if (elType === 'text') {
  61950. textContentStyle = srcStyle;
  61951. } else {
  61952. textContentStyle = {};
  61953. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  61954. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  61955. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  61956. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  61957. hasOwn(srcStyle, 'fontFamily') && (textContentStyle.fontFamily = srcStyle.fontFamily);
  61958. hasOwn(srcStyle, 'fontSize') && (textContentStyle.fontSize = srcStyle.fontSize);
  61959. hasOwn(srcStyle, 'fontStyle') && (textContentStyle.fontStyle = srcStyle.fontStyle);
  61960. hasOwn(srcStyle, 'fontWeight') && (textContentStyle.fontWeight = srcStyle.fontWeight);
  61961. textContent = {
  61962. type: 'text',
  61963. style: textContentStyle,
  61964. // ec4 do not support rectText trigger.
  61965. // And when text postion is different in normal and emphasis
  61966. // => hover text trigger emphasis;
  61967. // => text position changed, leave mouse pointer immediately;
  61968. // That might cause state incorrect.
  61969. silent: true
  61970. };
  61971. textConfig = {};
  61972. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  61973. if (isNormal) {
  61974. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  61975. } else {
  61976. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  61977. }
  61978. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  61979. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  61980. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  61981. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  61982. }
  61983. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  61984. each(textContentStyle.rich, function (richItem) {
  61985. convertEC4CompatibleRichItem(richItem, richItem);
  61986. });
  61987. return {
  61988. textConfig: textConfig,
  61989. textContent: textContent
  61990. };
  61991. }
  61992. /**
  61993. * The result will be set to `out`.
  61994. */
  61995. function convertEC4CompatibleRichItem(out, richItem) {
  61996. if (!richItem) {
  61997. return;
  61998. } // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  61999. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  62000. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  62001. // richText in ec5.
  62002. // (2) `out === richItem` if and only if `out` is text el or rich item.
  62003. // So we can overwite existing props in `out` since textXXX has higher priority.
  62004. richItem.font = richItem.textFont || richItem.font;
  62005. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  62006. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  62007. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  62008. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  62009. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  62010. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  62011. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  62012. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  62013. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  62014. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  62015. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  62016. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  62017. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  62018. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  62019. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  62020. }
  62021. /**
  62022. * Convert to pure echarts4 format style.
  62023. * `itemStyle` will be modified, added with ec4 style properties from
  62024. * `textStyle` and `textConfig`.
  62025. *
  62026. * [Caveat]: For simplicity, `insideRollback` in ec4 does not compat, where
  62027. * `styleEmphasis: {textFill: 'red'}` will remove the normal auto added stroke.
  62028. */
  62029. function convertToEC4StyleForCustomSerise(itemStl, txStl, txCfg) {
  62030. var out = itemStl; // See `custom.ts`, a trick to set extra `textPosition` firstly.
  62031. out.textPosition = out.textPosition || txCfg.position || 'inside';
  62032. txCfg.offset != null && (out.textOffset = txCfg.offset);
  62033. txCfg.rotation != null && (out.textRotation = txCfg.rotation);
  62034. txCfg.distance != null && (out.textDistance = txCfg.distance);
  62035. var isInside = out.textPosition.indexOf('inside') >= 0;
  62036. var hostFill = itemStl.fill || '#000';
  62037. convertToEC4RichItem(out, txStl);
  62038. var textFillNotSet = out.textFill == null;
  62039. if (isInside) {
  62040. if (textFillNotSet) {
  62041. out.textFill = txCfg.insideFill || '#fff';
  62042. !out.textStroke && txCfg.insideStroke && (out.textStroke = txCfg.insideStroke);
  62043. !out.textStroke && (out.textStroke = hostFill);
  62044. out.textStrokeWidth == null && (out.textStrokeWidth = 2);
  62045. }
  62046. } else {
  62047. if (textFillNotSet) {
  62048. out.textFill = itemStl.fill || txCfg.outsideFill || '#000';
  62049. }
  62050. !out.textStroke && txCfg.outsideStroke && (out.textStroke = txCfg.outsideStroke);
  62051. }
  62052. out.text = txStl.text;
  62053. out.rich = txStl.rich;
  62054. each(txStl.rich, function (richItem) {
  62055. convertToEC4RichItem(richItem, richItem);
  62056. });
  62057. return out;
  62058. }
  62059. function convertToEC4RichItem(out, richItem) {
  62060. if (!richItem) {
  62061. return;
  62062. }
  62063. hasOwn(richItem, 'fill') && (out.textFill = richItem.fill);
  62064. hasOwn(richItem, 'stroke') && (out.textStroke = richItem.fill);
  62065. hasOwn(richItem, 'lineWidth') && (out.textStrokeWidth = richItem.lineWidth);
  62066. hasOwn(richItem, 'font') && (out.font = richItem.font);
  62067. hasOwn(richItem, 'fontStyle') && (out.fontStyle = richItem.fontStyle);
  62068. hasOwn(richItem, 'fontWeight') && (out.fontWeight = richItem.fontWeight);
  62069. hasOwn(richItem, 'fontSize') && (out.fontSize = richItem.fontSize);
  62070. hasOwn(richItem, 'fontFamily') && (out.fontFamily = richItem.fontFamily);
  62071. hasOwn(richItem, 'align') && (out.textAlign = richItem.align);
  62072. hasOwn(richItem, 'verticalAlign') && (out.textVerticalAlign = richItem.verticalAlign);
  62073. hasOwn(richItem, 'lineHeight') && (out.textLineHeight = richItem.lineHeight);
  62074. hasOwn(richItem, 'width') && (out.textWidth = richItem.width);
  62075. hasOwn(richItem, 'height') && (out.textHeight = richItem.height);
  62076. hasOwn(richItem, 'backgroundColor') && (out.textBackgroundColor = richItem.backgroundColor);
  62077. hasOwn(richItem, 'padding') && (out.textPadding = richItem.padding);
  62078. hasOwn(richItem, 'borderColor') && (out.textBorderColor = richItem.borderColor);
  62079. hasOwn(richItem, 'borderWidth') && (out.textBorderWidth = richItem.borderWidth);
  62080. hasOwn(richItem, 'borderRadius') && (out.textBorderRadius = richItem.borderRadius);
  62081. hasOwn(richItem, 'shadowColor') && (out.textBoxShadowColor = richItem.shadowColor);
  62082. hasOwn(richItem, 'shadowBlur') && (out.textBoxShadowBlur = richItem.shadowBlur);
  62083. hasOwn(richItem, 'shadowOffsetX') && (out.textBoxShadowOffsetX = richItem.shadowOffsetX);
  62084. hasOwn(richItem, 'shadowOffsetY') && (out.textBoxShadowOffsetY = richItem.shadowOffsetY);
  62085. hasOwn(richItem, 'textShadowColor') && (out.textShadowColor = richItem.textShadowColor);
  62086. hasOwn(richItem, 'textShadowBlur') && (out.textShadowBlur = richItem.textShadowBlur);
  62087. hasOwn(richItem, 'textShadowOffsetX') && (out.textShadowOffsetX = richItem.textShadowOffsetX);
  62088. hasOwn(richItem, 'textShadowOffsetY') && (out.textShadowOffsetY = richItem.textShadowOffsetY);
  62089. }
  62090. function warnDeprecated(deprecated, insteadApproach) {
  62091. if ("development" !== 'production') {
  62092. var key = deprecated + '^_^' + insteadApproach;
  62093. if (!deprecatedLogs[key]) {
  62094. console.warn("[ECharts] DEPRECATED: \"" + deprecated + "\" has been deprecated. " + insteadApproach);
  62095. deprecatedLogs[key] = true;
  62096. }
  62097. }
  62098. }
  62099. var LEGACY_TRANSFORM_PROPS = {
  62100. position: ['x', 'y'],
  62101. scale: ['scaleX', 'scaleY'],
  62102. origin: ['originX', 'originY']
  62103. };
  62104. function setLegacyTransformProp(elOption, targetProps, legacyName) {
  62105. var legacyArr = elOption[legacyName];
  62106. var xyName = LEGACY_TRANSFORM_PROPS[legacyName];
  62107. if (legacyArr) {
  62108. targetProps[xyName[0]] = legacyArr[0];
  62109. targetProps[xyName[1]] = legacyArr[1];
  62110. }
  62111. }
  62112. function setTransformProp(elOption, allProps, name) {
  62113. if (elOption[name] != null) {
  62114. allProps[name] = elOption[name];
  62115. }
  62116. }
  62117. function setTransformPropToTransitionFrom(transitionFrom, name, fromTransformable // If provided, retrieve from the element.
  62118. ) {
  62119. if (fromTransformable) {
  62120. transitionFrom[name] = fromTransformable[name];
  62121. }
  62122. } // See [STRATEGY_TRANSITION]
  62123. function prepareShapeOrExtraTransitionFrom(mainAttr, fromEl, elOption, transFromProps, isInit) {
  62124. var attrOpt = elOption[mainAttr];
  62125. if (!attrOpt) {
  62126. return;
  62127. }
  62128. var elPropsInAttr = fromEl[mainAttr];
  62129. var transFromPropsInAttr;
  62130. var enterFrom = attrOpt.enterFrom;
  62131. if (isInit && enterFrom) {
  62132. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  62133. var enterFromKeys = keys(enterFrom);
  62134. for (var i = 0; i < enterFromKeys.length; i++) {
  62135. // `enterFrom` props are not necessarily also declared in `shape`/`style`/...,
  62136. // for example, `opacity` can only declared in `enterFrom` but not in `style`.
  62137. var key = enterFromKeys[i]; // Do not clone, animator will perform that clone.
  62138. transFromPropsInAttr[key] = enterFrom[key];
  62139. }
  62140. }
  62141. if (!isInit && elPropsInAttr) {
  62142. if (attrOpt.transition) {
  62143. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  62144. var transitionKeys = normalizeToArray(attrOpt.transition);
  62145. for (var i = 0; i < transitionKeys.length; i++) {
  62146. var key = transitionKeys[i];
  62147. var elVal = elPropsInAttr[key];
  62148. if ("development" !== 'production') {
  62149. checkNonStyleTansitionRefer(key, attrOpt[key], elVal);
  62150. } // Do not clone, see `checkNonStyleTansitionRefer`.
  62151. transFromPropsInAttr[key] = elVal;
  62152. }
  62153. } else if (indexOf(elOption.transition, mainAttr) >= 0) {
  62154. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  62155. var elPropsInAttrKeys = keys(elPropsInAttr);
  62156. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  62157. var key = elPropsInAttrKeys[i];
  62158. var elVal = elPropsInAttr[key];
  62159. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  62160. transFromPropsInAttr[key] = elVal;
  62161. }
  62162. }
  62163. }
  62164. }
  62165. var leaveTo = attrOpt.leaveTo;
  62166. if (leaveTo) {
  62167. var leaveToProps = getOrCreateLeaveToPropsFromEl(fromEl);
  62168. var leaveToPropsInAttr = leaveToProps[mainAttr] || (leaveToProps[mainAttr] = {});
  62169. var leaveToKeys = keys(leaveTo);
  62170. for (var i = 0; i < leaveToKeys.length; i++) {
  62171. var key = leaveToKeys[i];
  62172. leaveToPropsInAttr[key] = leaveTo[key];
  62173. }
  62174. }
  62175. }
  62176. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  62177. var attrOpt = elOption[mainAttr];
  62178. if (!attrOpt) {
  62179. return;
  62180. }
  62181. var allPropsInAttr = allProps[mainAttr] = {};
  62182. var keysInAttr = keys(attrOpt);
  62183. for (var i = 0; i < keysInAttr.length; i++) {
  62184. var key = keysInAttr[i]; // To avoid share one object with different element, and
  62185. // to avoid user modify the object inexpectedly, have to clone.
  62186. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  62187. }
  62188. } // See [STRATEGY_TRANSITION].
  62189. function prepareTransformTransitionFrom(el, elOption, transFromProps, isInit) {
  62190. var enterFrom = elOption.enterFrom;
  62191. if (isInit && enterFrom) {
  62192. var enterFromKeys = keys(enterFrom);
  62193. for (var i = 0; i < enterFromKeys.length; i++) {
  62194. var key = enterFromKeys[i];
  62195. if ("development" !== 'production') {
  62196. checkTransformPropRefer(key, 'el.enterFrom');
  62197. } // Do not clone, animator will perform that clone.
  62198. transFromProps[key] = enterFrom[key];
  62199. }
  62200. }
  62201. if (!isInit) {
  62202. if (elOption.transition) {
  62203. var transitionKeys = normalizeToArray(elOption.transition);
  62204. for (var i = 0; i < transitionKeys.length; i++) {
  62205. var key = transitionKeys[i];
  62206. if (key === 'style' || key === 'shape' || key === 'extra') {
  62207. continue;
  62208. }
  62209. var elVal = el[key];
  62210. if ("development" !== 'production') {
  62211. checkTransformPropRefer(key, 'el.transition');
  62212. checkNonStyleTansitionRefer(key, elOption[key], elVal);
  62213. } // Do not clone, see `checkNonStyleTansitionRefer`.
  62214. transFromProps[key] = elVal;
  62215. }
  62216. } // This default transition see [STRATEGY_TRANSITION]
  62217. else {
  62218. setTransformPropToTransitionFrom(transFromProps, 'x', el);
  62219. setTransformPropToTransitionFrom(transFromProps, 'y', el);
  62220. }
  62221. }
  62222. var leaveTo = elOption.leaveTo;
  62223. if (leaveTo) {
  62224. var leaveToProps = getOrCreateLeaveToPropsFromEl(el);
  62225. var leaveToKeys = keys(leaveTo);
  62226. for (var i = 0; i < leaveToKeys.length; i++) {
  62227. var key = leaveToKeys[i];
  62228. if ("development" !== 'production') {
  62229. checkTransformPropRefer(key, 'el.leaveTo');
  62230. }
  62231. leaveToProps[key] = leaveTo[key];
  62232. }
  62233. }
  62234. }
  62235. function prepareTransformAllPropsFinal(el, elOption, allProps) {
  62236. setLegacyTransformProp(elOption, allProps, 'position');
  62237. setLegacyTransformProp(elOption, allProps, 'scale');
  62238. setLegacyTransformProp(elOption, allProps, 'origin');
  62239. setTransformProp(elOption, allProps, 'x');
  62240. setTransformProp(elOption, allProps, 'y');
  62241. setTransformProp(elOption, allProps, 'scaleX');
  62242. setTransformProp(elOption, allProps, 'scaleY');
  62243. setTransformProp(elOption, allProps, 'originX');
  62244. setTransformProp(elOption, allProps, 'originY');
  62245. setTransformProp(elOption, allProps, 'rotation');
  62246. } // See [STRATEGY_TRANSITION].
  62247. function prepareStyleTransitionFrom(fromEl, elOption, styleOpt, transFromProps, isInit) {
  62248. if (!styleOpt) {
  62249. return;
  62250. }
  62251. var fromElStyle = fromEl.style;
  62252. var transFromStyleProps;
  62253. var enterFrom = styleOpt.enterFrom;
  62254. if (isInit && enterFrom) {
  62255. var enterFromKeys = keys(enterFrom);
  62256. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  62257. for (var i = 0; i < enterFromKeys.length; i++) {
  62258. var key = enterFromKeys[i]; // Do not clone, animator will perform that clone.
  62259. transFromStyleProps[key] = enterFrom[key];
  62260. }
  62261. }
  62262. if (!isInit && fromElStyle) {
  62263. if (styleOpt.transition) {
  62264. var transitionKeys = normalizeToArray(styleOpt.transition);
  62265. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  62266. for (var i = 0; i < transitionKeys.length; i++) {
  62267. var key = transitionKeys[i];
  62268. var elVal = fromElStyle[key]; // Do not clone, see `checkNonStyleTansitionRefer`.
  62269. transFromStyleProps[key] = elVal;
  62270. }
  62271. } else if (fromEl.getAnimationStyleProps && indexOf(elOption.transition, 'style') >= 0) {
  62272. var animationProps = fromEl.getAnimationStyleProps();
  62273. var animationStyleProps = animationProps ? animationProps.style : null;
  62274. if (animationStyleProps) {
  62275. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  62276. var styleKeys = keys(styleOpt);
  62277. for (var i = 0; i < styleKeys.length; i++) {
  62278. var key = styleKeys[i];
  62279. if (animationStyleProps[key]) {
  62280. var elVal = fromElStyle[key];
  62281. transFromStyleProps[key] = elVal;
  62282. }
  62283. }
  62284. }
  62285. }
  62286. }
  62287. var leaveTo = styleOpt.leaveTo;
  62288. if (leaveTo) {
  62289. var leaveToKeys = keys(leaveTo);
  62290. var leaveToProps = getOrCreateLeaveToPropsFromEl(fromEl);
  62291. var leaveToStyleProps = leaveToProps.style || (leaveToProps.style = {});
  62292. for (var i = 0; i < leaveToKeys.length; i++) {
  62293. var key = leaveToKeys[i];
  62294. leaveToStyleProps[key] = leaveTo[key];
  62295. }
  62296. }
  62297. }
  62298. var checkNonStyleTansitionRefer;
  62299. if ("development" !== 'production') {
  62300. checkNonStyleTansitionRefer = function (propName, optVal, elVal) {
  62301. if (!isArrayLike(optVal)) {
  62302. assert(optVal != null && isFinite(optVal), 'Prop `' + propName + '` must refer to a finite number or ArrayLike for transition.');
  62303. } else {
  62304. // Try not to copy array for performance, but if user use the same object in different
  62305. // call of `renderItem`, it will casue animation transition fail.
  62306. assert(optVal !== elVal, 'Prop `' + propName + '` must use different Array object each time for transition.');
  62307. }
  62308. };
  62309. }
  62310. function isNonStyleTransitionEnabled(optVal, elVal) {
  62311. // The same as `checkNonStyleTansitionRefer`.
  62312. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  62313. }
  62314. var checkTransformPropRefer;
  62315. if ("development" !== 'production') {
  62316. checkTransformPropRefer = function (key, usedIn) {
  62317. assert(hasOwn(TRANSFORM_PROPS, key), 'Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS).join('`, `') + '` are permitted.');
  62318. };
  62319. }
  62320. function getOrCreateLeaveToPropsFromEl(el) {
  62321. var innerEl = customInnerStore(el);
  62322. return innerEl.leaveToProps || (innerEl.leaveToProps = {});
  62323. }
  62324. var transformPropNamesStr = keys(TRANSFORM_PROPS).join(', ');
  62325. var EMPHASIS = 'emphasis';
  62326. var NORMAL = 'normal';
  62327. var BLUR = 'blur';
  62328. var SELECT = 'select';
  62329. var STATES = [NORMAL, EMPHASIS, BLUR, SELECT];
  62330. var PATH_ITEM_STYLE = {
  62331. normal: ['itemStyle'],
  62332. emphasis: [EMPHASIS, 'itemStyle'],
  62333. blur: [BLUR, 'itemStyle'],
  62334. select: [SELECT, 'itemStyle']
  62335. };
  62336. var PATH_LABEL = {
  62337. normal: ['label'],
  62338. emphasis: [EMPHASIS, 'label'],
  62339. blur: [BLUR, 'label'],
  62340. select: [SELECT, 'label']
  62341. }; // Use prefix to avoid index to be the same as el.name,
  62342. // which will cause weird update animation.
  62343. var GROUP_DIFF_PREFIX = 'e\0\0';
  62344. var attachedTxInfoTmp = {
  62345. normal: {},
  62346. emphasis: {},
  62347. blur: {},
  62348. select: {}
  62349. };
  62350. /**
  62351. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  62352. * of each coordinate systems are not required by each coordinate systems directly, but
  62353. * required by the module `custom`.
  62354. *
  62355. * prepareInfoForCustomSeries {Function}: optional
  62356. * @return {Object} {coordSys: {...}, api: {
  62357. * coord: function (data, clamp) {}, // return point in global.
  62358. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  62359. * }}
  62360. */
  62361. var prepareCustoms = {
  62362. cartesian2d: cartesianPrepareCustom,
  62363. geo: geoPrepareCustom,
  62364. singleAxis: singlePrepareCustom,
  62365. polar: polarPrepareCustom,
  62366. calendar: calendarPrepareCustom
  62367. };
  62368. function isPath$1(el) {
  62369. return el instanceof Path;
  62370. }
  62371. function isDisplayable(el) {
  62372. return el instanceof Displayable;
  62373. }
  62374. function copyElement(sourceEl, targetEl) {
  62375. targetEl.copyTransform(sourceEl);
  62376. if (isDisplayable(targetEl) && isDisplayable(sourceEl)) {
  62377. targetEl.setStyle(sourceEl.style);
  62378. targetEl.z = sourceEl.z;
  62379. targetEl.z2 = sourceEl.z2;
  62380. targetEl.zlevel = sourceEl.zlevel;
  62381. targetEl.invisible = sourceEl.invisible;
  62382. targetEl.ignore = sourceEl.ignore;
  62383. if (isPath$1(targetEl) && isPath$1(sourceEl)) {
  62384. targetEl.setShape(sourceEl.shape);
  62385. }
  62386. }
  62387. }
  62388. var CustomChartView =
  62389. /** @class */
  62390. function (_super) {
  62391. __extends(CustomChartView, _super);
  62392. function CustomChartView() {
  62393. var _this = _super !== null && _super.apply(this, arguments) || this;
  62394. _this.type = CustomChartView.type;
  62395. return _this;
  62396. }
  62397. CustomChartView.prototype.render = function (customSeries, ecModel, api, payload) {
  62398. var oldData = this._data;
  62399. var data = customSeries.getData();
  62400. var group = this.group;
  62401. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  62402. if (!oldData) {
  62403. // Previous render is incremental render or first render.
  62404. // Needs remove the incremental rendered elements.
  62405. group.removeAll();
  62406. }
  62407. data.diff(oldData).add(function (newIdx) {
  62408. createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  62409. }).remove(function (oldIdx) {
  62410. doRemoveEl(oldData.getItemGraphicEl(oldIdx), customSeries, group);
  62411. }).update(function (newIdx, oldIdx) {
  62412. var oldEl = oldData.getItemGraphicEl(oldIdx);
  62413. createOrUpdateItem(api, oldEl, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  62414. }).execute(); // Do clipping
  62415. var clipPath = customSeries.get('clip', true) ? createClipPath(customSeries.coordinateSystem, false, customSeries) : null;
  62416. if (clipPath) {
  62417. group.setClipPath(clipPath);
  62418. } else {
  62419. group.removeClipPath();
  62420. }
  62421. this._data = data;
  62422. };
  62423. CustomChartView.prototype.incrementalPrepareRender = function (customSeries, ecModel, api) {
  62424. this.group.removeAll();
  62425. this._data = null;
  62426. };
  62427. CustomChartView.prototype.incrementalRender = function (params, customSeries, ecModel, api, payload) {
  62428. var data = customSeries.getData();
  62429. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  62430. function setIncrementalAndHoverLayer(el) {
  62431. if (!el.isGroup) {
  62432. el.incremental = true;
  62433. el.ensureState('emphasis').hoverLayer = true;
  62434. }
  62435. }
  62436. for (var idx = params.start; idx < params.end; idx++) {
  62437. var el = createOrUpdateItem(null, null, idx, renderItem(idx, payload), customSeries, this.group, data);
  62438. el && el.traverse(setIncrementalAndHoverLayer);
  62439. }
  62440. };
  62441. CustomChartView.prototype.filterForExposedEvent = function (eventType, query, targetEl, packedEvent) {
  62442. var elementName = query.element;
  62443. if (elementName == null || targetEl.name === elementName) {
  62444. return true;
  62445. } // Enable to give a name on a group made by `renderItem`, and listen
  62446. // events that triggerd by its descendents.
  62447. while ((targetEl = targetEl.__hostTarget || targetEl.parent) && targetEl !== this.group) {
  62448. if (targetEl.name === elementName) {
  62449. return true;
  62450. }
  62451. }
  62452. return false;
  62453. };
  62454. CustomChartView.type = 'custom';
  62455. return CustomChartView;
  62456. }(ChartView);
  62457. function createEl(elOption) {
  62458. var graphicType = elOption.type;
  62459. var el; // Those graphic elements are not shapes. They should not be
  62460. // overwritten by users, so do them first.
  62461. if (graphicType === 'path') {
  62462. var shape = elOption.shape; // Using pathRect brings convenience to users sacle svg path.
  62463. var pathRect = shape.width != null && shape.height != null ? {
  62464. x: shape.x || 0,
  62465. y: shape.y || 0,
  62466. width: shape.width,
  62467. height: shape.height
  62468. } : null;
  62469. var pathData = getPathData(shape); // Path is also used for icon, so layout 'center' by default.
  62470. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  62471. customInnerStore(el).customPathData = pathData;
  62472. } else if (graphicType === 'image') {
  62473. el = new ZRImage({});
  62474. customInnerStore(el).customImagePath = elOption.style.image;
  62475. } else if (graphicType === 'text') {
  62476. el = new ZRText({}); // customInnerStore(el).customText = (elOption.style as TextStyleProps).text;
  62477. } else if (graphicType === 'group') {
  62478. el = new Group();
  62479. } else if (graphicType === 'compoundPath') {
  62480. throw new Error('"compoundPath" is not supported yet.');
  62481. } else {
  62482. var Clz = getShapeClass(graphicType);
  62483. if (!Clz) {
  62484. var errMsg = '';
  62485. if ("development" !== 'production') {
  62486. errMsg = 'graphic type "' + graphicType + '" can not be found.';
  62487. }
  62488. throwError(errMsg);
  62489. }
  62490. el = new Clz();
  62491. }
  62492. customInnerStore(el).customGraphicType = graphicType;
  62493. el.name = elOption.name; // Compat ec4: the default z2 lift is 1. If changing the number,
  62494. // some cases probably be broken: hierarchy layout along z, like circle packing,
  62495. // where emphasis only intending to modify color/border rather than lift z2.
  62496. el.z2EmphasisLift = 1;
  62497. el.z2SelectLift = 1;
  62498. return el;
  62499. }
  62500. function updateElNormal( // Can be null/undefined
  62501. api, el, dataIndex, elOption, attachedTxInfo, seriesModel, isInit, isTextContent) {
  62502. var txCfgOpt = attachedTxInfo && attachedTxInfo.normal.cfg;
  62503. if (txCfgOpt) {
  62504. // PENDING: whether use user object directly rather than clone?
  62505. // TODO:5.0 textConfig transition animation?
  62506. el.setTextConfig(txCfgOpt);
  62507. } // Do some normalization on style.
  62508. var styleOpt = elOption && elOption.style;
  62509. if (styleOpt) {
  62510. if (el.type === 'text') {
  62511. var textOptionStyle = styleOpt; // Compatible with ec4: if `textFill` or `textStroke` exists use them.
  62512. hasOwn(textOptionStyle, 'textFill') && (textOptionStyle.fill = textOptionStyle.textFill);
  62513. hasOwn(textOptionStyle, 'textStroke') && (textOptionStyle.stroke = textOptionStyle.textStroke);
  62514. }
  62515. var decalPattern = void 0;
  62516. var decalObj = isPath$1(el) ? styleOpt.decal : null;
  62517. if (api && decalObj) {
  62518. decalObj.dirty = true;
  62519. decalPattern = createOrUpdatePatternFromDecal(decalObj, api);
  62520. } // Always overwrite in case user specify this prop.
  62521. styleOpt.__decalPattern = decalPattern;
  62522. } // Save the meta info for further morphing. Like apply on the sub morphing elements.
  62523. var store = customInnerStore(el);
  62524. store.userDuring = elOption.during;
  62525. var transFromProps = {};
  62526. var propsToSet = {};
  62527. prepareShapeOrExtraTransitionFrom('shape', el, elOption, transFromProps, isInit);
  62528. prepareShapeOrExtraAllPropsFinal('shape', elOption, propsToSet);
  62529. prepareTransformTransitionFrom(el, elOption, transFromProps, isInit);
  62530. prepareTransformAllPropsFinal(el, elOption, propsToSet);
  62531. prepareShapeOrExtraTransitionFrom('extra', el, elOption, transFromProps, isInit);
  62532. prepareShapeOrExtraAllPropsFinal('extra', elOption, propsToSet);
  62533. prepareStyleTransitionFrom(el, elOption, styleOpt, transFromProps, isInit);
  62534. propsToSet.style = styleOpt;
  62535. applyPropsDirectly(el, propsToSet);
  62536. applyPropsTransition(el, dataIndex, seriesModel, transFromProps, isInit);
  62537. applyMiscProps(el, elOption, isTextContent);
  62538. styleOpt ? el.dirty() : el.markRedraw();
  62539. }
  62540. function applyMiscProps(el, elOption, isTextContent) {
  62541. // Merge by default.
  62542. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  62543. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  62544. if (isDisplayable(el)) {
  62545. hasOwn(elOption, 'invisible') && (el.invisible = elOption.invisible);
  62546. }
  62547. if (isPath$1(el)) {
  62548. hasOwn(elOption, 'autoBatch') && (el.autoBatch = elOption.autoBatch);
  62549. }
  62550. if (!isTextContent) {
  62551. // `elOption.info` enables user to mount some info on
  62552. // elements and use them in event handlers.
  62553. // Update them only when user specified, otherwise, remain.
  62554. hasOwn(elOption, 'info') && (customInnerStore(el).info = elOption.info);
  62555. }
  62556. }
  62557. function applyPropsDirectly(el, // Can be null/undefined
  62558. allPropsFinal) {
  62559. var elDisplayable = el.isGroup ? null : el;
  62560. var styleOpt = allPropsFinal.style;
  62561. if (elDisplayable && styleOpt) {
  62562. // PENDING: here the input style object is used directly.
  62563. // Good for performance but bad for compatibility control.
  62564. elDisplayable.useStyle(styleOpt);
  62565. var decalPattern = styleOpt.__decalPattern;
  62566. if (decalPattern) {
  62567. elDisplayable.style.decal = decalPattern;
  62568. } // When style object changed, how to trade the existing animation?
  62569. // It is probably complicated and not needed to cover all the cases.
  62570. // But still need consider the case:
  62571. // (1) When using init animation on `style.opacity`, and before the animation
  62572. // ended users triggers an update by mousewhel. At that time the init
  62573. // animation should better be continued rather than terminated.
  62574. // So after `useStyle` called, we should change the animation target manually
  62575. // to continue the effect of the init animation.
  62576. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  62577. // to update the value to `val2` and no animation declared, should be terminate
  62578. // the previous animation or just modify the target of the animation?
  62579. // Therotically That will happen not only on `style` but also on `shape` and
  62580. // `transfrom` props. But we haven't handle this case at present yet.
  62581. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  62582. var animators = elDisplayable.animators;
  62583. for (var i = 0; i < animators.length; i++) {
  62584. var animator = animators[i]; // targetName is the "topKey".
  62585. if (animator.targetName === 'style') {
  62586. animator.changeTarget(elDisplayable.style);
  62587. }
  62588. }
  62589. }
  62590. if (allPropsFinal) {
  62591. // Not set style here.
  62592. allPropsFinal.style = null; // Set el to the final state firstly.
  62593. allPropsFinal && el.attr(allPropsFinal);
  62594. allPropsFinal.style = styleOpt;
  62595. }
  62596. }
  62597. function applyPropsTransition(el, dataIndex, seriesModel, // Can be null/undefined
  62598. transFromProps, isInit) {
  62599. if (transFromProps) {
  62600. // NOTE: Do not use `el.updateDuringAnimation` here becuase `el.updateDuringAnimation` will
  62601. // be called mutiple time in each animation frame. For example, if both "transform" props
  62602. // and shape props and style props changed, it will generate three animator and called
  62603. // one-by-one in each animation frame.
  62604. // We use the during in `animateTo/From` params.
  62605. var userDuring = customInnerStore(el).userDuring; // For simplicity, if during not specified, the previous during will not work any more.
  62606. var cfgDuringCall = userDuring ? bind(duringCall, {
  62607. el: el,
  62608. userDuring: userDuring
  62609. }) : null;
  62610. var cfg = {
  62611. dataIndex: dataIndex,
  62612. isFrom: true,
  62613. during: cfgDuringCall
  62614. };
  62615. isInit ? initProps(el, transFromProps, seriesModel, cfg) : updateProps(el, transFromProps, seriesModel, cfg);
  62616. }
  62617. } // Use it to avoid it be exposed to user.
  62618. var tmpDuringScope = {};
  62619. var customDuringAPI = {
  62620. // Usually other props do not need to be changed in animation during.
  62621. setTransform: function (key, val) {
  62622. if ("development" !== 'production') {
  62623. assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  62624. }
  62625. tmpDuringScope.el[key] = val;
  62626. return this;
  62627. },
  62628. getTransform: function (key) {
  62629. if ("development" !== 'production') {
  62630. assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  62631. }
  62632. return tmpDuringScope.el[key];
  62633. },
  62634. setShape: function (key, val) {
  62635. if ("development" !== 'production') {
  62636. assertNotReserved(key);
  62637. }
  62638. var shape = tmpDuringScope.el.shape || (tmpDuringScope.el.shape = {});
  62639. shape[key] = val;
  62640. tmpDuringScope.isShapeDirty = true;
  62641. return this;
  62642. },
  62643. getShape: function (key) {
  62644. if ("development" !== 'production') {
  62645. assertNotReserved(key);
  62646. }
  62647. var shape = tmpDuringScope.el.shape;
  62648. if (shape) {
  62649. return shape[key];
  62650. }
  62651. },
  62652. setStyle: function (key, val) {
  62653. if ("development" !== 'production') {
  62654. assertNotReserved(key);
  62655. }
  62656. var style = tmpDuringScope.el.style;
  62657. if (style) {
  62658. if ("development" !== 'production') {
  62659. if (eqNaN(val)) {
  62660. warn('style.' + key + ' must not be assigned with NaN.');
  62661. }
  62662. }
  62663. style[key] = val;
  62664. tmpDuringScope.isStyleDirty = true;
  62665. }
  62666. return this;
  62667. },
  62668. getStyle: function (key) {
  62669. if ("development" !== 'production') {
  62670. assertNotReserved(key);
  62671. }
  62672. var style = tmpDuringScope.el.style;
  62673. if (style) {
  62674. return style[key];
  62675. }
  62676. },
  62677. setExtra: function (key, val) {
  62678. if ("development" !== 'production') {
  62679. assertNotReserved(key);
  62680. }
  62681. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  62682. extra[key] = val;
  62683. return this;
  62684. },
  62685. getExtra: function (key) {
  62686. if ("development" !== 'production') {
  62687. assertNotReserved(key);
  62688. }
  62689. var extra = tmpDuringScope.el.extra;
  62690. if (extra) {
  62691. return extra[key];
  62692. }
  62693. }
  62694. };
  62695. function assertNotReserved(key) {
  62696. if ("development" !== 'production') {
  62697. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  62698. throw new Error('key must not be "' + key + '"');
  62699. }
  62700. }
  62701. }
  62702. function duringCall() {
  62703. // Do not provide "percent" until some requirements come.
  62704. // Because consider thies case:
  62705. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  62706. // And enter duration is different from update duration.
  62707. // Thus it might be confused about the meaning of "percent" in during callback.
  62708. var scope = this;
  62709. var el = scope.el;
  62710. if (!el) {
  62711. return;
  62712. } // If el is remove from zr by reason like legend, during still need to called,
  62713. // becuase el will be added back to zr and the prop value should not be incorrect.
  62714. var latestUserDuring = customInnerStore(el).userDuring;
  62715. var scopeUserDuring = scope.userDuring; // Ensured a during is only called once in each animation frame.
  62716. // If a during is called multiple times in one frame, maybe some users' calulation logic
  62717. // might be wrong (not sure whether this usage exists).
  62718. // The case of a during might be called twice can be: by default there is a animator for
  62719. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  62720. // another animators for 'style'/'shape'/'extra'.
  62721. if (latestUserDuring !== scopeUserDuring) {
  62722. // release
  62723. scope.el = scope.userDuring = null;
  62724. return;
  62725. }
  62726. tmpDuringScope.el = el;
  62727. tmpDuringScope.isShapeDirty = false;
  62728. tmpDuringScope.isStyleDirty = false; // Give no `this` to user in "during" calling.
  62729. scopeUserDuring(customDuringAPI);
  62730. if (tmpDuringScope.isShapeDirty && el.dirtyShape) {
  62731. el.dirtyShape();
  62732. }
  62733. if (tmpDuringScope.isStyleDirty && el.dirtyStyle) {
  62734. el.dirtyStyle();
  62735. } // markRedraw() will be called by default in during.
  62736. // FIXME `this.markRedraw();` directly ?
  62737. // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  62738. // consider the issue that the prop might be incorrect when return to "normal" state.
  62739. }
  62740. function updateElOnState(state, el, elStateOpt, styleOpt, attachedTxInfo, isRoot, isTextContent) {
  62741. var elDisplayable = el.isGroup ? null : el;
  62742. var txCfgOpt = attachedTxInfo && attachedTxInfo[state].cfg; // PENDING:5.0 support customize scale change and transition animation?
  62743. if (elDisplayable) {
  62744. // By default support auto lift color when hover whether `emphasis` specified.
  62745. var stateObj = elDisplayable.ensureState(state);
  62746. if (styleOpt === false) {
  62747. var existingEmphasisState = elDisplayable.getState(state);
  62748. if (existingEmphasisState) {
  62749. existingEmphasisState.style = null;
  62750. }
  62751. } else {
  62752. // style is needed to enable defaut emphasis.
  62753. stateObj.style = styleOpt || null;
  62754. } // If `elOption.styleEmphasis` or `elOption.emphasis.style` is `false`,
  62755. // remove hover style.
  62756. // If `elOption.textConfig` or `elOption.emphasis.textConfig` is null/undefined, it does not
  62757. // make sense. So for simplicity, we do not ditinguish `hasOwnProperty` and null/undefined.
  62758. if (txCfgOpt) {
  62759. stateObj.textConfig = txCfgOpt;
  62760. }
  62761. setDefaultStateProxy(elDisplayable);
  62762. }
  62763. }
  62764. function updateZ$1(el, elOption, seriesModel) {
  62765. // Group not support textContent and not support z yet.
  62766. if (el.isGroup) {
  62767. return;
  62768. }
  62769. var elDisplayable = el;
  62770. var currentZ = seriesModel.currentZ;
  62771. var currentZLevel = seriesModel.currentZLevel; // Always erase.
  62772. elDisplayable.z = currentZ;
  62773. elDisplayable.zlevel = currentZLevel; // z2 must not be null/undefined, otherwise sort error may occur.
  62774. var optZ2 = elOption.z2;
  62775. optZ2 != null && (elDisplayable.z2 = optZ2 || 0);
  62776. for (var i = 0; i < STATES.length; i++) {
  62777. updateZForEachState(elDisplayable, elOption, STATES[i]);
  62778. }
  62779. }
  62780. function updateZForEachState(elDisplayable, elOption, state) {
  62781. var isNormal = state === NORMAL;
  62782. var elStateOpt = isNormal ? elOption : retrieveStateOption(elOption, state);
  62783. var optZ2 = elStateOpt ? elStateOpt.z2 : null;
  62784. var stateObj;
  62785. if (optZ2 != null) {
  62786. // Do not `ensureState` until required.
  62787. stateObj = isNormal ? elDisplayable : elDisplayable.ensureState(state);
  62788. stateObj.z2 = optZ2 || 0;
  62789. }
  62790. }
  62791. function makeRenderItem(customSeries, data, ecModel, api) {
  62792. var renderItem = customSeries.get('renderItem');
  62793. var coordSys = customSeries.coordinateSystem;
  62794. var prepareResult = {};
  62795. if (coordSys) {
  62796. if ("development" !== 'production') {
  62797. assert(renderItem, 'series.render is required.');
  62798. assert(coordSys.prepareCustoms || prepareCustoms[coordSys.type], 'This coordSys does not support custom series.');
  62799. } // `coordSys.prepareCustoms` is used for external coord sys like bmap.
  62800. prepareResult = coordSys.prepareCustoms ? coordSys.prepareCustoms(coordSys) : prepareCustoms[coordSys.type](coordSys);
  62801. }
  62802. var userAPI = defaults({
  62803. getWidth: api.getWidth,
  62804. getHeight: api.getHeight,
  62805. getZr: api.getZr,
  62806. getDevicePixelRatio: api.getDevicePixelRatio,
  62807. value: value,
  62808. style: style,
  62809. ordinalRawValue: ordinalRawValue,
  62810. styleEmphasis: styleEmphasis,
  62811. visual: visual,
  62812. barLayout: barLayout,
  62813. currentSeriesIndices: currentSeriesIndices,
  62814. font: font
  62815. }, prepareResult.api || {});
  62816. var userParams = {
  62817. // The life cycle of context: current round of rendering.
  62818. // The global life cycle is probably not necessary, because
  62819. // user can store global status by themselves.
  62820. context: {},
  62821. seriesId: customSeries.id,
  62822. seriesName: customSeries.name,
  62823. seriesIndex: customSeries.seriesIndex,
  62824. coordSys: prepareResult.coordSys,
  62825. dataInsideLength: data.count(),
  62826. encode: wrapEncodeDef(customSeries.getData())
  62827. }; // If someday intending to refactor them to a class, should consider do not
  62828. // break change: currently these attribute member are encapsulated in a closure
  62829. // so that do not need to force user to call these method with a scope.
  62830. // Do not support call `api` asynchronously without dataIndexInside input.
  62831. var currDataIndexInside;
  62832. var currItemModel;
  62833. var currItemStyleModels = {};
  62834. var currLabelModels = {};
  62835. var seriesItemStyleModels = {};
  62836. var seriesLabelModels = {};
  62837. for (var i = 0; i < STATES.length; i++) {
  62838. var stateName = STATES[i];
  62839. seriesItemStyleModels[stateName] = customSeries.getModel(PATH_ITEM_STYLE[stateName]);
  62840. seriesLabelModels[stateName] = customSeries.getModel(PATH_LABEL[stateName]);
  62841. }
  62842. function getItemModel(dataIndexInside) {
  62843. return dataIndexInside === currDataIndexInside ? currItemModel || (currItemModel = data.getItemModel(dataIndexInside)) : data.getItemModel(dataIndexInside);
  62844. }
  62845. function getItemStyleModel(dataIndexInside, state) {
  62846. 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]);
  62847. }
  62848. function getLabelModel(dataIndexInside, state) {
  62849. return !data.hasItemOption ? seriesLabelModels[state] : dataIndexInside === currDataIndexInside ? currLabelModels[state] || (currLabelModels[state] = getItemModel(dataIndexInside).getModel(PATH_LABEL[state])) : getItemModel(dataIndexInside).getModel(PATH_LABEL[state]);
  62850. }
  62851. return function (dataIndexInside, payload) {
  62852. currDataIndexInside = dataIndexInside;
  62853. currItemModel = null;
  62854. currItemStyleModels = {};
  62855. currLabelModels = {};
  62856. return renderItem && renderItem(defaults({
  62857. dataIndexInside: dataIndexInside,
  62858. dataIndex: data.getRawIndex(dataIndexInside),
  62859. // Can be used for optimization when zoom or roam.
  62860. actionType: payload ? payload.type : null
  62861. }, userParams), userAPI);
  62862. };
  62863. /**
  62864. * @public
  62865. * @param dim by default 0.
  62866. * @param dataIndexInside by default `currDataIndexInside`.
  62867. */
  62868. function value(dim, dataIndexInside) {
  62869. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  62870. return data.getStore().get(data.getDimensionIndex(dim || 0), dataIndexInside);
  62871. }
  62872. /**
  62873. * @public
  62874. * @param dim by default 0.
  62875. * @param dataIndexInside by default `currDataIndexInside`.
  62876. */
  62877. function ordinalRawValue(dim, dataIndexInside) {
  62878. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  62879. dim = dim || 0;
  62880. var dimInfo = data.getDimensionInfo(dim);
  62881. if (!dimInfo) {
  62882. var dimIndex = data.getDimensionIndex(dim);
  62883. return dimIndex >= 0 ? data.getStore().get(dimIndex, dataIndexInside) : undefined;
  62884. }
  62885. var val = data.get(dimInfo.name, dataIndexInside);
  62886. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  62887. return ordinalMeta ? ordinalMeta.categories[val] : val;
  62888. }
  62889. /**
  62890. * @deprecated The orgininal intention of `api.style` is enable to set itemStyle
  62891. * like other series. But it not necessary and not easy to give a strict definition
  62892. * of what it return. And since echarts5 it needs to be make compat work. So
  62893. * deprecates it since echarts5.
  62894. *
  62895. * By default, `visual` is applied to style (to support visualMap).
  62896. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  62897. * it can be implemented as:
  62898. * `api.style({stroke: api.visual('color'), fill: null})`;
  62899. *
  62900. * [Compat]: since ec5, RectText has been separated from its hosts el.
  62901. * so `api.style()` will only return the style from `itemStyle` but not handle `label`
  62902. * any more. But `series.label` config is never published in doc.
  62903. * We still compat it in `api.style()`. But not encourage to use it and will still not
  62904. * to pulish it to doc.
  62905. * @public
  62906. * @param dataIndexInside by default `currDataIndexInside`.
  62907. */
  62908. function style(userProps, dataIndexInside) {
  62909. if ("development" !== 'production') {
  62910. warnDeprecated('api.style', 'Please write literal style directly instead.');
  62911. }
  62912. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  62913. var style = data.getItemVisual(dataIndexInside, 'style');
  62914. var visualColor = style && style.fill;
  62915. var opacity = style && style.opacity;
  62916. var itemStyle = getItemStyleModel(dataIndexInside, NORMAL).getItemStyle();
  62917. visualColor != null && (itemStyle.fill = visualColor);
  62918. opacity != null && (itemStyle.opacity = opacity);
  62919. var opt = {
  62920. inheritColor: isString(visualColor) ? visualColor : '#000'
  62921. };
  62922. var labelModel = getLabelModel(dataIndexInside, NORMAL); // Now that the feture of "auto adjust text fill/stroke" has been migrated to zrender
  62923. // since ec5, we should set `isAttached` as `false` here and make compat in
  62924. // `convertToEC4StyleForCustomSerise`.
  62925. var textStyle = createTextStyle(labelModel, null, opt, false, true);
  62926. textStyle.text = labelModel.getShallow('show') ? retrieve2(customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  62927. var textConfig = createTextConfig(labelModel, opt, false);
  62928. preFetchFromExtra(userProps, itemStyle);
  62929. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  62930. userProps && applyUserPropsAfter(itemStyle, userProps);
  62931. itemStyle.legacy = true;
  62932. return itemStyle;
  62933. }
  62934. /**
  62935. * @deprecated The reason see `api.style()`
  62936. * @public
  62937. * @param dataIndexInside by default `currDataIndexInside`.
  62938. */
  62939. function styleEmphasis(userProps, dataIndexInside) {
  62940. if ("development" !== 'production') {
  62941. warnDeprecated('api.styleEmphasis', 'Please write literal style directly instead.');
  62942. }
  62943. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  62944. var itemStyle = getItemStyleModel(dataIndexInside, EMPHASIS).getItemStyle();
  62945. var labelModel = getLabelModel(dataIndexInside, EMPHASIS);
  62946. var textStyle = createTextStyle(labelModel, null, null, true, true);
  62947. textStyle.text = labelModel.getShallow('show') ? retrieve3(customSeries.getFormattedLabel(dataIndexInside, EMPHASIS), customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  62948. var textConfig = createTextConfig(labelModel, null, true);
  62949. preFetchFromExtra(userProps, itemStyle);
  62950. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  62951. userProps && applyUserPropsAfter(itemStyle, userProps);
  62952. itemStyle.legacy = true;
  62953. return itemStyle;
  62954. }
  62955. function applyUserPropsAfter(itemStyle, extra) {
  62956. for (var key in extra) {
  62957. if (hasOwn(extra, key)) {
  62958. itemStyle[key] = extra[key];
  62959. }
  62960. }
  62961. }
  62962. function preFetchFromExtra(extra, itemStyle) {
  62963. // A trick to retrieve those props firstly, which are used to
  62964. // apply auto inside fill/stroke in `convertToEC4StyleForCustomSerise`.
  62965. // (It's not reasonable but only for a degree of compat)
  62966. if (extra) {
  62967. extra.textFill && (itemStyle.textFill = extra.textFill);
  62968. extra.textPosition && (itemStyle.textPosition = extra.textPosition);
  62969. }
  62970. }
  62971. /**
  62972. * @public
  62973. * @param dataIndexInside by default `currDataIndexInside`.
  62974. */
  62975. function visual(visualType, dataIndexInside) {
  62976. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  62977. if (hasOwn(STYLE_VISUAL_TYPE, visualType)) {
  62978. var style_1 = data.getItemVisual(dataIndexInside, 'style');
  62979. return style_1 ? style_1[STYLE_VISUAL_TYPE[visualType]] : null;
  62980. } // Only support these visuals. Other visual might be inner tricky
  62981. // for performance (like `style`), do not expose to users.
  62982. if (hasOwn(NON_STYLE_VISUAL_PROPS, visualType)) {
  62983. return data.getItemVisual(dataIndexInside, visualType);
  62984. }
  62985. }
  62986. /**
  62987. * @public
  62988. * @return If not support, return undefined.
  62989. */
  62990. function barLayout(opt) {
  62991. if (coordSys.type === 'cartesian2d') {
  62992. var baseAxis = coordSys.getBaseAxis();
  62993. return getLayoutOnAxis(defaults({
  62994. axis: baseAxis
  62995. }, opt));
  62996. }
  62997. }
  62998. /**
  62999. * @public
  63000. */
  63001. function currentSeriesIndices() {
  63002. return ecModel.getCurrentSeriesIndices();
  63003. }
  63004. /**
  63005. * @public
  63006. * @return font string
  63007. */
  63008. function font(opt) {
  63009. return getFont(opt, ecModel);
  63010. }
  63011. }
  63012. function wrapEncodeDef(data) {
  63013. var encodeDef = {};
  63014. each(data.dimensions, function (dimName) {
  63015. var dimInfo = data.getDimensionInfo(dimName);
  63016. if (!dimInfo.isExtraCoord) {
  63017. var coordDim = dimInfo.coordDim;
  63018. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  63019. dataDims[dimInfo.coordDimIndex] = data.getDimensionIndex(dimName);
  63020. }
  63021. });
  63022. return encodeDef;
  63023. }
  63024. function createOrUpdateItem(api, existsEl, dataIndex, elOption, seriesModel, group, data) {
  63025. // [Rule]
  63026. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  63027. // (It seems that violate the "merge" principle, but most of users probably intuitively
  63028. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  63029. // most cases.)
  63030. // The rule or "merge" see [STRATEGY_MERGE].
  63031. // If `elOption` is `null`/`undefined`/`false` (when `renderItem` returns nothing).
  63032. if (!elOption) {
  63033. group.remove(existsEl);
  63034. return;
  63035. }
  63036. var el = doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group);
  63037. el && data.setItemGraphicEl(dataIndex, el);
  63038. el && enableHoverEmphasis(el, elOption.focus, elOption.blurScope);
  63039. return el;
  63040. }
  63041. function doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group, isRoot) {
  63042. if ("development" !== 'production') {
  63043. assert(elOption, 'should not have an null/undefined element setting');
  63044. }
  63045. var toBeReplacedIdx = -1;
  63046. var oldEl = existsEl;
  63047. if (existsEl && doesElNeedRecreate(existsEl, elOption, seriesModel) // || (
  63048. // // PENDING: even in one-to-one mapping case, if el is marked as morph,
  63049. // // do not sure whether the el will be mapped to another el with different
  63050. // // hierarchy in Group tree. So always recreate el rather than reuse the el.
  63051. // morphHelper && morphHelper.isOneToOneFrom(el)
  63052. // )
  63053. ) {
  63054. // Should keep at the original index, otherwise "merge by index" will be incorrect.
  63055. toBeReplacedIdx = indexOf(group.childrenRef(), existsEl);
  63056. existsEl = null;
  63057. }
  63058. var isInit = !existsEl;
  63059. var el = existsEl;
  63060. if (!el) {
  63061. el = createEl(elOption);
  63062. if (oldEl) {
  63063. copyElement(oldEl, el);
  63064. }
  63065. } else {
  63066. // FIMXE:NEXT unified clearState?
  63067. // If in some case the performance issue arised, consider
  63068. // do not clearState but update cached normal state directly.
  63069. el.clearStates();
  63070. } // Need to set morph: false explictly to disable automatically morphing.
  63071. if (elOption.morph === false) {
  63072. el.disableMorphing = true;
  63073. } else if (el.disableMorphing) {
  63074. el.disableMorphing = false;
  63075. }
  63076. 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;
  63077. attachedTxInfoTmp.isLegacy = false;
  63078. doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfoTmp);
  63079. doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit);
  63080. updateElNormal(api, el, dataIndex, elOption, attachedTxInfoTmp, seriesModel, isInit, false);
  63081. for (var i = 0; i < STATES.length; i++) {
  63082. var stateName = STATES[i];
  63083. if (stateName !== NORMAL) {
  63084. var otherStateOpt = retrieveStateOption(elOption, stateName);
  63085. var otherStyleOpt = retrieveStyleOptionOnState(elOption, otherStateOpt, stateName);
  63086. updateElOnState(stateName, el, otherStateOpt, otherStyleOpt, attachedTxInfoTmp);
  63087. }
  63088. }
  63089. updateZ$1(el, elOption, seriesModel);
  63090. if (elOption.type === 'group') {
  63091. mergeChildren(api, el, dataIndex, elOption, seriesModel);
  63092. }
  63093. if (toBeReplacedIdx >= 0) {
  63094. group.replaceAt(el, toBeReplacedIdx);
  63095. } else {
  63096. group.add(el);
  63097. }
  63098. return el;
  63099. } // `el` must not be null/undefined.
  63100. function doesElNeedRecreate(el, elOption, seriesModel) {
  63101. var elInner = customInnerStore(el);
  63102. var elOptionType = elOption.type;
  63103. var elOptionShape = elOption.shape;
  63104. var elOptionStyle = elOption.style;
  63105. return (// Always create new if universal transition is enabled.
  63106. // Because we do transition after render. It needs to know what old element is. Replacement will loose it.
  63107. seriesModel.isUniversalTransitionEnabled() // If `elOptionType` is `null`, follow the merge principle.
  63108. || 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?
  63109. // || (elOptionType === 'text'
  63110. // && hasOwn(elOptionStyle, 'text')
  63111. // && (elOptionStyle as TextStyleProps).text !== elInner.customText
  63112. // )
  63113. );
  63114. }
  63115. function doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit) {
  63116. // Based on the "merge" principle, if no clipPath provided,
  63117. // do nothing. The exists clip will be totally removed only if
  63118. // `el.clipPath` is `false`. Otherwise it will be merged/replaced.
  63119. var clipPathOpt = elOption.clipPath;
  63120. if (clipPathOpt === false) {
  63121. if (el && el.getClipPath()) {
  63122. el.removeClipPath();
  63123. }
  63124. } else if (clipPathOpt) {
  63125. var clipPath = el.getClipPath();
  63126. if (clipPath && doesElNeedRecreate(clipPath, clipPathOpt, seriesModel)) {
  63127. clipPath = null;
  63128. }
  63129. if (!clipPath) {
  63130. clipPath = createEl(clipPathOpt);
  63131. if ("development" !== 'production') {
  63132. assert(isPath$1(clipPath), 'Only any type of `path` can be used in `clipPath`, rather than ' + clipPath.type + '.');
  63133. }
  63134. el.setClipPath(clipPath);
  63135. }
  63136. updateElNormal(null, clipPath, dataIndex, clipPathOpt, null, seriesModel, isInit, false);
  63137. } // If not define `clipPath` in option, do nothing unnecessary.
  63138. }
  63139. function doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfo) {
  63140. // group do not support textContent temporarily untill necessary.
  63141. if (el.isGroup) {
  63142. return;
  63143. } // Normal must be called before emphasis, for `isLegacy` detection.
  63144. processTxInfo(elOption, null, attachedTxInfo);
  63145. processTxInfo(elOption, EMPHASIS, attachedTxInfo); // If `elOption.textConfig` or `elOption.textContent` is null/undefined, it does not make sence.
  63146. // So for simplicity, if "elOption hasOwnProperty of them but be null/undefined", we do not
  63147. // trade them as set to null to el.
  63148. // Especially:
  63149. // `elOption.textContent: false` means remove textContent.
  63150. // `elOption.textContent.emphasis.style: false` means remove the style from emphasis state.
  63151. var txConOptNormal = attachedTxInfo.normal.conOpt;
  63152. var txConOptEmphasis = attachedTxInfo.emphasis.conOpt;
  63153. var txConOptBlur = attachedTxInfo.blur.conOpt;
  63154. var txConOptSelect = attachedTxInfo.select.conOpt;
  63155. if (txConOptNormal != null || txConOptEmphasis != null || txConOptSelect != null || txConOptBlur != null) {
  63156. var textContent = el.getTextContent();
  63157. if (txConOptNormal === false) {
  63158. textContent && el.removeTextContent();
  63159. } else {
  63160. txConOptNormal = attachedTxInfo.normal.conOpt = txConOptNormal || {
  63161. type: 'text'
  63162. };
  63163. if (!textContent) {
  63164. textContent = createEl(txConOptNormal);
  63165. el.setTextContent(textContent);
  63166. } else {
  63167. // If in some case the performance issue arised, consider
  63168. // do not clearState but update cached normal state directly.
  63169. textContent.clearStates();
  63170. }
  63171. updateElNormal(null, textContent, dataIndex, txConOptNormal, null, seriesModel, isInit, true);
  63172. var txConStlOptNormal = txConOptNormal && txConOptNormal.style;
  63173. for (var i = 0; i < STATES.length; i++) {
  63174. var stateName = STATES[i];
  63175. if (stateName !== NORMAL) {
  63176. var txConOptOtherState = attachedTxInfo[stateName].conOpt;
  63177. updateElOnState(stateName, textContent, txConOptOtherState, retrieveStyleOptionOnState(txConOptNormal, txConOptOtherState, stateName), null);
  63178. }
  63179. }
  63180. txConStlOptNormal ? textContent.dirty() : textContent.markRedraw();
  63181. }
  63182. }
  63183. }
  63184. function processTxInfo(elOption, state, attachedTxInfo) {
  63185. var stateOpt = !state ? elOption : retrieveStateOption(elOption, state);
  63186. var styleOpt = !state ? elOption.style : retrieveStyleOptionOnState(elOption, stateOpt, EMPHASIS);
  63187. var elType = elOption.type;
  63188. var txCfg = stateOpt ? stateOpt.textConfig : null;
  63189. var txConOptNormal = elOption.textContent;
  63190. var txConOpt = !txConOptNormal ? null : !state ? txConOptNormal : retrieveStateOption(txConOptNormal, state);
  63191. if (styleOpt && ( // Because emphasis style has little info to detect legacy,
  63192. // if normal is legacy, emphasis is trade as legacy.
  63193. attachedTxInfo.isLegacy || isEC4CompatibleStyle(styleOpt, elType, !!txCfg, !!txConOpt))) {
  63194. attachedTxInfo.isLegacy = true;
  63195. var convertResult = convertFromEC4CompatibleStyle(styleOpt, elType, !state); // Explicitly specified `textConfig` and `textContent` has higher priority than
  63196. // the ones generated by legacy style. Otherwise if users use them and `api.style`
  63197. // at the same time, they not both work and hardly to known why.
  63198. if (!txCfg && convertResult.textConfig) {
  63199. txCfg = convertResult.textConfig;
  63200. }
  63201. if (!txConOpt && convertResult.textContent) {
  63202. txConOpt = convertResult.textContent;
  63203. }
  63204. }
  63205. if (!state && txConOpt) {
  63206. var txConOptNormal_1 = txConOpt; // `textContent: {type: 'text'}`, the "type" is easy to be missing. So we tolerate it.
  63207. !txConOptNormal_1.type && (txConOptNormal_1.type = 'text');
  63208. if ("development" !== 'production') {
  63209. // Do not tolerate incorret type for forward compat.
  63210. assert(txConOptNormal_1.type === 'text', 'textContent.type must be "text"');
  63211. }
  63212. }
  63213. var info = !state ? attachedTxInfo.normal : attachedTxInfo[state];
  63214. info.cfg = txCfg;
  63215. info.conOpt = txConOpt;
  63216. }
  63217. function retrieveStateOption(elOption, state) {
  63218. return !state ? elOption : elOption ? elOption[state] : null;
  63219. }
  63220. function retrieveStyleOptionOnState(stateOptionNormal, stateOption, state) {
  63221. var style = stateOption && stateOption.style;
  63222. if (style == null && state === EMPHASIS && stateOptionNormal) {
  63223. style = stateOptionNormal.styleEmphasis;
  63224. }
  63225. return style;
  63226. } // Usage:
  63227. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
  63228. // the existing children will not be removed, and enables the feature that
  63229. // update some of the props of some of the children simply by construct
  63230. // the returned children of `renderItem` like:
  63231. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  63232. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  63233. // by child.name. But that might be lower performance.
  63234. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  63235. // replaced totally.
  63236. // (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
  63237. //
  63238. // For implementation simpleness, do not provide a direct way to remove sinlge
  63239. // child (otherwise the total indicies of the children array have to be modified).
  63240. // User can remove a single child by set its `ignore` as `true`.
  63241. function mergeChildren(api, el, dataIndex, elOption, seriesModel) {
  63242. var newChildren = elOption.children;
  63243. var newLen = newChildren ? newChildren.length : 0;
  63244. var mergeChildren = elOption.$mergeChildren; // `diffChildrenByName` has been deprecated.
  63245. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  63246. var notMerge = mergeChildren === false; // For better performance on roam update, only enter if necessary.
  63247. if (!newLen && !byName && !notMerge) {
  63248. return;
  63249. }
  63250. if (byName) {
  63251. diffGroupChildren({
  63252. api: api,
  63253. oldChildren: el.children() || [],
  63254. newChildren: newChildren || [],
  63255. dataIndex: dataIndex,
  63256. seriesModel: seriesModel,
  63257. group: el
  63258. });
  63259. return;
  63260. }
  63261. notMerge && el.removeAll(); // Mapping children of a group simply by index, which
  63262. // might be better performance.
  63263. var index = 0;
  63264. for (; index < newLen; index++) {
  63265. newChildren[index] && doCreateOrUpdateEl(api, el.childAt(index), dataIndex, newChildren[index], seriesModel, el);
  63266. }
  63267. for (var i = el.childCount() - 1; i >= index; i--) {
  63268. // Do not supprot leave elements that are not mentioned in the latest
  63269. // `renderItem` return. Otherwise users may not have a clear and simple
  63270. // concept that how to contorl all of the elements.
  63271. doRemoveEl(el.childAt(i), seriesModel, el);
  63272. }
  63273. }
  63274. function diffGroupChildren(context) {
  63275. new DataDiffer(context.oldChildren, context.newChildren, getKey, getKey, context).add(processAddUpdate).update(processAddUpdate).remove(processRemove).execute();
  63276. }
  63277. function getKey(item, idx) {
  63278. var name = item && item.name;
  63279. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  63280. }
  63281. function processAddUpdate(newIndex, oldIndex) {
  63282. var context = this.context;
  63283. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  63284. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  63285. doCreateOrUpdateEl(context.api, child, context.dataIndex, childOption, context.seriesModel, context.group);
  63286. }
  63287. function processRemove(oldIndex) {
  63288. var context = this.context;
  63289. var child = context.oldChildren[oldIndex];
  63290. doRemoveEl(child, context.seriesModel, context.group);
  63291. }
  63292. function doRemoveEl(el, seriesModel, group) {
  63293. if (el) {
  63294. var leaveToProps = customInnerStore(el).leaveToProps;
  63295. leaveToProps ? updateProps(el, leaveToProps, seriesModel, {
  63296. cb: function () {
  63297. group.remove(el);
  63298. }
  63299. }) : group.remove(el);
  63300. }
  63301. }
  63302. /**
  63303. * @return SVG Path data.
  63304. */
  63305. function getPathData(shape) {
  63306. // "d" follows the SVG convention.
  63307. return shape && (shape.pathData || shape.d);
  63308. }
  63309. function hasOwnPathData(shape) {
  63310. return shape && (hasOwn(shape, 'pathData') || hasOwn(shape, 'd'));
  63311. }
  63312. function install$r(registers) {
  63313. registers.registerChartView(CustomChartView);
  63314. registers.registerSeriesModel(CustomSeriesModel);
  63315. }
  63316. var inner$a = makeInner();
  63317. var clone$3 = clone;
  63318. var bind$1 = bind;
  63319. /**
  63320. * Base axis pointer class in 2D.
  63321. */
  63322. var BaseAxisPointer =
  63323. /** @class */
  63324. function () {
  63325. function BaseAxisPointer() {
  63326. this._dragging = false;
  63327. /**
  63328. * In px, arbitrary value. Do not set too small,
  63329. * no animation is ok for most cases.
  63330. */
  63331. this.animationThreshold = 15;
  63332. }
  63333. /**
  63334. * @implement
  63335. */
  63336. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  63337. var value = axisPointerModel.get('value');
  63338. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  63339. // be replaced when user calling setOption in not merge mode.
  63340. this._axisModel = axisModel;
  63341. this._axisPointerModel = axisPointerModel;
  63342. this._api = api; // Optimize: `render` will be called repeatly during mouse move.
  63343. // So it is power consuming if performing `render` each time,
  63344. // especially on mobile device.
  63345. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  63346. return;
  63347. }
  63348. this._lastValue = value;
  63349. this._lastStatus = status;
  63350. var group = this._group;
  63351. var handle = this._handle;
  63352. if (!status || status === 'hide') {
  63353. // Do not clear here, for animation better.
  63354. group && group.hide();
  63355. handle && handle.hide();
  63356. return;
  63357. }
  63358. group && group.show();
  63359. handle && handle.show(); // Otherwise status is 'show'
  63360. var elOption = {};
  63361. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  63362. var graphicKey = elOption.graphicKey;
  63363. if (graphicKey !== this._lastGraphicKey) {
  63364. this.clear(api);
  63365. }
  63366. this._lastGraphicKey = graphicKey;
  63367. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  63368. if (!group) {
  63369. group = this._group = new Group();
  63370. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  63371. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  63372. api.getZr().add(group);
  63373. } else {
  63374. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  63375. this.updatePointerEl(group, elOption, doUpdateProps);
  63376. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  63377. }
  63378. updateMandatoryProps(group, axisPointerModel, true);
  63379. this._renderHandle(value);
  63380. };
  63381. /**
  63382. * @implement
  63383. */
  63384. BaseAxisPointer.prototype.remove = function (api) {
  63385. this.clear(api);
  63386. };
  63387. /**
  63388. * @implement
  63389. */
  63390. BaseAxisPointer.prototype.dispose = function (api) {
  63391. this.clear(api);
  63392. };
  63393. /**
  63394. * @protected
  63395. */
  63396. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  63397. var animation = axisPointerModel.get('animation');
  63398. var axis = axisModel.axis;
  63399. var isCategoryAxis = axis.type === 'category';
  63400. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  63401. if (!useSnap && !isCategoryAxis) {
  63402. return false;
  63403. }
  63404. if (animation === 'auto' || animation == null) {
  63405. var animationThreshold = this.animationThreshold;
  63406. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  63407. return true;
  63408. } // It is important to auto animation when snap used. Consider if there is
  63409. // a dataZoom, animation will be disabled when too many points exist, while
  63410. // it will be enabled for better visual effect when little points exist.
  63411. if (useSnap) {
  63412. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  63413. var axisExtent = axis.getExtent(); // Approximate band width
  63414. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  63415. }
  63416. return false;
  63417. }
  63418. return animation === true;
  63419. };
  63420. /**
  63421. * add {pointer, label, graphicKey} to elOption
  63422. * @protected
  63423. */
  63424. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {// Shoule be implemenented by sub-class.
  63425. };
  63426. /**
  63427. * @protected
  63428. */
  63429. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  63430. var pointerOption = elOption.pointer;
  63431. if (pointerOption) {
  63432. var pointerEl = inner$a(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  63433. group.add(pointerEl);
  63434. }
  63435. };
  63436. /**
  63437. * @protected
  63438. */
  63439. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  63440. if (elOption.label) {
  63441. var labelEl = inner$a(group).labelEl = new ZRText(clone$3(elOption.label));
  63442. group.add(labelEl);
  63443. updateLabelShowHide(labelEl, axisPointerModel);
  63444. }
  63445. };
  63446. /**
  63447. * @protected
  63448. */
  63449. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  63450. var pointerEl = inner$a(group).pointerEl;
  63451. if (pointerEl && elOption.pointer) {
  63452. pointerEl.setStyle(elOption.pointer.style);
  63453. updateProps(pointerEl, {
  63454. shape: elOption.pointer.shape
  63455. });
  63456. }
  63457. };
  63458. /**
  63459. * @protected
  63460. */
  63461. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  63462. var labelEl = inner$a(group).labelEl;
  63463. if (labelEl) {
  63464. labelEl.setStyle(elOption.label.style);
  63465. updateProps(labelEl, {
  63466. // Consider text length change in vertical axis, animation should
  63467. // be used on shape, otherwise the effect will be weird.
  63468. // TODOTODO
  63469. // shape: elOption.label.shape,
  63470. x: elOption.label.x,
  63471. y: elOption.label.y
  63472. });
  63473. updateLabelShowHide(labelEl, axisPointerModel);
  63474. }
  63475. };
  63476. /**
  63477. * @private
  63478. */
  63479. BaseAxisPointer.prototype._renderHandle = function (value) {
  63480. if (this._dragging || !this.updateHandleTransform) {
  63481. return;
  63482. }
  63483. var axisPointerModel = this._axisPointerModel;
  63484. var zr = this._api.getZr();
  63485. var handle = this._handle;
  63486. var handleModel = axisPointerModel.getModel('handle');
  63487. var status = axisPointerModel.get('status');
  63488. if (!handleModel.get('show') || !status || status === 'hide') {
  63489. handle && zr.remove(handle);
  63490. this._handle = null;
  63491. return;
  63492. }
  63493. var isInit;
  63494. if (!this._handle) {
  63495. isInit = true;
  63496. handle = this._handle = createIcon(handleModel.get('icon'), {
  63497. cursor: 'move',
  63498. draggable: true,
  63499. onmousemove: function (e) {
  63500. // Fot mobile devicem, prevent screen slider on the button.
  63501. stop(e.event);
  63502. },
  63503. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  63504. drift: bind$1(this._onHandleDragMove, this),
  63505. ondragend: bind$1(this._onHandleDragEnd, this)
  63506. });
  63507. zr.add(handle);
  63508. }
  63509. updateMandatoryProps(handle, axisPointerModel, false); // update style
  63510. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'])); // update position
  63511. var handleSize = handleModel.get('size');
  63512. if (!isArray(handleSize)) {
  63513. handleSize = [handleSize, handleSize];
  63514. }
  63515. handle.scaleX = handleSize[0] / 2;
  63516. handle.scaleY = handleSize[1] / 2;
  63517. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  63518. this._moveHandleToValue(value, isInit);
  63519. };
  63520. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  63521. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  63522. };
  63523. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  63524. var handle = this._handle;
  63525. if (!handle) {
  63526. return;
  63527. }
  63528. this._dragging = true; // Persistent for throttle.
  63529. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  63530. this._payloadInfo = trans;
  63531. handle.stopAnimation();
  63532. handle.attr(getHandleTransProps(trans));
  63533. inner$a(handle).lastProp = null;
  63534. this._doDispatchAxisPointer();
  63535. };
  63536. /**
  63537. * Throttled method.
  63538. */
  63539. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  63540. var handle = this._handle;
  63541. if (!handle) {
  63542. return;
  63543. }
  63544. var payloadInfo = this._payloadInfo;
  63545. var axisModel = this._axisModel;
  63546. this._api.dispatchAction({
  63547. type: 'updateAxisPointer',
  63548. x: payloadInfo.cursorPoint[0],
  63549. y: payloadInfo.cursorPoint[1],
  63550. tooltipOption: payloadInfo.tooltipOption,
  63551. axesInfo: [{
  63552. axisDim: axisModel.axis.dim,
  63553. axisIndex: axisModel.componentIndex
  63554. }]
  63555. });
  63556. };
  63557. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  63558. this._dragging = false;
  63559. var handle = this._handle;
  63560. if (!handle) {
  63561. return;
  63562. }
  63563. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  63564. // axisPointer. So move handle to align the exact value position when
  63565. // drag ended.
  63566. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  63567. // button, and will be hidden after finger left handle button.
  63568. this._api.dispatchAction({
  63569. type: 'hideTip'
  63570. });
  63571. };
  63572. /**
  63573. * @private
  63574. */
  63575. BaseAxisPointer.prototype.clear = function (api) {
  63576. this._lastValue = null;
  63577. this._lastStatus = null;
  63578. var zr = api.getZr();
  63579. var group = this._group;
  63580. var handle = this._handle;
  63581. if (zr && group) {
  63582. this._lastGraphicKey = null;
  63583. group && zr.remove(group);
  63584. handle && zr.remove(handle);
  63585. this._group = null;
  63586. this._handle = null;
  63587. this._payloadInfo = null;
  63588. }
  63589. };
  63590. /**
  63591. * @protected
  63592. */
  63593. BaseAxisPointer.prototype.doClear = function () {// Implemented by sub-class if necessary.
  63594. };
  63595. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  63596. xDimIndex = xDimIndex || 0;
  63597. return {
  63598. x: xy[xDimIndex],
  63599. y: xy[1 - xDimIndex],
  63600. width: wh[xDimIndex],
  63601. height: wh[1 - xDimIndex]
  63602. };
  63603. };
  63604. return BaseAxisPointer;
  63605. }();
  63606. function updateProps$1(animationModel, moveAnimation, el, props) {
  63607. // Animation optimize.
  63608. if (!propsEqual(inner$a(el).lastProp, props)) {
  63609. inner$a(el).lastProp = props;
  63610. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  63611. }
  63612. }
  63613. function propsEqual(lastProps, newProps) {
  63614. if (isObject(lastProps) && isObject(newProps)) {
  63615. var equals_1 = true;
  63616. each(newProps, function (item, key) {
  63617. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  63618. });
  63619. return !!equals_1;
  63620. } else {
  63621. return lastProps === newProps;
  63622. }
  63623. }
  63624. function updateLabelShowHide(labelEl, axisPointerModel) {
  63625. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  63626. }
  63627. function getHandleTransProps(trans) {
  63628. return {
  63629. x: trans.x || 0,
  63630. y: trans.y || 0,
  63631. rotation: trans.rotation || 0
  63632. };
  63633. }
  63634. function updateMandatoryProps(group, axisPointerModel, silent) {
  63635. var z = axisPointerModel.get('z');
  63636. var zlevel = axisPointerModel.get('zlevel');
  63637. group && group.traverse(function (el) {
  63638. if (el.type !== 'group') {
  63639. z != null && (el.z = z);
  63640. zlevel != null && (el.zlevel = zlevel);
  63641. el.silent = silent;
  63642. }
  63643. });
  63644. }
  63645. function buildElStyle(axisPointerModel) {
  63646. var axisPointerType = axisPointerModel.get('type');
  63647. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  63648. var style;
  63649. if (axisPointerType === 'line') {
  63650. style = styleModel.getLineStyle();
  63651. style.fill = null;
  63652. } else if (axisPointerType === 'shadow') {
  63653. style = styleModel.getAreaStyle();
  63654. style.stroke = null;
  63655. }
  63656. return style;
  63657. }
  63658. /**
  63659. * @param {Function} labelPos {align, verticalAlign, position}
  63660. */
  63661. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  63662. var value = axisPointerModel.get('value');
  63663. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  63664. precision: axisPointerModel.get(['label', 'precision']),
  63665. formatter: axisPointerModel.get(['label', 'formatter'])
  63666. });
  63667. var labelModel = axisPointerModel.getModel('label');
  63668. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  63669. var font = labelModel.getFont();
  63670. var textRect = getBoundingRect(text, font);
  63671. var position = labelPos.position;
  63672. var width = textRect.width + paddings[1] + paddings[3];
  63673. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  63674. var align = labelPos.align;
  63675. align === 'right' && (position[0] -= width);
  63676. align === 'center' && (position[0] -= width / 2);
  63677. var verticalAlign = labelPos.verticalAlign;
  63678. verticalAlign === 'bottom' && (position[1] -= height);
  63679. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  63680. confineInContainer(position, width, height, api);
  63681. var bgColor = labelModel.get('backgroundColor');
  63682. if (!bgColor || bgColor === 'auto') {
  63683. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  63684. }
  63685. elOption.label = {
  63686. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  63687. x: position[0],
  63688. y: position[1],
  63689. style: createTextStyle(labelModel, {
  63690. text: text,
  63691. font: font,
  63692. fill: labelModel.getTextColor(),
  63693. padding: paddings,
  63694. backgroundColor: bgColor
  63695. }),
  63696. // Lable should be over axisPointer.
  63697. z2: 10
  63698. };
  63699. } // Do not overflow ec container
  63700. function confineInContainer(position, width, height, api) {
  63701. var viewWidth = api.getWidth();
  63702. var viewHeight = api.getHeight();
  63703. position[0] = Math.min(position[0] + width, viewWidth) - width;
  63704. position[1] = Math.min(position[1] + height, viewHeight) - height;
  63705. position[0] = Math.max(position[0], 0);
  63706. position[1] = Math.max(position[1], 0);
  63707. }
  63708. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  63709. value = axis.scale.parse(value);
  63710. var text = axis.scale.getLabel({
  63711. value: value
  63712. }, {
  63713. // If `precision` is set, width can be fixed (like '12.00500'), which
  63714. // helps to debounce when when moving label.
  63715. precision: opt.precision
  63716. });
  63717. var formatter = opt.formatter;
  63718. if (formatter) {
  63719. var params_1 = {
  63720. value: getAxisRawValue(axis, {
  63721. value: value
  63722. }),
  63723. axisDimension: axis.dim,
  63724. axisIndex: axis.index,
  63725. seriesData: []
  63726. };
  63727. each(seriesDataIndices, function (idxItem) {
  63728. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  63729. var dataIndex = idxItem.dataIndexInside;
  63730. var dataParams = series && series.getDataParams(dataIndex);
  63731. dataParams && params_1.seriesData.push(dataParams);
  63732. });
  63733. if (isString(formatter)) {
  63734. text = formatter.replace('{value}', text);
  63735. } else if (isFunction(formatter)) {
  63736. text = formatter(params_1);
  63737. }
  63738. }
  63739. return text;
  63740. }
  63741. function getTransformedPosition(axis, value, layoutInfo) {
  63742. var transform = create$1();
  63743. rotate(transform, transform, layoutInfo.rotation);
  63744. translate(transform, transform, layoutInfo.position);
  63745. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  63746. }
  63747. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  63748. // @ts-ignore
  63749. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  63750. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  63751. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  63752. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  63753. align: textLayout.textAlign,
  63754. verticalAlign: textLayout.textVerticalAlign
  63755. });
  63756. }
  63757. function makeLineShape(p1, p2, xDimIndex) {
  63758. xDimIndex = xDimIndex || 0;
  63759. return {
  63760. x1: p1[xDimIndex],
  63761. y1: p1[1 - xDimIndex],
  63762. x2: p2[xDimIndex],
  63763. y2: p2[1 - xDimIndex]
  63764. };
  63765. }
  63766. function makeRectShape(xy, wh, xDimIndex) {
  63767. xDimIndex = xDimIndex || 0;
  63768. return {
  63769. x: xy[xDimIndex],
  63770. y: xy[1 - xDimIndex],
  63771. width: wh[xDimIndex],
  63772. height: wh[1 - xDimIndex]
  63773. };
  63774. }
  63775. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  63776. return {
  63777. cx: cx,
  63778. cy: cy,
  63779. r0: r0,
  63780. r: r,
  63781. startAngle: startAngle,
  63782. endAngle: endAngle,
  63783. clockwise: true
  63784. };
  63785. }
  63786. var CartesianAxisPointer =
  63787. /** @class */
  63788. function (_super) {
  63789. __extends(CartesianAxisPointer, _super);
  63790. function CartesianAxisPointer() {
  63791. return _super !== null && _super.apply(this, arguments) || this;
  63792. }
  63793. /**
  63794. * @override
  63795. */
  63796. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  63797. var axis = axisModel.axis;
  63798. var grid = axis.grid;
  63799. var axisPointerType = axisPointerModel.get('type');
  63800. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  63801. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  63802. if (axisPointerType && axisPointerType !== 'none') {
  63803. var elStyle = buildElStyle(axisPointerModel);
  63804. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  63805. pointerOption.style = elStyle;
  63806. elOption.graphicKey = pointerOption.type;
  63807. elOption.pointer = pointerOption;
  63808. }
  63809. var layoutInfo = layout$1(grid.model, axisModel);
  63810. buildCartesianSingleLabelElOption( // @ts-ignore
  63811. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  63812. };
  63813. /**
  63814. * @override
  63815. */
  63816. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  63817. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  63818. labelInside: false
  63819. }); // @ts-ignore
  63820. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  63821. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  63822. return {
  63823. x: pos[0],
  63824. y: pos[1],
  63825. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  63826. };
  63827. };
  63828. /**
  63829. * @override
  63830. */
  63831. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  63832. var axis = axisModel.axis;
  63833. var grid = axis.grid;
  63834. var axisExtent = axis.getGlobalExtent(true);
  63835. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  63836. var dimIndex = axis.dim === 'x' ? 0 : 1;
  63837. var currPosition = [transform.x, transform.y];
  63838. currPosition[dimIndex] += delta[dimIndex];
  63839. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  63840. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  63841. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  63842. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  63843. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  63844. var tooltipOptions = [{
  63845. verticalAlign: 'middle'
  63846. }, {
  63847. align: 'center'
  63848. }];
  63849. return {
  63850. x: currPosition[0],
  63851. y: currPosition[1],
  63852. rotation: transform.rotation,
  63853. cursorPoint: cursorPoint,
  63854. tooltipOption: tooltipOptions[dimIndex]
  63855. };
  63856. };
  63857. return CartesianAxisPointer;
  63858. }(BaseAxisPointer);
  63859. function getCartesian(grid, axis) {
  63860. var opt = {};
  63861. opt[axis.dim + 'AxisIndex'] = axis.index;
  63862. return grid.getCartesian(opt);
  63863. }
  63864. var pointerShapeBuilder = {
  63865. line: function (axis, pixelValue, otherExtent) {
  63866. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  63867. return {
  63868. type: 'Line',
  63869. subPixelOptimize: true,
  63870. shape: targetShape
  63871. };
  63872. },
  63873. shadow: function (axis, pixelValue, otherExtent) {
  63874. var bandWidth = Math.max(1, axis.getBandWidth());
  63875. var span = otherExtent[1] - otherExtent[0];
  63876. return {
  63877. type: 'Rect',
  63878. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  63879. };
  63880. }
  63881. };
  63882. function getAxisDimIndex(axis) {
  63883. return axis.dim === 'x' ? 0 : 1;
  63884. }
  63885. var AxisPointerModel =
  63886. /** @class */
  63887. function (_super) {
  63888. __extends(AxisPointerModel, _super);
  63889. function AxisPointerModel() {
  63890. var _this = _super !== null && _super.apply(this, arguments) || this;
  63891. _this.type = AxisPointerModel.type;
  63892. return _this;
  63893. }
  63894. AxisPointerModel.type = 'axisPointer';
  63895. AxisPointerModel.defaultOption = {
  63896. // 'auto' means that show when triggered by tooltip or handle.
  63897. show: 'auto',
  63898. zlevel: 0,
  63899. z: 50,
  63900. type: 'line',
  63901. // axispointer triggered by tootip determine snap automatically,
  63902. // see `modelHelper`.
  63903. snap: false,
  63904. triggerTooltip: true,
  63905. value: null,
  63906. status: null,
  63907. link: [],
  63908. // Do not set 'auto' here, otherwise global animation: false
  63909. // will not effect at this axispointer.
  63910. animation: null,
  63911. animationDurationUpdate: 200,
  63912. lineStyle: {
  63913. color: '#B9BEC9',
  63914. width: 1,
  63915. type: 'dashed'
  63916. },
  63917. shadowStyle: {
  63918. color: 'rgba(210,219,238,0.2)'
  63919. },
  63920. label: {
  63921. show: true,
  63922. formatter: null,
  63923. precision: 'auto',
  63924. margin: 3,
  63925. color: '#fff',
  63926. padding: [5, 7, 5, 7],
  63927. backgroundColor: 'auto',
  63928. borderColor: null,
  63929. borderWidth: 0,
  63930. borderRadius: 3
  63931. },
  63932. handle: {
  63933. show: false,
  63934. // eslint-disable-next-line
  63935. 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',
  63936. size: 45,
  63937. // handle margin is from symbol center to axis, which is stable when circular move.
  63938. margin: 50,
  63939. // color: '#1b8bbd'
  63940. // color: '#2f4554'
  63941. color: '#333',
  63942. shadowBlur: 3,
  63943. shadowColor: '#aaa',
  63944. shadowOffsetX: 0,
  63945. shadowOffsetY: 2,
  63946. // For mobile performance
  63947. throttle: 40
  63948. }
  63949. };
  63950. return AxisPointerModel;
  63951. }(ComponentModel);
  63952. var inner$b = makeInner();
  63953. var each$7 = each;
  63954. /**
  63955. * @param {string} key
  63956. * @param {module:echarts/ExtensionAPI} api
  63957. * @param {Function} handler
  63958. * param: {string} currTrigger
  63959. * param: {Array.<number>} point
  63960. */
  63961. function register(key, api, handler) {
  63962. if (env.node) {
  63963. return;
  63964. }
  63965. var zr = api.getZr();
  63966. inner$b(zr).records || (inner$b(zr).records = {});
  63967. initGlobalListeners(zr, api);
  63968. var record = inner$b(zr).records[key] || (inner$b(zr).records[key] = {});
  63969. record.handler = handler;
  63970. }
  63971. function initGlobalListeners(zr, api) {
  63972. if (inner$b(zr).initialized) {
  63973. return;
  63974. }
  63975. inner$b(zr).initialized = true;
  63976. useHandler('click', curry(doEnter, 'click'));
  63977. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  63978. useHandler('globalout', onLeave);
  63979. function useHandler(eventType, cb) {
  63980. zr.on(eventType, function (e) {
  63981. var dis = makeDispatchAction(api);
  63982. each$7(inner$b(zr).records, function (record) {
  63983. record && cb(record, e, dis.dispatchAction);
  63984. });
  63985. dispatchTooltipFinally(dis.pendings, api);
  63986. });
  63987. }
  63988. }
  63989. function dispatchTooltipFinally(pendings, api) {
  63990. var showLen = pendings.showTip.length;
  63991. var hideLen = pendings.hideTip.length;
  63992. var actuallyPayload;
  63993. if (showLen) {
  63994. actuallyPayload = pendings.showTip[showLen - 1];
  63995. } else if (hideLen) {
  63996. actuallyPayload = pendings.hideTip[hideLen - 1];
  63997. }
  63998. if (actuallyPayload) {
  63999. actuallyPayload.dispatchAction = null;
  64000. api.dispatchAction(actuallyPayload);
  64001. }
  64002. }
  64003. function onLeave(record, e, dispatchAction) {
  64004. record.handler('leave', null, dispatchAction);
  64005. }
  64006. function doEnter(currTrigger, record, e, dispatchAction) {
  64007. record.handler(currTrigger, e, dispatchAction);
  64008. }
  64009. function makeDispatchAction(api) {
  64010. var pendings = {
  64011. showTip: [],
  64012. hideTip: []
  64013. }; // FIXME
  64014. // better approach?
  64015. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  64016. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  64017. // So we have to add "final stage" to merge those dispatched actions.
  64018. var dispatchAction = function (payload) {
  64019. var pendingList = pendings[payload.type];
  64020. if (pendingList) {
  64021. pendingList.push(payload);
  64022. } else {
  64023. payload.dispatchAction = dispatchAction;
  64024. api.dispatchAction(payload);
  64025. }
  64026. };
  64027. return {
  64028. dispatchAction: dispatchAction,
  64029. pendings: pendings
  64030. };
  64031. }
  64032. function unregister(key, api) {
  64033. if (env.node) {
  64034. return;
  64035. }
  64036. var zr = api.getZr();
  64037. var record = (inner$b(zr).records || {})[key];
  64038. if (record) {
  64039. inner$b(zr).records[key] = null;
  64040. }
  64041. }
  64042. var AxisPointerView =
  64043. /** @class */
  64044. function (_super) {
  64045. __extends(AxisPointerView, _super);
  64046. function AxisPointerView() {
  64047. var _this = _super !== null && _super.apply(this, arguments) || this;
  64048. _this.type = AxisPointerView.type;
  64049. return _this;
  64050. }
  64051. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  64052. var globalTooltipModel = ecModel.getComponent('tooltip');
  64053. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  64054. // AxisPointerView to be independent to Tooltip.
  64055. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  64056. // If 'none', it is not controlled by mouse totally.
  64057. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  64058. dispatchAction({
  64059. type: 'updateAxisPointer',
  64060. currTrigger: currTrigger,
  64061. x: e && e.offsetX,
  64062. y: e && e.offsetY
  64063. });
  64064. }
  64065. });
  64066. };
  64067. AxisPointerView.prototype.remove = function (ecModel, api) {
  64068. unregister('axisPointer', api);
  64069. };
  64070. AxisPointerView.prototype.dispose = function (ecModel, api) {
  64071. unregister('axisPointer', api);
  64072. };
  64073. AxisPointerView.type = 'axisPointer';
  64074. return AxisPointerView;
  64075. }(ComponentView);
  64076. /**
  64077. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  64078. * @param ecModel
  64079. * @return {point: [x, y], el: ...} point Will not be null.
  64080. */
  64081. function findPointFromSeries(finder, ecModel) {
  64082. var point = [];
  64083. var seriesIndex = finder.seriesIndex;
  64084. var seriesModel;
  64085. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  64086. return {
  64087. point: []
  64088. };
  64089. }
  64090. var data = seriesModel.getData();
  64091. var dataIndex = queryDataIndex(data, finder);
  64092. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  64093. return {
  64094. point: []
  64095. };
  64096. }
  64097. var el = data.getItemGraphicEl(dataIndex);
  64098. var coordSys = seriesModel.coordinateSystem;
  64099. if (seriesModel.getTooltipPosition) {
  64100. point = seriesModel.getTooltipPosition(dataIndex) || [];
  64101. } else if (coordSys && coordSys.dataToPoint) {
  64102. if (finder.isStacked) {
  64103. var baseAxis = coordSys.getBaseAxis();
  64104. var valueAxis = coordSys.getOtherAxis(baseAxis);
  64105. var valueAxisDim = valueAxis.dim;
  64106. var baseAxisDim = baseAxis.dim;
  64107. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  64108. var baseDim = data.mapDimension(baseAxisDim);
  64109. var stackedData = [];
  64110. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  64111. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  64112. point = coordSys.dataToPoint(stackedData) || [];
  64113. } else {
  64114. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  64115. return data.mapDimension(dim);
  64116. }), dataIndex)) || [];
  64117. }
  64118. } else if (el) {
  64119. // Use graphic bounding rect
  64120. var rect = el.getBoundingRect().clone();
  64121. rect.applyTransform(el.transform);
  64122. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  64123. }
  64124. return {
  64125. point: point,
  64126. el: el
  64127. };
  64128. }
  64129. var inner$c = makeInner();
  64130. /**
  64131. * Basic logic: check all axis, if they do not demand show/highlight,
  64132. * then hide/downplay them.
  64133. *
  64134. * @return content of event obj for echarts.connect.
  64135. */
  64136. function axisTrigger(payload, ecModel, api) {
  64137. var currTrigger = payload.currTrigger;
  64138. var point = [payload.x, payload.y];
  64139. var finder = payload;
  64140. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  64141. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  64142. // See #6121. But we are not able to reproduce it yet.
  64143. if (!coordSysAxesInfo) {
  64144. return;
  64145. }
  64146. if (illegalPoint(point)) {
  64147. // Used in the default behavior of `connection`: use the sample seriesIndex
  64148. // and dataIndex. And also used in the tooltipView trigger.
  64149. point = findPointFromSeries({
  64150. seriesIndex: finder.seriesIndex,
  64151. // Do not use dataIndexInside from other ec instance.
  64152. // FIXME: auto detect it?
  64153. dataIndex: finder.dataIndex
  64154. }, ecModel).point;
  64155. }
  64156. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  64157. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  64158. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  64159. // and dataIndex.
  64160. var inputAxesInfo = finder.axesInfo;
  64161. var axesInfo = coordSysAxesInfo.axesInfo;
  64162. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  64163. var outputPayload = {};
  64164. var showValueMap = {};
  64165. var dataByCoordSys = {
  64166. list: [],
  64167. map: {}
  64168. };
  64169. var updaters = {
  64170. showPointer: curry(showPointer, showValueMap),
  64171. showTooltip: curry(showTooltip, dataByCoordSys)
  64172. }; // Process for triggered axes.
  64173. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  64174. // If a point given, it must be contained by the coordinate system.
  64175. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  64176. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  64177. var axis = axisInfo.axis;
  64178. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  64179. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  64180. var val = inputAxisInfo && inputAxisInfo.value;
  64181. if (val == null && !isIllegalPoint) {
  64182. val = axis.pointToData(point);
  64183. }
  64184. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  64185. }
  64186. });
  64187. }); // Process for linked axes.
  64188. var linkTriggers = {};
  64189. each(axesInfo, function (tarAxisInfo, tarKey) {
  64190. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  64191. if (linkGroup && !showValueMap[tarKey]) {
  64192. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  64193. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  64194. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  64195. var val = srcValItem.value;
  64196. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  64197. linkTriggers[tarAxisInfo.key] = val;
  64198. }
  64199. });
  64200. }
  64201. });
  64202. each(linkTriggers, function (val, tarKey) {
  64203. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  64204. });
  64205. updateModelActually(showValueMap, axesInfo, outputPayload);
  64206. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  64207. dispatchHighDownActually(axesInfo, dispatchAction, api);
  64208. return outputPayload;
  64209. }
  64210. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  64211. var axis = axisInfo.axis;
  64212. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  64213. return;
  64214. }
  64215. if (!axisInfo.involveSeries) {
  64216. updaters.showPointer(axisInfo, newValue);
  64217. return;
  64218. } // Heavy calculation. So put it after axis.containData checking.
  64219. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  64220. var payloadBatch = payloadInfo.payloadBatch;
  64221. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  64222. // By default use the first involved series data as a sample to connect.
  64223. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  64224. extend(outputFinder, payloadBatch[0]);
  64225. } // If no linkSource input, this process is for collecting link
  64226. // target, where snap should not be accepted.
  64227. if (!noSnap && axisInfo.snap) {
  64228. if (axis.containData(snapToValue) && snapToValue != null) {
  64229. newValue = snapToValue;
  64230. }
  64231. }
  64232. updaters.showPointer(axisInfo, newValue, payloadBatch); // Tooltip should always be snapToValue, otherwise there will be
  64233. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  64234. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  64235. }
  64236. function buildPayloadsBySeries(value, axisInfo) {
  64237. var axis = axisInfo.axis;
  64238. var dim = axis.dim;
  64239. var snapToValue = value;
  64240. var payloadBatch = [];
  64241. var minDist = Number.MAX_VALUE;
  64242. var minDiff = -1;
  64243. each(axisInfo.seriesModels, function (series, idx) {
  64244. var dataDim = series.getData().mapDimensionsAll(dim);
  64245. var seriesNestestValue;
  64246. var dataIndices;
  64247. if (series.getAxisTooltipData) {
  64248. var result = series.getAxisTooltipData(dataDim, value, axis);
  64249. dataIndices = result.dataIndices;
  64250. seriesNestestValue = result.nestestValue;
  64251. } else {
  64252. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  64253. // when data length is not same.
  64254. // false,
  64255. axis.type === 'category' ? 0.5 : null);
  64256. if (!dataIndices.length) {
  64257. return;
  64258. }
  64259. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  64260. }
  64261. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  64262. return;
  64263. }
  64264. var diff = value - seriesNestestValue;
  64265. var dist = Math.abs(diff); // Consider category case
  64266. if (dist <= minDist) {
  64267. if (dist < minDist || diff >= 0 && minDiff < 0) {
  64268. minDist = dist;
  64269. minDiff = diff;
  64270. snapToValue = seriesNestestValue;
  64271. payloadBatch.length = 0;
  64272. }
  64273. each(dataIndices, function (dataIndex) {
  64274. payloadBatch.push({
  64275. seriesIndex: series.seriesIndex,
  64276. dataIndexInside: dataIndex,
  64277. dataIndex: series.getData().getRawIndex(dataIndex)
  64278. });
  64279. });
  64280. }
  64281. });
  64282. return {
  64283. payloadBatch: payloadBatch,
  64284. snapToValue: snapToValue
  64285. };
  64286. }
  64287. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  64288. showValueMap[axisInfo.key] = {
  64289. value: value,
  64290. payloadBatch: payloadBatch
  64291. };
  64292. }
  64293. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  64294. var payloadBatch = payloadInfo.payloadBatch;
  64295. var axis = axisInfo.axis;
  64296. var axisModel = axis.model;
  64297. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  64298. // whose length will be used to judge whether dispatch action.
  64299. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  64300. return;
  64301. }
  64302. var coordSysModel = axisInfo.coordSys.model;
  64303. var coordSysKey = makeKey(coordSysModel);
  64304. var coordSysItem = dataByCoordSys.map[coordSysKey];
  64305. if (!coordSysItem) {
  64306. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  64307. coordSysId: coordSysModel.id,
  64308. coordSysIndex: coordSysModel.componentIndex,
  64309. coordSysType: coordSysModel.type,
  64310. coordSysMainType: coordSysModel.mainType,
  64311. dataByAxis: []
  64312. };
  64313. dataByCoordSys.list.push(coordSysItem);
  64314. }
  64315. coordSysItem.dataByAxis.push({
  64316. axisDim: axis.dim,
  64317. axisIndex: axisModel.componentIndex,
  64318. axisType: axisModel.type,
  64319. axisId: axisModel.id,
  64320. value: value,
  64321. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  64322. // depends that all models have been updated. So it should not be performed
  64323. // here. Considering axisPointerModel used here is volatile, which is hard
  64324. // to be retrieve in TooltipView, we prepare parameters here.
  64325. valueLabelOpt: {
  64326. precision: axisPointerModel.get(['label', 'precision']),
  64327. formatter: axisPointerModel.get(['label', 'formatter'])
  64328. },
  64329. seriesDataIndices: payloadBatch.slice()
  64330. });
  64331. }
  64332. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  64333. var outputAxesInfo = outputPayload.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  64334. each(axesInfo, function (axisInfo, key) {
  64335. var option = axisInfo.axisPointerModel.option;
  64336. var valItem = showValueMap[key];
  64337. if (valItem) {
  64338. !axisInfo.useHandle && (option.status = 'show');
  64339. option.value = valItem.value; // For label formatter param and highlight.
  64340. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  64341. } // When always show (e.g., handle used), remain
  64342. // original value and status.
  64343. else {
  64344. // If hide, value still need to be set, consider
  64345. // click legend to toggle axis blank.
  64346. !axisInfo.useHandle && (option.status = 'hide');
  64347. } // If status is 'hide', should be no info in payload.
  64348. option.status === 'show' && outputAxesInfo.push({
  64349. axisDim: axisInfo.axis.dim,
  64350. axisIndex: axisInfo.axis.model.componentIndex,
  64351. value: option.value
  64352. });
  64353. });
  64354. }
  64355. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  64356. // Basic logic: If no showTip required, hideTip will be dispatched.
  64357. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  64358. dispatchAction({
  64359. type: 'hideTip'
  64360. });
  64361. return;
  64362. } // In most case only one axis (or event one series is used). It is
  64363. // convinient to fetch payload.seriesIndex and payload.dataIndex
  64364. // dirtectly. So put the first seriesIndex and dataIndex of the first
  64365. // axis on the payload.
  64366. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  64367. dispatchAction({
  64368. type: 'showTip',
  64369. escapeConnect: true,
  64370. x: point[0],
  64371. y: point[1],
  64372. tooltipOption: payload.tooltipOption,
  64373. position: payload.position,
  64374. dataIndexInside: sampleItem.dataIndexInside,
  64375. dataIndex: sampleItem.dataIndex,
  64376. seriesIndex: sampleItem.seriesIndex,
  64377. dataByCoordSys: dataByCoordSys.list
  64378. });
  64379. }
  64380. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  64381. // FIXME
  64382. // highlight status modification shoule be a stage of main process?
  64383. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  64384. var zr = api.getZr();
  64385. var highDownKey = 'axisPointerLastHighlights';
  64386. var lastHighlights = inner$c(zr)[highDownKey] || {};
  64387. var newHighlights = inner$c(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  64388. // Build hash map and remove duplicate incidentally.
  64389. each(axesInfo, function (axisInfo, key) {
  64390. var option = axisInfo.axisPointerModel.option;
  64391. option.status === 'show' && each(option.seriesDataIndices, function (batchItem) {
  64392. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  64393. newHighlights[key] = batchItem;
  64394. });
  64395. }); // Diff.
  64396. var toHighlight = [];
  64397. var toDownplay = [];
  64398. each(lastHighlights, function (batchItem, key) {
  64399. !newHighlights[key] && toDownplay.push(batchItem);
  64400. });
  64401. each(newHighlights, function (batchItem, key) {
  64402. !lastHighlights[key] && toHighlight.push(batchItem);
  64403. });
  64404. toDownplay.length && api.dispatchAction({
  64405. type: 'downplay',
  64406. escapeConnect: true,
  64407. // Not blur others when highlight in axisPointer.
  64408. notBlur: true,
  64409. batch: toDownplay
  64410. });
  64411. toHighlight.length && api.dispatchAction({
  64412. type: 'highlight',
  64413. escapeConnect: true,
  64414. // Not blur others when highlight in axisPointer.
  64415. notBlur: true,
  64416. batch: toHighlight
  64417. });
  64418. }
  64419. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  64420. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  64421. var inputAxisInfo = inputAxesInfo[i];
  64422. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  64423. return inputAxisInfo;
  64424. }
  64425. }
  64426. }
  64427. function makeMapperParam(axisInfo) {
  64428. var axisModel = axisInfo.axis.model;
  64429. var item = {};
  64430. var dim = item.axisDim = axisInfo.axis.dim;
  64431. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  64432. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  64433. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  64434. return item;
  64435. }
  64436. function illegalPoint(point) {
  64437. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  64438. }
  64439. function install$s(registers) {
  64440. // CartesianAxisPointer is not supposed to be required here. But consider
  64441. // echarts.simple.js and online build tooltip, which only require gridSimple,
  64442. // CartesianAxisPointer should be able to required somewhere.
  64443. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  64444. registers.registerComponentModel(AxisPointerModel);
  64445. registers.registerComponentView(AxisPointerView);
  64446. registers.registerPreprocessor(function (option) {
  64447. // Always has a global axisPointerModel for default setting.
  64448. if (option) {
  64449. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  64450. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  64451. // is not set, remain null/undefined, otherwise it will
  64452. // override existent link setting.
  64453. if (link && !isArray(link)) {
  64454. option.axisPointer.link = [link];
  64455. }
  64456. }
  64457. }); // This process should proformed after coordinate systems created
  64458. // and series data processed. So put it on statistic processing stage.
  64459. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  64460. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  64461. // allAxesInfo should be updated when setOption performed.
  64462. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  64463. }); // Broadcast to all views.
  64464. registers.registerAction({
  64465. type: 'updateAxisPointer',
  64466. event: 'updateAxisPointer',
  64467. update: ':updateAxisPointer'
  64468. }, axisTrigger);
  64469. }
  64470. function install$t(registers) {
  64471. use(install$5);
  64472. use(install$s);
  64473. }
  64474. var PolarAxisPointer =
  64475. /** @class */
  64476. function (_super) {
  64477. __extends(PolarAxisPointer, _super);
  64478. function PolarAxisPointer() {
  64479. return _super !== null && _super.apply(this, arguments) || this;
  64480. }
  64481. /**
  64482. * @override
  64483. */
  64484. PolarAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  64485. var axis = axisModel.axis;
  64486. if (axis.dim === 'angle') {
  64487. this.animationThreshold = Math.PI / 18;
  64488. }
  64489. var polar = axis.polar;
  64490. var otherAxis = polar.getOtherAxis(axis);
  64491. var otherExtent = otherAxis.getExtent();
  64492. var coordValue = axis.dataToCoord(value);
  64493. var axisPointerType = axisPointerModel.get('type');
  64494. if (axisPointerType && axisPointerType !== 'none') {
  64495. var elStyle = buildElStyle(axisPointerModel);
  64496. var pointerOption = pointerShapeBuilder$1[axisPointerType](axis, polar, coordValue, otherExtent);
  64497. pointerOption.style = elStyle;
  64498. elOption.graphicKey = pointerOption.type;
  64499. elOption.pointer = pointerOption;
  64500. }
  64501. var labelMargin = axisPointerModel.get(['label', 'margin']);
  64502. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  64503. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  64504. };
  64505. return PolarAxisPointer;
  64506. }(BaseAxisPointer);
  64507. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  64508. var axis = axisModel.axis;
  64509. var coord = axis.dataToCoord(value);
  64510. var axisAngle = polar.getAngleAxis().getExtent()[0];
  64511. axisAngle = axisAngle / 180 * Math.PI;
  64512. var radiusExtent = polar.getRadiusAxis().getExtent();
  64513. var position;
  64514. var align;
  64515. var verticalAlign;
  64516. if (axis.dim === 'radius') {
  64517. var transform = create$1();
  64518. rotate(transform, transform, axisAngle);
  64519. translate(transform, transform, [polar.cx, polar.cy]);
  64520. position = applyTransform$1([coord, -labelMargin], transform);
  64521. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0; // @ts-ignore
  64522. var labelLayout = AxisBuilder.innerTextLayout(axisAngle, labelRotation * Math.PI / 180, -1);
  64523. align = labelLayout.textAlign;
  64524. verticalAlign = labelLayout.textVerticalAlign;
  64525. } else {
  64526. // angle axis
  64527. var r = radiusExtent[1];
  64528. position = polar.coordToPoint([r + labelMargin, coord]);
  64529. var cx = polar.cx;
  64530. var cy = polar.cy;
  64531. align = Math.abs(position[0] - cx) / r < 0.3 ? 'center' : position[0] > cx ? 'left' : 'right';
  64532. verticalAlign = Math.abs(position[1] - cy) / r < 0.3 ? 'middle' : position[1] > cy ? 'top' : 'bottom';
  64533. }
  64534. return {
  64535. position: position,
  64536. align: align,
  64537. verticalAlign: verticalAlign
  64538. };
  64539. }
  64540. var pointerShapeBuilder$1 = {
  64541. line: function (axis, polar, coordValue, otherExtent) {
  64542. return axis.dim === 'angle' ? {
  64543. type: 'Line',
  64544. shape: makeLineShape(polar.coordToPoint([otherExtent[0], coordValue]), polar.coordToPoint([otherExtent[1], coordValue]))
  64545. } : {
  64546. type: 'Circle',
  64547. shape: {
  64548. cx: polar.cx,
  64549. cy: polar.cy,
  64550. r: coordValue
  64551. }
  64552. };
  64553. },
  64554. shadow: function (axis, polar, coordValue, otherExtent) {
  64555. var bandWidth = Math.max(1, axis.getBandWidth());
  64556. var radian = Math.PI / 180;
  64557. return axis.dim === 'angle' ? {
  64558. type: 'Sector',
  64559. shape: makeSectorShape(polar.cx, polar.cy, otherExtent[0], otherExtent[1], // In ECharts y is negative if angle is positive
  64560. (-coordValue - bandWidth / 2) * radian, (-coordValue + bandWidth / 2) * radian)
  64561. } : {
  64562. type: 'Sector',
  64563. shape: makeSectorShape(polar.cx, polar.cy, coordValue - bandWidth / 2, coordValue + bandWidth / 2, 0, Math.PI * 2)
  64564. };
  64565. }
  64566. };
  64567. var PolarModel =
  64568. /** @class */
  64569. function (_super) {
  64570. __extends(PolarModel, _super);
  64571. function PolarModel() {
  64572. var _this = _super !== null && _super.apply(this, arguments) || this;
  64573. _this.type = PolarModel.type;
  64574. return _this;
  64575. }
  64576. PolarModel.prototype.findAxisModel = function (axisType) {
  64577. var foundAxisModel;
  64578. var ecModel = this.ecModel;
  64579. ecModel.eachComponent(axisType, function (axisModel) {
  64580. if (axisModel.getCoordSysModel() === this) {
  64581. foundAxisModel = axisModel;
  64582. }
  64583. }, this);
  64584. return foundAxisModel;
  64585. };
  64586. PolarModel.type = 'polar';
  64587. PolarModel.dependencies = ['radiusAxis', 'angleAxis'];
  64588. PolarModel.defaultOption = {
  64589. zlevel: 0,
  64590. z: 0,
  64591. center: ['50%', '50%'],
  64592. radius: '80%'
  64593. };
  64594. return PolarModel;
  64595. }(ComponentModel);
  64596. var PolarAxisModel =
  64597. /** @class */
  64598. function (_super) {
  64599. __extends(PolarAxisModel, _super);
  64600. function PolarAxisModel() {
  64601. return _super !== null && _super.apply(this, arguments) || this;
  64602. }
  64603. PolarAxisModel.prototype.getCoordSysModel = function () {
  64604. return this.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  64605. };
  64606. PolarAxisModel.type = 'polarAxis';
  64607. return PolarAxisModel;
  64608. }(ComponentModel);
  64609. mixin(PolarAxisModel, AxisModelCommonMixin);
  64610. var AngleAxisModel =
  64611. /** @class */
  64612. function (_super) {
  64613. __extends(AngleAxisModel, _super);
  64614. function AngleAxisModel() {
  64615. var _this = _super !== null && _super.apply(this, arguments) || this;
  64616. _this.type = AngleAxisModel.type;
  64617. return _this;
  64618. }
  64619. AngleAxisModel.type = 'angleAxis';
  64620. return AngleAxisModel;
  64621. }(PolarAxisModel);
  64622. var RadiusAxisModel =
  64623. /** @class */
  64624. function (_super) {
  64625. __extends(RadiusAxisModel, _super);
  64626. function RadiusAxisModel() {
  64627. var _this = _super !== null && _super.apply(this, arguments) || this;
  64628. _this.type = RadiusAxisModel.type;
  64629. return _this;
  64630. }
  64631. RadiusAxisModel.type = 'radiusAxis';
  64632. return RadiusAxisModel;
  64633. }(PolarAxisModel);
  64634. var RadiusAxis =
  64635. /** @class */
  64636. function (_super) {
  64637. __extends(RadiusAxis, _super);
  64638. function RadiusAxis(scale, radiusExtent) {
  64639. return _super.call(this, 'radius', scale, radiusExtent) || this;
  64640. }
  64641. RadiusAxis.prototype.pointToData = function (point, clamp) {
  64642. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  64643. };
  64644. return RadiusAxis;
  64645. }(Axis);
  64646. RadiusAxis.prototype.dataToRadius = Axis.prototype.dataToCoord;
  64647. RadiusAxis.prototype.radiusToData = Axis.prototype.coordToData;
  64648. var inner$d = makeInner();
  64649. var AngleAxis =
  64650. /** @class */
  64651. function (_super) {
  64652. __extends(AngleAxis, _super);
  64653. function AngleAxis(scale, angleExtent) {
  64654. return _super.call(this, 'angle', scale, angleExtent || [0, 360]) || this;
  64655. }
  64656. AngleAxis.prototype.pointToData = function (point, clamp) {
  64657. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  64658. };
  64659. /**
  64660. * Only be called in category axis.
  64661. * Angle axis uses text height to decide interval
  64662. *
  64663. * @override
  64664. * @return {number} Auto interval for cateogry axis tick and label
  64665. */
  64666. AngleAxis.prototype.calculateCategoryInterval = function () {
  64667. var axis = this;
  64668. var labelModel = axis.getLabelModel();
  64669. var ordinalScale = axis.scale;
  64670. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  64671. // avoid generating a long array by `getTicks`
  64672. // in large category data case.
  64673. var tickCount = ordinalScale.count();
  64674. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  64675. return 0;
  64676. }
  64677. var tickValue = ordinalExtent[0];
  64678. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  64679. var unitH = Math.abs(unitSpan); // Not precise, just use height as text width
  64680. // and each distance from axis line yet.
  64681. var rect = getBoundingRect(tickValue == null ? '' : tickValue + '', labelModel.getFont(), 'center', 'top');
  64682. var maxH = Math.max(rect.height, 7);
  64683. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  64684. isNaN(dh) && (dh = Infinity);
  64685. var interval = Math.max(0, Math.floor(dh));
  64686. var cache = inner$d(axis.model);
  64687. var lastAutoInterval = cache.lastAutoInterval;
  64688. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  64689. // otherwise the calculated interval might jitter when the zoom
  64690. // window size is close to the interval-changing size.
  64691. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  64692. // point is not the same when zooming in or zooming out.
  64693. && lastAutoInterval > interval) {
  64694. interval = lastAutoInterval;
  64695. } // Only update cache if cache not used, otherwise the
  64696. // changing of interval is too insensitive.
  64697. else {
  64698. cache.lastTickCount = tickCount;
  64699. cache.lastAutoInterval = interval;
  64700. }
  64701. return interval;
  64702. };
  64703. return AngleAxis;
  64704. }(Axis);
  64705. AngleAxis.prototype.dataToAngle = Axis.prototype.dataToCoord;
  64706. AngleAxis.prototype.angleToData = Axis.prototype.coordToData;
  64707. var polarDimensions = ['radius', 'angle'];
  64708. var Polar =
  64709. /** @class */
  64710. function () {
  64711. function Polar(name) {
  64712. this.dimensions = polarDimensions;
  64713. this.type = 'polar';
  64714. /**
  64715. * x of polar center
  64716. */
  64717. this.cx = 0;
  64718. /**
  64719. * y of polar center
  64720. */
  64721. this.cy = 0;
  64722. this._radiusAxis = new RadiusAxis();
  64723. this._angleAxis = new AngleAxis();
  64724. this.axisPointerEnabled = true;
  64725. this.name = name || '';
  64726. this._radiusAxis.polar = this._angleAxis.polar = this;
  64727. }
  64728. /**
  64729. * If contain coord
  64730. */
  64731. Polar.prototype.containPoint = function (point) {
  64732. var coord = this.pointToCoord(point);
  64733. return this._radiusAxis.contain(coord[0]) && this._angleAxis.contain(coord[1]);
  64734. };
  64735. /**
  64736. * If contain data
  64737. */
  64738. Polar.prototype.containData = function (data) {
  64739. return this._radiusAxis.containData(data[0]) && this._angleAxis.containData(data[1]);
  64740. };
  64741. Polar.prototype.getAxis = function (dim) {
  64742. var key = '_' + dim + 'Axis';
  64743. return this[key];
  64744. };
  64745. Polar.prototype.getAxes = function () {
  64746. return [this._radiusAxis, this._angleAxis];
  64747. };
  64748. /**
  64749. * Get axes by type of scale
  64750. */
  64751. Polar.prototype.getAxesByScale = function (scaleType) {
  64752. var axes = [];
  64753. var angleAxis = this._angleAxis;
  64754. var radiusAxis = this._radiusAxis;
  64755. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  64756. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  64757. return axes;
  64758. };
  64759. Polar.prototype.getAngleAxis = function () {
  64760. return this._angleAxis;
  64761. };
  64762. Polar.prototype.getRadiusAxis = function () {
  64763. return this._radiusAxis;
  64764. };
  64765. Polar.prototype.getOtherAxis = function (axis) {
  64766. var angleAxis = this._angleAxis;
  64767. return axis === angleAxis ? this._radiusAxis : angleAxis;
  64768. };
  64769. /**
  64770. * Base axis will be used on stacking.
  64771. *
  64772. */
  64773. Polar.prototype.getBaseAxis = function () {
  64774. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAngleAxis();
  64775. };
  64776. Polar.prototype.getTooltipAxes = function (dim) {
  64777. var baseAxis = dim != null && dim !== 'auto' ? this.getAxis(dim) : this.getBaseAxis();
  64778. return {
  64779. baseAxes: [baseAxis],
  64780. otherAxes: [this.getOtherAxis(baseAxis)]
  64781. };
  64782. };
  64783. /**
  64784. * Convert a single data item to (x, y) point.
  64785. * Parameter data is an array which the first element is radius and the second is angle
  64786. */
  64787. Polar.prototype.dataToPoint = function (data, clamp) {
  64788. return this.coordToPoint([this._radiusAxis.dataToRadius(data[0], clamp), this._angleAxis.dataToAngle(data[1], clamp)]);
  64789. };
  64790. /**
  64791. * Convert a (x, y) point to data
  64792. */
  64793. Polar.prototype.pointToData = function (point, clamp) {
  64794. var coord = this.pointToCoord(point);
  64795. return [this._radiusAxis.radiusToData(coord[0], clamp), this._angleAxis.angleToData(coord[1], clamp)];
  64796. };
  64797. /**
  64798. * Convert a (x, y) point to (radius, angle) coord
  64799. */
  64800. Polar.prototype.pointToCoord = function (point) {
  64801. var dx = point[0] - this.cx;
  64802. var dy = point[1] - this.cy;
  64803. var angleAxis = this.getAngleAxis();
  64804. var extent = angleAxis.getExtent();
  64805. var minAngle = Math.min(extent[0], extent[1]);
  64806. var maxAngle = Math.max(extent[0], extent[1]); // Fix fixed extent in polarCreator
  64807. // FIXME
  64808. angleAxis.inverse ? minAngle = maxAngle - 360 : maxAngle = minAngle + 360;
  64809. var radius = Math.sqrt(dx * dx + dy * dy);
  64810. dx /= radius;
  64811. dy /= radius;
  64812. var radian = Math.atan2(-dy, dx) / Math.PI * 180; // move to angleExtent
  64813. var dir = radian < minAngle ? 1 : -1;
  64814. while (radian < minAngle || radian > maxAngle) {
  64815. radian += dir * 360;
  64816. }
  64817. return [radius, radian];
  64818. };
  64819. /**
  64820. * Convert a (radius, angle) coord to (x, y) point
  64821. */
  64822. Polar.prototype.coordToPoint = function (coord) {
  64823. var radius = coord[0];
  64824. var radian = coord[1] / 180 * Math.PI;
  64825. var x = Math.cos(radian) * radius + this.cx; // Inverse the y
  64826. var y = -Math.sin(radian) * radius + this.cy;
  64827. return [x, y];
  64828. };
  64829. /**
  64830. * Get ring area of cartesian.
  64831. * Area will have a contain function to determine if a point is in the coordinate system.
  64832. */
  64833. Polar.prototype.getArea = function () {
  64834. var angleAxis = this.getAngleAxis();
  64835. var radiusAxis = this.getRadiusAxis();
  64836. var radiusExtent = radiusAxis.getExtent().slice();
  64837. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  64838. var angleExtent = angleAxis.getExtent();
  64839. var RADIAN = Math.PI / 180;
  64840. return {
  64841. cx: this.cx,
  64842. cy: this.cy,
  64843. r0: radiusExtent[0],
  64844. r: radiusExtent[1],
  64845. startAngle: -angleExtent[0] * RADIAN,
  64846. endAngle: -angleExtent[1] * RADIAN,
  64847. clockwise: angleAxis.inverse,
  64848. contain: function (x, y) {
  64849. // It's a ring shape.
  64850. // Start angle and end angle don't matter
  64851. var dx = x - this.cx;
  64852. var dy = y - this.cy;
  64853. var d2 = dx * dx + dy * dy;
  64854. var r = this.r;
  64855. var r0 = this.r0;
  64856. return d2 <= r * r && d2 >= r0 * r0;
  64857. }
  64858. };
  64859. };
  64860. Polar.prototype.convertToPixel = function (ecModel, finder, value) {
  64861. var coordSys = getCoordSys$2(finder);
  64862. return coordSys === this ? this.dataToPoint(value) : null;
  64863. };
  64864. Polar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  64865. var coordSys = getCoordSys$2(finder);
  64866. return coordSys === this ? this.pointToData(pixel) : null;
  64867. };
  64868. return Polar;
  64869. }();
  64870. function getCoordSys$2(finder) {
  64871. var seriesModel = finder.seriesModel;
  64872. var polarModel = finder.polarModel;
  64873. return polarModel && polarModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  64874. }
  64875. /**
  64876. * Resize method bound to the polar
  64877. */
  64878. function resizePolar(polar, polarModel, api) {
  64879. var center = polarModel.get('center');
  64880. var width = api.getWidth();
  64881. var height = api.getHeight();
  64882. polar.cx = parsePercent$1(center[0], width);
  64883. polar.cy = parsePercent$1(center[1], height);
  64884. var radiusAxis = polar.getRadiusAxis();
  64885. var size = Math.min(width, height) / 2;
  64886. var radius = polarModel.get('radius');
  64887. if (radius == null) {
  64888. radius = [0, '100%'];
  64889. } else if (!isArray(radius)) {
  64890. // r0 = 0
  64891. radius = [0, radius];
  64892. }
  64893. var parsedRadius = [parsePercent$1(radius[0], size), parsePercent$1(radius[1], size)];
  64894. radiusAxis.inverse ? radiusAxis.setExtent(parsedRadius[1], parsedRadius[0]) : radiusAxis.setExtent(parsedRadius[0], parsedRadius[1]);
  64895. }
  64896. /**
  64897. * Update polar
  64898. */
  64899. function updatePolarScale(ecModel, api) {
  64900. var polar = this;
  64901. var angleAxis = polar.getAngleAxis();
  64902. var radiusAxis = polar.getRadiusAxis(); // Reset scale
  64903. angleAxis.scale.setExtent(Infinity, -Infinity);
  64904. radiusAxis.scale.setExtent(Infinity, -Infinity);
  64905. ecModel.eachSeries(function (seriesModel) {
  64906. if (seriesModel.coordinateSystem === polar) {
  64907. var data_1 = seriesModel.getData();
  64908. each(getDataDimensionsOnAxis(data_1, 'radius'), function (dim) {
  64909. radiusAxis.scale.unionExtentFromData(data_1, dim);
  64910. });
  64911. each(getDataDimensionsOnAxis(data_1, 'angle'), function (dim) {
  64912. angleAxis.scale.unionExtentFromData(data_1, dim);
  64913. });
  64914. }
  64915. });
  64916. niceScaleExtent(angleAxis.scale, angleAxis.model);
  64917. niceScaleExtent(radiusAxis.scale, radiusAxis.model); // Fix extent of category angle axis
  64918. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  64919. var extent = angleAxis.getExtent();
  64920. var diff = 360 / angleAxis.scale.count();
  64921. angleAxis.inverse ? extent[1] += diff : extent[1] -= diff;
  64922. angleAxis.setExtent(extent[0], extent[1]);
  64923. }
  64924. }
  64925. function isAngleAxisModel(axisModel) {
  64926. return axisModel.mainType === 'angleAxis';
  64927. }
  64928. /**
  64929. * Set common axis properties
  64930. */
  64931. function setAxis(axis, axisModel) {
  64932. axis.type = axisModel.get('type');
  64933. axis.scale = createScaleByModel(axisModel);
  64934. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  64935. axis.inverse = axisModel.get('inverse');
  64936. if (isAngleAxisModel(axisModel)) {
  64937. axis.inverse = axis.inverse !== axisModel.get('clockwise');
  64938. var startAngle = axisModel.get('startAngle');
  64939. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  64940. } // Inject axis instance
  64941. axisModel.axis = axis;
  64942. axis.model = axisModel;
  64943. }
  64944. var polarCreator = {
  64945. dimensions: polarDimensions,
  64946. create: function (ecModel, api) {
  64947. var polarList = [];
  64948. ecModel.eachComponent('polar', function (polarModel, idx) {
  64949. var polar = new Polar(idx + ''); // Inject resize and update method
  64950. polar.update = updatePolarScale;
  64951. var radiusAxis = polar.getRadiusAxis();
  64952. var angleAxis = polar.getAngleAxis();
  64953. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  64954. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  64955. setAxis(radiusAxis, radiusAxisModel);
  64956. setAxis(angleAxis, angleAxisModel);
  64957. resizePolar(polar, polarModel, api);
  64958. polarList.push(polar);
  64959. polarModel.coordinateSystem = polar;
  64960. polar.model = polarModel;
  64961. }); // Inject coordinateSystem to series
  64962. ecModel.eachSeries(function (seriesModel) {
  64963. if (seriesModel.get('coordinateSystem') === 'polar') {
  64964. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  64965. if ("development" !== 'production') {
  64966. if (!polarModel) {
  64967. throw new Error('Polar "' + retrieve(seriesModel.get('polarIndex'), seriesModel.get('polarId'), 0) + '" not found');
  64968. }
  64969. }
  64970. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  64971. }
  64972. });
  64973. return polarList;
  64974. }
  64975. };
  64976. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea'];
  64977. function getAxisLineShape(polar, rExtent, angle) {
  64978. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  64979. var start = polar.coordToPoint([rExtent[0], angle]);
  64980. var end = polar.coordToPoint([rExtent[1], angle]);
  64981. return {
  64982. x1: start[0],
  64983. y1: start[1],
  64984. x2: end[0],
  64985. y2: end[1]
  64986. };
  64987. }
  64988. function getRadiusIdx(polar) {
  64989. var radiusAxis = polar.getRadiusAxis();
  64990. return radiusAxis.inverse ? 0 : 1;
  64991. } // Remove the last tick which will overlap the first tick
  64992. function fixAngleOverlap(list) {
  64993. var firstItem = list[0];
  64994. var lastItem = list[list.length - 1];
  64995. if (firstItem && lastItem && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4) {
  64996. list.pop();
  64997. }
  64998. }
  64999. var AngleAxisView =
  65000. /** @class */
  65001. function (_super) {
  65002. __extends(AngleAxisView, _super);
  65003. function AngleAxisView() {
  65004. var _this = _super !== null && _super.apply(this, arguments) || this;
  65005. _this.type = AngleAxisView.type;
  65006. _this.axisPointerClass = 'PolarAxisPointer';
  65007. return _this;
  65008. }
  65009. AngleAxisView.prototype.render = function (angleAxisModel, ecModel) {
  65010. this.group.removeAll();
  65011. if (!angleAxisModel.get('show')) {
  65012. return;
  65013. }
  65014. var angleAxis = angleAxisModel.axis;
  65015. var polar = angleAxis.polar;
  65016. var radiusExtent = polar.getRadiusAxis().getExtent();
  65017. var ticksAngles = angleAxis.getTicksCoords();
  65018. var minorTickAngles = angleAxis.getMinorTicksCoords();
  65019. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  65020. labelItem = clone(labelItem);
  65021. var scale = angleAxis.scale;
  65022. var tickValue = scale.type === 'ordinal' ? scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  65023. labelItem.coord = angleAxis.dataToCoord(tickValue);
  65024. return labelItem;
  65025. });
  65026. fixAngleOverlap(labels);
  65027. fixAngleOverlap(ticksAngles);
  65028. each(elementList$1, function (name) {
  65029. if (angleAxisModel.get([name, 'show']) && (!angleAxis.scale.isBlank() || name === 'axisLine')) {
  65030. angelAxisElementsBuilders[name](this.group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels);
  65031. }
  65032. }, this);
  65033. };
  65034. AngleAxisView.type = 'angleAxis';
  65035. return AngleAxisView;
  65036. }(AxisView);
  65037. var angelAxisElementsBuilders = {
  65038. axisLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65039. var lineStyleModel = angleAxisModel.getModel(['axisLine', 'lineStyle']); // extent id of the axis radius (r0 and r)
  65040. var rId = getRadiusIdx(polar);
  65041. var r0Id = rId ? 0 : 1;
  65042. var shape;
  65043. if (radiusExtent[r0Id] === 0) {
  65044. shape = new Circle({
  65045. shape: {
  65046. cx: polar.cx,
  65047. cy: polar.cy,
  65048. r: radiusExtent[rId]
  65049. },
  65050. style: lineStyleModel.getLineStyle(),
  65051. z2: 1,
  65052. silent: true
  65053. });
  65054. } else {
  65055. shape = new Ring({
  65056. shape: {
  65057. cx: polar.cx,
  65058. cy: polar.cy,
  65059. r: radiusExtent[rId],
  65060. r0: radiusExtent[r0Id]
  65061. },
  65062. style: lineStyleModel.getLineStyle(),
  65063. z2: 1,
  65064. silent: true
  65065. });
  65066. }
  65067. shape.style.fill = null;
  65068. group.add(shape);
  65069. },
  65070. axisTick: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65071. var tickModel = angleAxisModel.getModel('axisTick');
  65072. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  65073. var radius = radiusExtent[getRadiusIdx(polar)];
  65074. var lines = map(ticksAngles, function (tickAngleItem) {
  65075. return new Line({
  65076. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  65077. });
  65078. });
  65079. group.add(mergePath$1(lines, {
  65080. style: defaults(tickModel.getModel('lineStyle').getLineStyle(), {
  65081. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  65082. })
  65083. }));
  65084. },
  65085. minorTick: function (group, angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) {
  65086. if (!minorTickAngles.length) {
  65087. return;
  65088. }
  65089. var tickModel = angleAxisModel.getModel('axisTick');
  65090. var minorTickModel = angleAxisModel.getModel('minorTick');
  65091. var tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length');
  65092. var radius = radiusExtent[getRadiusIdx(polar)];
  65093. var lines = [];
  65094. for (var i = 0; i < minorTickAngles.length; i++) {
  65095. for (var k = 0; k < minorTickAngles[i].length; k++) {
  65096. lines.push(new Line({
  65097. shape: getAxisLineShape(polar, [radius, radius + tickLen], minorTickAngles[i][k].coord)
  65098. }));
  65099. }
  65100. }
  65101. group.add(mergePath$1(lines, {
  65102. style: defaults(minorTickModel.getModel('lineStyle').getLineStyle(), defaults(tickModel.getLineStyle(), {
  65103. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  65104. }))
  65105. }));
  65106. },
  65107. axisLabel: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) {
  65108. var rawCategoryData = angleAxisModel.getCategories(true);
  65109. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  65110. var labelMargin = commonLabelModel.get('margin');
  65111. var triggerEvent = angleAxisModel.get('triggerEvent'); // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  65112. each(labels, function (labelItem, idx) {
  65113. var labelModel = commonLabelModel;
  65114. var tickValue = labelItem.tickValue;
  65115. var r = radiusExtent[getRadiusIdx(polar)];
  65116. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  65117. var cx = polar.cx;
  65118. var cy = polar.cy;
  65119. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3 ? 'center' : p[0] > cx ? 'left' : 'right';
  65120. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3 ? 'middle' : p[1] > cy ? 'top' : 'bottom';
  65121. if (rawCategoryData && rawCategoryData[tickValue]) {
  65122. var rawCategoryItem = rawCategoryData[tickValue];
  65123. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  65124. labelModel = new Model(rawCategoryItem.textStyle, commonLabelModel, commonLabelModel.ecModel);
  65125. }
  65126. }
  65127. var textEl = new ZRText({
  65128. silent: AxisBuilder.isLabelSilent(angleAxisModel),
  65129. style: createTextStyle(labelModel, {
  65130. x: p[0],
  65131. y: p[1],
  65132. fill: labelModel.getTextColor() || angleAxisModel.get(['axisLine', 'lineStyle', 'color']),
  65133. text: labelItem.formattedLabel,
  65134. align: labelTextAlign,
  65135. verticalAlign: labelTextVerticalAlign
  65136. })
  65137. });
  65138. group.add(textEl); // Pack data for mouse event
  65139. if (triggerEvent) {
  65140. var eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel);
  65141. eventData.targetType = 'axisLabel';
  65142. eventData.value = labelItem.rawLabel;
  65143. getECData(textEl).eventData = eventData;
  65144. }
  65145. }, this);
  65146. },
  65147. splitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65148. var splitLineModel = angleAxisModel.getModel('splitLine');
  65149. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65150. var lineColors = lineStyleModel.get('color');
  65151. var lineCount = 0;
  65152. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65153. var splitLines = [];
  65154. for (var i = 0; i < ticksAngles.length; i++) {
  65155. var colorIndex = lineCount++ % lineColors.length;
  65156. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65157. splitLines[colorIndex].push(new Line({
  65158. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  65159. }));
  65160. } // Simple optimization
  65161. // Batching the lines if color are the same
  65162. for (var i = 0; i < splitLines.length; i++) {
  65163. group.add(mergePath$1(splitLines[i], {
  65164. style: defaults({
  65165. stroke: lineColors[i % lineColors.length]
  65166. }, lineStyleModel.getLineStyle()),
  65167. silent: true,
  65168. z: angleAxisModel.get('z')
  65169. }));
  65170. }
  65171. },
  65172. minorSplitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65173. if (!minorTickAngles.length) {
  65174. return;
  65175. }
  65176. var minorSplitLineModel = angleAxisModel.getModel('minorSplitLine');
  65177. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  65178. var lines = [];
  65179. for (var i = 0; i < minorTickAngles.length; i++) {
  65180. for (var k = 0; k < minorTickAngles[i].length; k++) {
  65181. lines.push(new Line({
  65182. shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord)
  65183. }));
  65184. }
  65185. }
  65186. group.add(mergePath$1(lines, {
  65187. style: lineStyleModel.getLineStyle(),
  65188. silent: true,
  65189. z: angleAxisModel.get('z')
  65190. }));
  65191. },
  65192. splitArea: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  65193. if (!ticksAngles.length) {
  65194. return;
  65195. }
  65196. var splitAreaModel = angleAxisModel.getModel('splitArea');
  65197. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65198. var areaColors = areaStyleModel.get('color');
  65199. var lineCount = 0;
  65200. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65201. var splitAreas = [];
  65202. var RADIAN = Math.PI / 180;
  65203. var prevAngle = -ticksAngles[0].coord * RADIAN;
  65204. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  65205. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  65206. var clockwise = angleAxisModel.get('clockwise');
  65207. for (var i = 1, len = ticksAngles.length; i <= len; i++) {
  65208. var coord = i === len ? ticksAngles[0].coord : ticksAngles[i].coord;
  65209. var colorIndex = lineCount++ % areaColors.length;
  65210. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65211. splitAreas[colorIndex].push(new Sector({
  65212. shape: {
  65213. cx: polar.cx,
  65214. cy: polar.cy,
  65215. r0: r0,
  65216. r: r1,
  65217. startAngle: prevAngle,
  65218. endAngle: -coord * RADIAN,
  65219. clockwise: clockwise
  65220. },
  65221. silent: true
  65222. }));
  65223. prevAngle = -coord * RADIAN;
  65224. } // Simple optimization
  65225. // Batching the lines if color are the same
  65226. for (var i = 0; i < splitAreas.length; i++) {
  65227. group.add(mergePath$1(splitAreas[i], {
  65228. style: defaults({
  65229. fill: areaColors[i % areaColors.length]
  65230. }, areaStyleModel.getAreaStyle()),
  65231. silent: true
  65232. }));
  65233. }
  65234. }
  65235. };
  65236. var axisBuilderAttrs$2 = ['axisLine', 'axisTickLabel', 'axisName'];
  65237. var selfBuilderAttrs$1 = ['splitLine', 'splitArea', 'minorSplitLine'];
  65238. var RadiusAxisView =
  65239. /** @class */
  65240. function (_super) {
  65241. __extends(RadiusAxisView, _super);
  65242. function RadiusAxisView() {
  65243. var _this = _super !== null && _super.apply(this, arguments) || this;
  65244. _this.type = RadiusAxisView.type;
  65245. _this.axisPointerClass = 'PolarAxisPointer';
  65246. return _this;
  65247. }
  65248. RadiusAxisView.prototype.render = function (radiusAxisModel, ecModel) {
  65249. this.group.removeAll();
  65250. if (!radiusAxisModel.get('show')) {
  65251. return;
  65252. }
  65253. var oldAxisGroup = this._axisGroup;
  65254. var newAxisGroup = this._axisGroup = new Group();
  65255. this.group.add(newAxisGroup);
  65256. var radiusAxis = radiusAxisModel.axis;
  65257. var polar = radiusAxis.polar;
  65258. var angleAxis = polar.getAngleAxis();
  65259. var ticksCoords = radiusAxis.getTicksCoords();
  65260. var minorTicksCoords = radiusAxis.getMinorTicksCoords();
  65261. var axisAngle = angleAxis.getExtent()[0];
  65262. var radiusExtent = radiusAxis.getExtent();
  65263. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  65264. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  65265. each(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  65266. newAxisGroup.add(axisBuilder.getGroup());
  65267. groupTransition(oldAxisGroup, newAxisGroup, radiusAxisModel);
  65268. each(selfBuilderAttrs$1, function (name) {
  65269. if (radiusAxisModel.get([name, 'show']) && !radiusAxis.scale.isBlank()) {
  65270. axisElementBuilders$1[name](this.group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords);
  65271. }
  65272. }, this);
  65273. };
  65274. RadiusAxisView.type = 'radiusAxis';
  65275. return RadiusAxisView;
  65276. }(AxisView);
  65277. var axisElementBuilders$1 = {
  65278. splitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  65279. var splitLineModel = radiusAxisModel.getModel('splitLine');
  65280. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65281. var lineColors = lineStyleModel.get('color');
  65282. var lineCount = 0;
  65283. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65284. var splitLines = [];
  65285. for (var i = 0; i < ticksCoords.length; i++) {
  65286. var colorIndex = lineCount++ % lineColors.length;
  65287. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65288. splitLines[colorIndex].push(new Circle({
  65289. shape: {
  65290. cx: polar.cx,
  65291. cy: polar.cy,
  65292. r: ticksCoords[i].coord
  65293. }
  65294. }));
  65295. } // Simple optimization
  65296. // Batching the lines if color are the same
  65297. for (var i = 0; i < splitLines.length; i++) {
  65298. group.add(mergePath$1(splitLines[i], {
  65299. style: defaults({
  65300. stroke: lineColors[i % lineColors.length],
  65301. fill: null
  65302. }, lineStyleModel.getLineStyle()),
  65303. silent: true
  65304. }));
  65305. }
  65306. },
  65307. minorSplitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) {
  65308. if (!minorTicksCoords.length) {
  65309. return;
  65310. }
  65311. var minorSplitLineModel = radiusAxisModel.getModel('minorSplitLine');
  65312. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  65313. var lines = [];
  65314. for (var i = 0; i < minorTicksCoords.length; i++) {
  65315. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  65316. lines.push(new Circle({
  65317. shape: {
  65318. cx: polar.cx,
  65319. cy: polar.cy,
  65320. r: minorTicksCoords[i][k].coord
  65321. }
  65322. }));
  65323. }
  65324. }
  65325. group.add(mergePath$1(lines, {
  65326. style: defaults({
  65327. fill: null
  65328. }, lineStyleModel.getLineStyle()),
  65329. silent: true
  65330. }));
  65331. },
  65332. splitArea: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  65333. if (!ticksCoords.length) {
  65334. return;
  65335. }
  65336. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  65337. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  65338. var areaColors = areaStyleModel.get('color');
  65339. var lineCount = 0;
  65340. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  65341. var splitAreas = [];
  65342. var prevRadius = ticksCoords[0].coord;
  65343. for (var i = 1; i < ticksCoords.length; i++) {
  65344. var colorIndex = lineCount++ % areaColors.length;
  65345. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  65346. splitAreas[colorIndex].push(new Sector({
  65347. shape: {
  65348. cx: polar.cx,
  65349. cy: polar.cy,
  65350. r0: prevRadius,
  65351. r: ticksCoords[i].coord,
  65352. startAngle: 0,
  65353. endAngle: Math.PI * 2
  65354. },
  65355. silent: true
  65356. }));
  65357. prevRadius = ticksCoords[i].coord;
  65358. } // Simple optimization
  65359. // Batching the lines if color are the same
  65360. for (var i = 0; i < splitAreas.length; i++) {
  65361. group.add(mergePath$1(splitAreas[i], {
  65362. style: defaults({
  65363. fill: areaColors[i % areaColors.length]
  65364. }, areaStyleModel.getAreaStyle()),
  65365. silent: true
  65366. }));
  65367. }
  65368. }
  65369. };
  65370. /**
  65371. * @inner
  65372. */
  65373. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  65374. return {
  65375. position: [polar.cx, polar.cy],
  65376. rotation: axisAngle / 180 * Math.PI,
  65377. labelDirection: -1,
  65378. tickDirection: -1,
  65379. nameDirection: 1,
  65380. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  65381. // Over splitLine and splitArea
  65382. z2: 1
  65383. };
  65384. }
  65385. function getSeriesStackId$1(seriesModel) {
  65386. return seriesModel.get('stack') || '__ec_stack_' + seriesModel.seriesIndex;
  65387. }
  65388. function getAxisKey$1(polar, axis) {
  65389. return axis.dim + polar.model.componentIndex;
  65390. }
  65391. function barLayoutPolar(seriesType, ecModel, api) {
  65392. var lastStackCoords = {};
  65393. var barWidthAndOffset = calRadialBar(filter(ecModel.getSeriesByType(seriesType), function (seriesModel) {
  65394. return !ecModel.isSeriesFiltered(seriesModel) && seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'polar';
  65395. }));
  65396. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  65397. // Check series coordinate, do layout for polar only
  65398. if (seriesModel.coordinateSystem.type !== 'polar') {
  65399. return;
  65400. }
  65401. var data = seriesModel.getData();
  65402. var polar = seriesModel.coordinateSystem;
  65403. var baseAxis = polar.getBaseAxis();
  65404. var axisKey = getAxisKey$1(polar, baseAxis);
  65405. var stackId = getSeriesStackId$1(seriesModel);
  65406. var columnLayoutInfo = barWidthAndOffset[axisKey][stackId];
  65407. var columnOffset = columnLayoutInfo.offset;
  65408. var columnWidth = columnLayoutInfo.width;
  65409. var valueAxis = polar.getOtherAxis(baseAxis);
  65410. var cx = seriesModel.coordinateSystem.cx;
  65411. var cy = seriesModel.coordinateSystem.cy;
  65412. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  65413. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  65414. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  65415. var valueDim = data.mapDimension(valueAxis.dim);
  65416. var baseDim = data.mapDimension(baseAxis.dim);
  65417. var stacked = isDimensionStacked(data, valueDim
  65418. /*, baseDim*/
  65419. );
  65420. var clampLayout = baseAxis.dim !== 'radius' || !seriesModel.get('roundCap', true);
  65421. var valueAxisStart = valueAxis.dataToCoord(0);
  65422. for (var idx = 0, len = data.count(); idx < len; idx++) {
  65423. var value = data.get(valueDim, idx);
  65424. var baseValue = data.get(baseDim, idx);
  65425. var sign = value >= 0 ? 'p' : 'n';
  65426. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  65427. // stackResultDimension directly.
  65428. // Only ordinal axis can be stacked.
  65429. if (stacked) {
  65430. if (!lastStackCoords[stackId][baseValue]) {
  65431. lastStackCoords[stackId][baseValue] = {
  65432. p: valueAxisStart,
  65433. n: valueAxisStart // Negative stack
  65434. };
  65435. } // Should also consider #4243
  65436. baseCoord = lastStackCoords[stackId][baseValue][sign];
  65437. }
  65438. var r0 = void 0;
  65439. var r = void 0;
  65440. var startAngle = void 0;
  65441. var endAngle = void 0; // radial sector
  65442. if (valueAxis.dim === 'radius') {
  65443. var radiusSpan = valueAxis.dataToCoord(value) - valueAxisStart;
  65444. var angle = baseAxis.dataToCoord(baseValue);
  65445. if (Math.abs(radiusSpan) < barMinHeight) {
  65446. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  65447. }
  65448. r0 = baseCoord;
  65449. r = baseCoord + radiusSpan;
  65450. startAngle = angle - columnOffset;
  65451. endAngle = startAngle - columnWidth;
  65452. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  65453. } // tangential sector
  65454. else {
  65455. var angleSpan = valueAxis.dataToCoord(value, clampLayout) - valueAxisStart;
  65456. var radius = baseAxis.dataToCoord(baseValue);
  65457. if (Math.abs(angleSpan) < barMinAngle) {
  65458. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  65459. }
  65460. r0 = radius + columnOffset;
  65461. r = r0 + columnWidth;
  65462. startAngle = baseCoord;
  65463. endAngle = baseCoord + angleSpan; // if the previous stack is at the end of the ring,
  65464. // add a round to differentiate it from origin
  65465. // let extent = angleAxis.getExtent();
  65466. // let stackCoord = angle;
  65467. // if (stackCoord === extent[0] && value > 0) {
  65468. // stackCoord = extent[1];
  65469. // }
  65470. // else if (stackCoord === extent[1] && value < 0) {
  65471. // stackCoord = extent[0];
  65472. // }
  65473. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  65474. }
  65475. data.setItemLayout(idx, {
  65476. cx: cx,
  65477. cy: cy,
  65478. r0: r0,
  65479. r: r,
  65480. // Consider that positive angle is anti-clockwise,
  65481. // while positive radian of sector is clockwise
  65482. startAngle: -startAngle * Math.PI / 180,
  65483. endAngle: -endAngle * Math.PI / 180
  65484. });
  65485. }
  65486. });
  65487. }
  65488. /**
  65489. * Calculate bar width and offset for radial bar charts
  65490. */
  65491. function calRadialBar(barSeries) {
  65492. // Columns info on each category axis. Key is polar name
  65493. var columnsMap = {};
  65494. each(barSeries, function (seriesModel, idx) {
  65495. var data = seriesModel.getData();
  65496. var polar = seriesModel.coordinateSystem;
  65497. var baseAxis = polar.getBaseAxis();
  65498. var axisKey = getAxisKey$1(polar, baseAxis);
  65499. var axisExtent = baseAxis.getExtent();
  65500. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  65501. var columnsOnAxis = columnsMap[axisKey] || {
  65502. bandWidth: bandWidth,
  65503. remainedWidth: bandWidth,
  65504. autoWidthCount: 0,
  65505. categoryGap: '20%',
  65506. gap: '30%',
  65507. stacks: {}
  65508. };
  65509. var stacks = columnsOnAxis.stacks;
  65510. columnsMap[axisKey] = columnsOnAxis;
  65511. var stackId = getSeriesStackId$1(seriesModel);
  65512. if (!stacks[stackId]) {
  65513. columnsOnAxis.autoWidthCount++;
  65514. }
  65515. stacks[stackId] = stacks[stackId] || {
  65516. width: 0,
  65517. maxWidth: 0
  65518. };
  65519. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  65520. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  65521. var barGap = seriesModel.get('barGap');
  65522. var barCategoryGap = seriesModel.get('barCategoryGap');
  65523. if (barWidth && !stacks[stackId].width) {
  65524. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  65525. stacks[stackId].width = barWidth;
  65526. columnsOnAxis.remainedWidth -= barWidth;
  65527. }
  65528. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  65529. barGap != null && (columnsOnAxis.gap = barGap);
  65530. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  65531. });
  65532. var result = {};
  65533. each(columnsMap, function (columnsOnAxis, coordSysName) {
  65534. result[coordSysName] = {};
  65535. var stacks = columnsOnAxis.stacks;
  65536. var bandWidth = columnsOnAxis.bandWidth;
  65537. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  65538. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  65539. var remainedWidth = columnsOnAxis.remainedWidth;
  65540. var autoWidthCount = columnsOnAxis.autoWidthCount;
  65541. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  65542. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  65543. each(stacks, function (column, stack) {
  65544. var maxWidth = column.maxWidth;
  65545. if (maxWidth && maxWidth < autoWidth) {
  65546. maxWidth = Math.min(maxWidth, remainedWidth);
  65547. if (column.width) {
  65548. maxWidth = Math.min(maxWidth, column.width);
  65549. }
  65550. remainedWidth -= maxWidth;
  65551. column.width = maxWidth;
  65552. autoWidthCount--;
  65553. }
  65554. }); // Recalculate width again
  65555. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  65556. autoWidth = Math.max(autoWidth, 0);
  65557. var widthSum = 0;
  65558. var lastColumn;
  65559. each(stacks, function (column, idx) {
  65560. if (!column.width) {
  65561. column.width = autoWidth;
  65562. }
  65563. lastColumn = column;
  65564. widthSum += column.width * (1 + barGapPercent);
  65565. });
  65566. if (lastColumn) {
  65567. widthSum -= lastColumn.width * barGapPercent;
  65568. }
  65569. var offset = -widthSum / 2;
  65570. each(stacks, function (column, stackId) {
  65571. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  65572. offset: offset,
  65573. width: column.width
  65574. };
  65575. offset += column.width * (1 + barGapPercent);
  65576. });
  65577. });
  65578. return result;
  65579. }
  65580. var angleAxisExtraOption = {
  65581. startAngle: 90,
  65582. clockwise: true,
  65583. splitNumber: 12,
  65584. axisLabel: {
  65585. rotate: 0
  65586. }
  65587. };
  65588. var radiusAxisExtraOption = {
  65589. splitNumber: 5
  65590. };
  65591. var PolarView =
  65592. /** @class */
  65593. function (_super) {
  65594. __extends(PolarView, _super);
  65595. function PolarView() {
  65596. var _this = _super !== null && _super.apply(this, arguments) || this;
  65597. _this.type = PolarView.type;
  65598. return _this;
  65599. }
  65600. PolarView.type = 'polar';
  65601. return PolarView;
  65602. }(ComponentView);
  65603. function install$u(registers) {
  65604. use(install$s);
  65605. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  65606. registers.registerCoordinateSystem('polar', polarCreator);
  65607. registers.registerComponentModel(PolarModel);
  65608. registers.registerComponentView(PolarView); // Model and view for angleAxis and radiusAxis
  65609. axisModelCreator(registers, 'angle', AngleAxisModel, angleAxisExtraOption);
  65610. axisModelCreator(registers, 'radius', RadiusAxisModel, radiusAxisExtraOption);
  65611. registers.registerComponentView(AngleAxisView);
  65612. registers.registerComponentView(RadiusAxisView);
  65613. registers.registerLayout(curry(barLayoutPolar, 'bar'));
  65614. }
  65615. function layout$2(axisModel, opt) {
  65616. opt = opt || {};
  65617. var single = axisModel.coordinateSystem;
  65618. var axis = axisModel.axis;
  65619. var layout = {};
  65620. var axisPosition = axis.position;
  65621. var orient = axis.orient;
  65622. var rect = single.getRect();
  65623. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  65624. var positionMap = {
  65625. horizontal: {
  65626. top: rectBound[2],
  65627. bottom: rectBound[3]
  65628. },
  65629. vertical: {
  65630. left: rectBound[0],
  65631. right: rectBound[1]
  65632. }
  65633. };
  65634. layout.position = [orient === 'vertical' ? positionMap.vertical[axisPosition] : rectBound[0], orient === 'horizontal' ? positionMap.horizontal[axisPosition] : rectBound[3]];
  65635. var r = {
  65636. horizontal: 0,
  65637. vertical: 1
  65638. };
  65639. layout.rotation = Math.PI / 2 * r[orient];
  65640. var directionMap = {
  65641. top: -1,
  65642. bottom: 1,
  65643. right: 1,
  65644. left: -1
  65645. };
  65646. layout.labelDirection = layout.tickDirection = layout.nameDirection = directionMap[axisPosition];
  65647. if (axisModel.get(['axisTick', 'inside'])) {
  65648. layout.tickDirection = -layout.tickDirection;
  65649. }
  65650. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  65651. layout.labelDirection = -layout.labelDirection;
  65652. }
  65653. var labelRotation = opt.rotate;
  65654. labelRotation == null && (labelRotation = axisModel.get(['axisLabel', 'rotate']));
  65655. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  65656. layout.z2 = 1;
  65657. return layout;
  65658. }
  65659. var axisBuilderAttrs$3 = ['axisLine', 'axisTickLabel', 'axisName'];
  65660. var selfBuilderAttrs$2 = ['splitArea', 'splitLine'];
  65661. var SingleAxisView =
  65662. /** @class */
  65663. function (_super) {
  65664. __extends(SingleAxisView, _super);
  65665. function SingleAxisView() {
  65666. var _this = _super !== null && _super.apply(this, arguments) || this;
  65667. _this.type = SingleAxisView.type;
  65668. _this.axisPointerClass = 'SingleAxisPointer';
  65669. return _this;
  65670. }
  65671. SingleAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  65672. var group = this.group;
  65673. group.removeAll();
  65674. var oldAxisGroup = this._axisGroup;
  65675. this._axisGroup = new Group();
  65676. var layout = layout$2(axisModel);
  65677. var axisBuilder = new AxisBuilder(axisModel, layout);
  65678. each(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  65679. group.add(this._axisGroup);
  65680. group.add(axisBuilder.getGroup());
  65681. each(selfBuilderAttrs$2, function (name) {
  65682. if (axisModel.get([name, 'show'])) {
  65683. axisElementBuilders$2[name](this, this.group, this._axisGroup, axisModel);
  65684. }
  65685. }, this);
  65686. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  65687. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  65688. };
  65689. SingleAxisView.prototype.remove = function () {
  65690. rectCoordAxisHandleRemove(this);
  65691. };
  65692. SingleAxisView.type = 'singleAxis';
  65693. return SingleAxisView;
  65694. }(AxisView);
  65695. var axisElementBuilders$2 = {
  65696. splitLine: function (axisView, group, axisGroup, axisModel) {
  65697. var axis = axisModel.axis;
  65698. if (axis.scale.isBlank()) {
  65699. return;
  65700. }
  65701. var splitLineModel = axisModel.getModel('splitLine');
  65702. var lineStyleModel = splitLineModel.getModel('lineStyle');
  65703. var lineColors = lineStyleModel.get('color');
  65704. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  65705. var gridRect = axisModel.coordinateSystem.getRect();
  65706. var isHorizontal = axis.isHorizontal();
  65707. var splitLines = [];
  65708. var lineCount = 0;
  65709. var ticksCoords = axis.getTicksCoords({
  65710. tickModel: splitLineModel
  65711. });
  65712. var p1 = [];
  65713. var p2 = [];
  65714. for (var i = 0; i < ticksCoords.length; ++i) {
  65715. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  65716. if (isHorizontal) {
  65717. p1[0] = tickCoord;
  65718. p1[1] = gridRect.y;
  65719. p2[0] = tickCoord;
  65720. p2[1] = gridRect.y + gridRect.height;
  65721. } else {
  65722. p1[0] = gridRect.x;
  65723. p1[1] = tickCoord;
  65724. p2[0] = gridRect.x + gridRect.width;
  65725. p2[1] = tickCoord;
  65726. }
  65727. var colorIndex = lineCount++ % lineColors.length;
  65728. splitLines[colorIndex] = splitLines[colorIndex] || [];
  65729. splitLines[colorIndex].push(new Line({
  65730. subPixelOptimize: true,
  65731. shape: {
  65732. x1: p1[0],
  65733. y1: p1[1],
  65734. x2: p2[0],
  65735. y2: p2[1]
  65736. },
  65737. silent: true
  65738. }));
  65739. }
  65740. var lineStyle = lineStyleModel.getLineStyle(['color']);
  65741. for (var i = 0; i < splitLines.length; ++i) {
  65742. group.add(mergePath$1(splitLines[i], {
  65743. style: defaults({
  65744. stroke: lineColors[i % lineColors.length]
  65745. }, lineStyle),
  65746. silent: true
  65747. }));
  65748. }
  65749. },
  65750. splitArea: function (axisView, group, axisGroup, axisModel) {
  65751. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, axisModel);
  65752. }
  65753. };
  65754. var SingleAxisModel =
  65755. /** @class */
  65756. function (_super) {
  65757. __extends(SingleAxisModel, _super);
  65758. function SingleAxisModel() {
  65759. var _this = _super !== null && _super.apply(this, arguments) || this;
  65760. _this.type = SingleAxisModel.type;
  65761. return _this;
  65762. }
  65763. SingleAxisModel.prototype.getCoordSysModel = function () {
  65764. return this;
  65765. };
  65766. SingleAxisModel.type = 'singleAxis';
  65767. SingleAxisModel.layoutMode = 'box';
  65768. SingleAxisModel.defaultOption = {
  65769. left: '5%',
  65770. top: '5%',
  65771. right: '5%',
  65772. bottom: '5%',
  65773. type: 'value',
  65774. position: 'bottom',
  65775. orient: 'horizontal',
  65776. axisLine: {
  65777. show: true,
  65778. lineStyle: {
  65779. width: 1,
  65780. type: 'solid'
  65781. }
  65782. },
  65783. // Single coordinate system and single axis is the,
  65784. // which is used as the parent tooltip model.
  65785. // same model, so we set default tooltip show as true.
  65786. tooltip: {
  65787. show: true
  65788. },
  65789. axisTick: {
  65790. show: true,
  65791. length: 6,
  65792. lineStyle: {
  65793. width: 1
  65794. }
  65795. },
  65796. axisLabel: {
  65797. show: true,
  65798. interval: 'auto'
  65799. },
  65800. splitLine: {
  65801. show: true,
  65802. lineStyle: {
  65803. type: 'dashed',
  65804. opacity: 0.2
  65805. }
  65806. }
  65807. };
  65808. return SingleAxisModel;
  65809. }(ComponentModel);
  65810. mixin(SingleAxisModel, AxisModelCommonMixin.prototype);
  65811. var SingleAxis =
  65812. /** @class */
  65813. function (_super) {
  65814. __extends(SingleAxis, _super);
  65815. function SingleAxis(dim, scale, coordExtent, axisType, position) {
  65816. var _this = _super.call(this, dim, scale, coordExtent) || this;
  65817. _this.type = axisType || 'value';
  65818. _this.position = position || 'bottom';
  65819. return _this;
  65820. }
  65821. /**
  65822. * Judge the orient of the axis.
  65823. */
  65824. SingleAxis.prototype.isHorizontal = function () {
  65825. var position = this.position;
  65826. return position === 'top' || position === 'bottom';
  65827. };
  65828. SingleAxis.prototype.pointToData = function (point, clamp) {
  65829. return this.coordinateSystem.pointToData(point)[0];
  65830. };
  65831. return SingleAxis;
  65832. }(Axis);
  65833. var singleDimensions = ['single'];
  65834. /**
  65835. * Create a single coordinates system.
  65836. */
  65837. var Single =
  65838. /** @class */
  65839. function () {
  65840. function Single(axisModel, ecModel, api) {
  65841. this.type = 'single';
  65842. this.dimension = 'single';
  65843. /**
  65844. * Add it just for draw tooltip.
  65845. */
  65846. this.dimensions = singleDimensions;
  65847. this.axisPointerEnabled = true;
  65848. this.model = axisModel;
  65849. this._init(axisModel, ecModel, api);
  65850. }
  65851. /**
  65852. * Initialize single coordinate system.
  65853. */
  65854. Single.prototype._init = function (axisModel, ecModel, api) {
  65855. var dim = this.dimension;
  65856. var axis = new SingleAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisModel.get('position'));
  65857. var isCategory = axis.type === 'category';
  65858. axis.onBand = isCategory && axisModel.get('boundaryGap');
  65859. axis.inverse = axisModel.get('inverse');
  65860. axis.orient = axisModel.get('orient');
  65861. axisModel.axis = axis;
  65862. axis.model = axisModel;
  65863. axis.coordinateSystem = this;
  65864. this._axis = axis;
  65865. };
  65866. /**
  65867. * Update axis scale after data processed
  65868. */
  65869. Single.prototype.update = function (ecModel, api) {
  65870. ecModel.eachSeries(function (seriesModel) {
  65871. if (seriesModel.coordinateSystem === this) {
  65872. var data_1 = seriesModel.getData();
  65873. each(data_1.mapDimensionsAll(this.dimension), function (dim) {
  65874. this._axis.scale.unionExtentFromData(data_1, dim);
  65875. }, this);
  65876. niceScaleExtent(this._axis.scale, this._axis.model);
  65877. }
  65878. }, this);
  65879. };
  65880. /**
  65881. * Resize the single coordinate system.
  65882. */
  65883. Single.prototype.resize = function (axisModel, api) {
  65884. this._rect = getLayoutRect({
  65885. left: axisModel.get('left'),
  65886. top: axisModel.get('top'),
  65887. right: axisModel.get('right'),
  65888. bottom: axisModel.get('bottom'),
  65889. width: axisModel.get('width'),
  65890. height: axisModel.get('height')
  65891. }, {
  65892. width: api.getWidth(),
  65893. height: api.getHeight()
  65894. });
  65895. this._adjustAxis();
  65896. };
  65897. Single.prototype.getRect = function () {
  65898. return this._rect;
  65899. };
  65900. Single.prototype._adjustAxis = function () {
  65901. var rect = this._rect;
  65902. var axis = this._axis;
  65903. var isHorizontal = axis.isHorizontal();
  65904. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  65905. var idx = axis.reverse ? 1 : 0;
  65906. axis.setExtent(extent[idx], extent[1 - idx]);
  65907. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  65908. };
  65909. Single.prototype._updateAxisTransform = function (axis, coordBase) {
  65910. var axisExtent = axis.getExtent();
  65911. var extentSum = axisExtent[0] + axisExtent[1];
  65912. var isHorizontal = axis.isHorizontal();
  65913. axis.toGlobalCoord = isHorizontal ? function (coord) {
  65914. return coord + coordBase;
  65915. } : function (coord) {
  65916. return extentSum - coord + coordBase;
  65917. };
  65918. axis.toLocalCoord = isHorizontal ? function (coord) {
  65919. return coord - coordBase;
  65920. } : function (coord) {
  65921. return extentSum - coord + coordBase;
  65922. };
  65923. };
  65924. /**
  65925. * Get axis.
  65926. */
  65927. Single.prototype.getAxis = function () {
  65928. return this._axis;
  65929. };
  65930. /**
  65931. * Get axis, add it just for draw tooltip.
  65932. */
  65933. Single.prototype.getBaseAxis = function () {
  65934. return this._axis;
  65935. };
  65936. Single.prototype.getAxes = function () {
  65937. return [this._axis];
  65938. };
  65939. Single.prototype.getTooltipAxes = function () {
  65940. return {
  65941. baseAxes: [this.getAxis()],
  65942. // Empty otherAxes
  65943. otherAxes: []
  65944. };
  65945. };
  65946. /**
  65947. * If contain point.
  65948. */
  65949. Single.prototype.containPoint = function (point) {
  65950. var rect = this.getRect();
  65951. var axis = this.getAxis();
  65952. var orient = axis.orient;
  65953. if (orient === 'horizontal') {
  65954. return axis.contain(axis.toLocalCoord(point[0])) && point[1] >= rect.y && point[1] <= rect.y + rect.height;
  65955. } else {
  65956. return axis.contain(axis.toLocalCoord(point[1])) && point[0] >= rect.y && point[0] <= rect.y + rect.height;
  65957. }
  65958. };
  65959. Single.prototype.pointToData = function (point) {
  65960. var axis = this.getAxis();
  65961. return [axis.coordToData(axis.toLocalCoord(point[axis.orient === 'horizontal' ? 0 : 1]))];
  65962. };
  65963. /**
  65964. * Convert the series data to concrete point.
  65965. * Can be [val] | val
  65966. */
  65967. Single.prototype.dataToPoint = function (val) {
  65968. var axis = this.getAxis();
  65969. var rect = this.getRect();
  65970. var pt = [];
  65971. var idx = axis.orient === 'horizontal' ? 0 : 1;
  65972. if (val instanceof Array) {
  65973. val = val[0];
  65974. }
  65975. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  65976. pt[1 - idx] = idx === 0 ? rect.y + rect.height / 2 : rect.x + rect.width / 2;
  65977. return pt;
  65978. };
  65979. Single.prototype.convertToPixel = function (ecModel, finder, value) {
  65980. var coordSys = getCoordSys$3(finder);
  65981. return coordSys === this ? this.dataToPoint(value) : null;
  65982. };
  65983. Single.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  65984. var coordSys = getCoordSys$3(finder);
  65985. return coordSys === this ? this.pointToData(pixel) : null;
  65986. };
  65987. return Single;
  65988. }();
  65989. function getCoordSys$3(finder) {
  65990. var seriesModel = finder.seriesModel;
  65991. var singleModel = finder.singleAxisModel;
  65992. return singleModel && singleModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  65993. }
  65994. /**
  65995. * Create single coordinate system and inject it into seriesModel.
  65996. */
  65997. function create$2(ecModel, api) {
  65998. var singles = [];
  65999. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  66000. var single = new Single(axisModel, ecModel, api);
  66001. single.name = 'single_' + idx;
  66002. single.resize(axisModel, api);
  66003. axisModel.coordinateSystem = single;
  66004. singles.push(single);
  66005. });
  66006. ecModel.eachSeries(function (seriesModel) {
  66007. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  66008. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  66009. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  66010. }
  66011. });
  66012. return singles;
  66013. }
  66014. var singleCreator = {
  66015. create: create$2,
  66016. dimensions: singleDimensions
  66017. };
  66018. var XY = ['x', 'y'];
  66019. var WH = ['width', 'height'];
  66020. var SingleAxisPointer =
  66021. /** @class */
  66022. function (_super) {
  66023. __extends(SingleAxisPointer, _super);
  66024. function SingleAxisPointer() {
  66025. return _super !== null && _super.apply(this, arguments) || this;
  66026. }
  66027. /**
  66028. * @override
  66029. */
  66030. SingleAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  66031. var axis = axisModel.axis;
  66032. var coordSys = axis.coordinateSystem;
  66033. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  66034. var pixelValue = coordSys.dataToPoint(value)[0];
  66035. var axisPointerType = axisPointerModel.get('type');
  66036. if (axisPointerType && axisPointerType !== 'none') {
  66037. var elStyle = buildElStyle(axisPointerModel);
  66038. var pointerOption = pointerShapeBuilder$2[axisPointerType](axis, pixelValue, otherExtent);
  66039. pointerOption.style = elStyle;
  66040. elOption.graphicKey = pointerOption.type;
  66041. elOption.pointer = pointerOption;
  66042. }
  66043. var layoutInfo = layout$2(axisModel);
  66044. buildCartesianSingleLabelElOption( // @ts-ignore
  66045. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  66046. };
  66047. /**
  66048. * @override
  66049. */
  66050. SingleAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  66051. var layoutInfo = layout$2(axisModel, {
  66052. labelInside: false
  66053. }); // @ts-ignore
  66054. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  66055. var position = getTransformedPosition(axisModel.axis, value, layoutInfo);
  66056. return {
  66057. x: position[0],
  66058. y: position[1],
  66059. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  66060. };
  66061. };
  66062. /**
  66063. * @override
  66064. */
  66065. SingleAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  66066. var axis = axisModel.axis;
  66067. var coordSys = axis.coordinateSystem;
  66068. var dimIndex = getPointDimIndex(axis);
  66069. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  66070. var currPosition = [transform.x, transform.y];
  66071. currPosition[dimIndex] += delta[dimIndex];
  66072. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  66073. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  66074. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  66075. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  66076. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  66077. cursorPoint[dimIndex] = currPosition[dimIndex];
  66078. return {
  66079. x: currPosition[0],
  66080. y: currPosition[1],
  66081. rotation: transform.rotation,
  66082. cursorPoint: cursorPoint,
  66083. tooltipOption: {
  66084. verticalAlign: 'middle'
  66085. }
  66086. };
  66087. };
  66088. return SingleAxisPointer;
  66089. }(BaseAxisPointer);
  66090. var pointerShapeBuilder$2 = {
  66091. line: function (axis, pixelValue, otherExtent) {
  66092. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getPointDimIndex(axis));
  66093. return {
  66094. type: 'Line',
  66095. subPixelOptimize: true,
  66096. shape: targetShape
  66097. };
  66098. },
  66099. shadow: function (axis, pixelValue, otherExtent) {
  66100. var bandWidth = axis.getBandWidth();
  66101. var span = otherExtent[1] - otherExtent[0];
  66102. return {
  66103. type: 'Rect',
  66104. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getPointDimIndex(axis))
  66105. };
  66106. }
  66107. };
  66108. function getPointDimIndex(axis) {
  66109. return axis.isHorizontal() ? 0 : 1;
  66110. }
  66111. function getGlobalExtent(coordSys, dimIndex) {
  66112. var rect = coordSys.getRect();
  66113. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  66114. }
  66115. var SingleView =
  66116. /** @class */
  66117. function (_super) {
  66118. __extends(SingleView, _super);
  66119. function SingleView() {
  66120. var _this = _super !== null && _super.apply(this, arguments) || this;
  66121. _this.type = SingleView.type;
  66122. return _this;
  66123. }
  66124. SingleView.type = 'single';
  66125. return SingleView;
  66126. }(ComponentView);
  66127. function install$v(registers) {
  66128. use(install$s);
  66129. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  66130. registers.registerComponentView(SingleView); // Axis
  66131. registers.registerComponentView(SingleAxisView);
  66132. registers.registerComponentModel(SingleAxisModel);
  66133. axisModelCreator(registers, 'single', SingleAxisModel, SingleAxisModel.defaultOption);
  66134. registers.registerCoordinateSystem('single', singleCreator);
  66135. }
  66136. var CalendarModel =
  66137. /** @class */
  66138. function (_super) {
  66139. __extends(CalendarModel, _super);
  66140. function CalendarModel() {
  66141. var _this = _super !== null && _super.apply(this, arguments) || this;
  66142. _this.type = CalendarModel.type;
  66143. return _this;
  66144. }
  66145. /**
  66146. * @override
  66147. */
  66148. CalendarModel.prototype.init = function (option, parentModel, ecModel) {
  66149. var inputPositionParams = getLayoutParams(option);
  66150. _super.prototype.init.apply(this, arguments);
  66151. mergeAndNormalizeLayoutParams(option, inputPositionParams);
  66152. };
  66153. /**
  66154. * @override
  66155. */
  66156. CalendarModel.prototype.mergeOption = function (option) {
  66157. _super.prototype.mergeOption.apply(this, arguments);
  66158. mergeAndNormalizeLayoutParams(this.option, option);
  66159. };
  66160. CalendarModel.prototype.getCellSize = function () {
  66161. // Has been normalized
  66162. return this.option.cellSize;
  66163. };
  66164. CalendarModel.type = 'calendar';
  66165. CalendarModel.defaultOption = {
  66166. zlevel: 0,
  66167. z: 2,
  66168. left: 80,
  66169. top: 60,
  66170. cellSize: 20,
  66171. // horizontal vertical
  66172. orient: 'horizontal',
  66173. // month separate line style
  66174. splitLine: {
  66175. show: true,
  66176. lineStyle: {
  66177. color: '#000',
  66178. width: 1,
  66179. type: 'solid'
  66180. }
  66181. },
  66182. // rect style temporarily unused emphasis
  66183. itemStyle: {
  66184. color: '#fff',
  66185. borderWidth: 1,
  66186. borderColor: '#ccc'
  66187. },
  66188. // week text style
  66189. dayLabel: {
  66190. show: true,
  66191. firstDay: 0,
  66192. // start end
  66193. position: 'start',
  66194. margin: '50%',
  66195. nameMap: 'en',
  66196. color: '#000'
  66197. },
  66198. // month text style
  66199. monthLabel: {
  66200. show: true,
  66201. // start end
  66202. position: 'start',
  66203. margin: 5,
  66204. // center or left
  66205. align: 'center',
  66206. // cn en []
  66207. nameMap: 'en',
  66208. formatter: null,
  66209. color: '#000'
  66210. },
  66211. // year text style
  66212. yearLabel: {
  66213. show: true,
  66214. // top bottom left right
  66215. position: null,
  66216. margin: 30,
  66217. formatter: null,
  66218. color: '#ccc',
  66219. fontFamily: 'sans-serif',
  66220. fontWeight: 'bolder',
  66221. fontSize: 20
  66222. }
  66223. };
  66224. return CalendarModel;
  66225. }(ComponentModel);
  66226. function mergeAndNormalizeLayoutParams(target, raw) {
  66227. // Normalize cellSize
  66228. var cellSize = target.cellSize;
  66229. var cellSizeArr;
  66230. if (!isArray(cellSize)) {
  66231. cellSizeArr = target.cellSize = [cellSize, cellSize];
  66232. } else {
  66233. cellSizeArr = cellSize;
  66234. }
  66235. if (cellSizeArr.length === 1) {
  66236. cellSizeArr[1] = cellSizeArr[0];
  66237. }
  66238. var ignoreSize = map([0, 1], function (hvIdx) {
  66239. // If user have set `width` or both `left` and `right`, cellSizeArr
  66240. // will be automatically set to 'auto', otherwise the default
  66241. // setting of cellSizeArr will make `width` setting not work.
  66242. if (sizeCalculable(raw, hvIdx)) {
  66243. cellSizeArr[hvIdx] = 'auto';
  66244. }
  66245. return cellSizeArr[hvIdx] != null && cellSizeArr[hvIdx] !== 'auto';
  66246. });
  66247. mergeLayoutParam(target, raw, {
  66248. type: 'box',
  66249. ignoreSize: ignoreSize
  66250. });
  66251. }
  66252. var MONTH_TEXT = {
  66253. EN: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  66254. CN: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
  66255. };
  66256. var WEEK_TEXT = {
  66257. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  66258. CN: ['日', '一', '二', '三', '四', '五', '六']
  66259. };
  66260. var CalendarView =
  66261. /** @class */
  66262. function (_super) {
  66263. __extends(CalendarView, _super);
  66264. function CalendarView() {
  66265. var _this = _super !== null && _super.apply(this, arguments) || this;
  66266. _this.type = CalendarView.type;
  66267. return _this;
  66268. }
  66269. CalendarView.prototype.render = function (calendarModel, ecModel, api) {
  66270. var group = this.group;
  66271. group.removeAll();
  66272. var coordSys = calendarModel.coordinateSystem; // range info
  66273. var rangeData = coordSys.getRangeInfo();
  66274. var orient = coordSys.getOrient();
  66275. this._renderDayRect(calendarModel, rangeData, group); // _renderLines must be called prior to following function
  66276. this._renderLines(calendarModel, rangeData, orient, group);
  66277. this._renderYearText(calendarModel, rangeData, orient, group);
  66278. this._renderMonthText(calendarModel, orient, group);
  66279. this._renderWeekText(calendarModel, rangeData, orient, group);
  66280. }; // render day rect
  66281. CalendarView.prototype._renderDayRect = function (calendarModel, rangeData, group) {
  66282. var coordSys = calendarModel.coordinateSystem;
  66283. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  66284. var sw = coordSys.getCellWidth();
  66285. var sh = coordSys.getCellHeight();
  66286. for (var i = rangeData.start.time; i <= rangeData.end.time; i = coordSys.getNextNDay(i, 1).time) {
  66287. var point = coordSys.dataToRect([i], false).tl; // every rect
  66288. var rect = new Rect({
  66289. shape: {
  66290. x: point[0],
  66291. y: point[1],
  66292. width: sw,
  66293. height: sh
  66294. },
  66295. cursor: 'default',
  66296. style: itemRectStyleModel
  66297. });
  66298. group.add(rect);
  66299. }
  66300. }; // render separate line
  66301. CalendarView.prototype._renderLines = function (calendarModel, rangeData, orient, group) {
  66302. var self = this;
  66303. var coordSys = calendarModel.coordinateSystem;
  66304. var lineStyleModel = calendarModel.getModel(['splitLine', 'lineStyle']).getLineStyle();
  66305. var show = calendarModel.get(['splitLine', 'show']);
  66306. var lineWidth = lineStyleModel.lineWidth;
  66307. this._tlpoints = [];
  66308. this._blpoints = [];
  66309. this._firstDayOfMonth = [];
  66310. this._firstDayPoints = [];
  66311. var firstDay = rangeData.start;
  66312. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  66313. addPoints(firstDay.formatedDate);
  66314. if (i === 0) {
  66315. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  66316. }
  66317. var date = firstDay.date;
  66318. date.setMonth(date.getMonth() + 1);
  66319. firstDay = coordSys.getDateInfo(date);
  66320. }
  66321. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  66322. function addPoints(date) {
  66323. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  66324. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  66325. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  66326. self._tlpoints.push(points[0]);
  66327. self._blpoints.push(points[points.length - 1]);
  66328. show && self._drawSplitline(points, lineStyleModel, group);
  66329. } // render top/left line
  66330. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group); // render bottom/right line
  66331. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  66332. }; // get points at both ends
  66333. CalendarView.prototype._getEdgesPoints = function (points, lineWidth, orient) {
  66334. var rs = [points[0].slice(), points[points.length - 1].slice()];
  66335. var idx = orient === 'horizontal' ? 0 : 1; // both ends of the line are extend half lineWidth
  66336. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  66337. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  66338. return rs;
  66339. }; // render split line
  66340. CalendarView.prototype._drawSplitline = function (points, lineStyle, group) {
  66341. var poyline = new Polyline({
  66342. z2: 20,
  66343. shape: {
  66344. points: points
  66345. },
  66346. style: lineStyle
  66347. });
  66348. group.add(poyline);
  66349. }; // render month line of one week points
  66350. CalendarView.prototype._getLinePointsOfOneWeek = function (calendarModel, date, orient) {
  66351. var coordSys = calendarModel.coordinateSystem;
  66352. var parsedDate = coordSys.getDateInfo(date);
  66353. var points = [];
  66354. for (var i = 0; i < 7; i++) {
  66355. var tmpD = coordSys.getNextNDay(parsedDate.time, i);
  66356. var point = coordSys.dataToRect([tmpD.time], false);
  66357. points[2 * tmpD.day] = point.tl;
  66358. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  66359. }
  66360. return points;
  66361. };
  66362. CalendarView.prototype._formatterLabel = function (formatter, params) {
  66363. if (typeof formatter === 'string' && formatter) {
  66364. return formatTplSimple(formatter, params);
  66365. }
  66366. if (typeof formatter === 'function') {
  66367. return formatter(params);
  66368. }
  66369. return params.nameMap;
  66370. };
  66371. CalendarView.prototype._yearTextPositionControl = function (textEl, point, orient, position, margin) {
  66372. var x = point[0];
  66373. var y = point[1];
  66374. var aligns = ['center', 'bottom'];
  66375. if (position === 'bottom') {
  66376. y += margin;
  66377. aligns = ['center', 'top'];
  66378. } else if (position === 'left') {
  66379. x -= margin;
  66380. } else if (position === 'right') {
  66381. x += margin;
  66382. aligns = ['center', 'top'];
  66383. } else {
  66384. // top
  66385. y -= margin;
  66386. }
  66387. var rotate = 0;
  66388. if (position === 'left' || position === 'right') {
  66389. rotate = Math.PI / 2;
  66390. }
  66391. return {
  66392. rotation: rotate,
  66393. x: x,
  66394. y: y,
  66395. style: {
  66396. align: aligns[0],
  66397. verticalAlign: aligns[1]
  66398. }
  66399. };
  66400. }; // render year
  66401. CalendarView.prototype._renderYearText = function (calendarModel, rangeData, orient, group) {
  66402. var yearLabel = calendarModel.getModel('yearLabel');
  66403. if (!yearLabel.get('show')) {
  66404. return;
  66405. }
  66406. var margin = yearLabel.get('margin');
  66407. var pos = yearLabel.get('position');
  66408. if (!pos) {
  66409. pos = orient !== 'horizontal' ? 'top' : 'left';
  66410. }
  66411. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  66412. var xc = (points[0][0] + points[1][0]) / 2;
  66413. var yc = (points[0][1] + points[1][1]) / 2;
  66414. var idx = orient === 'horizontal' ? 0 : 1;
  66415. var posPoints = {
  66416. top: [xc, points[idx][1]],
  66417. bottom: [xc, points[1 - idx][1]],
  66418. left: [points[1 - idx][0], yc],
  66419. right: [points[idx][0], yc]
  66420. };
  66421. var name = rangeData.start.y;
  66422. if (+rangeData.end.y > +rangeData.start.y) {
  66423. name = name + '-' + rangeData.end.y;
  66424. }
  66425. var formatter = yearLabel.get('formatter');
  66426. var params = {
  66427. start: rangeData.start.y,
  66428. end: rangeData.end.y,
  66429. nameMap: name
  66430. };
  66431. var content = this._formatterLabel(formatter, params);
  66432. var yearText = new ZRText({
  66433. z2: 30,
  66434. style: createTextStyle(yearLabel, {
  66435. text: content
  66436. })
  66437. });
  66438. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  66439. group.add(yearText);
  66440. };
  66441. CalendarView.prototype._monthTextPositionControl = function (point, isCenter, orient, position, margin) {
  66442. var align = 'left';
  66443. var vAlign = 'top';
  66444. var x = point[0];
  66445. var y = point[1];
  66446. if (orient === 'horizontal') {
  66447. y = y + margin;
  66448. if (isCenter) {
  66449. align = 'center';
  66450. }
  66451. if (position === 'start') {
  66452. vAlign = 'bottom';
  66453. }
  66454. } else {
  66455. x = x + margin;
  66456. if (isCenter) {
  66457. vAlign = 'middle';
  66458. }
  66459. if (position === 'start') {
  66460. align = 'right';
  66461. }
  66462. }
  66463. return {
  66464. x: x,
  66465. y: y,
  66466. align: align,
  66467. verticalAlign: vAlign
  66468. };
  66469. }; // render month and year text
  66470. CalendarView.prototype._renderMonthText = function (calendarModel, orient, group) {
  66471. var monthLabel = calendarModel.getModel('monthLabel');
  66472. if (!monthLabel.get('show')) {
  66473. return;
  66474. }
  66475. var nameMap = monthLabel.get('nameMap');
  66476. var margin = monthLabel.get('margin');
  66477. var pos = monthLabel.get('position');
  66478. var align = monthLabel.get('align');
  66479. var termPoints = [this._tlpoints, this._blpoints];
  66480. if (isString(nameMap)) {
  66481. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  66482. }
  66483. var idx = pos === 'start' ? 0 : 1;
  66484. var axis = orient === 'horizontal' ? 0 : 1;
  66485. margin = pos === 'start' ? -margin : margin;
  66486. var isCenter = align === 'center';
  66487. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  66488. var tmp = termPoints[idx][i].slice();
  66489. var firstDay = this._firstDayOfMonth[i];
  66490. if (isCenter) {
  66491. var firstDayPoints = this._firstDayPoints[i];
  66492. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  66493. }
  66494. var formatter = monthLabel.get('formatter');
  66495. var name_1 = nameMap[+firstDay.m - 1];
  66496. var params = {
  66497. yyyy: firstDay.y,
  66498. yy: (firstDay.y + '').slice(2),
  66499. MM: firstDay.m,
  66500. M: +firstDay.m,
  66501. nameMap: name_1
  66502. };
  66503. var content = this._formatterLabel(formatter, params);
  66504. var monthText = new ZRText({
  66505. z2: 30,
  66506. style: extend(createTextStyle(monthLabel, {
  66507. text: content
  66508. }), this._monthTextPositionControl(tmp, isCenter, orient, pos, margin))
  66509. });
  66510. group.add(monthText);
  66511. }
  66512. };
  66513. CalendarView.prototype._weekTextPositionControl = function (point, orient, position, margin, cellSize) {
  66514. var align = 'center';
  66515. var vAlign = 'middle';
  66516. var x = point[0];
  66517. var y = point[1];
  66518. var isStart = position === 'start';
  66519. if (orient === 'horizontal') {
  66520. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  66521. align = isStart ? 'right' : 'left';
  66522. } else {
  66523. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  66524. vAlign = isStart ? 'bottom' : 'top';
  66525. }
  66526. return {
  66527. x: x,
  66528. y: y,
  66529. align: align,
  66530. verticalAlign: vAlign
  66531. };
  66532. }; // render weeks
  66533. CalendarView.prototype._renderWeekText = function (calendarModel, rangeData, orient, group) {
  66534. var dayLabel = calendarModel.getModel('dayLabel');
  66535. if (!dayLabel.get('show')) {
  66536. return;
  66537. }
  66538. var coordSys = calendarModel.coordinateSystem;
  66539. var pos = dayLabel.get('position');
  66540. var nameMap = dayLabel.get('nameMap');
  66541. var margin = dayLabel.get('margin');
  66542. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  66543. if (isString(nameMap)) {
  66544. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  66545. }
  66546. var start = coordSys.getNextNDay(rangeData.end.time, 7 - rangeData.lweek).time;
  66547. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  66548. margin = parsePercent$1(margin, Math.min(cellSize[1], cellSize[0]));
  66549. if (pos === 'start') {
  66550. start = coordSys.getNextNDay(rangeData.start.time, -(7 + rangeData.fweek)).time;
  66551. margin = -margin;
  66552. }
  66553. for (var i = 0; i < 7; i++) {
  66554. var tmpD = coordSys.getNextNDay(start, i);
  66555. var point = coordSys.dataToRect([tmpD.time], false).center;
  66556. var day = i;
  66557. day = Math.abs((i + firstDayOfWeek) % 7);
  66558. var weekText = new ZRText({
  66559. z2: 30,
  66560. style: extend(createTextStyle(dayLabel, {
  66561. text: nameMap[day]
  66562. }), this._weekTextPositionControl(point, orient, pos, margin, cellSize))
  66563. });
  66564. group.add(weekText);
  66565. }
  66566. };
  66567. CalendarView.type = 'calendar';
  66568. return CalendarView;
  66569. }(ComponentView);
  66570. var PROXIMATE_ONE_DAY = 86400000;
  66571. var Calendar =
  66572. /** @class */
  66573. function () {
  66574. function Calendar(calendarModel, ecModel, api) {
  66575. this.type = 'calendar';
  66576. this.dimensions = Calendar.dimensions; // Required in createListFromData
  66577. this.getDimensionsInfo = Calendar.getDimensionsInfo;
  66578. this._model = calendarModel;
  66579. }
  66580. Calendar.getDimensionsInfo = function () {
  66581. return [{
  66582. name: 'time',
  66583. type: 'time'
  66584. }, 'value'];
  66585. };
  66586. Calendar.prototype.getRangeInfo = function () {
  66587. return this._rangeInfo;
  66588. };
  66589. Calendar.prototype.getModel = function () {
  66590. return this._model;
  66591. };
  66592. Calendar.prototype.getRect = function () {
  66593. return this._rect;
  66594. };
  66595. Calendar.prototype.getCellWidth = function () {
  66596. return this._sw;
  66597. };
  66598. Calendar.prototype.getCellHeight = function () {
  66599. return this._sh;
  66600. };
  66601. Calendar.prototype.getOrient = function () {
  66602. return this._orient;
  66603. };
  66604. /**
  66605. * getFirstDayOfWeek
  66606. *
  66607. * @example
  66608. * 0 : start at Sunday
  66609. * 1 : start at Monday
  66610. *
  66611. * @return {number}
  66612. */
  66613. Calendar.prototype.getFirstDayOfWeek = function () {
  66614. return this._firstDayOfWeek;
  66615. };
  66616. /**
  66617. * get date info
  66618. * }
  66619. */
  66620. Calendar.prototype.getDateInfo = function (date) {
  66621. date = parseDate(date);
  66622. var y = date.getFullYear();
  66623. var m = date.getMonth() + 1;
  66624. var mStr = m < 10 ? '0' + m : '' + m;
  66625. var d = date.getDate();
  66626. var dStr = d < 10 ? '0' + d : '' + d;
  66627. var day = date.getDay();
  66628. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  66629. return {
  66630. y: y + '',
  66631. m: mStr,
  66632. d: dStr,
  66633. day: day,
  66634. time: date.getTime(),
  66635. formatedDate: y + '-' + mStr + '-' + dStr,
  66636. date: date
  66637. };
  66638. };
  66639. Calendar.prototype.getNextNDay = function (date, n) {
  66640. n = n || 0;
  66641. if (n === 0) {
  66642. return this.getDateInfo(date);
  66643. }
  66644. date = new Date(this.getDateInfo(date).time);
  66645. date.setDate(date.getDate() + n);
  66646. return this.getDateInfo(date);
  66647. };
  66648. Calendar.prototype.update = function (ecModel, api) {
  66649. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  66650. this._orient = this._model.get('orient');
  66651. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  66652. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  66653. var weeks = this._rangeInfo.weeks || 1;
  66654. var whNames = ['width', 'height'];
  66655. var cellSize = this._model.getCellSize().slice();
  66656. var layoutParams = this._model.getBoxLayoutParams();
  66657. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  66658. each([0, 1], function (idx) {
  66659. if (cellSizeSpecified(cellSize, idx)) {
  66660. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  66661. }
  66662. });
  66663. var whGlobal = {
  66664. width: api.getWidth(),
  66665. height: api.getHeight()
  66666. };
  66667. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  66668. each([0, 1], function (idx) {
  66669. if (!cellSizeSpecified(cellSize, idx)) {
  66670. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  66671. }
  66672. });
  66673. function cellSizeSpecified(cellSize, idx) {
  66674. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  66675. } // Has been calculated out number.
  66676. this._sw = cellSize[0];
  66677. this._sh = cellSize[1];
  66678. };
  66679. /**
  66680. * Convert a time data(time, value) item to (x, y) point.
  66681. */
  66682. // TODO Clamp of calendar is not same with cartesian coordinate systems.
  66683. // It will return NaN if data exceeds.
  66684. Calendar.prototype.dataToPoint = function (data, clamp) {
  66685. isArray(data) && (data = data[0]);
  66686. clamp == null && (clamp = true);
  66687. var dayInfo = this.getDateInfo(data);
  66688. var range = this._rangeInfo;
  66689. var date = dayInfo.formatedDate; // if not in range return [NaN, NaN]
  66690. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY)) {
  66691. return [NaN, NaN];
  66692. }
  66693. var week = dayInfo.day;
  66694. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  66695. if (this._orient === 'vertical') {
  66696. return [this._rect.x + week * this._sw + this._sw / 2, this._rect.y + nthWeek * this._sh + this._sh / 2];
  66697. }
  66698. return [this._rect.x + nthWeek * this._sw + this._sw / 2, this._rect.y + week * this._sh + this._sh / 2];
  66699. };
  66700. /**
  66701. * Convert a (x, y) point to time data
  66702. */
  66703. Calendar.prototype.pointToData = function (point) {
  66704. var date = this.pointToDate(point);
  66705. return date && date.time;
  66706. };
  66707. /**
  66708. * Convert a time date item to (x, y) four point.
  66709. */
  66710. Calendar.prototype.dataToRect = function (data, clamp) {
  66711. var point = this.dataToPoint(data, clamp);
  66712. return {
  66713. contentShape: {
  66714. x: point[0] - (this._sw - this._lineWidth) / 2,
  66715. y: point[1] - (this._sh - this._lineWidth) / 2,
  66716. width: this._sw - this._lineWidth,
  66717. height: this._sh - this._lineWidth
  66718. },
  66719. center: point,
  66720. tl: [point[0] - this._sw / 2, point[1] - this._sh / 2],
  66721. tr: [point[0] + this._sw / 2, point[1] - this._sh / 2],
  66722. br: [point[0] + this._sw / 2, point[1] + this._sh / 2],
  66723. bl: [point[0] - this._sw / 2, point[1] + this._sh / 2]
  66724. };
  66725. };
  66726. /**
  66727. * Convert a (x, y) point to time date
  66728. *
  66729. * @param {Array} point point
  66730. * @return {Object} date
  66731. */
  66732. Calendar.prototype.pointToDate = function (point) {
  66733. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  66734. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  66735. var range = this._rangeInfo.range;
  66736. if (this._orient === 'vertical') {
  66737. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  66738. }
  66739. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  66740. };
  66741. Calendar.prototype.convertToPixel = function (ecModel, finder, value) {
  66742. var coordSys = getCoordSys$4(finder);
  66743. return coordSys === this ? coordSys.dataToPoint(value) : null;
  66744. };
  66745. Calendar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  66746. var coordSys = getCoordSys$4(finder);
  66747. return coordSys === this ? coordSys.pointToData(pixel) : null;
  66748. };
  66749. Calendar.prototype.containPoint = function (point) {
  66750. console.warn('Not implemented.');
  66751. return false;
  66752. };
  66753. /**
  66754. * initRange
  66755. * Normalize to an [start, end] array
  66756. */
  66757. Calendar.prototype._initRangeOption = function () {
  66758. var range = this._model.get('range');
  66759. var normalizedRange; // Convert [1990] to 1990
  66760. if (isArray(range) && range.length === 1) {
  66761. range = range[0];
  66762. }
  66763. if (!isArray(range)) {
  66764. var rangeStr = range.toString(); // One year.
  66765. if (/^\d{4}$/.test(rangeStr)) {
  66766. normalizedRange = [rangeStr + '-01-01', rangeStr + '-12-31'];
  66767. } // One month
  66768. if (/^\d{4}[\/|-]\d{1,2}$/.test(rangeStr)) {
  66769. var start = this.getDateInfo(rangeStr);
  66770. var firstDay = start.date;
  66771. firstDay.setMonth(firstDay.getMonth() + 1);
  66772. var end = this.getNextNDay(firstDay, -1);
  66773. normalizedRange = [start.formatedDate, end.formatedDate];
  66774. } // One day
  66775. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rangeStr)) {
  66776. normalizedRange = [rangeStr, rangeStr];
  66777. }
  66778. } else {
  66779. normalizedRange = range;
  66780. }
  66781. if (!normalizedRange) {
  66782. if ("development" !== 'production') {
  66783. logError('Invalid date range.');
  66784. } // Not handling it.
  66785. return range;
  66786. }
  66787. var tmp = this._getRangeInfo(normalizedRange);
  66788. if (tmp.start.time > tmp.end.time) {
  66789. normalizedRange.reverse();
  66790. }
  66791. return normalizedRange;
  66792. };
  66793. /**
  66794. * range info
  66795. *
  66796. * @private
  66797. * @param {Array} range range ['2017-01-01', '2017-07-08']
  66798. * If range[0] > range[1], they will not be reversed.
  66799. * @return {Object} obj
  66800. */
  66801. Calendar.prototype._getRangeInfo = function (range) {
  66802. var parsedRange = [this.getDateInfo(range[0]), this.getDateInfo(range[1])];
  66803. var reversed;
  66804. if (parsedRange[0].time > parsedRange[1].time) {
  66805. reversed = true;
  66806. parsedRange.reverse();
  66807. }
  66808. var allDay = Math.floor(parsedRange[1].time / PROXIMATE_ONE_DAY) - Math.floor(parsedRange[0].time / PROXIMATE_ONE_DAY) + 1; // Consider case1 (#11677 #10430):
  66809. // Set the system timezone as "UK", set the range to `['2016-07-01', '2016-12-31']`
  66810. // Consider case2:
  66811. // Firstly set system timezone as "Time Zone: America/Toronto",
  66812. // ```
  66813. // let first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  66814. // let second = new Date(1478412000000);
  66815. // let allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  66816. // ```
  66817. // will get wrong result because of DST. So we should fix it.
  66818. var date = new Date(parsedRange[0].time);
  66819. var startDateNum = date.getDate();
  66820. var endDateNum = parsedRange[1].date.getDate();
  66821. date.setDate(startDateNum + allDay - 1); // The bias can not over a month, so just compare date.
  66822. var dateNum = date.getDate();
  66823. if (dateNum !== endDateNum) {
  66824. var sign = date.getTime() - parsedRange[1].time > 0 ? 1 : -1;
  66825. while ((dateNum = date.getDate()) !== endDateNum && (date.getTime() - parsedRange[1].time) * sign > 0) {
  66826. allDay -= sign;
  66827. date.setDate(dateNum - sign);
  66828. }
  66829. }
  66830. var weeks = Math.floor((allDay + parsedRange[0].day + 6) / 7);
  66831. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  66832. reversed && parsedRange.reverse();
  66833. return {
  66834. range: [parsedRange[0].formatedDate, parsedRange[1].formatedDate],
  66835. start: parsedRange[0],
  66836. end: parsedRange[1],
  66837. allDay: allDay,
  66838. weeks: weeks,
  66839. // From 0.
  66840. nthWeek: nthWeek,
  66841. fweek: parsedRange[0].day,
  66842. lweek: parsedRange[1].day
  66843. };
  66844. };
  66845. /**
  66846. * get date by nthWeeks and week day in range
  66847. *
  66848. * @private
  66849. * @param {number} nthWeek the week
  66850. * @param {number} day the week day
  66851. * @param {Array} range [d1, d2]
  66852. * @return {Object}
  66853. */
  66854. Calendar.prototype._getDateByWeeksAndDay = function (nthWeek, day, range) {
  66855. var rangeInfo = this._getRangeInfo(range);
  66856. if (nthWeek > rangeInfo.weeks || nthWeek === 0 && day < rangeInfo.fweek || nthWeek === rangeInfo.weeks && day > rangeInfo.lweek) {
  66857. return null;
  66858. }
  66859. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  66860. var date = new Date(rangeInfo.start.time);
  66861. date.setDate(+rangeInfo.start.d + nthDay);
  66862. return this.getDateInfo(date);
  66863. };
  66864. Calendar.create = function (ecModel, api) {
  66865. var calendarList = [];
  66866. ecModel.eachComponent('calendar', function (calendarModel) {
  66867. var calendar = new Calendar(calendarModel, ecModel, api);
  66868. calendarList.push(calendar);
  66869. calendarModel.coordinateSystem = calendar;
  66870. });
  66871. ecModel.eachSeries(function (calendarSeries) {
  66872. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  66873. // Inject coordinate system
  66874. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  66875. }
  66876. });
  66877. return calendarList;
  66878. };
  66879. Calendar.dimensions = ['time', 'value'];
  66880. return Calendar;
  66881. }();
  66882. function getCoordSys$4(finder) {
  66883. var calendarModel = finder.calendarModel;
  66884. var seriesModel = finder.seriesModel;
  66885. var coordSys = calendarModel ? calendarModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem : null;
  66886. return coordSys;
  66887. }
  66888. function install$w(registers) {
  66889. registers.registerComponentModel(CalendarModel);
  66890. registers.registerComponentView(CalendarView);
  66891. registers.registerCoordinateSystem('calendar', Calendar);
  66892. }
  66893. var inner$e = makeInner();
  66894. var _nonShapeGraphicElements = {
  66895. // Reserved but not supported in graphic component.
  66896. path: null,
  66897. compoundPath: null,
  66898. // Supported in graphic component.
  66899. group: Group,
  66900. image: ZRImage,
  66901. text: ZRText
  66902. }; // ------------------------
  66903. // Preprocessor
  66904. // ------------------------
  66905. var preprocessor = function (option) {
  66906. var graphicOption = option.graphic; // Convert
  66907. // {graphic: [{left: 10, type: 'circle'}, ...]}
  66908. // or
  66909. // {graphic: {left: 10, type: 'circle'}}
  66910. // to
  66911. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  66912. if (isArray(graphicOption)) {
  66913. if (!graphicOption[0] || !graphicOption[0].elements) {
  66914. option.graphic = [{
  66915. elements: graphicOption
  66916. }];
  66917. } else {
  66918. // Only one graphic instance can be instantiated. (We dont
  66919. // want that too many views are created in echarts._viewMap)
  66920. option.graphic = [option.graphic[0]];
  66921. }
  66922. } else if (graphicOption && !graphicOption.elements) {
  66923. option.graphic = [{
  66924. elements: [graphicOption]
  66925. }];
  66926. }
  66927. };
  66928. var GraphicComponentModel =
  66929. /** @class */
  66930. function (_super) {
  66931. __extends(GraphicComponentModel, _super);
  66932. function GraphicComponentModel() {
  66933. var _this = _super !== null && _super.apply(this, arguments) || this;
  66934. _this.type = GraphicComponentModel.type;
  66935. _this.preventAutoZ = true;
  66936. return _this;
  66937. }
  66938. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  66939. // Prevent default merge to elements
  66940. var elements = this.option.elements;
  66941. this.option.elements = null;
  66942. _super.prototype.mergeOption.call(this, option, ecModel);
  66943. this.option.elements = elements;
  66944. };
  66945. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  66946. var thisOption = this.option;
  66947. var newList = (isInit ? thisOption : newOption).elements;
  66948. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  66949. var flattenedList = [];
  66950. this._flatten(newList, flattenedList, null);
  66951. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge'); // Clear elOptionsToUpdate
  66952. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  66953. each(mappingResult, function (resultItem, index) {
  66954. var newElOption = resultItem.newOption;
  66955. if ("development" !== 'production') {
  66956. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  66957. }
  66958. if (!newElOption) {
  66959. return;
  66960. }
  66961. elOptionsToUpdate.push(newElOption);
  66962. setKeyInfoToNewElOption(resultItem, newElOption);
  66963. mergeNewElOptionToExist(existList, index, newElOption);
  66964. setLayoutInfoToExist(existList[index], newElOption);
  66965. }, this); // Clean
  66966. for (var i = existList.length - 1; i >= 0; i--) {
  66967. if (existList[i] == null) {
  66968. existList.splice(i, 1);
  66969. } else {
  66970. // $action should be volatile, otherwise option gotten from
  66971. // `getOption` will contain unexpected $action.
  66972. delete existList[i].$action;
  66973. }
  66974. }
  66975. };
  66976. /**
  66977. * Convert
  66978. * [{
  66979. * type: 'group',
  66980. * id: 'xx',
  66981. * children: [{type: 'circle'}, {type: 'polygon'}]
  66982. * }]
  66983. * to
  66984. * [
  66985. * {type: 'group', id: 'xx'},
  66986. * {type: 'circle', parentId: 'xx'},
  66987. * {type: 'polygon', parentId: 'xx'}
  66988. * ]
  66989. */
  66990. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  66991. each(optionList, function (option) {
  66992. if (!option) {
  66993. return;
  66994. }
  66995. if (parentOption) {
  66996. option.parentOption = parentOption;
  66997. }
  66998. result.push(option);
  66999. var children = option.children;
  67000. if (option.type === 'group' && children) {
  67001. this._flatten(children, result, option);
  67002. } // Deleting for JSON output, and for not affecting group creation.
  67003. delete option.children;
  67004. }, this);
  67005. }; // FIXME
  67006. // Pass to view using payload? setOption has a payload?
  67007. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  67008. var els = this._elOptionsToUpdate; // Clear to avoid render duplicately when zooming.
  67009. this._elOptionsToUpdate = null;
  67010. return els;
  67011. };
  67012. GraphicComponentModel.type = 'graphic';
  67013. GraphicComponentModel.defaultOption = {
  67014. elements: [] // parentId: null
  67015. };
  67016. return GraphicComponentModel;
  67017. }(ComponentModel); // ------------------------
  67018. // View
  67019. // ------------------------
  67020. var GraphicComponentView =
  67021. /** @class */
  67022. function (_super) {
  67023. __extends(GraphicComponentView, _super);
  67024. function GraphicComponentView() {
  67025. var _this = _super !== null && _super.apply(this, arguments) || this;
  67026. _this.type = GraphicComponentView.type;
  67027. return _this;
  67028. }
  67029. GraphicComponentView.prototype.init = function () {
  67030. this._elMap = createHashMap();
  67031. };
  67032. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  67033. // Having leveraged between use cases and algorithm complexity, a very
  67034. // simple layout mechanism is used:
  67035. // The size(width/height) can be determined by itself or its parent (not
  67036. // implemented yet), but can not by its children. (Top-down travel)
  67037. // The location(x/y) can be determined by the bounding rect of itself
  67038. // (can including its descendants or not) and the size of its parent.
  67039. // (Bottom-up travel)
  67040. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  67041. // view will be reused.
  67042. if (graphicModel !== this._lastGraphicModel) {
  67043. this._clear();
  67044. }
  67045. this._lastGraphicModel = graphicModel;
  67046. this._updateElements(graphicModel);
  67047. this._relocate(graphicModel, api);
  67048. };
  67049. /**
  67050. * Update graphic elements.
  67051. */
  67052. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  67053. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  67054. if (!elOptionsToUpdate) {
  67055. return;
  67056. }
  67057. var elMap = this._elMap;
  67058. var rootGroup = this.group; // Top-down tranverse to assign graphic settings to each elements.
  67059. each(elOptionsToUpdate, function (elOption) {
  67060. var id = convertOptionIdName(elOption.id, null);
  67061. var elExisting = id != null ? elMap.get(id) : null;
  67062. var parentId = convertOptionIdName(elOption.parentId, null);
  67063. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  67064. var elType = elOption.type;
  67065. var elOptionStyle = elOption.style;
  67066. if (elType === 'text' && elOptionStyle) {
  67067. // In top/bottom mode, textVerticalAlign should not be used, which cause
  67068. // inaccurately locating.
  67069. if (elOption.hv && elOption.hv[1]) {
  67070. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  67071. }
  67072. }
  67073. var textContentOption = elOption.textContent;
  67074. var textConfig = elOption.textConfig;
  67075. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  67076. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  67077. if (!textConfig && convertResult.textConfig) {
  67078. textConfig = elOption.textConfig = convertResult.textConfig;
  67079. }
  67080. if (!textContentOption && convertResult.textContent) {
  67081. textContentOption = convertResult.textContent;
  67082. }
  67083. } // Remove unnecessary props to avoid potential problems.
  67084. var elOptionCleaned = getCleanedElOption(elOption); // For simple, do not support parent change, otherwise reorder is needed.
  67085. if ("development" !== 'production') {
  67086. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  67087. }
  67088. var $action = elOption.$action || 'merge';
  67089. if ($action === 'merge') {
  67090. elExisting ? elExisting.attr(elOptionCleaned) : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  67091. } else if ($action === 'replace') {
  67092. removeEl(elExisting, elMap);
  67093. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  67094. } else if ($action === 'remove') {
  67095. removeEl(elExisting, elMap);
  67096. }
  67097. var el = elMap.get(id);
  67098. if (el && textContentOption) {
  67099. if ($action === 'merge') {
  67100. var textContentExisting = el.getTextContent();
  67101. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  67102. } else if ($action === 'replace') {
  67103. el.setTextContent(new ZRText(textContentOption));
  67104. }
  67105. }
  67106. if (el) {
  67107. var elInner = inner$e(el);
  67108. elInner.__ecGraphicWidthOption = elOption.width;
  67109. elInner.__ecGraphicHeightOption = elOption.height;
  67110. setEventData(el, graphicModel, elOption);
  67111. setTooltipConfig({
  67112. el: el,
  67113. componentModel: graphicModel,
  67114. itemName: el.name,
  67115. itemTooltipOption: elOption.tooltip
  67116. });
  67117. }
  67118. });
  67119. };
  67120. /**
  67121. * Locate graphic elements.
  67122. */
  67123. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  67124. var elOptions = graphicModel.option.elements;
  67125. var rootGroup = this.group;
  67126. var elMap = this._elMap;
  67127. var apiWidth = api.getWidth();
  67128. var apiHeight = api.getHeight(); // Top-down to calculate percentage width/height of group
  67129. for (var i = 0; i < elOptions.length; i++) {
  67130. var elOption = elOptions[i];
  67131. var id = convertOptionIdName(elOption.id, null);
  67132. var el = id != null ? elMap.get(id) : null;
  67133. if (!el || !el.isGroup) {
  67134. continue;
  67135. }
  67136. var parentEl = el.parent;
  67137. var isParentRoot = parentEl === rootGroup; // Like 'position:absolut' in css, default 0.
  67138. var elInner = inner$e(el);
  67139. var parentElInner = inner$e(parentEl);
  67140. elInner.__ecGraphicWidth = parsePercent$1(elInner.__ecGraphicWidthOption, isParentRoot ? apiWidth : parentElInner.__ecGraphicWidth) || 0;
  67141. elInner.__ecGraphicHeight = parsePercent$1(elInner.__ecGraphicHeightOption, isParentRoot ? apiHeight : parentElInner.__ecGraphicHeight) || 0;
  67142. } // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  67143. for (var i = elOptions.length - 1; i >= 0; i--) {
  67144. var elOption = elOptions[i];
  67145. var id = convertOptionIdName(elOption.id, null);
  67146. var el = id != null ? elMap.get(id) : null;
  67147. if (!el) {
  67148. continue;
  67149. }
  67150. var parentEl = el.parent;
  67151. var parentElInner = inner$e(parentEl);
  67152. var containerInfo = parentEl === rootGroup ? {
  67153. width: apiWidth,
  67154. height: apiHeight
  67155. } : {
  67156. width: parentElInner.__ecGraphicWidth,
  67157. height: parentElInner.__ecGraphicHeight
  67158. }; // PENDING
  67159. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  67160. // does not include the rect of [0, 0, group.width, group.height], which
  67161. // is probably weird for users. Should we make a break change for it?
  67162. positionElement(el, elOption, containerInfo, null, {
  67163. hv: elOption.hv,
  67164. boundingMode: elOption.bounding
  67165. });
  67166. }
  67167. };
  67168. /**
  67169. * Clear all elements.
  67170. */
  67171. GraphicComponentView.prototype._clear = function () {
  67172. var elMap = this._elMap;
  67173. elMap.each(function (el) {
  67174. removeEl(el, elMap);
  67175. });
  67176. this._elMap = createHashMap();
  67177. };
  67178. GraphicComponentView.prototype.dispose = function () {
  67179. this._clear();
  67180. };
  67181. GraphicComponentView.type = 'graphic';
  67182. return GraphicComponentView;
  67183. }(ComponentView);
  67184. function createEl$1(id, targetElParent, elOption, elMap) {
  67185. var graphicType = elOption.type;
  67186. if ("development" !== 'production') {
  67187. assert(graphicType, 'graphic type MUST be set');
  67188. }
  67189. var Clz = hasOwn(_nonShapeGraphicElements, graphicType) // Those graphic elements are not shapes. They should not be
  67190. // overwritten by users, so do them first.
  67191. ? _nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  67192. if ("development" !== 'production') {
  67193. assert(Clz, 'graphic type can not be found');
  67194. }
  67195. var el = new Clz(elOption);
  67196. targetElParent.add(el);
  67197. elMap.set(id, el);
  67198. inner$e(el).__ecGraphicId = id;
  67199. }
  67200. function removeEl(elExisting, elMap) {
  67201. var existElParent = elExisting && elExisting.parent;
  67202. if (existElParent) {
  67203. elExisting.type === 'group' && elExisting.traverse(function (el) {
  67204. removeEl(el, elMap);
  67205. });
  67206. elMap.removeKey(inner$e(elExisting).__ecGraphicId);
  67207. existElParent.remove(elExisting);
  67208. }
  67209. } // Remove unnecessary props to avoid potential problems.
  67210. function getCleanedElOption(elOption) {
  67211. elOption = extend({}, elOption);
  67212. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent'].concat(LOCATION_PARAMS), function (name) {
  67213. delete elOption[name];
  67214. });
  67215. return elOption;
  67216. }
  67217. function isSetLoc(obj, props) {
  67218. var isSet;
  67219. each(props, function (prop) {
  67220. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  67221. });
  67222. return isSet;
  67223. }
  67224. function setKeyInfoToNewElOption(resultItem, newElOption) {
  67225. var existElOption = resultItem.existing; // Set id and type after id assigned.
  67226. newElOption.id = resultItem.keyInfo.id;
  67227. !newElOption.type && existElOption && (newElOption.type = existElOption.type); // Set parent id if not specified
  67228. if (newElOption.parentId == null) {
  67229. var newElParentOption = newElOption.parentOption;
  67230. if (newElParentOption) {
  67231. newElOption.parentId = newElParentOption.id;
  67232. } else if (existElOption) {
  67233. newElOption.parentId = existElOption.parentId;
  67234. }
  67235. } // Clear
  67236. newElOption.parentOption = null;
  67237. }
  67238. function mergeNewElOptionToExist(existList, index, newElOption) {
  67239. // Update existing options, for `getOption` feature.
  67240. var newElOptCopy = extend({}, newElOption);
  67241. var existElOption = existList[index];
  67242. var $action = newElOption.$action || 'merge';
  67243. if ($action === 'merge') {
  67244. if (existElOption) {
  67245. if ("development" !== 'production') {
  67246. var newType = newElOption.type;
  67247. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  67248. } // We can ensure that newElOptCopy and existElOption are not
  67249. // the same object, so `merge` will not change newElOptCopy.
  67250. merge(existElOption, newElOptCopy, true); // Rigid body, use ignoreSize.
  67251. mergeLayoutParam(existElOption, newElOptCopy, {
  67252. ignoreSize: true
  67253. }); // Will be used in render.
  67254. copyLayoutParams(newElOption, existElOption);
  67255. } else {
  67256. existList[index] = newElOptCopy;
  67257. }
  67258. } else if ($action === 'replace') {
  67259. existList[index] = newElOptCopy;
  67260. } else if ($action === 'remove') {
  67261. // null will be cleaned later.
  67262. existElOption && (existList[index] = null);
  67263. }
  67264. }
  67265. function setLayoutInfoToExist(existItem, newElOption) {
  67266. if (!existItem) {
  67267. return;
  67268. }
  67269. existItem.hv = newElOption.hv = [// Rigid body, dont care `width`.
  67270. isSetLoc(newElOption, ['left', 'right']), // Rigid body, dont care `height`.
  67271. isSetLoc(newElOption, ['top', 'bottom'])]; // Give default group size. Otherwise layout error may occur.
  67272. if (existItem.type === 'group') {
  67273. var existingGroupOpt = existItem;
  67274. var newGroupOpt = newElOption;
  67275. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  67276. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  67277. }
  67278. }
  67279. function setEventData(el, graphicModel, elOption) {
  67280. var eventData = getECData(el).eventData; // Simple optimize for large amount of elements that no need event.
  67281. if (!el.silent && !el.ignore && !eventData) {
  67282. eventData = getECData(el).eventData = {
  67283. componentType: 'graphic',
  67284. componentIndex: graphicModel.componentIndex,
  67285. name: el.name
  67286. };
  67287. } // `elOption.info` enables user to mount some info on
  67288. // elements and use them in event handlers.
  67289. if (eventData) {
  67290. eventData.info = elOption.info;
  67291. }
  67292. }
  67293. function install$x(registers) {
  67294. registers.registerComponentModel(GraphicComponentModel);
  67295. registers.registerComponentView(GraphicComponentView);
  67296. registers.registerPreprocessor(preprocessor);
  67297. }
  67298. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single']; // Supported coords.
  67299. // FIXME: polar has been broken (but rarely used).
  67300. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  67301. function isCoordSupported(seriesModel) {
  67302. var coordType = seriesModel.get('coordinateSystem');
  67303. return indexOf(SERIES_COORDS, coordType) >= 0;
  67304. }
  67305. function getAxisMainType(axisDim) {
  67306. if ("development" !== 'production') {
  67307. assert(axisDim);
  67308. }
  67309. return axisDim + 'Axis';
  67310. }
  67311. /**
  67312. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  67313. * This function finds all linked dataZoomModels start from the given payload.
  67314. */
  67315. function findEffectedDataZooms(ecModel, payload) {
  67316. // Key: `DataZoomAxisDimension`
  67317. var axisRecords = createHashMap();
  67318. var effectedModels = []; // Key: uid of dataZoomModel
  67319. var effectedModelMap = createHashMap(); // Find the dataZooms specified by payload.
  67320. ecModel.eachComponent({
  67321. mainType: 'dataZoom',
  67322. query: payload
  67323. }, function (dataZoomModel) {
  67324. if (!effectedModelMap.get(dataZoomModel.uid)) {
  67325. addToEffected(dataZoomModel);
  67326. }
  67327. }); // Start from the given dataZoomModels, travel the graph to find
  67328. // all of the linked dataZoom models.
  67329. var foundNewLink;
  67330. do {
  67331. foundNewLink = false;
  67332. ecModel.eachComponent('dataZoom', processSingle);
  67333. } while (foundNewLink);
  67334. function processSingle(dataZoomModel) {
  67335. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  67336. addToEffected(dataZoomModel);
  67337. foundNewLink = true;
  67338. }
  67339. }
  67340. function addToEffected(dataZoom) {
  67341. effectedModelMap.set(dataZoom.uid, true);
  67342. effectedModels.push(dataZoom);
  67343. markAxisControlled(dataZoom);
  67344. }
  67345. function isLinked(dataZoomModel) {
  67346. var isLink = false;
  67347. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  67348. var axisIdxArr = axisRecords.get(axisDim);
  67349. if (axisIdxArr && axisIdxArr[axisIndex]) {
  67350. isLink = true;
  67351. }
  67352. });
  67353. return isLink;
  67354. }
  67355. function markAxisControlled(dataZoomModel) {
  67356. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  67357. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  67358. });
  67359. }
  67360. return effectedModels;
  67361. }
  67362. /**
  67363. * Find the first target coordinate system.
  67364. * Available after model built.
  67365. *
  67366. * @return Like {
  67367. * grid: [
  67368. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  67369. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  67370. * ...
  67371. * ], // cartesians must not be null/undefined.
  67372. * polar: [
  67373. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  67374. * ...
  67375. * ], // polars must not be null/undefined.
  67376. * singleAxis: [
  67377. * {model: coord0, axisModels: [], coordIndex: 0}
  67378. * ]
  67379. * }
  67380. */
  67381. function collectReferCoordSysModelInfo(dataZoomModel) {
  67382. var ecModel = dataZoomModel.ecModel;
  67383. var coordSysInfoWrap = {
  67384. infoList: [],
  67385. infoMap: createHashMap()
  67386. };
  67387. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  67388. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  67389. if (!axisModel) {
  67390. return;
  67391. }
  67392. var coordSysModel = axisModel.getCoordSysModel();
  67393. if (!coordSysModel) {
  67394. return;
  67395. }
  67396. var coordSysUid = coordSysModel.uid;
  67397. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  67398. if (!coordSysInfo) {
  67399. coordSysInfo = {
  67400. model: coordSysModel,
  67401. axisModels: []
  67402. };
  67403. coordSysInfoWrap.infoList.push(coordSysInfo);
  67404. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  67405. }
  67406. coordSysInfo.axisModels.push(axisModel);
  67407. });
  67408. return coordSysInfoWrap;
  67409. }
  67410. var DataZoomAxisInfo =
  67411. /** @class */
  67412. function () {
  67413. function DataZoomAxisInfo() {
  67414. this.indexList = [];
  67415. this.indexMap = [];
  67416. }
  67417. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  67418. // Remove duplication.
  67419. if (!this.indexMap[axisCmptIdx]) {
  67420. this.indexList.push(axisCmptIdx);
  67421. this.indexMap[axisCmptIdx] = true;
  67422. }
  67423. };
  67424. return DataZoomAxisInfo;
  67425. }();
  67426. var DataZoomModel =
  67427. /** @class */
  67428. function (_super) {
  67429. __extends(DataZoomModel, _super);
  67430. function DataZoomModel() {
  67431. var _this = _super !== null && _super.apply(this, arguments) || this;
  67432. _this.type = DataZoomModel.type;
  67433. _this._autoThrottle = true;
  67434. _this._noTarget = true;
  67435. /**
  67436. * It is `[rangeModeForMin, rangeModeForMax]`.
  67437. * The optional values for `rangeMode`:
  67438. * + `'value'` mode: the axis extent will always be determined by
  67439. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  67440. * how data like and how `axis.min` and `axis.max` are.
  67441. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  67442. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  67443. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  67444. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  67445. *
  67446. * For example, when users are using dynamic data (update data periodically via `setOption`),
  67447. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  67448. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  67449. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  67450. */
  67451. _this._rangePropMode = ['percent', 'percent'];
  67452. return _this;
  67453. }
  67454. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  67455. var inputRawOption = retrieveRawOption(option);
  67456. /**
  67457. * Suppose a "main process" start at the point that model prepared (that is,
  67458. * model initialized or merged or method called in `action`).
  67459. * We should keep the `main process` idempotent, that is, given a set of values
  67460. * on `option`, we get the same result.
  67461. *
  67462. * But sometimes, values on `option` will be updated for providing users
  67463. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  67464. * should not be the base/input of the `main process`.
  67465. *
  67466. * So in that case we should save and keep the input of the `main process`
  67467. * separately, called `settledOption`.
  67468. *
  67469. * For example, consider the case:
  67470. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  67471. * where the original input `option.startValue`, `option.endValue` are earsed by
  67472. * calculated value.
  67473. * (Step)2) click the legend to hide and show a series,
  67474. * where the new range is calculated by the earsed `startValue` and `endValue`,
  67475. * which brings incorrect result.
  67476. */
  67477. this.settledOption = inputRawOption;
  67478. this.mergeDefaultAndTheme(option, ecModel);
  67479. this._doInit(inputRawOption);
  67480. };
  67481. DataZoomModel.prototype.mergeOption = function (newOption) {
  67482. var inputRawOption = retrieveRawOption(newOption); //FIX #2591
  67483. merge(this.option, newOption, true);
  67484. merge(this.settledOption, inputRawOption, true);
  67485. this._doInit(inputRawOption);
  67486. };
  67487. DataZoomModel.prototype._doInit = function (inputRawOption) {
  67488. var thisOption = this.option; // if (!env.canvasSupported) {
  67489. // thisOption.realtime = false;
  67490. // }
  67491. this._setDefaultThrottle(inputRawOption);
  67492. this._updateRangeUse(inputRawOption);
  67493. var settledOption = this.settledOption;
  67494. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  67495. // start/end has higher priority over startValue/endValue if they
  67496. // both set, but we should make chart.setOption({endValue: 1000})
  67497. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  67498. if (this._rangePropMode[index] === 'value') {
  67499. thisOption[names[0]] = settledOption[names[0]] = null;
  67500. } // Otherwise do nothing and use the merge result.
  67501. }, this);
  67502. this._resetTarget();
  67503. };
  67504. DataZoomModel.prototype._resetTarget = function () {
  67505. var optionOrient = this.get('orient', true);
  67506. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  67507. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  67508. if (hasAxisSpecified) {
  67509. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  67510. } else {
  67511. this._orient = optionOrient || 'horizontal';
  67512. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  67513. }
  67514. this._noTarget = true;
  67515. targetAxisIndexMap.each(function (axisInfo) {
  67516. if (axisInfo.indexList.length) {
  67517. this._noTarget = false;
  67518. }
  67519. }, this);
  67520. };
  67521. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  67522. var hasAxisSpecified = false;
  67523. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  67524. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING); // When user set axisIndex as a empty array, we think that user specify axisIndex
  67525. // but do not want use auto mode. Because empty array may be encountered when
  67526. // some error occured.
  67527. if (!refering.specified) {
  67528. return;
  67529. }
  67530. hasAxisSpecified = true;
  67531. var axisInfo = new DataZoomAxisInfo();
  67532. each(refering.models, function (axisModel) {
  67533. axisInfo.add(axisModel.componentIndex);
  67534. });
  67535. targetAxisIndexMap.set(axisDim, axisInfo);
  67536. }, this);
  67537. return hasAxisSpecified;
  67538. };
  67539. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  67540. var ecModel = this.ecModel;
  67541. var needAuto = true; // Find axis that parallel to dataZoom as default.
  67542. if (needAuto) {
  67543. var axisDim = orient === 'vertical' ? 'y' : 'x';
  67544. var axisModels = ecModel.findComponents({
  67545. mainType: axisDim + 'Axis'
  67546. });
  67547. setParallelAxis(axisModels, axisDim);
  67548. } // Find axis that parallel to dataZoom as default.
  67549. if (needAuto) {
  67550. var axisModels = ecModel.findComponents({
  67551. mainType: 'singleAxis',
  67552. filter: function (axisModel) {
  67553. return axisModel.get('orient', true) === orient;
  67554. }
  67555. });
  67556. setParallelAxis(axisModels, 'single');
  67557. }
  67558. function setParallelAxis(axisModels, axisDim) {
  67559. // At least use the first parallel axis as the target axis.
  67560. var axisModel = axisModels[0];
  67561. if (!axisModel) {
  67562. return;
  67563. }
  67564. var axisInfo = new DataZoomAxisInfo();
  67565. axisInfo.add(axisModel.componentIndex);
  67566. targetAxisIndexMap.set(axisDim, axisInfo);
  67567. needAuto = false; // Find parallel axes in the same grid.
  67568. if (axisDim === 'x' || axisDim === 'y') {
  67569. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  67570. gridModel_1 && each(axisModels, function (axModel) {
  67571. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  67572. axisInfo.add(axModel.componentIndex);
  67573. }
  67574. });
  67575. }
  67576. }
  67577. if (needAuto) {
  67578. // If no parallel axis, find the first category axis as default. (Also consider polar).
  67579. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  67580. if (!needAuto) {
  67581. return;
  67582. }
  67583. var axisModels = ecModel.findComponents({
  67584. mainType: getAxisMainType(axisDim),
  67585. filter: function (axisModel) {
  67586. return axisModel.get('type', true) === 'category';
  67587. }
  67588. });
  67589. if (axisModels[0]) {
  67590. var axisInfo = new DataZoomAxisInfo();
  67591. axisInfo.add(axisModels[0].componentIndex);
  67592. targetAxisIndexMap.set(axisDim, axisInfo);
  67593. needAuto = false;
  67594. }
  67595. }, this);
  67596. }
  67597. };
  67598. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  67599. var dim; // Find the first axis
  67600. this.eachTargetAxis(function (axisDim) {
  67601. !dim && (dim = axisDim);
  67602. }, this);
  67603. return dim === 'y' ? 'vertical' : 'horizontal';
  67604. };
  67605. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  67606. // When first time user set throttle, auto throttle ends.
  67607. if (inputRawOption.hasOwnProperty('throttle')) {
  67608. this._autoThrottle = false;
  67609. }
  67610. if (this._autoThrottle) {
  67611. var globalOption = this.ecModel.option;
  67612. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  67613. }
  67614. };
  67615. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  67616. var rangePropMode = this._rangePropMode;
  67617. var rangeModeInOption = this.get('rangeMode');
  67618. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  67619. var percentSpecified = inputRawOption[names[0]] != null;
  67620. var valueSpecified = inputRawOption[names[1]] != null;
  67621. if (percentSpecified && !valueSpecified) {
  67622. rangePropMode[index] = 'percent';
  67623. } else if (!percentSpecified && valueSpecified) {
  67624. rangePropMode[index] = 'value';
  67625. } else if (rangeModeInOption) {
  67626. rangePropMode[index] = rangeModeInOption[index];
  67627. } else if (percentSpecified) {
  67628. // percentSpecified && valueSpecified
  67629. rangePropMode[index] = 'percent';
  67630. } // else remain its original setting.
  67631. });
  67632. };
  67633. DataZoomModel.prototype.noTarget = function () {
  67634. return this._noTarget;
  67635. };
  67636. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  67637. var firstAxisModel;
  67638. this.eachTargetAxis(function (axisDim, axisIndex) {
  67639. if (firstAxisModel == null) {
  67640. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  67641. }
  67642. }, this);
  67643. return firstAxisModel;
  67644. };
  67645. /**
  67646. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  67647. */
  67648. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  67649. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  67650. each(axisInfo.indexList, function (axisIndex) {
  67651. callback.call(context, axisDim, axisIndex);
  67652. });
  67653. });
  67654. };
  67655. /**
  67656. * @return If not found, return null/undefined.
  67657. */
  67658. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  67659. var axisModel = this.getAxisModel(axisDim, axisIndex);
  67660. if (axisModel) {
  67661. return axisModel.__dzAxisProxy;
  67662. }
  67663. };
  67664. /**
  67665. * @return If not found, return null/undefined.
  67666. */
  67667. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  67668. if ("development" !== 'production') {
  67669. assert(axisDim && axisIndex != null);
  67670. }
  67671. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  67672. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  67673. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  67674. }
  67675. };
  67676. /**
  67677. * If not specified, set to undefined.
  67678. */
  67679. DataZoomModel.prototype.setRawRange = function (opt) {
  67680. var thisOption = this.option;
  67681. var settledOption = this.settledOption;
  67682. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  67683. // Consider the pair <start, startValue>:
  67684. // If one has value and the other one is `null/undefined`, we both set them
  67685. // to `settledOption`. This strategy enables the feature to clear the original
  67686. // value in `settledOption` to `null/undefined`.
  67687. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  67688. // and keep `settledOption` with the original value. This strategy enables users to
  67689. // only set <end or endValue> but not set <start or startValue> when calling
  67690. // `dispatchAction`.
  67691. // The pair <end, endValue> is treated in the same way.
  67692. if (opt[names[0]] != null || opt[names[1]] != null) {
  67693. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  67694. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  67695. }
  67696. }, this);
  67697. this._updateRangeUse(opt);
  67698. };
  67699. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  67700. var option = this.option;
  67701. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  67702. option[name] = opt[name];
  67703. });
  67704. };
  67705. DataZoomModel.prototype.getPercentRange = function () {
  67706. var axisProxy = this.findRepresentativeAxisProxy();
  67707. if (axisProxy) {
  67708. return axisProxy.getDataPercentWindow();
  67709. }
  67710. };
  67711. /**
  67712. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  67713. *
  67714. * @return [startValue, endValue] value can only be '-' or finite number.
  67715. */
  67716. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  67717. if (axisDim == null && axisIndex == null) {
  67718. var axisProxy = this.findRepresentativeAxisProxy();
  67719. if (axisProxy) {
  67720. return axisProxy.getDataValueWindow();
  67721. }
  67722. } else {
  67723. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  67724. }
  67725. };
  67726. /**
  67727. * @param axisModel If axisModel given, find axisProxy
  67728. * corresponding to the axisModel
  67729. */
  67730. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  67731. if (axisModel) {
  67732. return axisModel.__dzAxisProxy;
  67733. } // Find the first hosted axisProxy
  67734. var firstProxy;
  67735. var axisDimList = this._targetAxisInfoMap.keys();
  67736. for (var i = 0; i < axisDimList.length; i++) {
  67737. var axisDim = axisDimList[i];
  67738. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  67739. for (var j = 0; j < axisInfo.indexList.length; j++) {
  67740. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  67741. if (proxy.hostedBy(this)) {
  67742. return proxy;
  67743. }
  67744. if (!firstProxy) {
  67745. firstProxy = proxy;
  67746. }
  67747. }
  67748. } // If no hosted proxy found, still need to return a proxy.
  67749. // This case always happens in toolbox dataZoom, where axes are all hosted by
  67750. // other dataZooms.
  67751. return firstProxy;
  67752. };
  67753. DataZoomModel.prototype.getRangePropMode = function () {
  67754. return this._rangePropMode.slice();
  67755. };
  67756. DataZoomModel.prototype.getOrient = function () {
  67757. if ("development" !== 'production') {
  67758. // Should not be called before initialized.
  67759. assert(this._orient);
  67760. }
  67761. return this._orient;
  67762. };
  67763. DataZoomModel.type = 'dataZoom';
  67764. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  67765. DataZoomModel.defaultOption = {
  67766. zlevel: 0,
  67767. z: 4,
  67768. filterMode: 'filter',
  67769. start: 0,
  67770. end: 100
  67771. };
  67772. return DataZoomModel;
  67773. }(ComponentModel);
  67774. /**
  67775. * Retrieve the those raw params from option, which will be cached separately.
  67776. * becasue they will be overwritten by normalized/calculated values in the main
  67777. * process.
  67778. */
  67779. function retrieveRawOption(option) {
  67780. var ret = {};
  67781. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  67782. option.hasOwnProperty(name) && (ret[name] = option[name]);
  67783. });
  67784. return ret;
  67785. }
  67786. var SelectDataZoomModel =
  67787. /** @class */
  67788. function (_super) {
  67789. __extends(SelectDataZoomModel, _super);
  67790. function SelectDataZoomModel() {
  67791. var _this = _super !== null && _super.apply(this, arguments) || this;
  67792. _this.type = SelectDataZoomModel.type;
  67793. return _this;
  67794. }
  67795. SelectDataZoomModel.type = 'dataZoom.select';
  67796. return SelectDataZoomModel;
  67797. }(DataZoomModel);
  67798. var DataZoomView =
  67799. /** @class */
  67800. function (_super) {
  67801. __extends(DataZoomView, _super);
  67802. function DataZoomView() {
  67803. var _this = _super !== null && _super.apply(this, arguments) || this;
  67804. _this.type = DataZoomView.type;
  67805. return _this;
  67806. }
  67807. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  67808. this.dataZoomModel = dataZoomModel;
  67809. this.ecModel = ecModel;
  67810. this.api = api;
  67811. };
  67812. DataZoomView.type = 'dataZoom';
  67813. return DataZoomView;
  67814. }(ComponentView);
  67815. var SelectDataZoomView =
  67816. /** @class */
  67817. function (_super) {
  67818. __extends(SelectDataZoomView, _super);
  67819. function SelectDataZoomView() {
  67820. var _this = _super !== null && _super.apply(this, arguments) || this;
  67821. _this.type = SelectDataZoomView.type;
  67822. return _this;
  67823. }
  67824. SelectDataZoomView.type = 'dataZoom.select';
  67825. return SelectDataZoomView;
  67826. }(DataZoomView);
  67827. var each$8 = each;
  67828. var asc$1 = asc;
  67829. /**
  67830. * Operate single axis.
  67831. * One axis can only operated by one axis operator.
  67832. * Different dataZoomModels may be defined to operate the same axis.
  67833. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  67834. * So dataZoomModels share one axisProxy in that case.
  67835. */
  67836. var AxisProxy =
  67837. /** @class */
  67838. function () {
  67839. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  67840. this._dimName = dimName;
  67841. this._axisIndex = axisIndex;
  67842. this.ecModel = ecModel;
  67843. this._dataZoomModel = dataZoomModel; // /**
  67844. // * @readOnly
  67845. // * @private
  67846. // */
  67847. // this.hasSeriesStacked;
  67848. }
  67849. /**
  67850. * Whether the axisProxy is hosted by dataZoomModel.
  67851. */
  67852. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  67853. return this._dataZoomModel === dataZoomModel;
  67854. };
  67855. /**
  67856. * @return Value can only be NaN or finite value.
  67857. */
  67858. AxisProxy.prototype.getDataValueWindow = function () {
  67859. return this._valueWindow.slice();
  67860. };
  67861. /**
  67862. * @return {Array.<number>}
  67863. */
  67864. AxisProxy.prototype.getDataPercentWindow = function () {
  67865. return this._percentWindow.slice();
  67866. };
  67867. AxisProxy.prototype.getTargetSeriesModels = function () {
  67868. var seriesModels = [];
  67869. this.ecModel.eachSeries(function (seriesModel) {
  67870. if (isCoordSupported(seriesModel)) {
  67871. var axisMainType = getAxisMainType(this._dimName);
  67872. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  67873. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  67874. seriesModels.push(seriesModel);
  67875. }
  67876. }
  67877. }, this);
  67878. return seriesModels;
  67879. };
  67880. AxisProxy.prototype.getAxisModel = function () {
  67881. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  67882. };
  67883. AxisProxy.prototype.getMinMaxSpan = function () {
  67884. return clone(this._minMaxSpan);
  67885. };
  67886. /**
  67887. * Only calculate by given range and this._dataExtent, do not change anything.
  67888. */
  67889. AxisProxy.prototype.calculateDataWindow = function (opt) {
  67890. var dataExtent = this._dataExtent;
  67891. var axisModel = this.getAxisModel();
  67892. var scale = axisModel.axis.scale;
  67893. var rangePropMode = this._dataZoomModel.getRangePropMode();
  67894. var percentExtent = [0, 100];
  67895. var percentWindow = [];
  67896. var valueWindow = [];
  67897. var hasPropModeValue;
  67898. each$8(['start', 'end'], function (prop, idx) {
  67899. var boundPercent = opt[prop];
  67900. var boundValue = opt[prop + 'Value']; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  67901. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  67902. // but not min/max of axis, which will be calculated by data window then).
  67903. // The former one is suitable for cases that a dataZoom component controls multiple
  67904. // axes with different unit or extent, and the latter one is suitable for accurate
  67905. // zoom by pixel (e.g., in dataZoomSelect).
  67906. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  67907. // only when setOption or dispatchAction, otherwise it remains its original value.
  67908. // (Why not only record `percentProp` and always map to `valueProp`? Because
  67909. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  67910. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  67911. // data extent. All of values that are overflow the `dataExtent` will be calculated
  67912. // to percent '100%').
  67913. if (rangePropMode[idx] === 'percent') {
  67914. boundPercent == null && (boundPercent = percentExtent[idx]); // Use scale.parse to math round for category or time axis.
  67915. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  67916. } else {
  67917. hasPropModeValue = true;
  67918. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue); // Calculating `percent` from `value` may be not accurate, because
  67919. // This calculation can not be inversed, because all of values that
  67920. // are overflow the `dataExtent` will be calculated to percent '100%'
  67921. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  67922. } // valueWindow[idx] = round(boundValue);
  67923. // percentWindow[idx] = round(boundPercent);
  67924. valueWindow[idx] = boundValue;
  67925. percentWindow[idx] = boundPercent;
  67926. });
  67927. asc$1(valueWindow);
  67928. asc$1(percentWindow); // The windows from user calling of `dispatchAction` might be out of the extent,
  67929. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  67930. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  67931. // where API is able to initialize/modify the window size even though `zoomLock`
  67932. // specified.
  67933. var spans = this._minMaxSpan;
  67934. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  67935. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  67936. var suffix = toValue ? 'Span' : 'ValueSpan';
  67937. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  67938. for (var i = 0; i < 2; i++) {
  67939. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  67940. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  67941. }
  67942. }
  67943. return {
  67944. valueWindow: valueWindow,
  67945. percentWindow: percentWindow
  67946. };
  67947. };
  67948. /**
  67949. * Notice: reset should not be called before series.restoreData() called,
  67950. * so it is recommanded to be called in "process stage" but not "model init
  67951. * stage".
  67952. */
  67953. AxisProxy.prototype.reset = function (dataZoomModel) {
  67954. if (dataZoomModel !== this._dataZoomModel) {
  67955. return;
  67956. }
  67957. var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them.
  67958. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // `calculateDataWindow` uses min/maxSpan.
  67959. this._updateMinMaxSpan();
  67960. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  67961. this._valueWindow = dataWindow.valueWindow;
  67962. this._percentWindow = dataWindow.percentWindow; // Update axis setting then.
  67963. this._setAxisModel();
  67964. };
  67965. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  67966. if (dataZoomModel !== this._dataZoomModel) {
  67967. return;
  67968. }
  67969. var axisDim = this._dimName;
  67970. var seriesModels = this.getTargetSeriesModels();
  67971. var filterMode = dataZoomModel.get('filterMode');
  67972. var valueWindow = this._valueWindow;
  67973. if (filterMode === 'none') {
  67974. return;
  67975. } // FIXME
  67976. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  67977. // with NaN data, NaN will be filtered and stack will be wrong.
  67978. // So we need to force the mode to be set empty.
  67979. // In fect, it is not a big deal that do not support filterMode-'filter'
  67980. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  67981. // selection" some day, which might need "adapt to data extent on the
  67982. // otherAxis", which is disabled by filterMode-'empty'.
  67983. // But currently, stack has been fixed to based on value but not index,
  67984. // so this is not an issue any more.
  67985. // let otherAxisModel = this.getOtherAxisModel();
  67986. // if (dataZoomModel.get('$fromToolbox')
  67987. // && otherAxisModel
  67988. // && otherAxisModel.hasSeriesStacked
  67989. // ) {
  67990. // filterMode = 'empty';
  67991. // }
  67992. // TODO
  67993. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  67994. each$8(seriesModels, function (seriesModel) {
  67995. var seriesData = seriesModel.getData();
  67996. var dataDims = seriesData.mapDimensionsAll(axisDim);
  67997. if (!dataDims.length) {
  67998. return;
  67999. }
  68000. if (filterMode === 'weakFilter') {
  68001. var store_1 = seriesData.getStore();
  68002. var dataDimIndices_1 = map(dataDims, function (dim) {
  68003. return seriesData.getDimensionIndex(dim);
  68004. }, seriesData);
  68005. seriesData.filterSelf(function (dataIndex) {
  68006. var leftOut;
  68007. var rightOut;
  68008. var hasValue;
  68009. for (var i = 0; i < dataDims.length; i++) {
  68010. var value = store_1.get(dataDimIndices_1[i], dataIndex);
  68011. var thisHasValue = !isNaN(value);
  68012. var thisLeftOut = value < valueWindow[0];
  68013. var thisRightOut = value > valueWindow[1];
  68014. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  68015. return true;
  68016. }
  68017. thisHasValue && (hasValue = true);
  68018. thisLeftOut && (leftOut = true);
  68019. thisRightOut && (rightOut = true);
  68020. } // If both left out and right out, do not filter.
  68021. return hasValue && leftOut && rightOut;
  68022. });
  68023. } else {
  68024. each$8(dataDims, function (dim) {
  68025. if (filterMode === 'empty') {
  68026. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  68027. return !isInWindow(value) ? NaN : value;
  68028. }));
  68029. } else {
  68030. var range = {};
  68031. range[dim] = valueWindow; // console.time('select');
  68032. seriesData.selectRange(range); // console.timeEnd('select');
  68033. }
  68034. });
  68035. }
  68036. each$8(dataDims, function (dim) {
  68037. seriesData.setApproximateExtent(valueWindow, dim);
  68038. });
  68039. });
  68040. function isInWindow(value) {
  68041. return value >= valueWindow[0] && value <= valueWindow[1];
  68042. }
  68043. };
  68044. AxisProxy.prototype._updateMinMaxSpan = function () {
  68045. var minMaxSpan = this._minMaxSpan = {};
  68046. var dataZoomModel = this._dataZoomModel;
  68047. var dataExtent = this._dataExtent;
  68048. each$8(['min', 'max'], function (minMax) {
  68049. var percentSpan = dataZoomModel.get(minMax + 'Span');
  68050. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  68051. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan)); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  68052. if (valueSpan != null) {
  68053. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  68054. } else if (percentSpan != null) {
  68055. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  68056. }
  68057. minMaxSpan[minMax + 'Span'] = percentSpan;
  68058. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  68059. }, this);
  68060. };
  68061. AxisProxy.prototype._setAxisModel = function () {
  68062. var axisModel = this.getAxisModel();
  68063. var percentWindow = this._percentWindow;
  68064. var valueWindow = this._valueWindow;
  68065. if (!percentWindow) {
  68066. return;
  68067. } // [0, 500]: arbitrary value, guess axis extent.
  68068. var precision = getPixelPrecision(valueWindow, [0, 500]);
  68069. precision = Math.min(precision, 20); // For value axis, if min/max/scale are not set, we just use the extent obtained
  68070. // by series data, which may be a little different from the extent calculated by
  68071. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  68072. // little when zooming. So it will not be fixed until some users require it strongly.
  68073. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  68074. if (percentWindow[0] !== 0) {
  68075. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  68076. }
  68077. if (percentWindow[1] !== 100) {
  68078. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  68079. }
  68080. rawExtentInfo.freeze();
  68081. };
  68082. return AxisProxy;
  68083. }();
  68084. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  68085. var dataExtent = [Infinity, -Infinity];
  68086. each$8(seriesModels, function (seriesModel) {
  68087. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  68088. }); // It is important to get "consistent" extent when more then one axes is
  68089. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  68090. // when zooming. But it is difficult to know what is "consistent", considering
  68091. // axes have different type or even different meanings (For example, two
  68092. // time axes are used to compare data of the same date in different years).
  68093. // So basically dataZoom just obtains extent by series.data (in category axis
  68094. // extent can be obtained from axis.data).
  68095. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  68096. // consistent.
  68097. var axisModel = axisProxy.getAxisModel();
  68098. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  68099. return [rawExtentResult.min, rawExtentResult.max];
  68100. }
  68101. var dataZoomProcessor = {
  68102. // `dataZoomProcessor` will only be performed in needed series. Consider if
  68103. // there is a line series and a pie series, it is better not to update the
  68104. // line series if only pie series is needed to be updated.
  68105. getTargetSeries: function (ecModel) {
  68106. function eachAxisModel(cb) {
  68107. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68108. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68109. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  68110. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  68111. });
  68112. });
  68113. } // FIXME: it brings side-effect to `getTargetSeries`.
  68114. // Prepare axis proxies.
  68115. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  68116. // dispose all last axis proxy, in case that some axis are deleted.
  68117. axisModel.__dzAxisProxy = null;
  68118. });
  68119. var proxyList = [];
  68120. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  68121. // Different dataZooms may constrol the same axis. In that case,
  68122. // an axisProxy serves both of them.
  68123. if (!axisModel.__dzAxisProxy) {
  68124. // Use the first dataZoomModel as the main model of axisProxy.
  68125. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  68126. proxyList.push(axisModel.__dzAxisProxy);
  68127. }
  68128. });
  68129. var seriesModelMap = createHashMap();
  68130. each(proxyList, function (axisProxy) {
  68131. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  68132. seriesModelMap.set(seriesModel.uid, seriesModel);
  68133. });
  68134. });
  68135. return seriesModelMap;
  68136. },
  68137. // Consider appendData, where filter should be performed. Because data process is
  68138. // in block mode currently, it is not need to worry about that the overallProgress
  68139. // execute every frame.
  68140. overallReset: function (ecModel, api) {
  68141. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68142. // We calculate window and reset axis here but not in model
  68143. // init stage and not after action dispatch handler, because
  68144. // reset should be called after seriesData.restoreData.
  68145. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68146. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  68147. }); // Caution: data zoom filtering is order sensitive when using
  68148. // percent range and no min/max/scale set on axis.
  68149. // For example, we have dataZoom definition:
  68150. // [
  68151. // {xAxisIndex: 0, start: 30, end: 70},
  68152. // {yAxisIndex: 0, start: 20, end: 80}
  68153. // ]
  68154. // In this case, [20, 80] of y-dataZoom should be based on data
  68155. // that have filtered by x-dataZoom using range of [30, 70],
  68156. // but should not be based on full raw data. Thus sliding
  68157. // x-dataZoom will change both ranges of xAxis and yAxis,
  68158. // while sliding y-dataZoom will only change the range of yAxis.
  68159. // So we should filter x-axis after reset x-axis immediately,
  68160. // and then reset y-axis and filter y-axis.
  68161. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68162. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  68163. });
  68164. });
  68165. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68166. // Fullfill all of the range props so that user
  68167. // is able to get them from chart.getOption().
  68168. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  68169. if (axisProxy) {
  68170. var percentRange = axisProxy.getDataPercentWindow();
  68171. var valueRange = axisProxy.getDataValueWindow();
  68172. dataZoomModel.setCalculatedRange({
  68173. start: percentRange[0],
  68174. end: percentRange[1],
  68175. startValue: valueRange[0],
  68176. endValue: valueRange[1]
  68177. });
  68178. }
  68179. });
  68180. }
  68181. };
  68182. function installDataZoomAction(registers) {
  68183. registers.registerAction('dataZoom', function (payload, ecModel) {
  68184. var effectedModels = findEffectedDataZooms(ecModel, payload);
  68185. each(effectedModels, function (dataZoomModel) {
  68186. dataZoomModel.setRawRange({
  68187. start: payload.start,
  68188. end: payload.end,
  68189. startValue: payload.startValue,
  68190. endValue: payload.endValue
  68191. });
  68192. });
  68193. });
  68194. }
  68195. var installed = false;
  68196. function installCommon(registers) {
  68197. if (installed) {
  68198. return;
  68199. }
  68200. installed = true;
  68201. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  68202. installDataZoomAction(registers);
  68203. registers.registerSubTypeDefaulter('dataZoom', function () {
  68204. // Default 'slider' when no type specified.
  68205. return 'slider';
  68206. });
  68207. }
  68208. function install$y(registers) {
  68209. registers.registerComponentModel(SelectDataZoomModel);
  68210. registers.registerComponentView(SelectDataZoomView);
  68211. installCommon(registers);
  68212. }
  68213. /*
  68214. * Licensed to the Apache Software Foundation (ASF) under one
  68215. * or more contributor license agreements. See the NOTICE file
  68216. * distributed with this work for additional information
  68217. * regarding copyright ownership. The ASF licenses this file
  68218. * to you under the Apache License, Version 2.0 (the
  68219. * "License"); you may not use this file except in compliance
  68220. * with the License. You may obtain a copy of the License at
  68221. *
  68222. * http://www.apache.org/licenses/LICENSE-2.0
  68223. *
  68224. * Unless required by applicable law or agreed to in writing,
  68225. * software distributed under the License is distributed on an
  68226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68227. * KIND, either express or implied. See the License for the
  68228. * specific language governing permissions and limitations
  68229. * under the License.
  68230. */
  68231. /**
  68232. * AUTO-GENERATED FILE. DO NOT MODIFY.
  68233. */
  68234. var ToolboxFeature =
  68235. /** @class */
  68236. function () {
  68237. function ToolboxFeature() {}
  68238. return ToolboxFeature;
  68239. }();
  68240. var features = {};
  68241. function registerFeature(name, ctor) {
  68242. features[name] = ctor;
  68243. }
  68244. function getFeature(name) {
  68245. return features[name];
  68246. }
  68247. var ToolboxModel =
  68248. /** @class */
  68249. function (_super) {
  68250. __extends(ToolboxModel, _super);
  68251. function ToolboxModel() {
  68252. var _this = _super !== null && _super.apply(this, arguments) || this;
  68253. _this.type = ToolboxModel.type;
  68254. return _this;
  68255. }
  68256. ToolboxModel.prototype.optionUpdated = function () {
  68257. _super.prototype.optionUpdated.apply(this, arguments);
  68258. var ecModel = this.ecModel;
  68259. each(this.option.feature, function (featureOpt, featureName) {
  68260. var Feature = getFeature(featureName);
  68261. if (Feature) {
  68262. if (Feature.getDefaultOption) {
  68263. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  68264. }
  68265. merge(featureOpt, Feature.defaultOption);
  68266. }
  68267. });
  68268. };
  68269. ToolboxModel.type = 'toolbox';
  68270. ToolboxModel.layoutMode = {
  68271. type: 'box',
  68272. ignoreSize: true
  68273. };
  68274. ToolboxModel.defaultOption = {
  68275. show: true,
  68276. z: 6,
  68277. zlevel: 0,
  68278. orient: 'horizontal',
  68279. left: 'right',
  68280. top: 'top',
  68281. // right
  68282. // bottom
  68283. backgroundColor: 'transparent',
  68284. borderColor: '#ccc',
  68285. borderRadius: 0,
  68286. borderWidth: 0,
  68287. padding: 5,
  68288. itemSize: 15,
  68289. itemGap: 8,
  68290. showTitle: true,
  68291. iconStyle: {
  68292. borderColor: '#666',
  68293. color: 'none'
  68294. },
  68295. emphasis: {
  68296. iconStyle: {
  68297. borderColor: '#3E98C5'
  68298. }
  68299. },
  68300. // textStyle: {},
  68301. // feature
  68302. tooltip: {
  68303. show: false,
  68304. position: 'bottom'
  68305. }
  68306. };
  68307. return ToolboxModel;
  68308. }(ComponentModel);
  68309. /**
  68310. * Layout list like component.
  68311. * It will box layout each items in group of component and then position the whole group in the viewport
  68312. * @param {module:zrender/group/Group} group
  68313. * @param {module:echarts/model/Component} componentModel
  68314. * @param {module:echarts/ExtensionAPI}
  68315. */
  68316. function layout$3(group, componentModel, api) {
  68317. var boxLayoutParams = componentModel.getBoxLayoutParams();
  68318. var padding = componentModel.get('padding');
  68319. var viewportSize = {
  68320. width: api.getWidth(),
  68321. height: api.getHeight()
  68322. };
  68323. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  68324. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  68325. positionElement(group, boxLayoutParams, viewportSize, padding);
  68326. }
  68327. function makeBackground(rect, componentModel) {
  68328. var padding = normalizeCssArray$1(componentModel.get('padding'));
  68329. var style = componentModel.getItemStyle(['color', 'opacity']);
  68330. style.fill = componentModel.get('backgroundColor');
  68331. rect = new Rect({
  68332. shape: {
  68333. x: rect.x - padding[3],
  68334. y: rect.y - padding[0],
  68335. width: rect.width + padding[1] + padding[3],
  68336. height: rect.height + padding[0] + padding[2],
  68337. r: componentModel.get('borderRadius')
  68338. },
  68339. style: style,
  68340. silent: true,
  68341. z2: -1
  68342. }); // FIXME
  68343. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  68344. // and background rect when setting like `left: 0`, `top: 0`.
  68345. // graphic.subPixelOptimizeRect(rect);
  68346. return rect;
  68347. }
  68348. var ToolboxView =
  68349. /** @class */
  68350. function (_super) {
  68351. __extends(ToolboxView, _super);
  68352. function ToolboxView() {
  68353. return _super !== null && _super.apply(this, arguments) || this;
  68354. }
  68355. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  68356. var group = this.group;
  68357. group.removeAll();
  68358. if (!toolboxModel.get('show')) {
  68359. return;
  68360. }
  68361. var itemSize = +toolboxModel.get('itemSize');
  68362. var featureOpts = toolboxModel.get('feature') || {};
  68363. var features = this._features || (this._features = {});
  68364. var featureNames = [];
  68365. each(featureOpts, function (opt, name) {
  68366. featureNames.push(name);
  68367. });
  68368. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(); // Keep for diff.
  68369. this._featureNames = featureNames;
  68370. function processFeature(newIndex, oldIndex) {
  68371. var featureName = featureNames[newIndex];
  68372. var oldName = featureNames[oldIndex];
  68373. var featureOpt = featureOpts[featureName];
  68374. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  68375. var feature; // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  68376. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  68377. featureOpt.title = payload.newTitle;
  68378. }
  68379. if (featureName && !oldName) {
  68380. // Create
  68381. if (isUserFeatureName(featureName)) {
  68382. feature = {
  68383. onclick: featureModel.option.onclick,
  68384. featureName: featureName
  68385. };
  68386. } else {
  68387. var Feature = getFeature(featureName);
  68388. if (!Feature) {
  68389. return;
  68390. }
  68391. feature = new Feature();
  68392. }
  68393. features[featureName] = feature;
  68394. } else {
  68395. feature = features[oldName]; // If feature does not exsit.
  68396. if (!feature) {
  68397. return;
  68398. }
  68399. }
  68400. feature.uid = getUID('toolbox-feature');
  68401. feature.model = featureModel;
  68402. feature.ecModel = ecModel;
  68403. feature.api = api;
  68404. var isToolboxFeature = feature instanceof ToolboxFeature;
  68405. if (!featureName && oldName) {
  68406. isToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  68407. return;
  68408. }
  68409. if (!featureModel.get('show') || isToolboxFeature && feature.unusable) {
  68410. isToolboxFeature && feature.remove && feature.remove(ecModel, api);
  68411. return;
  68412. }
  68413. createIconPaths(featureModel, feature, featureName);
  68414. featureModel.setIconStatus = function (iconName, status) {
  68415. var option = this.option;
  68416. var iconPaths = this.iconPaths;
  68417. option.iconStatus = option.iconStatus || {};
  68418. option.iconStatus[iconName] = status;
  68419. if (iconPaths[iconName]) {
  68420. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  68421. }
  68422. };
  68423. if (feature instanceof ToolboxFeature) {
  68424. if (feature.render) {
  68425. feature.render(featureModel, ecModel, api, payload);
  68426. }
  68427. }
  68428. }
  68429. function createIconPaths(featureModel, feature, featureName) {
  68430. var iconStyleModel = featureModel.getModel('iconStyle');
  68431. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']); // If one feature has mutiple icon. they are orginaized as
  68432. // {
  68433. // icon: {
  68434. // foo: '',
  68435. // bar: ''
  68436. // },
  68437. // title: {
  68438. // foo: '',
  68439. // bar: ''
  68440. // }
  68441. // }
  68442. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  68443. var titles = featureModel.get('title') || {};
  68444. var iconsMap;
  68445. var titlesMap;
  68446. if (typeof icons === 'string') {
  68447. iconsMap = {};
  68448. iconsMap[featureName] = icons;
  68449. } else {
  68450. iconsMap = icons;
  68451. }
  68452. if (typeof titles === 'string') {
  68453. titlesMap = {};
  68454. titlesMap[featureName] = titles;
  68455. } else {
  68456. titlesMap = titles;
  68457. }
  68458. var iconPaths = featureModel.iconPaths = {};
  68459. each(iconsMap, function (iconStr, iconName) {
  68460. var path = createIcon(iconStr, {}, {
  68461. x: -itemSize / 2,
  68462. y: -itemSize / 2,
  68463. width: itemSize,
  68464. height: itemSize
  68465. }); // TODO handling image
  68466. path.setStyle(iconStyleModel.getItemStyle());
  68467. var pathEmphasisState = path.ensureState('emphasis');
  68468. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle(); // Text position calculation
  68469. var textContent = new ZRText({
  68470. style: {
  68471. text: titlesMap[iconName],
  68472. align: iconStyleEmphasisModel.get('textAlign'),
  68473. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  68474. padding: iconStyleEmphasisModel.get('textPadding'),
  68475. fill: null
  68476. },
  68477. ignore: true
  68478. });
  68479. path.setTextContent(textContent);
  68480. setTooltipConfig({
  68481. el: path,
  68482. componentModel: toolboxModel,
  68483. itemName: iconName,
  68484. formatterParamsExtra: {
  68485. title: titlesMap[iconName]
  68486. }
  68487. }); // graphic.enableHoverEmphasis(path);
  68488. path.__title = titlesMap[iconName];
  68489. path.on('mouseover', function () {
  68490. // Should not reuse above hoverStyle, which might be modified.
  68491. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  68492. var defaultTextPosition = toolboxModel.get('orient') === 'vertical' ? toolboxModel.get('right') == null ? 'right' : 'left' : toolboxModel.get('bottom') == null ? 'bottom' : 'top';
  68493. textContent.setStyle({
  68494. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  68495. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  68496. });
  68497. path.setTextConfig({
  68498. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  68499. });
  68500. textContent.ignore = !toolboxModel.get('showTitle'); // Use enterEmphasis and leaveEmphasis provide by ec.
  68501. // There are flags managed by the echarts.
  68502. enterEmphasis(this);
  68503. }).on('mouseout', function () {
  68504. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  68505. leaveEmphasis(this);
  68506. }
  68507. textContent.hide();
  68508. });
  68509. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  68510. group.add(path);
  68511. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  68512. iconPaths[iconName] = path;
  68513. });
  68514. }
  68515. layout$3(group, toolboxModel, api); // Render background after group is layout
  68516. // FIXME
  68517. group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen
  68518. group.eachChild(function (icon) {
  68519. var titleText = icon.__title; // const hoverStyle = icon.hoverStyle;
  68520. // TODO simplify code?
  68521. var emphasisState = icon.ensureState('emphasis');
  68522. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  68523. var textContent = icon.getTextContent();
  68524. var emphasisTextState = textContent && textContent.states.emphasis; // May be background element
  68525. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  68526. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  68527. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  68528. var offsetX = icon.x + group.x;
  68529. var offsetY = icon.y + group.y + itemSize;
  68530. var needPutOnTop = false;
  68531. if (offsetY + rect.height > api.getHeight()) {
  68532. emphasisTextConfig.position = 'top';
  68533. needPutOnTop = true;
  68534. }
  68535. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 8;
  68536. if (offsetX + rect.width / 2 > api.getWidth()) {
  68537. emphasisTextConfig.position = ['100%', topOffset];
  68538. emphasisTextStyle.align = 'right';
  68539. } else if (offsetX - rect.width / 2 < 0) {
  68540. emphasisTextConfig.position = [0, topOffset];
  68541. emphasisTextStyle.align = 'left';
  68542. }
  68543. }
  68544. });
  68545. };
  68546. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  68547. each(this._features, function (feature) {
  68548. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  68549. });
  68550. }; // updateLayout(toolboxModel, ecModel, api, payload) {
  68551. // zrUtil.each(this._features, function (feature) {
  68552. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  68553. // });
  68554. // },
  68555. ToolboxView.prototype.remove = function (ecModel, api) {
  68556. each(this._features, function (feature) {
  68557. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  68558. });
  68559. this.group.removeAll();
  68560. };
  68561. ToolboxView.prototype.dispose = function (ecModel, api) {
  68562. each(this._features, function (feature) {
  68563. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  68564. });
  68565. };
  68566. ToolboxView.type = 'toolbox';
  68567. return ToolboxView;
  68568. }(ComponentView);
  68569. function isUserFeatureName(featureName) {
  68570. return featureName.indexOf('my') === 0;
  68571. }
  68572. /* global window, document */
  68573. var SaveAsImage =
  68574. /** @class */
  68575. function (_super) {
  68576. __extends(SaveAsImage, _super);
  68577. function SaveAsImage() {
  68578. return _super !== null && _super.apply(this, arguments) || this;
  68579. }
  68580. SaveAsImage.prototype.onclick = function (ecModel, api) {
  68581. var model = this.model;
  68582. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  68583. var isSvg = api.getZr().painter.getType() === 'svg';
  68584. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  68585. var url = api.getConnectedDataURL({
  68586. type: type,
  68587. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  68588. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  68589. excludeComponents: model.get('excludeComponents'),
  68590. pixelRatio: model.get('pixelRatio')
  68591. }); // Chrome, Firefox, New Edge
  68592. if (typeof MouseEvent === 'function' && (env.browser.newEdge || !env.browser.ie && !env.browser.edge)) {
  68593. var $a = document.createElement('a');
  68594. $a.download = title + '.' + type;
  68595. $a.target = '_blank';
  68596. $a.href = url;
  68597. var evt = new MouseEvent('click', {
  68598. // some micro front-end framework, window maybe is a Proxy
  68599. view: document.defaultView,
  68600. bubbles: true,
  68601. cancelable: false
  68602. });
  68603. $a.dispatchEvent(evt);
  68604. } // IE or old Edge
  68605. else {
  68606. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  68607. var parts = url.split(','); // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  68608. var base64Encoded = parts[0].indexOf('base64') > -1;
  68609. var bstr = isSvg // should decode the svg data uri first
  68610. ? decodeURIComponent(parts[1]) : parts[1]; // only `atob` when the data uri is encoded with base64
  68611. // otherwise, like `svg` data uri exported by zrender,
  68612. // there will be an error, for it's not encoded with base64.
  68613. // (just a url-encoded string through `encodeURIComponent`)
  68614. base64Encoded && (bstr = window.atob(bstr));
  68615. var filename = title + '.' + type;
  68616. if (window.navigator.msSaveOrOpenBlob) {
  68617. var n = bstr.length;
  68618. var u8arr = new Uint8Array(n);
  68619. while (n--) {
  68620. u8arr[n] = bstr.charCodeAt(n);
  68621. }
  68622. var blob = new Blob([u8arr]);
  68623. window.navigator.msSaveOrOpenBlob(blob, filename);
  68624. } else {
  68625. var frame = document.createElement('iframe');
  68626. document.body.appendChild(frame);
  68627. var cw = frame.contentWindow;
  68628. var doc = cw.document;
  68629. doc.open('image/svg+xml', 'replace');
  68630. doc.write(bstr);
  68631. doc.close();
  68632. cw.focus();
  68633. doc.execCommand('SaveAs', true, filename);
  68634. document.body.removeChild(frame);
  68635. }
  68636. } else {
  68637. var lang = model.get('lang');
  68638. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  68639. var tab = window.open();
  68640. tab.document.write(html);
  68641. tab.document.title = title;
  68642. }
  68643. }
  68644. };
  68645. SaveAsImage.getDefaultOption = function (ecModel) {
  68646. var defaultOption = {
  68647. show: true,
  68648. 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',
  68649. title: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'title']),
  68650. type: 'png',
  68651. // Default use option.backgroundColor
  68652. // backgroundColor: '#fff',
  68653. connectedBackgroundColor: '#fff',
  68654. name: '',
  68655. excludeComponents: ['toolbox'],
  68656. // use current pixel ratio of device by default
  68657. // pixelRatio: 1,
  68658. lang: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'lang'])
  68659. };
  68660. return defaultOption;
  68661. };
  68662. return SaveAsImage;
  68663. }(ToolboxFeature);
  68664. SaveAsImage.prototype.unusable = !env.canvasSupported;
  68665. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  68666. var radioTypes = [['line', 'bar'], ['stack']];
  68667. var MagicType =
  68668. /** @class */
  68669. function (_super) {
  68670. __extends(MagicType, _super);
  68671. function MagicType() {
  68672. return _super !== null && _super.apply(this, arguments) || this;
  68673. }
  68674. MagicType.prototype.getIcons = function () {
  68675. var model = this.model;
  68676. var availableIcons = model.get('icon');
  68677. var icons = {};
  68678. each(model.get('type'), function (type) {
  68679. if (availableIcons[type]) {
  68680. icons[type] = availableIcons[type];
  68681. }
  68682. });
  68683. return icons;
  68684. };
  68685. MagicType.getDefaultOption = function (ecModel) {
  68686. var defaultOption = {
  68687. show: true,
  68688. type: [],
  68689. // Icon group
  68690. icon: {
  68691. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  68692. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  68693. // eslint-disable-next-line
  68694. 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
  68695. },
  68696. // `line`, `bar`, `stack`, `tiled`
  68697. title: ecModel.getLocaleModel().get(['toolbox', 'magicType', 'title']),
  68698. option: {},
  68699. seriesIndex: {}
  68700. };
  68701. return defaultOption;
  68702. };
  68703. MagicType.prototype.onclick = function (ecModel, api, type) {
  68704. var model = this.model;
  68705. var seriesIndex = model.get(['seriesIndex', type]); // Not supported magicType
  68706. if (!seriesOptGenreator[type]) {
  68707. return;
  68708. }
  68709. var newOption = {
  68710. series: []
  68711. };
  68712. var generateNewSeriesTypes = function (seriesModel) {
  68713. var seriesType = seriesModel.subType;
  68714. var seriesId = seriesModel.id;
  68715. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  68716. if (newSeriesOpt) {
  68717. // PENDING If merge original option?
  68718. defaults(newSeriesOpt, seriesModel.option);
  68719. newOption.series.push(newSeriesOpt);
  68720. } // Modify boundaryGap
  68721. var coordSys = seriesModel.coordinateSystem;
  68722. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  68723. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  68724. if (categoryAxis) {
  68725. var axisDim = categoryAxis.dim;
  68726. var axisType = axisDim + 'Axis';
  68727. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  68728. var axisIndex = axisModel.componentIndex;
  68729. newOption[axisType] = newOption[axisType] || [];
  68730. for (var i = 0; i <= axisIndex; i++) {
  68731. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  68732. }
  68733. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  68734. }
  68735. }
  68736. };
  68737. each(radioTypes, function (radio) {
  68738. if (indexOf(radio, type) >= 0) {
  68739. each(radio, function (item) {
  68740. model.setIconStatus(item, 'normal');
  68741. });
  68742. }
  68743. });
  68744. model.setIconStatus(type, 'emphasis');
  68745. ecModel.eachComponent({
  68746. mainType: 'series',
  68747. query: seriesIndex == null ? null : {
  68748. seriesIndex: seriesIndex
  68749. }
  68750. }, generateNewSeriesTypes);
  68751. var newTitle;
  68752. var currentType = type; // Change title of stack
  68753. if (type === 'stack') {
  68754. // use titles in model instead of ecModel
  68755. // as stack and tiled appears in pair, just flip them
  68756. // no need of checking stack state
  68757. newTitle = merge({
  68758. stack: model.option.title.tiled,
  68759. tiled: model.option.title.stack
  68760. }, model.option.title);
  68761. if (model.get(['iconStatus', type]) !== 'emphasis') {
  68762. currentType = 'tiled';
  68763. }
  68764. }
  68765. api.dispatchAction({
  68766. type: 'changeMagicType',
  68767. currentType: currentType,
  68768. newOption: newOption,
  68769. newTitle: newTitle,
  68770. featureName: 'magicType'
  68771. });
  68772. };
  68773. return MagicType;
  68774. }(ToolboxFeature);
  68775. var seriesOptGenreator = {
  68776. 'line': function (seriesType, seriesId, seriesModel, model) {
  68777. if (seriesType === 'bar') {
  68778. return merge({
  68779. id: seriesId,
  68780. type: 'line',
  68781. // Preserve data related option
  68782. data: seriesModel.get('data'),
  68783. stack: seriesModel.get('stack'),
  68784. markPoint: seriesModel.get('markPoint'),
  68785. markLine: seriesModel.get('markLine')
  68786. }, model.get(['option', 'line']) || {}, true);
  68787. }
  68788. },
  68789. 'bar': function (seriesType, seriesId, seriesModel, model) {
  68790. if (seriesType === 'line') {
  68791. return merge({
  68792. id: seriesId,
  68793. type: 'bar',
  68794. // Preserve data related option
  68795. data: seriesModel.get('data'),
  68796. stack: seriesModel.get('stack'),
  68797. markPoint: seriesModel.get('markPoint'),
  68798. markLine: seriesModel.get('markLine')
  68799. }, model.get(['option', 'bar']) || {}, true);
  68800. }
  68801. },
  68802. 'stack': function (seriesType, seriesId, seriesModel, model) {
  68803. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  68804. if (seriesType === 'line' || seriesType === 'bar') {
  68805. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  68806. return merge({
  68807. id: seriesId,
  68808. stack: isStack ? '' : INNER_STACK_KEYWORD
  68809. }, model.get(['option', 'stack']) || {}, true);
  68810. }
  68811. }
  68812. }; // TODO: SELF REGISTERED.
  68813. registerAction({
  68814. type: 'changeMagicType',
  68815. event: 'magicTypeChanged',
  68816. update: 'prepareAndUpdate'
  68817. }, function (payload, ecModel) {
  68818. ecModel.mergeOption(payload.newOption);
  68819. });
  68820. /* global document */
  68821. var BLOCK_SPLITER = new Array(60).join('-');
  68822. var ITEM_SPLITER = '\t';
  68823. /**
  68824. * Group series into two types
  68825. * 1. on category axis, like line, bar
  68826. * 2. others, like scatter, pie
  68827. */
  68828. function groupSeries(ecModel) {
  68829. var seriesGroupByCategoryAxis = {};
  68830. var otherSeries = [];
  68831. var meta = [];
  68832. ecModel.eachRawSeries(function (seriesModel) {
  68833. var coordSys = seriesModel.coordinateSystem;
  68834. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  68835. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  68836. var baseAxis = coordSys.getBaseAxis();
  68837. if (baseAxis.type === 'category') {
  68838. var key = baseAxis.dim + '_' + baseAxis.index;
  68839. if (!seriesGroupByCategoryAxis[key]) {
  68840. seriesGroupByCategoryAxis[key] = {
  68841. categoryAxis: baseAxis,
  68842. valueAxis: coordSys.getOtherAxis(baseAxis),
  68843. series: []
  68844. };
  68845. meta.push({
  68846. axisDim: baseAxis.dim,
  68847. axisIndex: baseAxis.index
  68848. });
  68849. }
  68850. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  68851. } else {
  68852. otherSeries.push(seriesModel);
  68853. }
  68854. } else {
  68855. otherSeries.push(seriesModel);
  68856. }
  68857. });
  68858. return {
  68859. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  68860. other: otherSeries,
  68861. meta: meta
  68862. };
  68863. }
  68864. /**
  68865. * Assemble content of series on cateogory axis
  68866. * @inner
  68867. */
  68868. function assembleSeriesWithCategoryAxis(groups) {
  68869. var tables = [];
  68870. each(groups, function (group, key) {
  68871. var categoryAxis = group.categoryAxis;
  68872. var valueAxis = group.valueAxis;
  68873. var valueAxisDim = valueAxis.dim;
  68874. var headers = [' '].concat(map(group.series, function (series) {
  68875. return series.name;
  68876. })); // @ts-ignore TODO Polar
  68877. var columns = [categoryAxis.model.getCategories()];
  68878. each(group.series, function (series) {
  68879. var rawData = series.getRawData();
  68880. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  68881. return val;
  68882. }));
  68883. }); // Assemble table content
  68884. var lines = [headers.join(ITEM_SPLITER)];
  68885. for (var i = 0; i < columns[0].length; i++) {
  68886. var items = [];
  68887. for (var j = 0; j < columns.length; j++) {
  68888. items.push(columns[j][i]);
  68889. }
  68890. lines.push(items.join(ITEM_SPLITER));
  68891. }
  68892. tables.push(lines.join('\n'));
  68893. });
  68894. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  68895. }
  68896. /**
  68897. * Assemble content of other series
  68898. */
  68899. function assembleOtherSeries(series) {
  68900. return map(series, function (series) {
  68901. var data = series.getRawData();
  68902. var lines = [series.name];
  68903. var vals = [];
  68904. data.each(data.dimensions, function () {
  68905. var argLen = arguments.length;
  68906. var dataIndex = arguments[argLen - 1];
  68907. var name = data.getName(dataIndex);
  68908. for (var i = 0; i < argLen - 1; i++) {
  68909. vals[i] = arguments[i];
  68910. }
  68911. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  68912. });
  68913. return lines.join('\n');
  68914. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  68915. }
  68916. function getContentFromModel(ecModel) {
  68917. var result = groupSeries(ecModel);
  68918. return {
  68919. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  68920. return !!str.replace(/[\n\t\s]/g, '');
  68921. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  68922. meta: result.meta
  68923. };
  68924. }
  68925. function trim$1(str) {
  68926. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  68927. }
  68928. /**
  68929. * If a block is tsv format
  68930. */
  68931. function isTSVFormat(block) {
  68932. // Simple method to find out if a block is tsv format
  68933. var firstLine = block.slice(0, block.indexOf('\n'));
  68934. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  68935. return true;
  68936. }
  68937. }
  68938. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  68939. /**
  68940. * @param {string} tsv
  68941. * @return {Object}
  68942. */
  68943. function parseTSVContents(tsv) {
  68944. var tsvLines = tsv.split(/\n+/g);
  68945. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  68946. var categories = [];
  68947. var series = map(headers, function (header) {
  68948. return {
  68949. name: header,
  68950. data: []
  68951. };
  68952. });
  68953. for (var i = 0; i < tsvLines.length; i++) {
  68954. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  68955. categories.push(items.shift());
  68956. for (var j = 0; j < items.length; j++) {
  68957. series[j] && (series[j].data[i] = items[j]);
  68958. }
  68959. }
  68960. return {
  68961. series: series,
  68962. categories: categories
  68963. };
  68964. }
  68965. function parseListContents(str) {
  68966. var lines = str.split(/\n+/g);
  68967. var seriesName = trim$1(lines.shift());
  68968. var data = [];
  68969. for (var i = 0; i < lines.length; i++) {
  68970. // if line is empty, ignore it.
  68971. // there is a case that a user forgot to delete `\n`.
  68972. var line = trim$1(lines[i]);
  68973. if (!line) {
  68974. continue;
  68975. }
  68976. var items = line.split(itemSplitRegex);
  68977. var name_1 = '';
  68978. var value = void 0;
  68979. var hasName = false;
  68980. if (isNaN(items[0])) {
  68981. // First item is name
  68982. hasName = true;
  68983. name_1 = items[0];
  68984. items = items.slice(1);
  68985. data[i] = {
  68986. name: name_1,
  68987. value: []
  68988. };
  68989. value = data[i].value;
  68990. } else {
  68991. value = data[i] = [];
  68992. }
  68993. for (var j = 0; j < items.length; j++) {
  68994. value.push(+items[j]);
  68995. }
  68996. if (value.length === 1) {
  68997. hasName ? data[i].value = value[0] : data[i] = value[0];
  68998. }
  68999. }
  69000. return {
  69001. name: seriesName,
  69002. data: data
  69003. };
  69004. }
  69005. function parseContents(str, blockMetaList) {
  69006. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  69007. var newOption = {
  69008. series: []
  69009. };
  69010. each(blocks, function (block, idx) {
  69011. if (isTSVFormat(block)) {
  69012. var result = parseTSVContents(block);
  69013. var blockMeta = blockMetaList[idx];
  69014. var axisKey = blockMeta.axisDim + 'Axis';
  69015. if (blockMeta) {
  69016. newOption[axisKey] = newOption[axisKey] || [];
  69017. newOption[axisKey][blockMeta.axisIndex] = {
  69018. data: result.categories
  69019. };
  69020. newOption.series = newOption.series.concat(result.series);
  69021. }
  69022. } else {
  69023. var result = parseListContents(block);
  69024. newOption.series.push(result);
  69025. }
  69026. });
  69027. return newOption;
  69028. }
  69029. var DataView =
  69030. /** @class */
  69031. function (_super) {
  69032. __extends(DataView, _super);
  69033. function DataView() {
  69034. return _super !== null && _super.apply(this, arguments) || this;
  69035. }
  69036. DataView.prototype.onclick = function (ecModel, api) {
  69037. var container = api.getDom();
  69038. var model = this.model;
  69039. if (this._dom) {
  69040. container.removeChild(this._dom);
  69041. }
  69042. var root = document.createElement('div');
  69043. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  69044. root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements
  69045. var header = document.createElement('h4');
  69046. var lang = model.get('lang') || [];
  69047. header.innerHTML = lang[0] || model.get('title');
  69048. header.style.cssText = 'margin: 10px 20px;';
  69049. header.style.color = model.get('textColor');
  69050. var viewMain = document.createElement('div');
  69051. var textarea = document.createElement('textarea');
  69052. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  69053. var optionToContent = model.get('optionToContent');
  69054. var contentToOption = model.get('contentToOption');
  69055. var result = getContentFromModel(ecModel);
  69056. if (typeof optionToContent === 'function') {
  69057. var htmlOrDom = optionToContent(api.getOption());
  69058. if (typeof htmlOrDom === 'string') {
  69059. viewMain.innerHTML = htmlOrDom;
  69060. } else if (isDom(htmlOrDom)) {
  69061. viewMain.appendChild(htmlOrDom);
  69062. }
  69063. } else {
  69064. // Use default textarea
  69065. viewMain.appendChild(textarea);
  69066. textarea.readOnly = model.get('readOnly');
  69067. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  69068. textarea.style.color = model.get('textColor');
  69069. textarea.style.borderColor = model.get('textareaBorderColor');
  69070. textarea.style.backgroundColor = model.get('textareaColor');
  69071. textarea.value = result.value;
  69072. }
  69073. var blockMetaList = result.meta;
  69074. var buttonContainer = document.createElement('div');
  69075. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  69076. var buttonStyle = 'float:right;margin-right:20px;border:none;' + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  69077. var closeButton = document.createElement('div');
  69078. var refreshButton = document.createElement('div');
  69079. buttonStyle += ';background-color:' + model.get('buttonColor');
  69080. buttonStyle += ';color:' + model.get('buttonTextColor');
  69081. var self = this;
  69082. function close() {
  69083. container.removeChild(root);
  69084. self._dom = null;
  69085. }
  69086. addEventListener(closeButton, 'click', close);
  69087. addEventListener(refreshButton, 'click', function () {
  69088. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  69089. if ("development" !== 'production') {
  69090. // eslint-disable-next-line
  69091. console.warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  69092. }
  69093. close();
  69094. return;
  69095. }
  69096. var newOption;
  69097. try {
  69098. if (typeof contentToOption === 'function') {
  69099. newOption = contentToOption(viewMain, api.getOption());
  69100. } else {
  69101. newOption = parseContents(textarea.value, blockMetaList);
  69102. }
  69103. } catch (e) {
  69104. close();
  69105. throw new Error('Data view format error ' + e);
  69106. }
  69107. if (newOption) {
  69108. api.dispatchAction({
  69109. type: 'changeDataView',
  69110. newOption: newOption
  69111. });
  69112. }
  69113. close();
  69114. });
  69115. closeButton.innerHTML = lang[1];
  69116. refreshButton.innerHTML = lang[2];
  69117. refreshButton.style.cssText = buttonStyle;
  69118. closeButton.style.cssText = buttonStyle;
  69119. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  69120. buttonContainer.appendChild(closeButton);
  69121. root.appendChild(header);
  69122. root.appendChild(viewMain);
  69123. root.appendChild(buttonContainer);
  69124. viewMain.style.height = container.clientHeight - 80 + 'px';
  69125. container.appendChild(root);
  69126. this._dom = root;
  69127. };
  69128. DataView.prototype.remove = function (ecModel, api) {
  69129. this._dom && api.getDom().removeChild(this._dom);
  69130. };
  69131. DataView.prototype.dispose = function (ecModel, api) {
  69132. this.remove(ecModel, api);
  69133. };
  69134. DataView.getDefaultOption = function (ecModel) {
  69135. var defaultOption = {
  69136. show: true,
  69137. readOnly: false,
  69138. optionToContent: null,
  69139. contentToOption: null,
  69140. // eslint-disable-next-line
  69141. 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',
  69142. title: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'title']),
  69143. lang: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'lang']),
  69144. backgroundColor: '#fff',
  69145. textColor: '#000',
  69146. textareaColor: '#fff',
  69147. textareaBorderColor: '#333',
  69148. buttonColor: '#c23531',
  69149. buttonTextColor: '#fff'
  69150. };
  69151. return defaultOption;
  69152. };
  69153. return DataView;
  69154. }(ToolboxFeature);
  69155. /**
  69156. * @inner
  69157. */
  69158. function tryMergeDataOption(newData, originalData) {
  69159. return map(newData, function (newVal, idx) {
  69160. var original = originalData && originalData[idx];
  69161. if (isObject(original) && !isArray(original)) {
  69162. var newValIsObject = isObject(newVal) && !isArray(newVal);
  69163. if (!newValIsObject) {
  69164. newVal = {
  69165. value: newVal
  69166. };
  69167. } // original data has name but new data has no name
  69168. var shouldDeleteName = original.name != null && newVal.name == null; // Original data has option
  69169. newVal = defaults(newVal, original);
  69170. shouldDeleteName && delete newVal.name;
  69171. return newVal;
  69172. } else {
  69173. return newVal;
  69174. }
  69175. });
  69176. } // TODO: SELF REGISTERED.
  69177. registerAction({
  69178. type: 'changeDataView',
  69179. event: 'dataViewChanged',
  69180. update: 'prepareAndUpdate'
  69181. }, function (payload, ecModel) {
  69182. var newSeriesOptList = [];
  69183. each(payload.newOption.series, function (seriesOpt) {
  69184. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  69185. if (!seriesModel) {
  69186. // New created series
  69187. // Geuss the series type
  69188. newSeriesOptList.push(extend({
  69189. // Default is scatter
  69190. type: 'scatter'
  69191. }, seriesOpt));
  69192. } else {
  69193. var originalData = seriesModel.get('data');
  69194. newSeriesOptList.push({
  69195. name: seriesOpt.name,
  69196. data: tryMergeDataOption(seriesOpt.data, originalData)
  69197. });
  69198. }
  69199. });
  69200. ecModel.mergeOption(defaults({
  69201. series: newSeriesOptList
  69202. }, payload.newOption));
  69203. });
  69204. var each$9 = each;
  69205. var inner$f = makeInner();
  69206. /**
  69207. * @param ecModel
  69208. * @param newSnapshot key is dataZoomId
  69209. */
  69210. function push(ecModel, newSnapshot) {
  69211. var storedSnapshots = getStoreSnapshots(ecModel); // If previous dataZoom can not be found,
  69212. // complete an range with current range.
  69213. each$9(newSnapshot, function (batchItem, dataZoomId) {
  69214. var i = storedSnapshots.length - 1;
  69215. for (; i >= 0; i--) {
  69216. var snapshot = storedSnapshots[i];
  69217. if (snapshot[dataZoomId]) {
  69218. break;
  69219. }
  69220. }
  69221. if (i < 0) {
  69222. // No origin range set, create one by current range.
  69223. var dataZoomModel = ecModel.queryComponents({
  69224. mainType: 'dataZoom',
  69225. subType: 'select',
  69226. id: dataZoomId
  69227. })[0];
  69228. if (dataZoomModel) {
  69229. var percentRange = dataZoomModel.getPercentRange();
  69230. storedSnapshots[0][dataZoomId] = {
  69231. dataZoomId: dataZoomId,
  69232. start: percentRange[0],
  69233. end: percentRange[1]
  69234. };
  69235. }
  69236. }
  69237. });
  69238. storedSnapshots.push(newSnapshot);
  69239. }
  69240. function pop(ecModel) {
  69241. var storedSnapshots = getStoreSnapshots(ecModel);
  69242. var head = storedSnapshots[storedSnapshots.length - 1];
  69243. storedSnapshots.length > 1 && storedSnapshots.pop(); // Find top for all dataZoom.
  69244. var snapshot = {};
  69245. each$9(head, function (batchItem, dataZoomId) {
  69246. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  69247. batchItem = storedSnapshots[i][dataZoomId];
  69248. if (batchItem) {
  69249. snapshot[dataZoomId] = batchItem;
  69250. break;
  69251. }
  69252. }
  69253. });
  69254. return snapshot;
  69255. }
  69256. function clear$1(ecModel) {
  69257. inner$f(ecModel).snapshots = null;
  69258. }
  69259. function count(ecModel) {
  69260. return getStoreSnapshots(ecModel).length;
  69261. }
  69262. /**
  69263. * History length of each dataZoom may be different.
  69264. * this._history[0] is used to store origin range.
  69265. */
  69266. function getStoreSnapshots(ecModel) {
  69267. var store = inner$f(ecModel);
  69268. if (!store.snapshots) {
  69269. store.snapshots = [{}];
  69270. }
  69271. return store.snapshots;
  69272. }
  69273. var RestoreOption =
  69274. /** @class */
  69275. function (_super) {
  69276. __extends(RestoreOption, _super);
  69277. function RestoreOption() {
  69278. return _super !== null && _super.apply(this, arguments) || this;
  69279. }
  69280. RestoreOption.prototype.onclick = function (ecModel, api) {
  69281. clear$1(ecModel);
  69282. api.dispatchAction({
  69283. type: 'restore',
  69284. from: this.uid
  69285. });
  69286. };
  69287. RestoreOption.getDefaultOption = function (ecModel) {
  69288. var defaultOption = {
  69289. show: true,
  69290. // eslint-disable-next-line
  69291. 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',
  69292. title: ecModel.getLocaleModel().get(['toolbox', 'restore', 'title'])
  69293. };
  69294. return defaultOption;
  69295. };
  69296. return RestoreOption;
  69297. }(ToolboxFeature); // TODO: SELF REGISTERED.
  69298. registerAction({
  69299. type: 'restore',
  69300. event: 'restore',
  69301. update: 'prepareAndUpdate'
  69302. }, function (payload, ecModel) {
  69303. ecModel.resetOption('recreate');
  69304. });
  69305. // how to genarialize to more coordinate systems.
  69306. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  69307. var BrushTargetManager =
  69308. /** @class */
  69309. function () {
  69310. /**
  69311. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  69312. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  69313. * @param opt.include include coordinate system types.
  69314. */
  69315. function BrushTargetManager(finder, ecModel, opt) {
  69316. var _this = this;
  69317. this._targetInfoList = [];
  69318. var foundCpts = parseFinder$1(ecModel, finder);
  69319. each(targetInfoBuilders, function (builder, type) {
  69320. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  69321. builder(foundCpts, _this._targetInfoList);
  69322. }
  69323. });
  69324. }
  69325. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  69326. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  69327. (area.coordRanges || (area.coordRanges = [])).push(coordRange); // area.coordRange is the first of area.coordRanges
  69328. if (!area.coordRange) {
  69329. area.coordRange = coordRange; // In 'category' axis, coord to pixel is not reversible, so we can not
  69330. // rebuild range by coordRange accrately, which may bring trouble when
  69331. // brushing only one item. So we use __rangeOffset to rebuilding range
  69332. // by coordRange. And this it only used in brush component so it is no
  69333. // need to be adapted to coordRanges.
  69334. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  69335. area.__rangeOffset = {
  69336. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  69337. xyMinMax: result.xyMinMax
  69338. };
  69339. }
  69340. });
  69341. return areas;
  69342. };
  69343. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  69344. each(areas, function (area) {
  69345. var targetInfo = this.findTargetInfo(area, ecModel);
  69346. if (targetInfo && targetInfo !== true) {
  69347. each(targetInfo.coordSyses, function (coordSys) {
  69348. var result = coordConvert[area.brushType](1, coordSys, area.range, true);
  69349. cb(area, result.values, coordSys, ecModel);
  69350. });
  69351. }
  69352. }, this);
  69353. };
  69354. /**
  69355. * the `areas` is `BrushModel.areas`.
  69356. * Called in layout stage.
  69357. * convert `area.coordRange` to global range and set panelId to `area.range`.
  69358. */
  69359. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  69360. each(areas, function (area) {
  69361. var targetInfo = this.findTargetInfo(area, ecModel);
  69362. if ("development" !== 'production') {
  69363. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  69364. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  69365. }
  69366. area.range = area.range || []; // convert coordRange to global range and set panelId.
  69367. if (targetInfo && targetInfo !== true) {
  69368. area.panelId = targetInfo.panelId; // (1) area.range shoule always be calculate from coordRange but does
  69369. // not keep its original value, for the sake of the dataZoom scenario,
  69370. // where area.coordRange remains unchanged but area.range may be changed.
  69371. // (2) Only support converting one coordRange to pixel range in brush
  69372. // component. So do not consider `coordRanges`.
  69373. // (3) About __rangeOffset, see comment above.
  69374. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  69375. var rangeOffset = area.__rangeOffset;
  69376. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  69377. }
  69378. }, this);
  69379. };
  69380. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  69381. return map(this._targetInfoList, function (targetInfo) {
  69382. var rect = targetInfo.getPanelRect();
  69383. return {
  69384. panelId: targetInfo.panelId,
  69385. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  69386. clipPath: makeRectPanelClipPath(rect),
  69387. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  69388. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  69389. };
  69390. });
  69391. };
  69392. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  69393. // Check whether area is bound in coord, and series do not belong to that coord.
  69394. // If do not do this check, some brush (like lineX) will controll all axes.
  69395. var targetInfo = this.findTargetInfo(area, ecModel);
  69396. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  69397. };
  69398. /**
  69399. * If return Object, a coord found.
  69400. * If reutrn true, global found.
  69401. * Otherwise nothing found.
  69402. */
  69403. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  69404. var targetInfoList = this._targetInfoList;
  69405. var foundCpts = parseFinder$1(ecModel, area);
  69406. for (var i = 0; i < targetInfoList.length; i++) {
  69407. var targetInfo = targetInfoList[i];
  69408. var areaPanelId = area.panelId;
  69409. if (areaPanelId) {
  69410. if (targetInfo.panelId === areaPanelId) {
  69411. return targetInfo;
  69412. }
  69413. } else {
  69414. for (var j = 0; j < targetInfoMatchers.length; j++) {
  69415. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  69416. return targetInfo;
  69417. }
  69418. }
  69419. }
  69420. }
  69421. return true;
  69422. };
  69423. return BrushTargetManager;
  69424. }();
  69425. function formatMinMax(minMax) {
  69426. minMax[0] > minMax[1] && minMax.reverse();
  69427. return minMax;
  69428. }
  69429. function parseFinder$1(ecModel, finder) {
  69430. return parseFinder(ecModel, finder, {
  69431. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  69432. });
  69433. }
  69434. var targetInfoBuilders = {
  69435. grid: function (foundCpts, targetInfoList) {
  69436. var xAxisModels = foundCpts.xAxisModels;
  69437. var yAxisModels = foundCpts.yAxisModels;
  69438. var gridModels = foundCpts.gridModels; // Remove duplicated.
  69439. var gridModelMap = createHashMap();
  69440. var xAxesHas = {};
  69441. var yAxesHas = {};
  69442. if (!xAxisModels && !yAxisModels && !gridModels) {
  69443. return;
  69444. }
  69445. each(xAxisModels, function (axisModel) {
  69446. var gridModel = axisModel.axis.grid.model;
  69447. gridModelMap.set(gridModel.id, gridModel);
  69448. xAxesHas[gridModel.id] = true;
  69449. });
  69450. each(yAxisModels, function (axisModel) {
  69451. var gridModel = axisModel.axis.grid.model;
  69452. gridModelMap.set(gridModel.id, gridModel);
  69453. yAxesHas[gridModel.id] = true;
  69454. });
  69455. each(gridModels, function (gridModel) {
  69456. gridModelMap.set(gridModel.id, gridModel);
  69457. xAxesHas[gridModel.id] = true;
  69458. yAxesHas[gridModel.id] = true;
  69459. });
  69460. gridModelMap.each(function (gridModel) {
  69461. var grid = gridModel.coordinateSystem;
  69462. var cartesians = [];
  69463. each(grid.getCartesians(), function (cartesian, index) {
  69464. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  69465. cartesians.push(cartesian);
  69466. }
  69467. });
  69468. targetInfoList.push({
  69469. panelId: 'grid--' + gridModel.id,
  69470. gridModel: gridModel,
  69471. coordSysModel: gridModel,
  69472. // Use the first one as the representitive coordSys.
  69473. coordSys: cartesians[0],
  69474. coordSyses: cartesians,
  69475. getPanelRect: panelRectBuilders.grid,
  69476. xAxisDeclared: xAxesHas[gridModel.id],
  69477. yAxisDeclared: yAxesHas[gridModel.id]
  69478. });
  69479. });
  69480. },
  69481. geo: function (foundCpts, targetInfoList) {
  69482. each(foundCpts.geoModels, function (geoModel) {
  69483. var coordSys = geoModel.coordinateSystem;
  69484. targetInfoList.push({
  69485. panelId: 'geo--' + geoModel.id,
  69486. geoModel: geoModel,
  69487. coordSysModel: geoModel,
  69488. coordSys: coordSys,
  69489. coordSyses: [coordSys],
  69490. getPanelRect: panelRectBuilders.geo
  69491. });
  69492. });
  69493. }
  69494. };
  69495. var targetInfoMatchers = [// grid
  69496. function (foundCpts, targetInfo) {
  69497. var xAxisModel = foundCpts.xAxisModel;
  69498. var yAxisModel = foundCpts.yAxisModel;
  69499. var gridModel = foundCpts.gridModel;
  69500. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  69501. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  69502. return gridModel && gridModel === targetInfo.gridModel;
  69503. }, // geo
  69504. function (foundCpts, targetInfo) {
  69505. var geoModel = foundCpts.geoModel;
  69506. return geoModel && geoModel === targetInfo.geoModel;
  69507. }];
  69508. var panelRectBuilders = {
  69509. grid: function () {
  69510. // grid is not Transformable.
  69511. return this.coordSys.master.getRect().clone();
  69512. },
  69513. geo: function () {
  69514. var coordSys = this.coordSys;
  69515. var rect = coordSys.getBoundingRect().clone(); // geo roam and zoom transform
  69516. rect.applyTransform(getTransform(coordSys));
  69517. return rect;
  69518. }
  69519. };
  69520. var coordConvert = {
  69521. lineX: curry(axisConvert, 0),
  69522. lineY: curry(axisConvert, 1),
  69523. rect: function (to, coordSys, rangeOrCoordRange, clamp) {
  69524. var xminymin = to ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
  69525. var xmaxymax = to ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
  69526. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  69527. return {
  69528. values: values,
  69529. xyMinMax: values
  69530. };
  69531. },
  69532. polygon: function (to, coordSys, rangeOrCoordRange, clamp) {
  69533. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  69534. var values = map(rangeOrCoordRange, function (item) {
  69535. var p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
  69536. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  69537. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  69538. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  69539. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  69540. return p;
  69541. });
  69542. return {
  69543. values: values,
  69544. xyMinMax: xyMinMax
  69545. };
  69546. }
  69547. };
  69548. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  69549. if ("development" !== 'production') {
  69550. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  69551. }
  69552. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  69553. var values = formatMinMax(map([0, 1], function (i) {
  69554. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  69555. }));
  69556. var xyMinMax = [];
  69557. xyMinMax[axisNameIndex] = values;
  69558. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  69559. return {
  69560. values: values,
  69561. xyMinMax: xyMinMax
  69562. };
  69563. }
  69564. var diffProcessor = {
  69565. lineX: curry(axisDiffProcessor, 0),
  69566. lineY: curry(axisDiffProcessor, 1),
  69567. rect: function (values, refer, scales) {
  69568. 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]]];
  69569. },
  69570. polygon: function (values, refer, scales) {
  69571. return map(values, function (item, idx) {
  69572. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  69573. });
  69574. }
  69575. };
  69576. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  69577. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  69578. } // We have to process scale caused by dataZoom manually,
  69579. // although it might be not accurate.
  69580. // Return [0~1, 0~1]
  69581. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  69582. var sizeCurr = getSize(xyMinMaxCurr);
  69583. var sizeOrigin = getSize(xyMinMaxOrigin);
  69584. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  69585. isNaN(scales[0]) && (scales[0] = 1);
  69586. isNaN(scales[1]) && (scales[1] = 1);
  69587. return scales;
  69588. }
  69589. function getSize(xyMinMax) {
  69590. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  69591. }
  69592. var each$a = each;
  69593. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  69594. var DataZoomFeature =
  69595. /** @class */
  69596. function (_super) {
  69597. __extends(DataZoomFeature, _super);
  69598. function DataZoomFeature() {
  69599. return _super !== null && _super.apply(this, arguments) || this;
  69600. }
  69601. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  69602. if (!this._brushController) {
  69603. this._brushController = new BrushController(api.getZr());
  69604. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  69605. }
  69606. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  69607. updateBackBtnStatus(featureModel, ecModel);
  69608. };
  69609. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  69610. handlers$1[type].call(this);
  69611. };
  69612. DataZoomFeature.prototype.remove = function (ecModel, api) {
  69613. this._brushController && this._brushController.unmount();
  69614. };
  69615. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  69616. this._brushController && this._brushController.dispose();
  69617. };
  69618. DataZoomFeature.prototype._onBrush = function (eventParam) {
  69619. var areas = eventParam.areas;
  69620. if (!eventParam.isEnd || !areas.length) {
  69621. return;
  69622. }
  69623. var snapshot = {};
  69624. var ecModel = this.ecModel;
  69625. this._brushController.updateCovers([]); // remove cover
  69626. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  69627. include: ['grid']
  69628. });
  69629. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  69630. if (coordSys.type !== 'cartesian2d') {
  69631. return;
  69632. }
  69633. var brushType = area.brushType;
  69634. if (brushType === 'rect') {
  69635. setBatch('x', coordSys, coordRange[0]);
  69636. setBatch('y', coordSys, coordRange[1]);
  69637. } else {
  69638. setBatch({
  69639. lineX: 'x',
  69640. lineY: 'y'
  69641. }[brushType], coordSys, coordRange);
  69642. }
  69643. });
  69644. push(ecModel, snapshot);
  69645. this._dispatchZoomAction(snapshot);
  69646. function setBatch(dimName, coordSys, minMax) {
  69647. var axis = coordSys.getAxis(dimName);
  69648. var axisModel = axis.model;
  69649. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range.
  69650. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  69651. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  69652. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  69653. }
  69654. dataZoomModel && (snapshot[dataZoomModel.id] = {
  69655. dataZoomId: dataZoomModel.id,
  69656. startValue: minMax[0],
  69657. endValue: minMax[1]
  69658. });
  69659. }
  69660. function findDataZoom(dimName, axisModel, ecModel) {
  69661. var found;
  69662. ecModel.eachComponent({
  69663. mainType: 'dataZoom',
  69664. subType: 'select'
  69665. }, function (dzModel) {
  69666. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  69667. has && (found = dzModel);
  69668. });
  69669. return found;
  69670. }
  69671. };
  69672. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  69673. var batch = []; // Convert from hash map to array.
  69674. each$a(snapshot, function (batchItem, dataZoomId) {
  69675. batch.push(clone(batchItem));
  69676. });
  69677. batch.length && this.api.dispatchAction({
  69678. type: 'dataZoom',
  69679. from: this.uid,
  69680. batch: batch
  69681. });
  69682. };
  69683. DataZoomFeature.getDefaultOption = function (ecModel) {
  69684. var defaultOption = {
  69685. show: true,
  69686. filterMode: 'filter',
  69687. // Icon group
  69688. icon: {
  69689. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  69690. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  69691. },
  69692. // `zoom`, `back`
  69693. title: ecModel.getLocaleModel().get(['toolbox', 'dataZoom', 'title']),
  69694. brushStyle: {
  69695. borderWidth: 0,
  69696. color: 'rgba(210,219,238,0.2)'
  69697. }
  69698. };
  69699. return defaultOption;
  69700. };
  69701. return DataZoomFeature;
  69702. }(ToolboxFeature);
  69703. var handlers$1 = {
  69704. zoom: function () {
  69705. var nextActive = !this._isZoomActive;
  69706. this.api.dispatchAction({
  69707. type: 'takeGlobalCursor',
  69708. key: 'dataZoomSelect',
  69709. dataZoomSelectActive: nextActive
  69710. });
  69711. },
  69712. back: function () {
  69713. this._dispatchZoomAction(pop(this.ecModel));
  69714. }
  69715. };
  69716. function makeAxisFinder(dzFeatureModel) {
  69717. var setting = {
  69718. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  69719. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  69720. xAxisId: dzFeatureModel.get('xAxisId', true),
  69721. yAxisId: dzFeatureModel.get('yAxisId', true)
  69722. }; // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  69723. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  69724. // Some old cases set like this below to close yAxis control but leave xAxis control:
  69725. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  69726. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  69727. setting.xAxisIndex = 'all';
  69728. }
  69729. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  69730. setting.yAxisIndex = 'all';
  69731. }
  69732. return setting;
  69733. }
  69734. function updateBackBtnStatus(featureModel, ecModel) {
  69735. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  69736. }
  69737. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  69738. var zoomActive = view._isZoomActive;
  69739. if (payload && payload.type === 'takeGlobalCursor') {
  69740. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  69741. }
  69742. view._isZoomActive = zoomActive;
  69743. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  69744. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  69745. include: ['grid']
  69746. });
  69747. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  69748. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  69749. });
  69750. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  69751. brushType: 'auto',
  69752. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  69753. } : false);
  69754. }
  69755. registerInternalOptionCreator('dataZoom', function (ecModel) {
  69756. var toolboxModel = ecModel.getComponent('toolbox', 0);
  69757. var featureDataZoomPath = ['feature', 'dataZoom'];
  69758. if (!toolboxModel || toolboxModel.get(featureDataZoomPath) == null) {
  69759. return;
  69760. }
  69761. var dzFeatureModel = toolboxModel.getModel(featureDataZoomPath);
  69762. var dzOptions = [];
  69763. var finder = makeAxisFinder(dzFeatureModel);
  69764. var finderResult = parseFinder(ecModel, finder);
  69765. each$a(finderResult.xAxisModels, function (axisModel) {
  69766. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  69767. });
  69768. each$a(finderResult.yAxisModels, function (axisModel) {
  69769. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  69770. });
  69771. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  69772. var axisIndex = axisModel.componentIndex;
  69773. var newOpt = {
  69774. type: 'select',
  69775. $fromToolbox: true,
  69776. // Default to be filter
  69777. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  69778. // Id for merge mapping.
  69779. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  69780. };
  69781. newOpt[axisIndexPropName] = axisIndex;
  69782. dzOptions.push(newOpt);
  69783. }
  69784. return dzOptions;
  69785. });
  69786. function install$z(registers) {
  69787. registers.registerComponentModel(ToolboxModel);
  69788. registers.registerComponentView(ToolboxView);
  69789. registerFeature('saveAsImage', SaveAsImage);
  69790. registerFeature('magicType', MagicType);
  69791. registerFeature('dataView', DataView);
  69792. registerFeature('dataZoom', DataZoomFeature);
  69793. registerFeature('restore', RestoreOption);
  69794. use(install$y);
  69795. }
  69796. var TooltipModel =
  69797. /** @class */
  69798. function (_super) {
  69799. __extends(TooltipModel, _super);
  69800. function TooltipModel() {
  69801. var _this = _super !== null && _super.apply(this, arguments) || this;
  69802. _this.type = TooltipModel.type;
  69803. return _this;
  69804. }
  69805. TooltipModel.type = 'tooltip';
  69806. TooltipModel.dependencies = ['axisPointer'];
  69807. TooltipModel.defaultOption = {
  69808. zlevel: 0,
  69809. z: 60,
  69810. show: true,
  69811. // tooltip main content
  69812. showContent: true,
  69813. // 'trigger' only works on coordinate system.
  69814. // 'item' | 'axis' | 'none'
  69815. trigger: 'item',
  69816. // 'click' | 'mousemove' | 'none'
  69817. triggerOn: 'mousemove|click',
  69818. alwaysShowContent: false,
  69819. displayMode: 'single',
  69820. renderMode: 'auto',
  69821. // whether restraint content inside viewRect.
  69822. // If renderMode: 'richText', default true.
  69823. // If renderMode: 'html', defaut false (for backward compat).
  69824. confine: null,
  69825. showDelay: 0,
  69826. hideDelay: 100,
  69827. // Animation transition time, unit is second
  69828. transitionDuration: 0.4,
  69829. enterable: false,
  69830. backgroundColor: '#fff',
  69831. // box shadow
  69832. shadowBlur: 10,
  69833. shadowColor: 'rgba(0, 0, 0, .2)',
  69834. shadowOffsetX: 1,
  69835. shadowOffsetY: 2,
  69836. // tooltip border radius, unit is px, default is 4
  69837. borderRadius: 4,
  69838. // tooltip border width, unit is px, default is 0 (no border)
  69839. borderWidth: 1,
  69840. // Tooltip inside padding, default is 5 for all direction
  69841. // Array is allowed to set up, right, bottom, left, same with css
  69842. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  69843. padding: null,
  69844. // Extra css text
  69845. extraCssText: '',
  69846. // axis indicator, trigger by axis
  69847. axisPointer: {
  69848. // default is line
  69849. // legal values: 'line' | 'shadow' | 'cross'
  69850. type: 'line',
  69851. // Valid when type is line, appoint tooltip line locate on which line. Optional
  69852. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  69853. // default is 'auto', chose the axis which type is category.
  69854. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  69855. axis: 'auto',
  69856. animation: 'auto',
  69857. animationDurationUpdate: 200,
  69858. animationEasingUpdate: 'exponentialOut',
  69859. crossStyle: {
  69860. color: '#999',
  69861. width: 1,
  69862. type: 'dashed',
  69863. // TODO formatter
  69864. textStyle: {}
  69865. } // lineStyle and shadowStyle should not be specified here,
  69866. // otherwise it will always override those styles on option.axisPointer.
  69867. },
  69868. textStyle: {
  69869. color: '#666',
  69870. fontSize: 14
  69871. }
  69872. };
  69873. return TooltipModel;
  69874. }(ComponentModel);
  69875. /* global document */
  69876. function shouldTooltipConfine(tooltipModel) {
  69877. var confineOption = tooltipModel.get('confine');
  69878. return confineOption != null ? !!confineOption // In richText mode, the outside part can not be visible.
  69879. : tooltipModel.get('renderMode') === 'richText';
  69880. }
  69881. function testStyle(styleProps) {
  69882. if (!env.domSupported) {
  69883. return;
  69884. }
  69885. var style = document.documentElement.style;
  69886. for (var i = 0, len = styleProps.length; i < len; i++) {
  69887. if (styleProps[i] in style) {
  69888. return styleProps[i];
  69889. }
  69890. }
  69891. }
  69892. var TRANSFORM_VENDOR = testStyle(['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  69893. var TRANSITION_VENDOR = testStyle(['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  69894. function toCSSVendorPrefix(styleVendor, styleProp) {
  69895. if (!styleVendor) {
  69896. return styleProp;
  69897. }
  69898. styleProp = toCamelCase(styleProp, true);
  69899. var idx = styleVendor.indexOf(styleProp);
  69900. styleVendor = idx === -1 ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp;
  69901. return styleVendor.toLowerCase();
  69902. }
  69903. function getComputedStyle(el, style) {
  69904. var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el);
  69905. return stl ? style ? stl[style] : stl : null;
  69906. }
  69907. /* global document, window */
  69908. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  69909. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform'); // eslint-disable-next-line
  69910. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  69911. function mirrorPos(pos) {
  69912. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  69913. return pos;
  69914. }
  69915. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  69916. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  69917. return '';
  69918. }
  69919. var backgroundColor = tooltipModel.get('backgroundColor');
  69920. var borderWidth = tooltipModel.get('borderWidth');
  69921. borderColor = convertToColorString(borderColor);
  69922. var arrowPos = mirrorPos(arrowPosition);
  69923. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  69924. var positionStyle = '';
  69925. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  69926. var rotateDeg;
  69927. if (indexOf(['left', 'right'], arrowPos) > -1) {
  69928. positionStyle += 'top:50%';
  69929. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  69930. } else {
  69931. positionStyle += 'left:50%';
  69932. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  69933. }
  69934. var rotateRadian = rotateDeg * Math.PI / 180;
  69935. var arrowWH = arrowSize + borderWidth;
  69936. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  69937. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  69938. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  69939. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  69940. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  69941. return "<div style=\"" + styleCss.join('') + "\"></div>";
  69942. }
  69943. function assembleTransition(duration, onlyFade) {
  69944. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  69945. var transitionOption = " " + duration / 2 + "s " + transitionCurve;
  69946. var transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  69947. if (!onlyFade) {
  69948. transitionOption = " " + duration + "s " + transitionCurve;
  69949. transitionText += env.transformSupported ? "," + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption;
  69950. }
  69951. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  69952. }
  69953. function assembleTransform(x, y, toString) {
  69954. // If using float on style, the final width of the dom might
  69955. // keep changing slightly while mouse move. So `toFixed(0)` them.
  69956. var x0 = x.toFixed(0) + 'px';
  69957. var y0 = y.toFixed(0) + 'px'; // not support transform, use `left` and `top` instead.
  69958. if (!env.transformSupported) {
  69959. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  69960. } // support transform
  69961. var is3d = env.transform3dSupported;
  69962. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  69963. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  69964. }
  69965. /**
  69966. * @param {Object} textStyle
  69967. * @return {string}
  69968. * @inner
  69969. */
  69970. function assembleFont(textStyleModel) {
  69971. var cssText = [];
  69972. var fontSize = textStyleModel.get('fontSize');
  69973. var color = textStyleModel.getTextColor();
  69974. color && cssText.push('color:' + color);
  69975. cssText.push('font:' + textStyleModel.getFont());
  69976. fontSize // @ts-ignore, leave it to the tooltip refactor.
  69977. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  69978. var shadowColor = textStyleModel.get('textShadowColor');
  69979. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  69980. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  69981. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  69982. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  69983. each(['decoration', 'align'], function (name) {
  69984. var val = textStyleModel.get(name);
  69985. val && cssText.push('text-' + name + ':' + val);
  69986. });
  69987. return cssText.join(';');
  69988. }
  69989. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  69990. var cssText = [];
  69991. var transitionDuration = tooltipModel.get('transitionDuration');
  69992. var backgroundColor = tooltipModel.get('backgroundColor');
  69993. var shadowBlur = tooltipModel.get('shadowBlur');
  69994. var shadowColor = tooltipModel.get('shadowColor');
  69995. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  69996. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  69997. var textStyleModel = tooltipModel.getModel('textStyle');
  69998. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  69999. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  70000. cssText.push('box-shadow:' + boxShadow); // Animation transition. Do not animate when transitionDuration is 0.
  70001. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  70002. if (backgroundColor) {
  70003. if (env.canvasSupported) {
  70004. cssText.push('background-color:' + backgroundColor);
  70005. } else {
  70006. // for ie
  70007. cssText.push('background-color:#' + toHex(backgroundColor));
  70008. cssText.push('filter:alpha(opacity=70)');
  70009. }
  70010. } // Border style
  70011. each(['width', 'color', 'radius'], function (name) {
  70012. var borderName = 'border-' + name;
  70013. var camelCase = toCamelCase(borderName);
  70014. var val = tooltipModel.get(camelCase);
  70015. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  70016. }); // Text style
  70017. cssText.push(assembleFont(textStyleModel)); // Padding
  70018. if (padding != null) {
  70019. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  70020. }
  70021. return cssText.join(';') + ';';
  70022. } // If not able to make, do not modify the input `out`.
  70023. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  70024. var zrPainter = zr && zr.painter;
  70025. if (appendToBody) {
  70026. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  70027. if (zrViewportRoot) {
  70028. // Some APPs might use scale on body, so we support CSS transform here.
  70029. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  70030. }
  70031. } else {
  70032. out[0] = zrX;
  70033. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  70034. // the sibling of canvas root. So padding of ec container
  70035. // should be considered here.
  70036. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  70037. if (viewportRootOffset) {
  70038. out[0] += viewportRootOffset.offsetLeft;
  70039. out[1] += viewportRootOffset.offsetTop;
  70040. }
  70041. }
  70042. out[2] = out[0] / zr.getWidth();
  70043. out[3] = out[1] / zr.getHeight();
  70044. }
  70045. var TooltipHTMLContent =
  70046. /** @class */
  70047. function () {
  70048. function TooltipHTMLContent(container, api, opt) {
  70049. this._show = false;
  70050. this._styleCoord = [0, 0, 0, 0];
  70051. this._enterable = true;
  70052. this._firstShow = true;
  70053. this._longHide = true;
  70054. if (env.wxa) {
  70055. return null;
  70056. }
  70057. var el = document.createElement('div'); // TODO: TYPE
  70058. el.domBelongToZr = true;
  70059. this.el = el;
  70060. var zr = this._zr = api.getZr();
  70061. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  70062. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  70063. if (appendToBody) {
  70064. document.body.appendChild(el);
  70065. } else {
  70066. container.appendChild(el);
  70067. }
  70068. this._container = container; // FIXME
  70069. // Is it needed to trigger zr event manually if
  70070. // the browser do not support `pointer-events: none`.
  70071. var self = this;
  70072. el.onmouseenter = function () {
  70073. // clear the timeout in hideLater and keep showing tooltip
  70074. if (self._enterable) {
  70075. clearTimeout(self._hideTimeout);
  70076. self._show = true;
  70077. }
  70078. self._inContent = true;
  70079. };
  70080. el.onmousemove = function (e) {
  70081. e = e || window.event;
  70082. if (!self._enterable) {
  70083. // `pointer-events: none` is set to tooltip content div
  70084. // if `enterable` is set as `false`, and `el.onmousemove`
  70085. // can not be triggered. But in browser that do not
  70086. // support `pointer-events`, we need to do this:
  70087. // Try trigger zrender event to avoid mouse
  70088. // in and out shape too frequently
  70089. var handler = zr.handler;
  70090. var zrViewportRoot = zr.painter.getViewportRoot();
  70091. normalizeEvent(zrViewportRoot, e, true);
  70092. handler.dispatch('mousemove', e);
  70093. }
  70094. };
  70095. el.onmouseleave = function () {
  70096. // set `_inContent` to `false` before `hideLater`
  70097. self._inContent = false;
  70098. if (self._enterable) {
  70099. if (self._show) {
  70100. self.hideLater(self._hideDelay);
  70101. }
  70102. }
  70103. };
  70104. }
  70105. /**
  70106. * Update when tooltip is rendered
  70107. */
  70108. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  70109. // FIXME
  70110. // Move this logic to ec main?
  70111. var container = this._container;
  70112. var position = getComputedStyle(container, 'position');
  70113. var domStyle = container.style;
  70114. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  70115. domStyle.position = 'relative';
  70116. } // move tooltip if chart resized
  70117. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  70118. alwaysShowContent && this._moveIfResized(); // update className
  70119. this.el.className = tooltipModel.get('className') || ''; // Hide the tooltip
  70120. // PENDING
  70121. // this.hide();
  70122. };
  70123. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  70124. clearTimeout(this._hideTimeout);
  70125. clearTimeout(this._longHideTimeout);
  70126. var el = this.el;
  70127. var style = el.style;
  70128. var styleCoord = this._styleCoord;
  70129. if (!el.innerHTML) {
  70130. style.display = 'none';
  70131. } else {
  70132. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide) // initial transform
  70133. + 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
  70134. // triggered by canvas, and cause some unexpectable result like dragging
  70135. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  70136. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  70137. // scenario.
  70138. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  70139. }
  70140. this._show = true;
  70141. this._firstShow = false;
  70142. this._longHide = false;
  70143. };
  70144. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  70145. var el = this.el;
  70146. if (content == null) {
  70147. el.innerHTML = '';
  70148. return;
  70149. }
  70150. var arrow = '';
  70151. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  70152. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  70153. }
  70154. if (isString(content)) {
  70155. el.innerHTML = content + arrow;
  70156. } else if (content) {
  70157. // Clear previous
  70158. el.innerHTML = '';
  70159. if (!isArray(content)) {
  70160. content = [content];
  70161. }
  70162. for (var i = 0; i < content.length; i++) {
  70163. if (isDom(content[i]) && content[i].parentNode !== el) {
  70164. el.appendChild(content[i]);
  70165. }
  70166. } // no arrow if empty
  70167. if (arrow && el.childNodes.length) {
  70168. // no need to create a new parent element, but it's not supported by IE 10 and older.
  70169. // const arrowEl = document.createRange().createContextualFragment(arrow);
  70170. var arrowEl = document.createElement('div');
  70171. arrowEl.innerHTML = arrow;
  70172. el.appendChild(arrowEl);
  70173. }
  70174. }
  70175. };
  70176. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  70177. this._enterable = enterable;
  70178. };
  70179. TooltipHTMLContent.prototype.getSize = function () {
  70180. var el = this.el;
  70181. return [el.offsetWidth, el.offsetHeight];
  70182. };
  70183. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  70184. var styleCoord = this._styleCoord;
  70185. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  70186. if (styleCoord[0] != null && styleCoord[1] != null) {
  70187. var style_1 = this.el.style;
  70188. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  70189. each(transforms, function (transform) {
  70190. style_1[transform[0]] = transform[1];
  70191. });
  70192. }
  70193. };
  70194. /**
  70195. * when `alwaysShowContent` is true,
  70196. * move the tooltip after chart resized
  70197. */
  70198. TooltipHTMLContent.prototype._moveIfResized = function () {
  70199. // The ratio of left to width
  70200. var ratioX = this._styleCoord[2]; // The ratio of top to height
  70201. var ratioY = this._styleCoord[3];
  70202. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  70203. };
  70204. TooltipHTMLContent.prototype.hide = function () {
  70205. var _this = this;
  70206. var style = this.el.style;
  70207. style.visibility = 'hidden';
  70208. style.opacity = '0';
  70209. env.transform3dSupported && (style.willChange = '');
  70210. this._show = false;
  70211. this._longHideTimeout = setTimeout(function () {
  70212. return _this._longHide = true;
  70213. }, 500);
  70214. };
  70215. TooltipHTMLContent.prototype.hideLater = function (time) {
  70216. if (this._show && !(this._inContent && this._enterable)) {
  70217. if (time) {
  70218. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  70219. this._show = false;
  70220. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  70221. } else {
  70222. this.hide();
  70223. }
  70224. }
  70225. };
  70226. TooltipHTMLContent.prototype.isShow = function () {
  70227. return this._show;
  70228. };
  70229. TooltipHTMLContent.prototype.dispose = function () {
  70230. this.el.parentNode.removeChild(this.el);
  70231. };
  70232. return TooltipHTMLContent;
  70233. }();
  70234. var TooltipRichContent =
  70235. /** @class */
  70236. function () {
  70237. function TooltipRichContent(api) {
  70238. this._show = false;
  70239. this._styleCoord = [0, 0, 0, 0];
  70240. this._enterable = true;
  70241. this._zr = api.getZr();
  70242. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  70243. }
  70244. /**
  70245. * Update when tooltip is rendered
  70246. */
  70247. TooltipRichContent.prototype.update = function (tooltipModel) {
  70248. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  70249. alwaysShowContent && this._moveIfResized();
  70250. };
  70251. TooltipRichContent.prototype.show = function () {
  70252. if (this._hideTimeout) {
  70253. clearTimeout(this._hideTimeout);
  70254. }
  70255. this.el.show();
  70256. this._show = true;
  70257. };
  70258. /**
  70259. * Set tooltip content
  70260. */
  70261. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  70262. if (isObject(content)) {
  70263. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  70264. }
  70265. if (this.el) {
  70266. this._zr.remove(this.el);
  70267. }
  70268. var textStyleModel = tooltipModel.getModel('textStyle');
  70269. this.el = new ZRText({
  70270. style: {
  70271. rich: markupStyleCreator.richTextStyles,
  70272. text: content,
  70273. lineHeight: 22,
  70274. backgroundColor: tooltipModel.get('backgroundColor'),
  70275. borderRadius: tooltipModel.get('borderRadius'),
  70276. borderWidth: 1,
  70277. borderColor: borderColor,
  70278. shadowColor: tooltipModel.get('shadowColor'),
  70279. shadowBlur: tooltipModel.get('shadowBlur'),
  70280. shadowOffsetX: tooltipModel.get('shadowOffsetX'),
  70281. shadowOffsetY: tooltipModel.get('shadowOffsetY'),
  70282. textShadowColor: textStyleModel.get('textShadowColor'),
  70283. textShadowBlur: textStyleModel.get('textShadowBlur') || 0,
  70284. textShadowOffsetX: textStyleModel.get('textShadowOffsetX') || 0,
  70285. textShadowOffsetY: textStyleModel.get('textShadowOffsetY') || 0,
  70286. fill: tooltipModel.get(['textStyle', 'color']),
  70287. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  70288. verticalAlign: 'top',
  70289. align: 'left'
  70290. },
  70291. z: tooltipModel.get('z')
  70292. });
  70293. this._zr.add(this.el);
  70294. var self = this;
  70295. this.el.on('mouseover', function () {
  70296. // clear the timeout in hideLater and keep showing tooltip
  70297. if (self._enterable) {
  70298. clearTimeout(self._hideTimeout);
  70299. self._show = true;
  70300. }
  70301. self._inContent = true;
  70302. });
  70303. this.el.on('mouseout', function () {
  70304. if (self._enterable) {
  70305. if (self._show) {
  70306. self.hideLater(self._hideDelay);
  70307. }
  70308. }
  70309. self._inContent = false;
  70310. });
  70311. };
  70312. TooltipRichContent.prototype.setEnterable = function (enterable) {
  70313. this._enterable = enterable;
  70314. };
  70315. TooltipRichContent.prototype.getSize = function () {
  70316. var el = this.el;
  70317. var bounding = this.el.getBoundingRect(); // bounding rect does not include shadow. For renderMode richText,
  70318. // if overflow, it will be cut. So calculate them accurately.
  70319. var shadowOuterSize = calcShadowOuterSize(el.style);
  70320. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  70321. };
  70322. TooltipRichContent.prototype.moveTo = function (x, y) {
  70323. var el = this.el;
  70324. if (el) {
  70325. var styleCoord = this._styleCoord;
  70326. makeStyleCoord$1(styleCoord, this._zr, x, y);
  70327. x = styleCoord[0];
  70328. y = styleCoord[1];
  70329. var style = el.style;
  70330. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  70331. var shadowOuterSize = calcShadowOuterSize(style); // rich text x, y do not include border.
  70332. el.x = x + borderWidth + shadowOuterSize.left;
  70333. el.y = y + borderWidth + shadowOuterSize.top;
  70334. el.markRedraw();
  70335. }
  70336. };
  70337. /**
  70338. * when `alwaysShowContent` is true,
  70339. * move the tooltip after chart resized
  70340. */
  70341. TooltipRichContent.prototype._moveIfResized = function () {
  70342. // The ratio of left to width
  70343. var ratioX = this._styleCoord[2]; // The ratio of top to height
  70344. var ratioY = this._styleCoord[3];
  70345. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  70346. };
  70347. TooltipRichContent.prototype.hide = function () {
  70348. if (this.el) {
  70349. this.el.hide();
  70350. }
  70351. this._show = false;
  70352. };
  70353. TooltipRichContent.prototype.hideLater = function (time) {
  70354. if (this._show && !(this._inContent && this._enterable)) {
  70355. if (time) {
  70356. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  70357. this._show = false;
  70358. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  70359. } else {
  70360. this.hide();
  70361. }
  70362. }
  70363. };
  70364. TooltipRichContent.prototype.isShow = function () {
  70365. return this._show;
  70366. };
  70367. TooltipRichContent.prototype.dispose = function () {
  70368. this._zr.remove(this.el);
  70369. };
  70370. return TooltipRichContent;
  70371. }();
  70372. function mathMaxWith0(val) {
  70373. return Math.max(0, val);
  70374. }
  70375. function calcShadowOuterSize(style) {
  70376. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  70377. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  70378. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  70379. return {
  70380. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  70381. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  70382. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  70383. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  70384. };
  70385. }
  70386. function makeStyleCoord$1(out, zr, zrX, zrY) {
  70387. out[0] = zrX;
  70388. out[1] = zrY;
  70389. out[2] = out[0] / zr.getWidth();
  70390. out[3] = out[1] / zr.getHeight();
  70391. }
  70392. var bind$2 = bind;
  70393. var each$b = each;
  70394. var parsePercent$2 = parsePercent$1;
  70395. var proxyRect = new Rect({
  70396. shape: {
  70397. x: -1,
  70398. y: -1,
  70399. width: 2,
  70400. height: 2
  70401. }
  70402. });
  70403. var TooltipView =
  70404. /** @class */
  70405. function (_super) {
  70406. __extends(TooltipView, _super);
  70407. function TooltipView() {
  70408. var _this = _super !== null && _super.apply(this, arguments) || this;
  70409. _this.type = TooltipView.type;
  70410. return _this;
  70411. }
  70412. TooltipView.prototype.init = function (ecModel, api) {
  70413. if (env.node) {
  70414. return;
  70415. }
  70416. var tooltipModel = ecModel.getComponent('tooltip');
  70417. var renderMode = tooltipModel.get('renderMode');
  70418. this._renderMode = getTooltipRenderMode(renderMode);
  70419. this._tooltipContent = this._renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api.getDom(), api, {
  70420. appendToBody: tooltipModel.get('appendToBody', true)
  70421. });
  70422. };
  70423. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  70424. if (env.node) {
  70425. return;
  70426. } // Reset
  70427. this.group.removeAll();
  70428. this._tooltipModel = tooltipModel;
  70429. this._ecModel = ecModel;
  70430. this._api = api;
  70431. /**
  70432. * @private
  70433. * @type {boolean}
  70434. */
  70435. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  70436. var tooltipContent = this._tooltipContent;
  70437. tooltipContent.update(tooltipModel);
  70438. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  70439. this._initGlobalListener();
  70440. this._keepShow();
  70441. };
  70442. TooltipView.prototype._initGlobalListener = function () {
  70443. var tooltipModel = this._tooltipModel;
  70444. var triggerOn = tooltipModel.get('triggerOn');
  70445. register('itemTooltip', this._api, bind$2(function (currTrigger, e, dispatchAction) {
  70446. // If 'none', it is not controlled by mouse totally.
  70447. if (triggerOn !== 'none') {
  70448. if (triggerOn.indexOf(currTrigger) >= 0) {
  70449. this._tryShow(e, dispatchAction);
  70450. } else if (currTrigger === 'leave') {
  70451. this._hide(dispatchAction);
  70452. }
  70453. }
  70454. }, this));
  70455. };
  70456. TooltipView.prototype._keepShow = function () {
  70457. var tooltipModel = this._tooltipModel;
  70458. var ecModel = this._ecModel;
  70459. var api = this._api; // Try to keep the tooltip show when refreshing
  70460. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  70461. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  70462. // which is not expected.
  70463. && tooltipModel.get('triggerOn') !== 'none') {
  70464. var self_1 = this;
  70465. clearTimeout(this._refreshUpdateTimeout);
  70466. this._refreshUpdateTimeout = setTimeout(function () {
  70467. // Show tip next tick after other charts are rendered
  70468. // In case highlight action has wrong result
  70469. // FIXME
  70470. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  70471. x: self_1._lastX,
  70472. y: self_1._lastY,
  70473. dataByCoordSys: self_1._lastDataByCoordSys
  70474. });
  70475. });
  70476. }
  70477. };
  70478. /**
  70479. * Show tip manually by
  70480. * dispatchAction({
  70481. * type: 'showTip',
  70482. * x: 10,
  70483. * y: 10
  70484. * });
  70485. * Or
  70486. * dispatchAction({
  70487. * type: 'showTip',
  70488. * seriesIndex: 0,
  70489. * dataIndex or dataIndexInside or name
  70490. * });
  70491. *
  70492. * TODO Batch
  70493. */
  70494. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  70495. if (payload.from === this.uid || env.node) {
  70496. return;
  70497. }
  70498. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  70499. this._ticket = ''; // When triggered from axisPointer.
  70500. var dataByCoordSys = payload.dataByCoordSys;
  70501. var cmptRef = findComponentReference(payload, ecModel, api);
  70502. if (cmptRef) {
  70503. var rect = cmptRef.el.getBoundingRect().clone();
  70504. rect.applyTransform(cmptRef.el.transform);
  70505. this._tryShow({
  70506. offsetX: rect.x + rect.width / 2,
  70507. offsetY: rect.y + rect.height / 2,
  70508. target: cmptRef.el,
  70509. position: payload.position,
  70510. // When manully trigger, the mouse is not on the el, so we'd better to
  70511. // position tooltip on the bottom of the el and display arrow is possible.
  70512. positionDefault: 'bottom'
  70513. }, dispatchAction);
  70514. } else if (payload.tooltip && payload.x != null && payload.y != null) {
  70515. var el = proxyRect;
  70516. el.x = payload.x;
  70517. el.y = payload.y;
  70518. el.update();
  70519. getECData(el).tooltipConfig = {
  70520. name: null,
  70521. option: payload.tooltip
  70522. }; // Manually show tooltip while view is not using zrender elements.
  70523. this._tryShow({
  70524. offsetX: payload.x,
  70525. offsetY: payload.y,
  70526. target: el
  70527. }, dispatchAction);
  70528. } else if (dataByCoordSys) {
  70529. this._tryShow({
  70530. offsetX: payload.x,
  70531. offsetY: payload.y,
  70532. position: payload.position,
  70533. dataByCoordSys: dataByCoordSys,
  70534. tooltipOption: payload.tooltipOption
  70535. }, dispatchAction);
  70536. } else if (payload.seriesIndex != null) {
  70537. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  70538. return;
  70539. }
  70540. var pointInfo = findPointFromSeries(payload, ecModel);
  70541. var cx = pointInfo.point[0];
  70542. var cy = pointInfo.point[1];
  70543. if (cx != null && cy != null) {
  70544. this._tryShow({
  70545. offsetX: cx,
  70546. offsetY: cy,
  70547. target: pointInfo.el,
  70548. position: payload.position,
  70549. // When manully trigger, the mouse is not on the el, so we'd better to
  70550. // position tooltip on the bottom of the el and display arrow is possible.
  70551. positionDefault: 'bottom'
  70552. }, dispatchAction);
  70553. }
  70554. } else if (payload.x != null && payload.y != null) {
  70555. // FIXME
  70556. // should wrap dispatchAction like `axisPointer/globalListener` ?
  70557. api.dispatchAction({
  70558. type: 'updateAxisPointer',
  70559. x: payload.x,
  70560. y: payload.y
  70561. });
  70562. this._tryShow({
  70563. offsetX: payload.x,
  70564. offsetY: payload.y,
  70565. position: payload.position,
  70566. target: api.getZr().findHover(payload.x, payload.y).target
  70567. }, dispatchAction);
  70568. }
  70569. };
  70570. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  70571. var tooltipContent = this._tooltipContent;
  70572. if (!this._alwaysShowContent && this._tooltipModel) {
  70573. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  70574. }
  70575. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  70576. if (payload.from !== this.uid) {
  70577. this._hide(makeDispatchAction$1(payload, api));
  70578. }
  70579. }; // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  70580. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  70581. // and tooltip.
  70582. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  70583. var seriesIndex = payload.seriesIndex;
  70584. var dataIndex = payload.dataIndex; // @ts-ignore
  70585. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  70586. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  70587. return;
  70588. }
  70589. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  70590. if (!seriesModel) {
  70591. return;
  70592. }
  70593. var data = seriesModel.getData();
  70594. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model], this._tooltipModel);
  70595. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  70596. return;
  70597. }
  70598. api.dispatchAction({
  70599. type: 'updateAxisPointer',
  70600. seriesIndex: seriesIndex,
  70601. dataIndex: dataIndex,
  70602. position: payload.position
  70603. });
  70604. return true;
  70605. };
  70606. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  70607. var el = e.target;
  70608. var tooltipModel = this._tooltipModel;
  70609. if (!tooltipModel) {
  70610. return;
  70611. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  70612. this._lastX = e.offsetX;
  70613. this._lastY = e.offsetY;
  70614. var dataByCoordSys = e.dataByCoordSys;
  70615. if (dataByCoordSys && dataByCoordSys.length) {
  70616. this._showAxisTooltip(dataByCoordSys, e);
  70617. } else if (el) {
  70618. this._lastDataByCoordSys = null;
  70619. var seriesDispatcher_1;
  70620. var cmptDispatcher_1;
  70621. findEventDispatcher(el, function (target) {
  70622. // Always show item tooltip if mouse is on the element with dataIndex
  70623. if (getECData(target).dataIndex != null) {
  70624. seriesDispatcher_1 = target;
  70625. return true;
  70626. } // Tooltip provided directly. Like legend.
  70627. if (getECData(target).tooltipConfig != null) {
  70628. cmptDispatcher_1 = target;
  70629. return true;
  70630. }
  70631. }, true);
  70632. if (seriesDispatcher_1) {
  70633. this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction);
  70634. } else if (cmptDispatcher_1) {
  70635. this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction);
  70636. } else {
  70637. this._hide(dispatchAction);
  70638. }
  70639. } else {
  70640. this._lastDataByCoordSys = null;
  70641. this._hide(dispatchAction);
  70642. }
  70643. };
  70644. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  70645. // showDelay is used in this case: tooltip.enterable is set
  70646. // as true. User intent to move mouse into tooltip and click
  70647. // something. `showDelay` makes it easier to enter the content
  70648. // but tooltip do not move immediately.
  70649. var delay = tooltipModel.get('showDelay');
  70650. cb = bind(cb, this);
  70651. clearTimeout(this._showTimout);
  70652. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  70653. };
  70654. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  70655. var ecModel = this._ecModel;
  70656. var globalTooltipModel = this._tooltipModel;
  70657. var point = [e.offsetX, e.offsetY];
  70658. var singleTooltipModel = buildTooltipModel([e.tooltipOption], globalTooltipModel);
  70659. var renderMode = this._renderMode;
  70660. var cbParamsList = [];
  70661. var articleMarkup = createTooltipMarkup('section', {
  70662. blocks: [],
  70663. noHeader: true
  70664. }); // Only for legacy: `Serise['formatTooltip']` returns a string.
  70665. var markupTextArrLegacy = [];
  70666. var markupStyleCreator = new TooltipMarkupStyleCreator();
  70667. each$b(dataByCoordSys, function (itemCoordSys) {
  70668. each$b(itemCoordSys.dataByAxis, function (axisItem) {
  70669. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  70670. var axisValue = axisItem.value;
  70671. if (!axisModel || axisValue == null) {
  70672. return;
  70673. }
  70674. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  70675. var axisSectionMarkup = createTooltipMarkup('section', {
  70676. header: axisValueLabel,
  70677. noHeader: !trim(axisValueLabel),
  70678. sortBlocks: true,
  70679. blocks: []
  70680. });
  70681. articleMarkup.blocks.push(axisSectionMarkup);
  70682. each(axisItem.seriesDataIndices, function (idxItem) {
  70683. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  70684. var dataIndex = idxItem.dataIndexInside;
  70685. var cbParams = series.getDataParams(dataIndex); // Can't find data.
  70686. if (cbParams.dataIndex < 0) {
  70687. return;
  70688. }
  70689. cbParams.axisDim = axisItem.axisDim;
  70690. cbParams.axisIndex = axisItem.axisIndex;
  70691. cbParams.axisType = axisItem.axisType;
  70692. cbParams.axisId = axisItem.axisId;
  70693. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  70694. value: axisValue
  70695. });
  70696. cbParams.axisValueLabel = axisValueLabel; // Pre-create marker style for makers. Users can assemble richText
  70697. // text in `formatter` callback and use those markers style.
  70698. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  70699. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  70700. if (seriesTooltipResult.markupFragment) {
  70701. axisSectionMarkup.blocks.push(seriesTooltipResult.markupFragment);
  70702. }
  70703. if (seriesTooltipResult.markupText) {
  70704. markupTextArrLegacy.push(seriesTooltipResult.markupText);
  70705. }
  70706. cbParamsList.push(cbParams);
  70707. });
  70708. });
  70709. }); // In most cases, the second axis is displays upper on the first one.
  70710. // So we reverse it to look better.
  70711. articleMarkup.blocks.reverse();
  70712. markupTextArrLegacy.reverse();
  70713. var positionExpr = e.position;
  70714. var orderMode = singleTooltipModel.get('order');
  70715. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  70716. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  70717. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  70718. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  70719. this._showOrMove(singleTooltipModel, function () {
  70720. if (this._updateContentNotChangedOnAxis(dataByCoordSys, cbParamsList)) {
  70721. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  70722. } else {
  70723. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  70724. }
  70725. }); // Do not trigger events here, because this branch only be entered
  70726. // from dispatchAction.
  70727. };
  70728. TooltipView.prototype._showSeriesItemTooltip = function (e, dispatcher, dispatchAction) {
  70729. var ecModel = this._ecModel;
  70730. var ecData = getECData(dispatcher); // Use dataModel in element if possible
  70731. // Used when mouseover on a element like markPoint or edge
  70732. // In which case, the data is not main data in series.
  70733. var seriesIndex = ecData.seriesIndex;
  70734. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  70735. var dataModel = ecData.dataModel || seriesModel;
  70736. var dataIndex = ecData.dataIndex;
  70737. var dataType = ecData.dataType;
  70738. var data = dataModel.getData(dataType);
  70739. var renderMode = this._renderMode;
  70740. var positionDefault = e.positionDefault;
  70741. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model], this._tooltipModel, positionDefault ? {
  70742. position: positionDefault
  70743. } : null);
  70744. var tooltipTrigger = tooltipModel.get('trigger');
  70745. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  70746. return;
  70747. }
  70748. var params = dataModel.getDataParams(dataIndex, dataType);
  70749. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Pre-create marker style for makers. Users can assemble richText
  70750. // text in `formatter` callback and use those markers style.
  70751. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  70752. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  70753. var orderMode = tooltipModel.get('order');
  70754. var markupText = seriesTooltipResult.markupFragment ? buildTooltipMarkup(seriesTooltipResult.markupFragment, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.markupText;
  70755. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  70756. this._showOrMove(tooltipModel, function () {
  70757. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  70758. }); // FIXME
  70759. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  70760. dispatchAction({
  70761. type: 'showTip',
  70762. dataIndexInside: dataIndex,
  70763. dataIndex: data.getRawIndex(dataIndex),
  70764. seriesIndex: seriesIndex,
  70765. from: this.uid
  70766. });
  70767. };
  70768. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  70769. var ecData = getECData(el);
  70770. var tooltipConfig = ecData.tooltipConfig;
  70771. var tooltipOpt = tooltipConfig.option || {};
  70772. if (isString(tooltipOpt)) {
  70773. var content = tooltipOpt;
  70774. tooltipOpt = {
  70775. content: content,
  70776. // Fixed formatter
  70777. formatter: content
  70778. };
  70779. }
  70780. var tooltipModelCascade = [tooltipOpt];
  70781. var cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex);
  70782. if (cmpt) {
  70783. tooltipModelCascade.push(cmpt);
  70784. } // In most cases, component tooltip formatter has different params with series tooltip formatter,
  70785. // so that they can not share the same formatter. Since the global tooltip formatter is used for series
  70786. // by convension, we do not use it as the default formatter for component.
  70787. tooltipModelCascade.push({
  70788. formatter: tooltipOpt.content
  70789. });
  70790. var positionDefault = e.positionDefault;
  70791. var subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? {
  70792. position: positionDefault
  70793. } : null);
  70794. var defaultHtml = subTooltipModel.get('content');
  70795. var asyncTicket = Math.random() + ''; // PENDING: this case do not support richText style yet.
  70796. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Do not check whether `trigger` is 'none' here, because `trigger`
  70797. // only works on coordinate system. In fact, we have not found case
  70798. // that requires setting `trigger` nothing on component yet.
  70799. this._showOrMove(subTooltipModel, function () {
  70800. // Use formatterParams from element defined in component
  70801. // Avoid users modify it.
  70802. var formatterParams = clone(subTooltipModel.get('formatterParams') || {});
  70803. this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  70804. }); // If not dispatch showTip, tip may be hide triggered by axis.
  70805. dispatchAction({
  70806. type: 'showTip',
  70807. from: this.uid
  70808. });
  70809. };
  70810. TooltipView.prototype._showTooltipContent = function ( // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  70811. // Instead of top level tooltip.
  70812. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  70813. // Reset ticket
  70814. this._ticket = '';
  70815. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  70816. return;
  70817. }
  70818. var tooltipContent = this._tooltipContent;
  70819. var formatter = tooltipModel.get('formatter');
  70820. positionExpr = positionExpr || tooltipModel.get('position');
  70821. var html = defaultHtml;
  70822. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  70823. var nearPointColor = nearPoint.color;
  70824. if (formatter) {
  70825. if (isString(formatter)) {
  70826. var useUTC = tooltipModel.ecModel.get('useUTC');
  70827. var params0 = isArray(params) ? params[0] : params;
  70828. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  70829. html = formatter;
  70830. if (isTimeAxis) {
  70831. html = format(params0.axisValue, html, useUTC);
  70832. }
  70833. html = formatTpl(html, params, true);
  70834. } else if (isFunction(formatter)) {
  70835. var callback = bind$2(function (cbTicket, html) {
  70836. if (cbTicket === this._ticket) {
  70837. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  70838. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  70839. }
  70840. }, this);
  70841. this._ticket = asyncTicket;
  70842. html = formatter(params, asyncTicket, callback);
  70843. } else {
  70844. html = formatter;
  70845. }
  70846. }
  70847. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  70848. tooltipContent.show(tooltipModel, nearPointColor);
  70849. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  70850. };
  70851. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  70852. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  70853. return {
  70854. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  70855. };
  70856. }
  70857. if (!isArray(tooltipDataParams)) {
  70858. return {
  70859. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  70860. };
  70861. }
  70862. };
  70863. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x, // Mouse x
  70864. y, // Mouse y
  70865. content, params, el) {
  70866. var viewWidth = this._api.getWidth();
  70867. var viewHeight = this._api.getHeight();
  70868. positionExpr = positionExpr || tooltipModel.get('position');
  70869. var contentSize = content.getSize();
  70870. var align = tooltipModel.get('align');
  70871. var vAlign = tooltipModel.get('verticalAlign');
  70872. var rect = el && el.getBoundingRect().clone();
  70873. el && rect.applyTransform(el.transform);
  70874. if (isFunction(positionExpr)) {
  70875. // Callback of position can be an array or a string specify the position
  70876. positionExpr = positionExpr([x, y], params, content.el, rect, {
  70877. viewSize: [viewWidth, viewHeight],
  70878. contentSize: contentSize.slice()
  70879. });
  70880. }
  70881. if (isArray(positionExpr)) {
  70882. x = parsePercent$2(positionExpr[0], viewWidth);
  70883. y = parsePercent$2(positionExpr[1], viewHeight);
  70884. } else if (isObject(positionExpr)) {
  70885. var boxLayoutPosition = positionExpr;
  70886. boxLayoutPosition.width = contentSize[0];
  70887. boxLayoutPosition.height = contentSize[1];
  70888. var layoutRect = getLayoutRect(boxLayoutPosition, {
  70889. width: viewWidth,
  70890. height: viewHeight
  70891. });
  70892. x = layoutRect.x;
  70893. y = layoutRect.y;
  70894. align = null; // When positionExpr is left/top/right/bottom,
  70895. // align and verticalAlign will not work.
  70896. vAlign = null;
  70897. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  70898. else if (isString(positionExpr) && el) {
  70899. var pos = calcTooltipPosition(positionExpr, rect, contentSize, tooltipModel.get('borderWidth'));
  70900. x = pos[0];
  70901. y = pos[1];
  70902. } else {
  70903. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  70904. x = pos[0];
  70905. y = pos[1];
  70906. }
  70907. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  70908. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  70909. if (shouldTooltipConfine(tooltipModel)) {
  70910. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  70911. x = pos[0];
  70912. y = pos[1];
  70913. }
  70914. content.moveTo(x, y);
  70915. }; // FIXME
  70916. // Should we remove this but leave this to user?
  70917. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys, cbParamsList) {
  70918. var lastCoordSys = this._lastDataByCoordSys;
  70919. var lastCbParamsList = this._cbParamsList;
  70920. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  70921. contentNotChanged && each$b(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  70922. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  70923. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  70924. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  70925. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  70926. contentNotChanged && each$b(lastDataByAxis, function (lastItem, indexAxis) {
  70927. var thisItem = thisDataByAxis[indexAxis] || {};
  70928. var lastIndices = lastItem.seriesDataIndices || [];
  70929. var newIndices = thisItem.seriesDataIndices || [];
  70930. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  70931. contentNotChanged && each$b(lastIndices, function (lastIdxItem, j) {
  70932. var newIdxItem = newIndices[j];
  70933. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  70934. }); // check is cbParams data value changed
  70935. lastCbParamsList && each(lastItem.seriesDataIndices, function (idxItem) {
  70936. var seriesIdx = idxItem.seriesIndex;
  70937. var cbParams = cbParamsList[seriesIdx];
  70938. var lastCbParams = lastCbParamsList[seriesIdx];
  70939. if (cbParams && lastCbParams && lastCbParams.data !== cbParams.data) {
  70940. contentNotChanged = false;
  70941. }
  70942. });
  70943. });
  70944. });
  70945. this._lastDataByCoordSys = dataByCoordSys;
  70946. this._cbParamsList = cbParamsList;
  70947. return !!contentNotChanged;
  70948. };
  70949. TooltipView.prototype._hide = function (dispatchAction) {
  70950. // Do not directly hideLater here, because this behavior may be prevented
  70951. // in dispatchAction when showTip is dispatched.
  70952. // FIXME
  70953. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  70954. this._lastDataByCoordSys = null;
  70955. dispatchAction({
  70956. type: 'hideTip',
  70957. from: this.uid
  70958. });
  70959. };
  70960. TooltipView.prototype.dispose = function (ecModel, api) {
  70961. if (env.node) {
  70962. return;
  70963. }
  70964. this._tooltipContent.dispose();
  70965. unregister('itemTooltip', api);
  70966. };
  70967. TooltipView.type = 'tooltip';
  70968. return TooltipView;
  70969. }(ComponentView);
  70970. /**
  70971. * From top to bottom. (the last one should be globalTooltipModel);
  70972. */
  70973. function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) {
  70974. // Last is always tooltip model.
  70975. var ecModel = globalTooltipModel.ecModel;
  70976. var resultModel;
  70977. if (defaultTooltipOption) {
  70978. resultModel = new Model(defaultTooltipOption, ecModel, ecModel);
  70979. resultModel = new Model(globalTooltipModel.option, resultModel, ecModel);
  70980. } else {
  70981. resultModel = globalTooltipModel;
  70982. }
  70983. for (var i = modelCascade.length - 1; i >= 0; i--) {
  70984. var tooltipOpt = modelCascade[i];
  70985. if (tooltipOpt) {
  70986. if (tooltipOpt instanceof Model) {
  70987. tooltipOpt = tooltipOpt.get('tooltip', true);
  70988. } // In each data item tooltip can be simply write:
  70989. // {
  70990. // value: 10,
  70991. // tooltip: 'Something you need to know'
  70992. // }
  70993. if (isString(tooltipOpt)) {
  70994. tooltipOpt = {
  70995. formatter: tooltipOpt
  70996. };
  70997. }
  70998. if (tooltipOpt) {
  70999. resultModel = new Model(tooltipOpt, resultModel, ecModel);
  71000. }
  71001. }
  71002. }
  71003. return resultModel;
  71004. }
  71005. function makeDispatchAction$1(payload, api) {
  71006. return payload.dispatchAction || bind(api.dispatchAction, api);
  71007. }
  71008. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  71009. var size = content.getSize();
  71010. var width = size[0];
  71011. var height = size[1];
  71012. if (gapH != null) {
  71013. // Add extra 2 pixels for this case:
  71014. // At present the "values" in defaut tooltip are using CSS `float: right`.
  71015. // When the right edge of the tooltip box is on the right side of the
  71016. // viewport, the `float` layout might push the "values" to the second line.
  71017. if (x + width + gapH + 2 > viewWidth) {
  71018. x -= width + gapH;
  71019. } else {
  71020. x += gapH;
  71021. }
  71022. }
  71023. if (gapV != null) {
  71024. if (y + height + gapV > viewHeight) {
  71025. y -= height + gapV;
  71026. } else {
  71027. y += gapV;
  71028. }
  71029. }
  71030. return [x, y];
  71031. }
  71032. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  71033. var size = content.getSize();
  71034. var width = size[0];
  71035. var height = size[1];
  71036. x = Math.min(x + width, viewWidth) - width;
  71037. y = Math.min(y + height, viewHeight) - height;
  71038. x = Math.max(x, 0);
  71039. y = Math.max(y, 0);
  71040. return [x, y];
  71041. }
  71042. function calcTooltipPosition(position, rect, contentSize, borderWidth) {
  71043. var domWidth = contentSize[0];
  71044. var domHeight = contentSize[1];
  71045. var offset = Math.ceil(Math.SQRT2 * borderWidth) + 8;
  71046. var x = 0;
  71047. var y = 0;
  71048. var rectWidth = rect.width;
  71049. var rectHeight = rect.height;
  71050. switch (position) {
  71051. case 'inside':
  71052. x = rect.x + rectWidth / 2 - domWidth / 2;
  71053. y = rect.y + rectHeight / 2 - domHeight / 2;
  71054. break;
  71055. case 'top':
  71056. x = rect.x + rectWidth / 2 - domWidth / 2;
  71057. y = rect.y - domHeight - offset;
  71058. break;
  71059. case 'bottom':
  71060. x = rect.x + rectWidth / 2 - domWidth / 2;
  71061. y = rect.y + rectHeight + offset;
  71062. break;
  71063. case 'left':
  71064. x = rect.x - domWidth - offset;
  71065. y = rect.y + rectHeight / 2 - domHeight / 2;
  71066. break;
  71067. case 'right':
  71068. x = rect.x + rectWidth + offset;
  71069. y = rect.y + rectHeight / 2 - domHeight / 2;
  71070. }
  71071. return [x, y];
  71072. }
  71073. function isCenterAlign(align) {
  71074. return align === 'center' || align === 'middle';
  71075. }
  71076. /**
  71077. * Find target component by payload like:
  71078. * ```js
  71079. * { legendId: 'some_id', name: 'xxx' }
  71080. * { toolboxIndex: 1, name: 'xxx' }
  71081. * { geoName: 'some_name', name: 'xxx' }
  71082. * ```
  71083. * PENDING: at present only
  71084. *
  71085. * If not found, return null/undefined.
  71086. */
  71087. function findComponentReference(payload, ecModel, api) {
  71088. var queryOptionMap = preParseFinder(payload).queryOptionMap;
  71089. var componentMainType = queryOptionMap.keys()[0];
  71090. if (!componentMainType || componentMainType === 'series') {
  71091. return;
  71092. }
  71093. var queryResult = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), {
  71094. useDefault: false,
  71095. enableAll: false,
  71096. enableNone: false
  71097. });
  71098. var model = queryResult.models[0];
  71099. if (!model) {
  71100. return;
  71101. }
  71102. var view = api.getViewOfComponentModel(model);
  71103. var el;
  71104. view.group.traverse(function (subEl) {
  71105. var tooltipConfig = getECData(subEl).tooltipConfig;
  71106. if (tooltipConfig && tooltipConfig.name === payload.name) {
  71107. el = subEl;
  71108. return true; // stop
  71109. }
  71110. });
  71111. if (el) {
  71112. return {
  71113. componentMainType: componentMainType,
  71114. componentIndex: model.componentIndex,
  71115. el: el
  71116. };
  71117. }
  71118. }
  71119. function install$A(registers) {
  71120. use(install$s);
  71121. registers.registerComponentModel(TooltipModel);
  71122. registers.registerComponentView(TooltipView);
  71123. /**
  71124. * @action
  71125. * @property {string} type
  71126. * @property {number} seriesIndex
  71127. * @property {number} dataIndex
  71128. * @property {number} [x]
  71129. * @property {number} [y]
  71130. */
  71131. registers.registerAction({
  71132. type: 'showTip',
  71133. event: 'showTip',
  71134. update: 'tooltip:manuallyShowTip'
  71135. }, // noop
  71136. function () {});
  71137. registers.registerAction({
  71138. type: 'hideTip',
  71139. event: 'hideTip',
  71140. update: 'tooltip:manuallyHideTip'
  71141. }, // noop
  71142. function () {});
  71143. }
  71144. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  71145. function brushPreprocessor(option, isNew) {
  71146. var brushComponents = normalizeToArray(option ? option.brush : []);
  71147. if (!brushComponents.length) {
  71148. return;
  71149. }
  71150. var brushComponentSpecifiedBtns = [];
  71151. each(brushComponents, function (brushOpt) {
  71152. var tbs = brushOpt.hasOwnProperty('toolbox') ? brushOpt.toolbox : [];
  71153. if (tbs instanceof Array) {
  71154. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  71155. }
  71156. });
  71157. var toolbox = option && option.toolbox;
  71158. if (isArray(toolbox)) {
  71159. toolbox = toolbox[0];
  71160. }
  71161. if (!toolbox) {
  71162. toolbox = {
  71163. feature: {}
  71164. };
  71165. option.toolbox = [toolbox];
  71166. }
  71167. var toolboxFeature = toolbox.feature || (toolbox.feature = {});
  71168. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  71169. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  71170. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  71171. removeDuplicate(brushTypes);
  71172. if (isNew && !brushTypes.length) {
  71173. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  71174. }
  71175. }
  71176. function removeDuplicate(arr) {
  71177. var map = {};
  71178. each(arr, function (val) {
  71179. map[val] = 1;
  71180. });
  71181. arr.length = 0;
  71182. each(map, function (flag, val) {
  71183. arr.push(val);
  71184. });
  71185. }
  71186. var each$c = each;
  71187. function hasKeys(obj) {
  71188. if (obj) {
  71189. for (var name_1 in obj) {
  71190. if (obj.hasOwnProperty(name_1)) {
  71191. return true;
  71192. }
  71193. }
  71194. }
  71195. }
  71196. function createVisualMappings(option, stateList, supplementVisualOption) {
  71197. var visualMappings = {};
  71198. each$c(stateList, function (state) {
  71199. var mappings = visualMappings[state] = createMappings();
  71200. each$c(option[state], function (visualData, visualType) {
  71201. if (!VisualMapping.isValidType(visualType)) {
  71202. return;
  71203. }
  71204. var mappingOption = {
  71205. type: visualType,
  71206. visual: visualData
  71207. };
  71208. supplementVisualOption && supplementVisualOption(mappingOption, state);
  71209. mappings[visualType] = new VisualMapping(mappingOption); // Prepare a alpha for opacity, for some case that opacity
  71210. // is not supported, such as rendering using gradient color.
  71211. if (visualType === 'opacity') {
  71212. mappingOption = clone(mappingOption);
  71213. mappingOption.type = 'colorAlpha';
  71214. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  71215. }
  71216. });
  71217. });
  71218. return visualMappings;
  71219. function createMappings() {
  71220. var Creater = function () {}; // Make sure hidden fields will not be visited by
  71221. // object iteration (with hasOwnProperty checking).
  71222. Creater.prototype.__hidden = Creater.prototype;
  71223. var obj = new Creater();
  71224. return obj;
  71225. }
  71226. }
  71227. function replaceVisualOption(thisOption, newOption, keys) {
  71228. // Visual attributes merge is not supported, otherwise it
  71229. // brings overcomplicated merge logic. See #2853. So if
  71230. // newOption has anyone of these keys, all of these keys
  71231. // will be reset. Otherwise, all keys remain.
  71232. var has;
  71233. each(keys, function (key) {
  71234. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  71235. has = true;
  71236. }
  71237. });
  71238. has && each(keys, function (key) {
  71239. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  71240. thisOption[key] = clone(newOption[key]);
  71241. } else {
  71242. delete thisOption[key];
  71243. }
  71244. });
  71245. }
  71246. /**
  71247. * @param stateList
  71248. * @param visualMappings
  71249. * @param list
  71250. * @param getValueState param: valueOrIndex, return: state.
  71251. * @param scope Scope for getValueState
  71252. * @param dimension Concrete dimension, if used.
  71253. */
  71254. // ???! handle brush?
  71255. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  71256. var visualTypesMap = {};
  71257. each(stateList, function (state) {
  71258. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  71259. visualTypesMap[state] = visualTypes;
  71260. });
  71261. var dataIndex;
  71262. function getVisual(key) {
  71263. return getItemVisualFromData(data, dataIndex, key);
  71264. }
  71265. function setVisual(key, value) {
  71266. setItemVisualFromData(data, dataIndex, key, value);
  71267. }
  71268. if (dimension == null) {
  71269. data.each(eachItem);
  71270. } else {
  71271. data.each([dimension], eachItem);
  71272. }
  71273. function eachItem(valueOrIndex, index) {
  71274. dataIndex = dimension == null ? valueOrIndex // First argument is index
  71275. : index;
  71276. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  71277. // @ts-ignore
  71278. if (rawDataItem && rawDataItem.visualMap === false) {
  71279. return;
  71280. }
  71281. var valueState = getValueState.call(scope, valueOrIndex);
  71282. var mappings = visualMappings[valueState];
  71283. var visualTypes = visualTypesMap[valueState];
  71284. for (var i = 0, len = visualTypes.length; i < len; i++) {
  71285. var type = visualTypes[i];
  71286. mappings[type] && mappings[type].applyVisual(valueOrIndex, getVisual, setVisual);
  71287. }
  71288. }
  71289. }
  71290. /**
  71291. * @param data
  71292. * @param stateList
  71293. * @param visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  71294. * @param getValueState param: valueOrIndex, return: state.
  71295. * @param dim dimension or dimension index.
  71296. */
  71297. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  71298. var visualTypesMap = {};
  71299. each(stateList, function (state) {
  71300. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  71301. visualTypesMap[state] = visualTypes;
  71302. });
  71303. return {
  71304. progress: function progress(params, data) {
  71305. var dimIndex;
  71306. if (dim != null) {
  71307. dimIndex = data.getDimensionIndex(dim);
  71308. }
  71309. function getVisual(key) {
  71310. return getItemVisualFromData(data, dataIndex, key);
  71311. }
  71312. function setVisual(key, value) {
  71313. setItemVisualFromData(data, dataIndex, key, value);
  71314. }
  71315. var dataIndex;
  71316. var store = data.getStore();
  71317. while ((dataIndex = params.next()) != null) {
  71318. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  71319. // @ts-ignore
  71320. if (rawDataItem && rawDataItem.visualMap === false) {
  71321. continue;
  71322. }
  71323. var value = dim != null ? store.get(dimIndex, dataIndex) : dataIndex;
  71324. var valueState = getValueState(value);
  71325. var mappings = visualMappings[valueState];
  71326. var visualTypes = visualTypesMap[valueState];
  71327. for (var i = 0, len = visualTypes.length; i < len; i++) {
  71328. var type = visualTypes[i];
  71329. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  71330. }
  71331. }
  71332. }
  71333. };
  71334. }
  71335. function makeBrushCommonSelectorForSeries(area) {
  71336. var brushType = area.brushType; // Do not use function binding or curry for performance.
  71337. var selectors = {
  71338. point: function (itemLayout) {
  71339. return selector[brushType].point(itemLayout, selectors, area);
  71340. },
  71341. rect: function (itemLayout) {
  71342. return selector[brushType].rect(itemLayout, selectors, area);
  71343. }
  71344. };
  71345. return selectors;
  71346. }
  71347. var selector = {
  71348. lineX: getLineSelectors(0),
  71349. lineY: getLineSelectors(1),
  71350. rect: {
  71351. point: function (itemLayout, selectors, area) {
  71352. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  71353. },
  71354. rect: function (itemLayout, selectors, area) {
  71355. return itemLayout && area.boundingRect.intersect(itemLayout);
  71356. }
  71357. },
  71358. polygon: {
  71359. point: function (itemLayout, selectors, area) {
  71360. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]) && contain$1(area.range, itemLayout[0], itemLayout[1]);
  71361. },
  71362. rect: function (itemLayout, selectors, area) {
  71363. var points = area.range;
  71364. if (!itemLayout || points.length <= 1) {
  71365. return false;
  71366. }
  71367. var x = itemLayout.x;
  71368. var y = itemLayout.y;
  71369. var width = itemLayout.width;
  71370. var height = itemLayout.height;
  71371. var p = points[0];
  71372. if (contain$1(points, x, y) || contain$1(points, x + width, y) || contain$1(points, x, y + height) || contain$1(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)) {
  71373. return true;
  71374. }
  71375. }
  71376. }
  71377. };
  71378. function getLineSelectors(xyIndex) {
  71379. var xy = ['x', 'y'];
  71380. var wh = ['width', 'height'];
  71381. return {
  71382. point: function (itemLayout, selectors, area) {
  71383. if (itemLayout) {
  71384. var range = area.range;
  71385. var p = itemLayout[xyIndex];
  71386. return inLineRange(p, range);
  71387. }
  71388. },
  71389. rect: function (itemLayout, selectors, area) {
  71390. if (itemLayout) {
  71391. var range = area.range;
  71392. var layoutRange = [itemLayout[xy[xyIndex]], itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]];
  71393. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  71394. return inLineRange(layoutRange[0], range) || inLineRange(layoutRange[1], range) || inLineRange(range[0], layoutRange) || inLineRange(range[1], layoutRange);
  71395. }
  71396. }
  71397. };
  71398. }
  71399. function inLineRange(p, range) {
  71400. return range[0] <= p && p <= range[1];
  71401. }
  71402. var STATE_LIST = ['inBrush', 'outOfBrush'];
  71403. var DISPATCH_METHOD = '__ecBrushSelect';
  71404. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  71405. function layoutCovers(ecModel) {
  71406. ecModel.eachComponent({
  71407. mainType: 'brush'
  71408. }, function (brushModel) {
  71409. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  71410. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  71411. });
  71412. }
  71413. /**
  71414. * Register the visual encoding if this modules required.
  71415. */
  71416. function brushVisual(ecModel, api, payload) {
  71417. var brushSelected = [];
  71418. var throttleType;
  71419. var throttleDelay;
  71420. ecModel.eachComponent({
  71421. mainType: 'brush'
  71422. }, function (brushModel) {
  71423. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(payload.key === 'brush' ? payload.brushOption : {
  71424. brushType: false
  71425. });
  71426. });
  71427. layoutCovers(ecModel);
  71428. ecModel.eachComponent({
  71429. mainType: 'brush'
  71430. }, function (brushModel, brushIndex) {
  71431. var thisBrushSelected = {
  71432. brushId: brushModel.id,
  71433. brushIndex: brushIndex,
  71434. brushName: brushModel.name,
  71435. areas: clone(brushModel.areas),
  71436. selected: []
  71437. }; // Every brush component exists in event params, convenient
  71438. // for user to find by index.
  71439. brushSelected.push(thisBrushSelected);
  71440. var brushOption = brushModel.option;
  71441. var brushLink = brushOption.brushLink;
  71442. var linkedSeriesMap = [];
  71443. var selectedDataIndexForLink = [];
  71444. var rangeInfoBySeries = [];
  71445. var hasBrushExists = false;
  71446. if (!brushIndex) {
  71447. // Only the first throttle setting works.
  71448. throttleType = brushOption.throttleType;
  71449. throttleDelay = brushOption.throttleDelay;
  71450. } // Add boundingRect and selectors to range.
  71451. var areas = map(brushModel.areas, function (area) {
  71452. var builder = boundingRectBuilders[area.brushType];
  71453. var selectableArea = defaults({
  71454. boundingRect: builder ? builder(area) : void 0
  71455. }, area);
  71456. selectableArea.selectors = makeBrushCommonSelectorForSeries(selectableArea);
  71457. return selectableArea;
  71458. });
  71459. var visualMappings = createVisualMappings(brushModel.option, STATE_LIST, function (mappingOption) {
  71460. mappingOption.mappingMethod = 'fixed';
  71461. });
  71462. isArray(brushLink) && each(brushLink, function (seriesIndex) {
  71463. linkedSeriesMap[seriesIndex] = 1;
  71464. });
  71465. function linkOthers(seriesIndex) {
  71466. return brushLink === 'all' || !!linkedSeriesMap[seriesIndex];
  71467. } // If no supported brush or no brush on the series,
  71468. // all visuals should be in original state.
  71469. function brushed(rangeInfoList) {
  71470. return !!rangeInfoList.length;
  71471. }
  71472. /**
  71473. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  71474. *
  71475. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  71476. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  71477. * └!hasBrushExist┘ └nothing.
  71478. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  71479. * └!hasBrushExist┘ └nothing.
  71480. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  71481. * !brushed┘ └nothing.
  71482. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  71483. */
  71484. // Step A
  71485. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  71486. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  71487. seriesModel.subType === 'parallel' ? stepAParallel(seriesModel, seriesIndex) : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  71488. });
  71489. function stepAParallel(seriesModel, seriesIndex) {
  71490. var coordSys = seriesModel.coordinateSystem;
  71491. hasBrushExists = hasBrushExists || coordSys.hasAxisBrushed();
  71492. linkOthers(seriesIndex) && coordSys.eachActiveState(seriesModel.getData(), function (activeState, dataIndex) {
  71493. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  71494. });
  71495. }
  71496. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  71497. if (!seriesModel.brushSelector || brushModelNotControll(brushModel, seriesIndex)) {
  71498. return;
  71499. }
  71500. each(areas, function (area) {
  71501. if (brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)) {
  71502. rangeInfoList.push(area);
  71503. }
  71504. hasBrushExists = hasBrushExists || brushed(rangeInfoList);
  71505. });
  71506. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  71507. var data_1 = seriesModel.getData();
  71508. data_1.each(function (dataIndex) {
  71509. if (checkInRange(seriesModel, rangeInfoList, data_1, dataIndex)) {
  71510. selectedDataIndexForLink[dataIndex] = 1;
  71511. }
  71512. });
  71513. }
  71514. } // Step B
  71515. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  71516. var seriesBrushSelected = {
  71517. seriesId: seriesModel.id,
  71518. seriesIndex: seriesIndex,
  71519. seriesName: seriesModel.name,
  71520. dataIndex: []
  71521. }; // Every series exists in event params, convenient
  71522. // for user to find series by seriesIndex.
  71523. thisBrushSelected.selected.push(seriesBrushSelected);
  71524. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  71525. var data = seriesModel.getData();
  71526. var getValueState = linkOthers(seriesIndex) ? function (dataIndex) {
  71527. return selectedDataIndexForLink[dataIndex] ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  71528. } : function (dataIndex) {
  71529. return checkInRange(seriesModel, rangeInfoList, data, dataIndex) ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  71530. }; // If no supported brush or no brush, all visuals are in original state.
  71531. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList)) && applyVisual(STATE_LIST, visualMappings, data, getValueState);
  71532. });
  71533. });
  71534. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  71535. }
  71536. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  71537. // This event will not be triggered when `setOpion`, otherwise dead lock may
  71538. // triggered when do `setOption` in event listener, which we do not find
  71539. // satisfactory way to solve yet. Some considered resolutions:
  71540. // (a) Diff with prevoius selected data ant only trigger event when changed.
  71541. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  71542. // also detect value changes in selected data) might bring complexity or fragility.
  71543. // (b) Use spectial param like `silent` to suppress event triggering.
  71544. // But such kind of volatile param may be weird in `setOption`.
  71545. if (!payload) {
  71546. return;
  71547. }
  71548. var zr = api.getZr();
  71549. if (zr[DISPATCH_FLAG]) {
  71550. return;
  71551. }
  71552. if (!zr[DISPATCH_METHOD]) {
  71553. zr[DISPATCH_METHOD] = doDispatch;
  71554. }
  71555. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  71556. fn(api, brushSelected);
  71557. }
  71558. function doDispatch(api, brushSelected) {
  71559. if (!api.isDisposed()) {
  71560. var zr = api.getZr();
  71561. zr[DISPATCH_FLAG] = true;
  71562. api.dispatchAction({
  71563. type: 'brushSelect',
  71564. batch: brushSelected
  71565. });
  71566. zr[DISPATCH_FLAG] = false;
  71567. }
  71568. }
  71569. function checkInRange(seriesModel, rangeInfoList, data, dataIndex) {
  71570. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  71571. var area = rangeInfoList[i];
  71572. if (seriesModel.brushSelector(dataIndex, data, area.selectors, area)) {
  71573. return true;
  71574. }
  71575. }
  71576. }
  71577. function brushModelNotControll(brushModel, seriesIndex) {
  71578. var seriesIndices = brushModel.option.seriesIndex;
  71579. return seriesIndices != null && seriesIndices !== 'all' && (isArray(seriesIndices) ? indexOf(seriesIndices, seriesIndex) < 0 : seriesIndex !== seriesIndices);
  71580. }
  71581. var boundingRectBuilders = {
  71582. rect: function (area) {
  71583. return getBoundingRectFromMinMax(area.range);
  71584. },
  71585. polygon: function (area) {
  71586. var minMax;
  71587. var range = area.range;
  71588. for (var i = 0, len = range.length; i < len; i++) {
  71589. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  71590. var rg = range[i];
  71591. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  71592. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  71593. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  71594. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  71595. }
  71596. return minMax && getBoundingRectFromMinMax(minMax);
  71597. }
  71598. };
  71599. function getBoundingRectFromMinMax(minMax) {
  71600. return new BoundingRect(minMax[0][0], minMax[1][0], minMax[0][1] - minMax[0][0], minMax[1][1] - minMax[1][0]);
  71601. }
  71602. var BrushView =
  71603. /** @class */
  71604. function (_super) {
  71605. __extends(BrushView, _super);
  71606. function BrushView() {
  71607. var _this = _super !== null && _super.apply(this, arguments) || this;
  71608. _this.type = BrushView.type;
  71609. return _this;
  71610. }
  71611. BrushView.prototype.init = function (ecModel, api) {
  71612. this.ecModel = ecModel;
  71613. this.api = api;
  71614. this.model;
  71615. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this)).mount();
  71616. };
  71617. BrushView.prototype.render = function (brushModel, ecModel, api, payload) {
  71618. this.model = brushModel;
  71619. this._updateController(brushModel, ecModel, api, payload);
  71620. };
  71621. BrushView.prototype.updateTransform = function (brushModel, ecModel, api, payload) {
  71622. // PENDING: `updateTransform` is a little tricky, whose layout need
  71623. // to be calculate mandatorily and other stages will not be performed.
  71624. // Take care the correctness of the logic. See #11754 .
  71625. layoutCovers(ecModel);
  71626. this._updateController(brushModel, ecModel, api, payload);
  71627. };
  71628. BrushView.prototype.updateVisual = function (brushModel, ecModel, api, payload) {
  71629. this.updateTransform(brushModel, ecModel, api, payload);
  71630. };
  71631. BrushView.prototype.updateView = function (brushModel, ecModel, api, payload) {
  71632. this._updateController(brushModel, ecModel, api, payload);
  71633. };
  71634. BrushView.prototype._updateController = function (brushModel, ecModel, api, payload) {
  71635. // Do not update controller when drawing.
  71636. (!payload || payload.$from !== brushModel.id) && this._brushController.setPanels(brushModel.brushTargetManager.makePanelOpts(api)).enableBrush(brushModel.brushOption).updateCovers(brushModel.areas.slice());
  71637. }; // updateLayout: updateController,
  71638. // updateVisual: updateController,
  71639. BrushView.prototype.dispose = function () {
  71640. this._brushController.dispose();
  71641. };
  71642. BrushView.prototype._onBrush = function (eventParam) {
  71643. var modelId = this.model.id;
  71644. var areas = this.model.brushTargetManager.setOutputRanges(eventParam.areas, this.ecModel); // Action is not dispatched on drag end, because the drag end
  71645. // emits the same params with the last drag move event, and
  71646. // may have some delay when using touch pad, which makes
  71647. // animation not smooth (when using debounce).
  71648. (!eventParam.isEnd || eventParam.removeOnClick) && this.api.dispatchAction({
  71649. type: 'brush',
  71650. brushId: modelId,
  71651. areas: clone(areas),
  71652. $from: modelId
  71653. });
  71654. eventParam.isEnd && this.api.dispatchAction({
  71655. type: 'brushEnd',
  71656. brushId: modelId,
  71657. areas: clone(areas),
  71658. $from: modelId
  71659. });
  71660. };
  71661. BrushView.type = 'brush';
  71662. return BrushView;
  71663. }(ComponentView);
  71664. var DEFAULT_OUT_OF_BRUSH_COLOR = '#ddd';
  71665. var BrushModel =
  71666. /** @class */
  71667. function (_super) {
  71668. __extends(BrushModel, _super);
  71669. function BrushModel() {
  71670. var _this = _super !== null && _super.apply(this, arguments) || this;
  71671. _this.type = BrushModel.type;
  71672. /**
  71673. * @readOnly
  71674. */
  71675. _this.areas = [];
  71676. /**
  71677. * Current brush painting area settings.
  71678. * @readOnly
  71679. */
  71680. _this.brushOption = {};
  71681. return _this;
  71682. }
  71683. BrushModel.prototype.optionUpdated = function (newOption, isInit) {
  71684. var thisOption = this.option;
  71685. !isInit && replaceVisualOption(thisOption, newOption, ['inBrush', 'outOfBrush']);
  71686. var inBrush = thisOption.inBrush = thisOption.inBrush || {}; // Always give default visual, consider setOption at the second time.
  71687. thisOption.outOfBrush = thisOption.outOfBrush || {
  71688. color: DEFAULT_OUT_OF_BRUSH_COLOR
  71689. };
  71690. if (!inBrush.hasOwnProperty('liftZ')) {
  71691. // Bigger than the highlight z lift, otherwise it will
  71692. // be effected by the highlight z when brush.
  71693. inBrush.liftZ = 5;
  71694. }
  71695. };
  71696. /**
  71697. * If `areas` is null/undefined, range state remain.
  71698. */
  71699. BrushModel.prototype.setAreas = function (areas) {
  71700. if ("development" !== 'production') {
  71701. assert(isArray(areas));
  71702. each(areas, function (area) {
  71703. assert(area.brushType, 'Illegal areas');
  71704. });
  71705. } // If areas is null/undefined, range state remain.
  71706. // This helps user to dispatchAction({type: 'brush'}) with no areas
  71707. // set but just want to get the current brush select info from a `brush` event.
  71708. if (!areas) {
  71709. return;
  71710. }
  71711. this.areas = map(areas, function (area) {
  71712. return generateBrushOption(this.option, area);
  71713. }, this);
  71714. };
  71715. /**
  71716. * Set the current painting brush option.
  71717. */
  71718. BrushModel.prototype.setBrushOption = function (brushOption) {
  71719. this.brushOption = generateBrushOption(this.option, brushOption);
  71720. this.brushType = this.brushOption.brushType;
  71721. };
  71722. BrushModel.type = 'brush';
  71723. BrushModel.dependencies = ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'];
  71724. BrushModel.defaultOption = {
  71725. seriesIndex: 'all',
  71726. brushType: 'rect',
  71727. brushMode: 'single',
  71728. transformable: true,
  71729. brushStyle: {
  71730. borderWidth: 1,
  71731. color: 'rgba(210,219,238,0.3)',
  71732. borderColor: '#D2DBEE'
  71733. },
  71734. throttleType: 'fixRate',
  71735. throttleDelay: 0,
  71736. removeOnClick: true,
  71737. z: 10000
  71738. };
  71739. return BrushModel;
  71740. }(ComponentModel);
  71741. function generateBrushOption(option, brushOption) {
  71742. return merge({
  71743. brushType: option.brushType,
  71744. brushMode: option.brushMode,
  71745. transformable: option.transformable,
  71746. brushStyle: new Model(option.brushStyle).getItemStyle(),
  71747. removeOnClick: option.removeOnClick,
  71748. z: option.z
  71749. }, brushOption, true);
  71750. }
  71751. var ICON_TYPES = ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'];
  71752. var BrushFeature =
  71753. /** @class */
  71754. function (_super) {
  71755. __extends(BrushFeature, _super);
  71756. function BrushFeature() {
  71757. return _super !== null && _super.apply(this, arguments) || this;
  71758. }
  71759. BrushFeature.prototype.render = function (featureModel, ecModel, api) {
  71760. var brushType;
  71761. var brushMode;
  71762. var isBrushed;
  71763. ecModel.eachComponent({
  71764. mainType: 'brush'
  71765. }, function (brushModel) {
  71766. brushType = brushModel.brushType;
  71767. brushMode = brushModel.brushOption.brushMode || 'single';
  71768. isBrushed = isBrushed || !!brushModel.areas.length;
  71769. });
  71770. this._brushType = brushType;
  71771. this._brushMode = brushMode;
  71772. each(featureModel.get('type', true), function (type) {
  71773. featureModel.setIconStatus(type, (type === 'keep' ? brushMode === 'multiple' : type === 'clear' ? isBrushed : type === brushType) ? 'emphasis' : 'normal');
  71774. });
  71775. };
  71776. BrushFeature.prototype.updateView = function (featureModel, ecModel, api) {
  71777. this.render(featureModel, ecModel, api);
  71778. };
  71779. BrushFeature.prototype.getIcons = function () {
  71780. var model = this.model;
  71781. var availableIcons = model.get('icon', true);
  71782. var icons = {};
  71783. each(model.get('type', true), function (type) {
  71784. if (availableIcons[type]) {
  71785. icons[type] = availableIcons[type];
  71786. }
  71787. });
  71788. return icons;
  71789. };
  71790. BrushFeature.prototype.onclick = function (ecModel, api, type) {
  71791. var brushType = this._brushType;
  71792. var brushMode = this._brushMode;
  71793. if (type === 'clear') {
  71794. // Trigger parallel action firstly
  71795. api.dispatchAction({
  71796. type: 'axisAreaSelect',
  71797. intervals: []
  71798. });
  71799. api.dispatchAction({
  71800. type: 'brush',
  71801. command: 'clear',
  71802. // Clear all areas of all brush components.
  71803. areas: []
  71804. });
  71805. } else {
  71806. api.dispatchAction({
  71807. type: 'takeGlobalCursor',
  71808. key: 'brush',
  71809. brushOption: {
  71810. brushType: type === 'keep' ? brushType : brushType === type ? false : type,
  71811. brushMode: type === 'keep' ? brushMode === 'multiple' ? 'single' : 'multiple' : brushMode
  71812. }
  71813. });
  71814. }
  71815. };
  71816. BrushFeature.getDefaultOption = function (ecModel) {
  71817. var defaultOption = {
  71818. show: true,
  71819. type: ICON_TYPES.slice(),
  71820. icon: {
  71821. /* eslint-disable */
  71822. 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',
  71823. 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',
  71824. 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',
  71825. 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',
  71826. 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',
  71827. 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
  71828. /* eslint-enable */
  71829. },
  71830. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  71831. title: ecModel.getLocaleModel().get(['toolbox', 'brush', 'title'])
  71832. };
  71833. return defaultOption;
  71834. };
  71835. return BrushFeature;
  71836. }(ToolboxFeature);
  71837. function install$B(registers) {
  71838. registers.registerComponentView(BrushView);
  71839. registers.registerComponentModel(BrushModel);
  71840. registers.registerPreprocessor(brushPreprocessor);
  71841. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, brushVisual);
  71842. registers.registerAction({
  71843. type: 'brush',
  71844. event: 'brush',
  71845. update: 'updateVisual'
  71846. }, function (payload, ecModel) {
  71847. ecModel.eachComponent({
  71848. mainType: 'brush',
  71849. query: payload
  71850. }, function (brushModel) {
  71851. brushModel.setAreas(payload.areas);
  71852. });
  71853. });
  71854. /**
  71855. * payload: {
  71856. * brushComponents: [
  71857. * {
  71858. * brushId,
  71859. * brushIndex,
  71860. * brushName,
  71861. * series: [
  71862. * {
  71863. * seriesId,
  71864. * seriesIndex,
  71865. * seriesName,
  71866. * rawIndices: [21, 34, ...]
  71867. * },
  71868. * ...
  71869. * ]
  71870. * },
  71871. * ...
  71872. * ]
  71873. * }
  71874. */
  71875. registers.registerAction({
  71876. type: 'brushSelect',
  71877. event: 'brushSelected',
  71878. update: 'none'
  71879. }, function () {});
  71880. registers.registerAction({
  71881. type: 'brushEnd',
  71882. event: 'brushEnd',
  71883. update: 'none'
  71884. }, function () {});
  71885. registerFeature('brush', BrushFeature);
  71886. }
  71887. var TitleModel =
  71888. /** @class */
  71889. function (_super) {
  71890. __extends(TitleModel, _super);
  71891. function TitleModel() {
  71892. var _this = _super !== null && _super.apply(this, arguments) || this;
  71893. _this.type = TitleModel.type;
  71894. _this.layoutMode = {
  71895. type: 'box',
  71896. ignoreSize: true
  71897. };
  71898. return _this;
  71899. }
  71900. TitleModel.type = 'title';
  71901. TitleModel.defaultOption = {
  71902. zlevel: 0,
  71903. z: 6,
  71904. show: true,
  71905. text: '',
  71906. target: 'blank',
  71907. subtext: '',
  71908. subtarget: 'blank',
  71909. left: 0,
  71910. top: 0,
  71911. backgroundColor: 'rgba(0,0,0,0)',
  71912. borderColor: '#ccc',
  71913. borderWidth: 0,
  71914. padding: 5,
  71915. itemGap: 10,
  71916. textStyle: {
  71917. fontSize: 18,
  71918. fontWeight: 'bold',
  71919. color: '#464646'
  71920. },
  71921. subtextStyle: {
  71922. fontSize: 12,
  71923. color: '#6E7079'
  71924. }
  71925. };
  71926. return TitleModel;
  71927. }(ComponentModel); // View
  71928. var TitleView =
  71929. /** @class */
  71930. function (_super) {
  71931. __extends(TitleView, _super);
  71932. function TitleView() {
  71933. var _this = _super !== null && _super.apply(this, arguments) || this;
  71934. _this.type = TitleView.type;
  71935. return _this;
  71936. }
  71937. TitleView.prototype.render = function (titleModel, ecModel, api) {
  71938. this.group.removeAll();
  71939. if (!titleModel.get('show')) {
  71940. return;
  71941. }
  71942. var group = this.group;
  71943. var textStyleModel = titleModel.getModel('textStyle');
  71944. var subtextStyleModel = titleModel.getModel('subtextStyle');
  71945. var textAlign = titleModel.get('textAlign');
  71946. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  71947. var textEl = new ZRText({
  71948. style: createTextStyle(textStyleModel, {
  71949. text: titleModel.get('text'),
  71950. fill: textStyleModel.getTextColor()
  71951. }, {
  71952. disableBox: true
  71953. }),
  71954. z2: 10
  71955. });
  71956. var textRect = textEl.getBoundingRect();
  71957. var subText = titleModel.get('subtext');
  71958. var subTextEl = new ZRText({
  71959. style: createTextStyle(subtextStyleModel, {
  71960. text: subText,
  71961. fill: subtextStyleModel.getTextColor(),
  71962. y: textRect.height + titleModel.get('itemGap'),
  71963. verticalAlign: 'top'
  71964. }, {
  71965. disableBox: true
  71966. }),
  71967. z2: 10
  71968. });
  71969. var link = titleModel.get('link');
  71970. var sublink = titleModel.get('sublink');
  71971. var triggerEvent = titleModel.get('triggerEvent', true);
  71972. textEl.silent = !link && !triggerEvent;
  71973. subTextEl.silent = !sublink && !triggerEvent;
  71974. if (link) {
  71975. textEl.on('click', function () {
  71976. windowOpen(link, '_' + titleModel.get('target'));
  71977. });
  71978. }
  71979. if (sublink) {
  71980. subTextEl.on('click', function () {
  71981. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  71982. });
  71983. }
  71984. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  71985. componentType: 'title',
  71986. componentIndex: titleModel.componentIndex
  71987. } : null;
  71988. group.add(textEl);
  71989. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  71990. var groupRect = group.getBoundingRect();
  71991. var layoutOption = titleModel.getBoxLayoutParams();
  71992. layoutOption.width = groupRect.width;
  71993. layoutOption.height = groupRect.height;
  71994. var layoutRect = getLayoutRect(layoutOption, {
  71995. width: api.getWidth(),
  71996. height: api.getHeight()
  71997. }, titleModel.get('padding')); // Adjust text align based on position
  71998. if (!textAlign) {
  71999. // Align left if title is on the left. center and right is same
  72000. textAlign = titleModel.get('left') || titleModel.get('right'); // @ts-ignore
  72001. if (textAlign === 'middle') {
  72002. textAlign = 'center';
  72003. } // Adjust layout by text align
  72004. if (textAlign === 'right') {
  72005. layoutRect.x += layoutRect.width;
  72006. } else if (textAlign === 'center') {
  72007. layoutRect.x += layoutRect.width / 2;
  72008. }
  72009. }
  72010. if (!textVerticalAlign) {
  72011. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom'); // @ts-ignore
  72012. if (textVerticalAlign === 'center') {
  72013. textVerticalAlign = 'middle';
  72014. }
  72015. if (textVerticalAlign === 'bottom') {
  72016. layoutRect.y += layoutRect.height;
  72017. } else if (textVerticalAlign === 'middle') {
  72018. layoutRect.y += layoutRect.height / 2;
  72019. }
  72020. textVerticalAlign = textVerticalAlign || 'top';
  72021. }
  72022. group.x = layoutRect.x;
  72023. group.y = layoutRect.y;
  72024. group.markRedraw();
  72025. var alignStyle = {
  72026. align: textAlign,
  72027. verticalAlign: textVerticalAlign
  72028. };
  72029. textEl.setStyle(alignStyle);
  72030. subTextEl.setStyle(alignStyle); // Render background
  72031. // Get groupRect again because textAlign has been changed
  72032. groupRect = group.getBoundingRect();
  72033. var padding = layoutRect.margin;
  72034. var style = titleModel.getItemStyle(['color', 'opacity']);
  72035. style.fill = titleModel.get('backgroundColor');
  72036. var rect = new Rect({
  72037. shape: {
  72038. x: groupRect.x - padding[3],
  72039. y: groupRect.y - padding[0],
  72040. width: groupRect.width + padding[1] + padding[3],
  72041. height: groupRect.height + padding[0] + padding[2],
  72042. r: titleModel.get('borderRadius')
  72043. },
  72044. style: style,
  72045. subPixelOptimize: true,
  72046. silent: true
  72047. });
  72048. group.add(rect);
  72049. };
  72050. TitleView.type = 'title';
  72051. return TitleView;
  72052. }(ComponentView);
  72053. function install$C(registers) {
  72054. registers.registerComponentModel(TitleModel);
  72055. registers.registerComponentView(TitleView);
  72056. }
  72057. var TimelineModel =
  72058. /** @class */
  72059. function (_super) {
  72060. __extends(TimelineModel, _super);
  72061. function TimelineModel() {
  72062. var _this = _super !== null && _super.apply(this, arguments) || this;
  72063. _this.type = TimelineModel.type;
  72064. _this.layoutMode = 'box';
  72065. return _this;
  72066. }
  72067. /**
  72068. * @override
  72069. */
  72070. TimelineModel.prototype.init = function (option, parentModel, ecModel) {
  72071. this.mergeDefaultAndTheme(option, ecModel);
  72072. this._initData();
  72073. };
  72074. /**
  72075. * @override
  72076. */
  72077. TimelineModel.prototype.mergeOption = function (option) {
  72078. _super.prototype.mergeOption.apply(this, arguments);
  72079. this._initData();
  72080. };
  72081. TimelineModel.prototype.setCurrentIndex = function (currentIndex) {
  72082. if (currentIndex == null) {
  72083. currentIndex = this.option.currentIndex;
  72084. }
  72085. var count = this._data.count();
  72086. if (this.option.loop) {
  72087. currentIndex = (currentIndex % count + count) % count;
  72088. } else {
  72089. currentIndex >= count && (currentIndex = count - 1);
  72090. currentIndex < 0 && (currentIndex = 0);
  72091. }
  72092. this.option.currentIndex = currentIndex;
  72093. };
  72094. /**
  72095. * @return {number} currentIndex
  72096. */
  72097. TimelineModel.prototype.getCurrentIndex = function () {
  72098. return this.option.currentIndex;
  72099. };
  72100. /**
  72101. * @return {boolean}
  72102. */
  72103. TimelineModel.prototype.isIndexMax = function () {
  72104. return this.getCurrentIndex() >= this._data.count() - 1;
  72105. };
  72106. /**
  72107. * @param {boolean} state true: play, false: stop
  72108. */
  72109. TimelineModel.prototype.setPlayState = function (state) {
  72110. this.option.autoPlay = !!state;
  72111. };
  72112. /**
  72113. * @return {boolean} true: play, false: stop
  72114. */
  72115. TimelineModel.prototype.getPlayState = function () {
  72116. return !!this.option.autoPlay;
  72117. };
  72118. /**
  72119. * @private
  72120. */
  72121. TimelineModel.prototype._initData = function () {
  72122. var thisOption = this.option;
  72123. var dataArr = thisOption.data || [];
  72124. var axisType = thisOption.axisType;
  72125. var names = this._names = [];
  72126. var processedDataArr;
  72127. if (axisType === 'category') {
  72128. processedDataArr = [];
  72129. each(dataArr, function (item, index) {
  72130. var value = convertOptionIdName(getDataItemValue(item), '');
  72131. var newItem;
  72132. if (isObject(item)) {
  72133. newItem = clone(item);
  72134. newItem.value = index;
  72135. } else {
  72136. newItem = index;
  72137. }
  72138. processedDataArr.push(newItem);
  72139. names.push(value);
  72140. });
  72141. } else {
  72142. processedDataArr = dataArr;
  72143. }
  72144. var dimType = {
  72145. category: 'ordinal',
  72146. time: 'time',
  72147. value: 'number'
  72148. }[axisType] || 'number';
  72149. var data = this._data = new SeriesData([{
  72150. name: 'value',
  72151. type: dimType
  72152. }], this);
  72153. data.initData(processedDataArr, names);
  72154. };
  72155. TimelineModel.prototype.getData = function () {
  72156. return this._data;
  72157. };
  72158. /**
  72159. * @public
  72160. * @return {Array.<string>} categoreis
  72161. */
  72162. TimelineModel.prototype.getCategories = function () {
  72163. if (this.get('axisType') === 'category') {
  72164. return this._names.slice();
  72165. }
  72166. };
  72167. TimelineModel.type = 'timeline';
  72168. /**
  72169. * @protected
  72170. */
  72171. TimelineModel.defaultOption = {
  72172. zlevel: 0,
  72173. z: 4,
  72174. show: true,
  72175. axisType: 'time',
  72176. realtime: true,
  72177. left: '20%',
  72178. top: null,
  72179. right: '20%',
  72180. bottom: 0,
  72181. width: null,
  72182. height: 40,
  72183. padding: 5,
  72184. controlPosition: 'left',
  72185. autoPlay: false,
  72186. rewind: false,
  72187. loop: true,
  72188. playInterval: 2000,
  72189. currentIndex: 0,
  72190. itemStyle: {},
  72191. label: {
  72192. color: '#000'
  72193. },
  72194. data: []
  72195. };
  72196. return TimelineModel;
  72197. }(ComponentModel);
  72198. var SliderTimelineModel =
  72199. /** @class */
  72200. function (_super) {
  72201. __extends(SliderTimelineModel, _super);
  72202. function SliderTimelineModel() {
  72203. var _this = _super !== null && _super.apply(this, arguments) || this;
  72204. _this.type = SliderTimelineModel.type;
  72205. return _this;
  72206. }
  72207. SliderTimelineModel.type = 'timeline.slider';
  72208. /**
  72209. * @protected
  72210. */
  72211. SliderTimelineModel.defaultOption = inheritDefaultOption(TimelineModel.defaultOption, {
  72212. backgroundColor: 'rgba(0,0,0,0)',
  72213. borderColor: '#ccc',
  72214. borderWidth: 0,
  72215. orient: 'horizontal',
  72216. inverse: false,
  72217. tooltip: {
  72218. trigger: 'item' // data item may also have tootip attr.
  72219. },
  72220. symbol: 'circle',
  72221. symbolSize: 12,
  72222. lineStyle: {
  72223. show: true,
  72224. width: 2,
  72225. color: '#DAE1F5'
  72226. },
  72227. label: {
  72228. position: 'auto',
  72229. // When using number, label position is not
  72230. // restricted by viewRect.
  72231. // positive: right/bottom, negative: left/top
  72232. show: true,
  72233. interval: 'auto',
  72234. rotate: 0,
  72235. // formatter: null,
  72236. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  72237. color: '#A4B1D7'
  72238. },
  72239. itemStyle: {
  72240. color: '#A4B1D7',
  72241. borderWidth: 1
  72242. },
  72243. checkpointStyle: {
  72244. symbol: 'circle',
  72245. symbolSize: 15,
  72246. color: '#316bf3',
  72247. borderColor: '#fff',
  72248. borderWidth: 2,
  72249. shadowBlur: 2,
  72250. shadowOffsetX: 1,
  72251. shadowOffsetY: 1,
  72252. shadowColor: 'rgba(0, 0, 0, 0.3)',
  72253. // borderColor: 'rgba(194,53,49, 0.5)',
  72254. animation: true,
  72255. animationDuration: 300,
  72256. animationEasing: 'quinticInOut'
  72257. },
  72258. controlStyle: {
  72259. show: true,
  72260. showPlayBtn: true,
  72261. showPrevBtn: true,
  72262. showNextBtn: true,
  72263. itemSize: 24,
  72264. itemGap: 12,
  72265. position: 'left',
  72266. 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',
  72267. 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',
  72268. // eslint-disable-next-line max-len
  72269. 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',
  72270. // eslint-disable-next-line max-len
  72271. 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',
  72272. prevBtnSize: 18,
  72273. nextBtnSize: 18,
  72274. color: '#A4B1D7',
  72275. borderColor: '#A4B1D7',
  72276. borderWidth: 1
  72277. },
  72278. emphasis: {
  72279. label: {
  72280. show: true,
  72281. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  72282. color: '#6f778d'
  72283. },
  72284. itemStyle: {
  72285. color: '#316BF3'
  72286. },
  72287. controlStyle: {
  72288. color: '#316BF3',
  72289. borderColor: '#316BF3',
  72290. borderWidth: 2
  72291. }
  72292. },
  72293. progress: {
  72294. lineStyle: {
  72295. color: '#316BF3'
  72296. },
  72297. itemStyle: {
  72298. color: '#316BF3'
  72299. },
  72300. label: {
  72301. color: '#6f778d'
  72302. }
  72303. },
  72304. data: []
  72305. });
  72306. return SliderTimelineModel;
  72307. }(TimelineModel);
  72308. mixin(SliderTimelineModel, DataFormatMixin.prototype);
  72309. var TimelineView =
  72310. /** @class */
  72311. function (_super) {
  72312. __extends(TimelineView, _super);
  72313. function TimelineView() {
  72314. var _this = _super !== null && _super.apply(this, arguments) || this;
  72315. _this.type = TimelineView.type;
  72316. return _this;
  72317. }
  72318. TimelineView.type = 'timeline';
  72319. return TimelineView;
  72320. }(ComponentView);
  72321. /**
  72322. * Extend axis 2d
  72323. */
  72324. var TimelineAxis =
  72325. /** @class */
  72326. function (_super) {
  72327. __extends(TimelineAxis, _super);
  72328. function TimelineAxis(dim, scale, coordExtent, axisType) {
  72329. var _this = _super.call(this, dim, scale, coordExtent) || this;
  72330. _this.type = axisType || 'value';
  72331. return _this;
  72332. }
  72333. /**
  72334. * @override
  72335. */
  72336. TimelineAxis.prototype.getLabelModel = function () {
  72337. // Force override
  72338. return this.model.getModel('label');
  72339. };
  72340. /**
  72341. * @override
  72342. */
  72343. TimelineAxis.prototype.isHorizontal = function () {
  72344. return this.model.get('orient') === 'horizontal';
  72345. };
  72346. return TimelineAxis;
  72347. }(Axis);
  72348. var PI$8 = Math.PI;
  72349. var labelDataIndexStore = makeInner();
  72350. var SliderTimelineView =
  72351. /** @class */
  72352. function (_super) {
  72353. __extends(SliderTimelineView, _super);
  72354. function SliderTimelineView() {
  72355. var _this = _super !== null && _super.apply(this, arguments) || this;
  72356. _this.type = SliderTimelineView.type;
  72357. return _this;
  72358. }
  72359. SliderTimelineView.prototype.init = function (ecModel, api) {
  72360. this.api = api;
  72361. };
  72362. /**
  72363. * @override
  72364. */
  72365. SliderTimelineView.prototype.render = function (timelineModel, ecModel, api) {
  72366. this.model = timelineModel;
  72367. this.api = api;
  72368. this.ecModel = ecModel;
  72369. this.group.removeAll();
  72370. if (timelineModel.get('show', true)) {
  72371. var layoutInfo_1 = this._layout(timelineModel, api);
  72372. var mainGroup_1 = this._createGroup('_mainGroup');
  72373. var labelGroup = this._createGroup('_labelGroup');
  72374. var axis_1 = this._axis = this._createAxis(layoutInfo_1, timelineModel);
  72375. timelineModel.formatTooltip = function (dataIndex) {
  72376. var name = axis_1.scale.getLabel({
  72377. value: dataIndex
  72378. });
  72379. return createTooltipMarkup('nameValue', {
  72380. noName: true,
  72381. value: name
  72382. });
  72383. };
  72384. each(['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'], function (name) {
  72385. this['_render' + name](layoutInfo_1, mainGroup_1, axis_1, timelineModel);
  72386. }, this);
  72387. this._renderAxisLabel(layoutInfo_1, labelGroup, axis_1, timelineModel);
  72388. this._position(layoutInfo_1, timelineModel);
  72389. }
  72390. this._doPlayStop();
  72391. this._updateTicksStatus();
  72392. };
  72393. /**
  72394. * @override
  72395. */
  72396. SliderTimelineView.prototype.remove = function () {
  72397. this._clearTimer();
  72398. this.group.removeAll();
  72399. };
  72400. /**
  72401. * @override
  72402. */
  72403. SliderTimelineView.prototype.dispose = function () {
  72404. this._clearTimer();
  72405. };
  72406. SliderTimelineView.prototype._layout = function (timelineModel, api) {
  72407. var labelPosOpt = timelineModel.get(['label', 'position']);
  72408. var orient = timelineModel.get('orient');
  72409. var viewRect = getViewRect$5(timelineModel, api);
  72410. var parsedLabelPos; // Auto label offset.
  72411. if (labelPosOpt == null || labelPosOpt === 'auto') {
  72412. parsedLabelPos = orient === 'horizontal' ? viewRect.y + viewRect.height / 2 < api.getHeight() / 2 ? '-' : '+' : viewRect.x + viewRect.width / 2 < api.getWidth() / 2 ? '+' : '-';
  72413. } else if (isString(labelPosOpt)) {
  72414. parsedLabelPos = {
  72415. horizontal: {
  72416. top: '-',
  72417. bottom: '+'
  72418. },
  72419. vertical: {
  72420. left: '-',
  72421. right: '+'
  72422. }
  72423. }[orient][labelPosOpt];
  72424. } else {
  72425. // is number
  72426. parsedLabelPos = labelPosOpt;
  72427. }
  72428. var labelAlignMap = {
  72429. horizontal: 'center',
  72430. vertical: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'left' : 'right'
  72431. };
  72432. var labelBaselineMap = {
  72433. horizontal: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'top' : 'bottom',
  72434. vertical: 'middle'
  72435. };
  72436. var rotationMap = {
  72437. horizontal: 0,
  72438. vertical: PI$8 / 2
  72439. }; // Position
  72440. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  72441. var controlModel = timelineModel.getModel('controlStyle');
  72442. var showControl = controlModel.get('show', true);
  72443. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  72444. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  72445. var sizePlusGap = controlSize + controlGap; // Special label rotate.
  72446. var labelRotation = timelineModel.get(['label', 'rotate']) || 0;
  72447. labelRotation = labelRotation * PI$8 / 180; // To radian.
  72448. var playPosition;
  72449. var prevBtnPosition;
  72450. var nextBtnPosition;
  72451. var controlPosition = controlModel.get('position', true);
  72452. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  72453. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  72454. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  72455. var xLeft = 0;
  72456. var xRight = mainLength; // position[0] means left, position[1] means middle.
  72457. if (controlPosition === 'left' || controlPosition === 'bottom') {
  72458. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  72459. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  72460. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  72461. } else {
  72462. // 'top' 'right'
  72463. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  72464. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  72465. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  72466. }
  72467. var axisExtent = [xLeft, xRight];
  72468. if (timelineModel.get('inverse')) {
  72469. axisExtent.reverse();
  72470. }
  72471. return {
  72472. viewRect: viewRect,
  72473. mainLength: mainLength,
  72474. orient: orient,
  72475. rotation: rotationMap[orient],
  72476. labelRotation: labelRotation,
  72477. labelPosOpt: parsedLabelPos,
  72478. labelAlign: timelineModel.get(['label', 'align']) || labelAlignMap[orient],
  72479. labelBaseline: timelineModel.get(['label', 'verticalAlign']) || timelineModel.get(['label', 'baseline']) || labelBaselineMap[orient],
  72480. // Based on mainGroup.
  72481. playPosition: playPosition,
  72482. prevBtnPosition: prevBtnPosition,
  72483. nextBtnPosition: nextBtnPosition,
  72484. axisExtent: axisExtent,
  72485. controlSize: controlSize,
  72486. controlGap: controlGap
  72487. };
  72488. };
  72489. SliderTimelineView.prototype._position = function (layoutInfo, timelineModel) {
  72490. // Position is be called finally, because bounding rect is needed for
  72491. // adapt content to fill viewRect (auto adapt offset).
  72492. // Timeline may be not all in the viewRect when 'offset' is specified
  72493. // as a number, because it is more appropriate that label aligns at
  72494. // 'offset' but not the other edge defined by viewRect.
  72495. var mainGroup = this._mainGroup;
  72496. var labelGroup = this._labelGroup;
  72497. var viewRect = layoutInfo.viewRect;
  72498. if (layoutInfo.orient === 'vertical') {
  72499. // transform to horizontal, inverse rotate by left-top point.
  72500. var m = create$1();
  72501. var rotateOriginX = viewRect.x;
  72502. var rotateOriginY = viewRect.y + viewRect.height;
  72503. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  72504. rotate(m, m, -PI$8 / 2);
  72505. translate(m, m, [rotateOriginX, rotateOriginY]);
  72506. viewRect = viewRect.clone();
  72507. viewRect.applyTransform(m);
  72508. }
  72509. var viewBound = getBound(viewRect);
  72510. var mainBound = getBound(mainGroup.getBoundingRect());
  72511. var labelBound = getBound(labelGroup.getBoundingRect());
  72512. var mainPosition = [mainGroup.x, mainGroup.y];
  72513. var labelsPosition = [labelGroup.x, labelGroup.y];
  72514. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  72515. var labelPosOpt = layoutInfo.labelPosOpt;
  72516. if (labelPosOpt == null || isString(labelPosOpt)) {
  72517. // '+' or '-'
  72518. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  72519. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  72520. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  72521. } else {
  72522. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  72523. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  72524. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  72525. }
  72526. mainGroup.setPosition(mainPosition);
  72527. labelGroup.setPosition(labelsPosition);
  72528. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  72529. setOrigin(mainGroup);
  72530. setOrigin(labelGroup);
  72531. function setOrigin(targetGroup) {
  72532. targetGroup.originX = viewBound[0][0] - targetGroup.x;
  72533. targetGroup.originY = viewBound[1][0] - targetGroup.y;
  72534. }
  72535. function getBound(rect) {
  72536. // [[xmin, xmax], [ymin, ymax]]
  72537. return [[rect.x, rect.x + rect.width], [rect.y, rect.y + rect.height]];
  72538. }
  72539. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  72540. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  72541. }
  72542. };
  72543. SliderTimelineView.prototype._createAxis = function (layoutInfo, timelineModel) {
  72544. var data = timelineModel.getData();
  72545. var axisType = timelineModel.get('axisType');
  72546. var scale = createScaleByModel$1(timelineModel, axisType); // Customize scale. The `tickValue` is `dataIndex`.
  72547. scale.getTicks = function () {
  72548. return data.mapArray(['value'], function (value) {
  72549. return {
  72550. value: value
  72551. };
  72552. });
  72553. };
  72554. var dataExtent = data.getDataExtent('value');
  72555. scale.setExtent(dataExtent[0], dataExtent[1]);
  72556. scale.niceTicks();
  72557. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  72558. axis.model = timelineModel;
  72559. return axis;
  72560. };
  72561. SliderTimelineView.prototype._createGroup = function (key) {
  72562. var newGroup = this[key] = new Group();
  72563. this.group.add(newGroup);
  72564. return newGroup;
  72565. };
  72566. SliderTimelineView.prototype._renderAxisLine = function (layoutInfo, group, axis, timelineModel) {
  72567. var axisExtent = axis.getExtent();
  72568. if (!timelineModel.get(['lineStyle', 'show'])) {
  72569. return;
  72570. }
  72571. var line = new Line({
  72572. shape: {
  72573. x1: axisExtent[0],
  72574. y1: 0,
  72575. x2: axisExtent[1],
  72576. y2: 0
  72577. },
  72578. style: extend({
  72579. lineCap: 'round'
  72580. }, timelineModel.getModel('lineStyle').getLineStyle()),
  72581. silent: true,
  72582. z2: 1
  72583. });
  72584. group.add(line);
  72585. var progressLine = this._progressLine = new Line({
  72586. shape: {
  72587. x1: axisExtent[0],
  72588. x2: this._currentPointer ? this._currentPointer.x : axisExtent[0],
  72589. y1: 0,
  72590. y2: 0
  72591. },
  72592. style: defaults({
  72593. lineCap: 'round',
  72594. lineWidth: line.style.lineWidth
  72595. }, timelineModel.getModel(['progress', 'lineStyle']).getLineStyle()),
  72596. silent: true,
  72597. z2: 1
  72598. });
  72599. group.add(progressLine);
  72600. };
  72601. SliderTimelineView.prototype._renderAxisTick = function (layoutInfo, group, axis, timelineModel) {
  72602. var _this = this;
  72603. var data = timelineModel.getData(); // Show all ticks, despite ignoring strategy.
  72604. var ticks = axis.scale.getTicks();
  72605. this._tickSymbols = []; // The value is dataIndex, see the costomized scale.
  72606. each(ticks, function (tick) {
  72607. var tickCoord = axis.dataToCoord(tick.value);
  72608. var itemModel = data.getItemModel(tick.value);
  72609. var itemStyleModel = itemModel.getModel('itemStyle');
  72610. var hoverStyleModel = itemModel.getModel(['emphasis', 'itemStyle']);
  72611. var progressStyleModel = itemModel.getModel(['progress', 'itemStyle']);
  72612. var symbolOpt = {
  72613. x: tickCoord,
  72614. y: 0,
  72615. onclick: bind(_this._changeTimeline, _this, tick.value)
  72616. };
  72617. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  72618. el.ensureState('emphasis').style = hoverStyleModel.getItemStyle();
  72619. el.ensureState('progress').style = progressStyleModel.getItemStyle();
  72620. enableHoverEmphasis(el);
  72621. var ecData = getECData(el);
  72622. if (itemModel.get('tooltip')) {
  72623. ecData.dataIndex = tick.value;
  72624. ecData.dataModel = timelineModel;
  72625. } else {
  72626. ecData.dataIndex = ecData.dataModel = null;
  72627. }
  72628. _this._tickSymbols.push(el);
  72629. });
  72630. };
  72631. SliderTimelineView.prototype._renderAxisLabel = function (layoutInfo, group, axis, timelineModel) {
  72632. var _this = this;
  72633. var labelModel = axis.getLabelModel();
  72634. if (!labelModel.get('show')) {
  72635. return;
  72636. }
  72637. var data = timelineModel.getData();
  72638. var labels = axis.getViewLabels();
  72639. this._tickLabels = [];
  72640. each(labels, function (labelItem) {
  72641. // The tickValue is dataIndex, see the costomized scale.
  72642. var dataIndex = labelItem.tickValue;
  72643. var itemModel = data.getItemModel(dataIndex);
  72644. var normalLabelModel = itemModel.getModel('label');
  72645. var hoverLabelModel = itemModel.getModel(['emphasis', 'label']);
  72646. var progressLabelModel = itemModel.getModel(['progress', 'label']);
  72647. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  72648. var textEl = new ZRText({
  72649. x: tickCoord,
  72650. y: 0,
  72651. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  72652. onclick: bind(_this._changeTimeline, _this, dataIndex),
  72653. silent: false,
  72654. style: createTextStyle(normalLabelModel, {
  72655. text: labelItem.formattedLabel,
  72656. align: layoutInfo.labelAlign,
  72657. verticalAlign: layoutInfo.labelBaseline
  72658. })
  72659. });
  72660. textEl.ensureState('emphasis').style = createTextStyle(hoverLabelModel);
  72661. textEl.ensureState('progress').style = createTextStyle(progressLabelModel);
  72662. group.add(textEl);
  72663. enableHoverEmphasis(textEl);
  72664. labelDataIndexStore(textEl).dataIndex = dataIndex;
  72665. _this._tickLabels.push(textEl);
  72666. });
  72667. };
  72668. SliderTimelineView.prototype._renderControl = function (layoutInfo, group, axis, timelineModel) {
  72669. var controlSize = layoutInfo.controlSize;
  72670. var rotation = layoutInfo.rotation;
  72671. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  72672. var hoverStyle = timelineModel.getModel(['emphasis', 'controlStyle']).getItemStyle();
  72673. var playState = timelineModel.getPlayState();
  72674. var inverse = timelineModel.get('inverse', true);
  72675. makeBtn(layoutInfo.nextBtnPosition, 'next', bind(this._changeTimeline, this, inverse ? '-' : '+'));
  72676. makeBtn(layoutInfo.prevBtnPosition, 'prev', bind(this._changeTimeline, this, inverse ? '+' : '-'));
  72677. makeBtn(layoutInfo.playPosition, playState ? 'stop' : 'play', bind(this._handlePlayClick, this, !playState), true);
  72678. function makeBtn(position, iconName, onclick, willRotate) {
  72679. if (!position) {
  72680. return;
  72681. }
  72682. var iconSize = parsePercent(retrieve2(timelineModel.get(['controlStyle', iconName + 'BtnSize']), controlSize), controlSize);
  72683. var rect = [0, -iconSize / 2, iconSize, iconSize];
  72684. var btn = makeControlIcon(timelineModel, iconName + 'Icon', rect, {
  72685. x: position[0],
  72686. y: position[1],
  72687. originX: controlSize / 2,
  72688. originY: 0,
  72689. rotation: willRotate ? -rotation : 0,
  72690. rectHover: true,
  72691. style: itemStyle,
  72692. onclick: onclick
  72693. });
  72694. btn.ensureState('emphasis').style = hoverStyle;
  72695. group.add(btn);
  72696. enableHoverEmphasis(btn);
  72697. }
  72698. };
  72699. SliderTimelineView.prototype._renderCurrentPointer = function (layoutInfo, group, axis, timelineModel) {
  72700. var data = timelineModel.getData();
  72701. var currentIndex = timelineModel.getCurrentIndex();
  72702. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  72703. var me = this;
  72704. var callback = {
  72705. onCreate: function (pointer) {
  72706. pointer.draggable = true;
  72707. pointer.drift = bind(me._handlePointerDrag, me);
  72708. pointer.ondragend = bind(me._handlePointerDragend, me);
  72709. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel, true);
  72710. },
  72711. onUpdate: function (pointer) {
  72712. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel);
  72713. }
  72714. }; // Reuse when exists, for animation and drag.
  72715. this._currentPointer = giveSymbol(pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback);
  72716. };
  72717. SliderTimelineView.prototype._handlePlayClick = function (nextState) {
  72718. this._clearTimer();
  72719. this.api.dispatchAction({
  72720. type: 'timelinePlayChange',
  72721. playState: nextState,
  72722. from: this.uid
  72723. });
  72724. };
  72725. SliderTimelineView.prototype._handlePointerDrag = function (dx, dy, e) {
  72726. this._clearTimer();
  72727. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  72728. };
  72729. SliderTimelineView.prototype._handlePointerDragend = function (e) {
  72730. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  72731. };
  72732. SliderTimelineView.prototype._pointerChangeTimeline = function (mousePos, trigger) {
  72733. var toCoord = this._toAxisCoord(mousePos)[0];
  72734. var axis = this._axis;
  72735. var axisExtent = asc(axis.getExtent().slice());
  72736. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  72737. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  72738. this._currentPointer.x = toCoord;
  72739. this._currentPointer.markRedraw();
  72740. this._progressLine.shape.x2 = toCoord;
  72741. this._progressLine.dirty();
  72742. var targetDataIndex = this._findNearestTick(toCoord);
  72743. var timelineModel = this.model;
  72744. if (trigger || targetDataIndex !== timelineModel.getCurrentIndex() && timelineModel.get('realtime')) {
  72745. this._changeTimeline(targetDataIndex);
  72746. }
  72747. };
  72748. SliderTimelineView.prototype._doPlayStop = function () {
  72749. var _this = this;
  72750. this._clearTimer();
  72751. if (this.model.getPlayState()) {
  72752. this._timer = setTimeout(function () {
  72753. // Do not cache
  72754. var timelineModel = _this.model;
  72755. _this._changeTimeline(timelineModel.getCurrentIndex() + (timelineModel.get('rewind', true) ? -1 : 1));
  72756. }, this.model.get('playInterval'));
  72757. }
  72758. };
  72759. SliderTimelineView.prototype._toAxisCoord = function (vertex) {
  72760. var trans = this._mainGroup.getLocalTransform();
  72761. return applyTransform$1(vertex, trans, true);
  72762. };
  72763. SliderTimelineView.prototype._findNearestTick = function (axisCoord) {
  72764. var data = this.model.getData();
  72765. var dist = Infinity;
  72766. var targetDataIndex;
  72767. var axis = this._axis;
  72768. data.each(['value'], function (value, dataIndex) {
  72769. var coord = axis.dataToCoord(value);
  72770. var d = Math.abs(coord - axisCoord);
  72771. if (d < dist) {
  72772. dist = d;
  72773. targetDataIndex = dataIndex;
  72774. }
  72775. });
  72776. return targetDataIndex;
  72777. };
  72778. SliderTimelineView.prototype._clearTimer = function () {
  72779. if (this._timer) {
  72780. clearTimeout(this._timer);
  72781. this._timer = null;
  72782. }
  72783. };
  72784. SliderTimelineView.prototype._changeTimeline = function (nextIndex) {
  72785. var currentIndex = this.model.getCurrentIndex();
  72786. if (nextIndex === '+') {
  72787. nextIndex = currentIndex + 1;
  72788. } else if (nextIndex === '-') {
  72789. nextIndex = currentIndex - 1;
  72790. }
  72791. this.api.dispatchAction({
  72792. type: 'timelineChange',
  72793. currentIndex: nextIndex,
  72794. from: this.uid
  72795. });
  72796. };
  72797. SliderTimelineView.prototype._updateTicksStatus = function () {
  72798. var currentIndex = this.model.getCurrentIndex();
  72799. var tickSymbols = this._tickSymbols;
  72800. var tickLabels = this._tickLabels;
  72801. if (tickSymbols) {
  72802. for (var i = 0; i < tickSymbols.length; i++) {
  72803. tickSymbols && tickSymbols[i] && tickSymbols[i].toggleState('progress', i < currentIndex);
  72804. }
  72805. }
  72806. if (tickLabels) {
  72807. for (var i = 0; i < tickLabels.length; i++) {
  72808. tickLabels && tickLabels[i] && tickLabels[i].toggleState('progress', labelDataIndexStore(tickLabels[i]).dataIndex <= currentIndex);
  72809. }
  72810. }
  72811. };
  72812. SliderTimelineView.type = 'timeline.slider';
  72813. return SliderTimelineView;
  72814. }(TimelineView);
  72815. function createScaleByModel$1(model, axisType) {
  72816. axisType = axisType || model.get('type');
  72817. if (axisType) {
  72818. switch (axisType) {
  72819. // Buildin scale
  72820. case 'category':
  72821. return new OrdinalScale({
  72822. ordinalMeta: model.getCategories(),
  72823. extent: [Infinity, -Infinity]
  72824. });
  72825. case 'time':
  72826. return new TimeScale({
  72827. locale: model.ecModel.getLocaleModel(),
  72828. useUTC: model.ecModel.get('useUTC')
  72829. });
  72830. default:
  72831. // default to be value
  72832. return new IntervalScale();
  72833. }
  72834. }
  72835. }
  72836. function getViewRect$5(model, api) {
  72837. return getLayoutRect(model.getBoxLayoutParams(), {
  72838. width: api.getWidth(),
  72839. height: api.getHeight()
  72840. }, model.get('padding'));
  72841. }
  72842. function makeControlIcon(timelineModel, objPath, rect, opts) {
  72843. var style = opts.style;
  72844. 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.
  72845. if (style) {
  72846. icon.setStyle(style);
  72847. }
  72848. return icon;
  72849. }
  72850. /**
  72851. * Create symbol or update symbol
  72852. * opt: basic position and event handlers
  72853. */
  72854. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  72855. var color = itemStyleModel.get('color');
  72856. if (!symbol) {
  72857. var symbolType = hostModel.get('symbol');
  72858. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  72859. symbol.setStyle('strokeNoScale', true);
  72860. group.add(symbol);
  72861. callback && callback.onCreate(symbol);
  72862. } else {
  72863. symbol.setColor(color);
  72864. group.add(symbol); // Group may be new, also need to add.
  72865. callback && callback.onUpdate(symbol);
  72866. } // Style
  72867. var itemStyle = itemStyleModel.getItemStyle(['color']);
  72868. symbol.setStyle(itemStyle); // Transform and events.
  72869. opt = merge({
  72870. rectHover: true,
  72871. z2: 100
  72872. }, opt, true);
  72873. var symbolSize = normalizeSymbolSize(hostModel.get('symbolSize'));
  72874. opt.scaleX = symbolSize[0] / 2;
  72875. opt.scaleY = symbolSize[1] / 2;
  72876. var symbolOffset = normalizeSymbolOffset(hostModel.get('symbolOffset'), symbolSize);
  72877. if (symbolOffset) {
  72878. opt.x = (opt.x || 0) + symbolOffset[0];
  72879. opt.y = (opt.y || 0) + symbolOffset[1];
  72880. }
  72881. var symbolRotate = hostModel.get('symbolRotate');
  72882. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  72883. symbol.attr(opt); // FIXME
  72884. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  72885. // getBoundingRect will return wrong result.
  72886. // (This is supposed to be resolved in zrender, but it is a little difficult to
  72887. // leverage performance and auto updateTransform)
  72888. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  72889. symbol.updateTransform();
  72890. return symbol;
  72891. }
  72892. function pointerMoveTo(pointer, progressLine, dataIndex, axis, timelineModel, noAnimation) {
  72893. if (pointer.dragging) {
  72894. return;
  72895. }
  72896. var pointerModel = timelineModel.getModel('checkpointStyle');
  72897. var toCoord = axis.dataToCoord(timelineModel.getData().get('value', dataIndex));
  72898. if (noAnimation || !pointerModel.get('animation', true)) {
  72899. pointer.attr({
  72900. x: toCoord,
  72901. y: 0
  72902. });
  72903. progressLine && progressLine.attr({
  72904. shape: {
  72905. x2: toCoord
  72906. }
  72907. });
  72908. } else {
  72909. var animationCfg = {
  72910. duration: pointerModel.get('animationDuration', true),
  72911. easing: pointerModel.get('animationEasing', true)
  72912. };
  72913. pointer.stopAnimation(null, true);
  72914. pointer.animateTo({
  72915. x: toCoord,
  72916. y: 0
  72917. }, animationCfg);
  72918. progressLine && progressLine.animateTo({
  72919. shape: {
  72920. x2: toCoord
  72921. }
  72922. }, animationCfg);
  72923. }
  72924. }
  72925. function installTimelineAction(registers) {
  72926. registers.registerAction({
  72927. type: 'timelineChange',
  72928. event: 'timelineChanged',
  72929. update: 'prepareAndUpdate'
  72930. }, function (payload, ecModel, api) {
  72931. var timelineModel = ecModel.getComponent('timeline');
  72932. if (timelineModel && payload.currentIndex != null) {
  72933. timelineModel.setCurrentIndex(payload.currentIndex);
  72934. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax() && timelineModel.getPlayState()) {
  72935. timelineModel.setPlayState(false); // The timeline has played to the end, trigger event
  72936. api.dispatchAction({
  72937. type: 'timelinePlayChange',
  72938. playState: false,
  72939. from: payload.from
  72940. });
  72941. }
  72942. } // Set normalized currentIndex to payload.
  72943. ecModel.resetOption('timeline', {
  72944. replaceMerge: timelineModel.get('replaceMerge', true)
  72945. });
  72946. return defaults({
  72947. currentIndex: timelineModel.option.currentIndex
  72948. }, payload);
  72949. });
  72950. registers.registerAction({
  72951. type: 'timelinePlayChange',
  72952. event: 'timelinePlayChanged',
  72953. update: 'update'
  72954. }, function (payload, ecModel) {
  72955. var timelineModel = ecModel.getComponent('timeline');
  72956. if (timelineModel && payload.playState != null) {
  72957. timelineModel.setPlayState(payload.playState);
  72958. }
  72959. });
  72960. }
  72961. function timelinePreprocessor(option) {
  72962. var timelineOpt = option && option.timeline;
  72963. if (!isArray(timelineOpt)) {
  72964. timelineOpt = timelineOpt ? [timelineOpt] : [];
  72965. }
  72966. each(timelineOpt, function (opt) {
  72967. if (!opt) {
  72968. return;
  72969. }
  72970. compatibleEC2(opt);
  72971. });
  72972. }
  72973. function compatibleEC2(opt) {
  72974. var type = opt.type;
  72975. var ec2Types = {
  72976. 'number': 'value',
  72977. 'time': 'time'
  72978. }; // Compatible with ec2
  72979. if (ec2Types[type]) {
  72980. opt.axisType = ec2Types[type];
  72981. delete opt.type;
  72982. }
  72983. transferItem(opt);
  72984. if (has(opt, 'controlPosition')) {
  72985. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  72986. if (!has(controlStyle, 'position')) {
  72987. controlStyle.position = opt.controlPosition;
  72988. }
  72989. if (controlStyle.position === 'none' && !has(controlStyle, 'show')) {
  72990. controlStyle.show = false;
  72991. delete controlStyle.position;
  72992. }
  72993. delete opt.controlPosition;
  72994. }
  72995. each(opt.data || [], function (dataItem) {
  72996. if (isObject(dataItem) && !isArray(dataItem)) {
  72997. if (!has(dataItem, 'value') && has(dataItem, 'name')) {
  72998. // In ec2, using name as value.
  72999. dataItem.value = dataItem.name;
  73000. }
  73001. transferItem(dataItem);
  73002. }
  73003. });
  73004. }
  73005. function transferItem(opt) {
  73006. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  73007. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {}); // Transfer label out
  73008. var label = opt.label || opt.label || {};
  73009. var labelNormal = label.normal || (label.normal = {});
  73010. var excludeLabelAttr = {
  73011. normal: 1,
  73012. emphasis: 1
  73013. };
  73014. each(label, function (value, name) {
  73015. if (!excludeLabelAttr[name] && !has(labelNormal, name)) {
  73016. labelNormal[name] = value;
  73017. }
  73018. });
  73019. if (itemStyleEmphasis.label && !has(label, 'emphasis')) {
  73020. label.emphasis = itemStyleEmphasis.label;
  73021. delete itemStyleEmphasis.label;
  73022. }
  73023. }
  73024. function has(obj, attr) {
  73025. return obj.hasOwnProperty(attr);
  73026. }
  73027. function install$D(registers) {
  73028. registers.registerComponentModel(SliderTimelineModel);
  73029. registers.registerComponentView(SliderTimelineView);
  73030. registers.registerSubTypeDefaulter('timeline', function () {
  73031. // Only slider now.
  73032. return 'slider';
  73033. });
  73034. installTimelineAction(registers);
  73035. registers.registerPreprocessor(timelinePreprocessor);
  73036. }
  73037. function checkMarkerInSeries(seriesOpts, markerType) {
  73038. if (!seriesOpts) {
  73039. return false;
  73040. }
  73041. var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [seriesOpts];
  73042. for (var idx = 0; idx < seriesOptArr.length; idx++) {
  73043. if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) {
  73044. return true;
  73045. }
  73046. }
  73047. return false;
  73048. }
  73049. function fillLabel(opt) {
  73050. defaultEmphasis(opt, 'label', ['show']);
  73051. } // { [componentType]: MarkerModel }
  73052. var inner$g = makeInner();
  73053. var MarkerModel =
  73054. /** @class */
  73055. function (_super) {
  73056. __extends(MarkerModel, _super);
  73057. function MarkerModel() {
  73058. var _this = _super !== null && _super.apply(this, arguments) || this;
  73059. _this.type = MarkerModel.type;
  73060. /**
  73061. * If marker model is created by self from series
  73062. */
  73063. _this.createdBySelf = false;
  73064. return _this;
  73065. }
  73066. /**
  73067. * @overrite
  73068. */
  73069. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  73070. if ("development" !== 'production') {
  73071. if (this.type === 'marker') {
  73072. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  73073. }
  73074. }
  73075. this.mergeDefaultAndTheme(option, ecModel);
  73076. this._mergeOption(option, ecModel, false, true);
  73077. };
  73078. MarkerModel.prototype.isAnimationEnabled = function () {
  73079. if (env.node) {
  73080. return false;
  73081. }
  73082. var hostSeries = this.__hostSeries;
  73083. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  73084. };
  73085. /**
  73086. * @overrite
  73087. */
  73088. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  73089. this._mergeOption(newOpt, ecModel, false, false);
  73090. };
  73091. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  73092. var componentType = this.mainType;
  73093. if (!createdBySelf) {
  73094. ecModel.eachSeries(function (seriesModel) {
  73095. // mainType can be markPoint, markLine, markArea
  73096. var markerOpt = seriesModel.get(this.mainType, true);
  73097. var markerModel = inner$g(seriesModel)[componentType];
  73098. if (!markerOpt || !markerOpt.data) {
  73099. inner$g(seriesModel)[componentType] = null;
  73100. return;
  73101. }
  73102. if (!markerModel) {
  73103. if (isInit) {
  73104. // Default label emphasis `position` and `show`
  73105. fillLabel(markerOpt);
  73106. }
  73107. each(markerOpt.data, function (item) {
  73108. // FIXME Overwrite fillLabel method ?
  73109. if (item instanceof Array) {
  73110. fillLabel(item[0]);
  73111. fillLabel(item[1]);
  73112. } else {
  73113. fillLabel(item);
  73114. }
  73115. });
  73116. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel); // markerModel = new ImplementedMarkerModel(
  73117. // markerOpt, this, ecModel
  73118. // );
  73119. extend(markerModel, {
  73120. mainType: this.mainType,
  73121. // Use the same series index and name
  73122. seriesIndex: seriesModel.seriesIndex,
  73123. name: seriesModel.name,
  73124. createdBySelf: true
  73125. });
  73126. markerModel.__hostSeries = seriesModel;
  73127. } else {
  73128. markerModel._mergeOption(markerOpt, ecModel, true);
  73129. }
  73130. inner$g(seriesModel)[componentType] = markerModel;
  73131. }, this);
  73132. }
  73133. };
  73134. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  73135. var data = this.getData();
  73136. var value = this.getRawValue(dataIndex);
  73137. var itemName = data.getName(dataIndex);
  73138. return createTooltipMarkup('section', {
  73139. header: this.name,
  73140. blocks: [createTooltipMarkup('nameValue', {
  73141. name: itemName,
  73142. value: value,
  73143. noName: !itemName,
  73144. noValue: value == null
  73145. })]
  73146. });
  73147. };
  73148. MarkerModel.prototype.getData = function () {
  73149. return this._data;
  73150. };
  73151. MarkerModel.prototype.setData = function (data) {
  73152. this._data = data;
  73153. };
  73154. MarkerModel.getMarkerModelFromSeries = function (seriesModel, // Support three types of markers. Strict check.
  73155. componentType) {
  73156. return inner$g(seriesModel)[componentType];
  73157. };
  73158. MarkerModel.type = 'marker';
  73159. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  73160. return MarkerModel;
  73161. }(ComponentModel);
  73162. mixin(MarkerModel, DataFormatMixin.prototype);
  73163. var MarkPointModel =
  73164. /** @class */
  73165. function (_super) {
  73166. __extends(MarkPointModel, _super);
  73167. function MarkPointModel() {
  73168. var _this = _super !== null && _super.apply(this, arguments) || this;
  73169. _this.type = MarkPointModel.type;
  73170. return _this;
  73171. }
  73172. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  73173. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  73174. };
  73175. MarkPointModel.type = 'markPoint';
  73176. MarkPointModel.defaultOption = {
  73177. zlevel: 0,
  73178. z: 5,
  73179. symbol: 'pin',
  73180. symbolSize: 50,
  73181. //symbolRotate: 0,
  73182. //symbolOffset: [0, 0]
  73183. tooltip: {
  73184. trigger: 'item'
  73185. },
  73186. label: {
  73187. show: true,
  73188. position: 'inside'
  73189. },
  73190. itemStyle: {
  73191. borderWidth: 2
  73192. },
  73193. emphasis: {
  73194. label: {
  73195. show: true
  73196. }
  73197. }
  73198. };
  73199. return MarkPointModel;
  73200. }(MarkerModel);
  73201. function hasXOrY(item) {
  73202. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  73203. }
  73204. function hasXAndY(item) {
  73205. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  73206. }
  73207. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  73208. var coordArr = [];
  73209. var stacked = isDimensionStacked(data, targetDataDim
  73210. /*, otherDataDim*/
  73211. );
  73212. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  73213. var value = numCalculate(data, calcDataDim, markerType);
  73214. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  73215. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  73216. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  73217. var coordArrValue = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision.
  73218. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  73219. precision = Math.min(precision, 20);
  73220. if (precision >= 0) {
  73221. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  73222. }
  73223. return [coordArr, coordArrValue];
  73224. } // TODO Specified percent
  73225. var markerTypeCalculator = {
  73226. min: curry(markerTypeCalculatorWithExtent, 'min'),
  73227. max: curry(markerTypeCalculatorWithExtent, 'max'),
  73228. average: curry(markerTypeCalculatorWithExtent, 'average'),
  73229. median: curry(markerTypeCalculatorWithExtent, 'median')
  73230. };
  73231. /**
  73232. * Transform markPoint data item to format used in List by do the following
  73233. * 1. Calculate statistic like `max`, `min`, `average`
  73234. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  73235. */
  73236. function dataTransform(seriesModel, item) {
  73237. var data = seriesModel.getData();
  73238. var coordSys = seriesModel.coordinateSystem; // 1. If not specify the position with pixel directly
  73239. // 2. If `coord` is not a data array. Which uses `xAxis`,
  73240. // `yAxis` to specify the coord on each dimension
  73241. // parseFloat first because item.x and item.y can be percent string like '20%'
  73242. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  73243. var dims = coordSys.dimensions;
  73244. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option
  73245. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  73246. item = clone(item);
  73247. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  73248. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  73249. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  73250. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  73251. item.coord = coordInfo[0]; // Force to use the value of calculated value.
  73252. // let item use the value without stack.
  73253. item.value = coordInfo[1];
  73254. } else {
  73255. // FIXME Only has one of xAxis and yAxis.
  73256. var coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis]; // Each coord support max, min, average
  73257. for (var i = 0; i < 2; i++) {
  73258. if (markerTypeCalculator[coord[i]]) {
  73259. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  73260. }
  73261. }
  73262. item.coord = coord;
  73263. }
  73264. }
  73265. return item;
  73266. }
  73267. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  73268. var ret = {};
  73269. if (item.valueIndex != null || item.valueDim != null) {
  73270. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  73271. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  73272. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  73273. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  73274. } else {
  73275. ret.baseAxis = seriesModel.getBaseAxis();
  73276. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  73277. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  73278. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  73279. }
  73280. return ret;
  73281. }
  73282. function dataDimToCoordDim(seriesModel, dataDim) {
  73283. var dimItem = seriesModel.getData().getDimensionInfo(dataDim);
  73284. return dimItem && dimItem.coordDim;
  73285. }
  73286. /**
  73287. * Filter data which is out of coordinateSystem range
  73288. * [dataFilter description]
  73289. */
  73290. function dataFilter$1( // Currently only polar and cartesian has containData.
  73291. coordSys, item) {
  73292. // Alwalys return true if there is no coordSys
  73293. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  73294. }
  73295. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  73296. // x, y, radius, angle
  73297. if (dimIndex < 2) {
  73298. return item.coord && item.coord[dimIndex];
  73299. }
  73300. return item.value;
  73301. }
  73302. function numCalculate(data, valueDataDim, type) {
  73303. if (type === 'average') {
  73304. var sum_1 = 0;
  73305. var count_1 = 0;
  73306. data.each(valueDataDim, function (val, idx) {
  73307. if (!isNaN(val)) {
  73308. sum_1 += val;
  73309. count_1++;
  73310. }
  73311. });
  73312. return sum_1 / count_1;
  73313. } else if (type === 'median') {
  73314. return data.getMedian(valueDataDim);
  73315. } else {
  73316. // max & min
  73317. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  73318. }
  73319. }
  73320. var inner$h = makeInner();
  73321. var MarkerView =
  73322. /** @class */
  73323. function (_super) {
  73324. __extends(MarkerView, _super);
  73325. function MarkerView() {
  73326. var _this = _super !== null && _super.apply(this, arguments) || this;
  73327. _this.type = MarkerView.type;
  73328. return _this;
  73329. }
  73330. MarkerView.prototype.init = function () {
  73331. this.markerGroupMap = createHashMap();
  73332. };
  73333. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  73334. var _this = this;
  73335. var markerGroupMap = this.markerGroupMap;
  73336. markerGroupMap.each(function (item) {
  73337. inner$h(item).keep = false;
  73338. });
  73339. ecModel.eachSeries(function (seriesModel) {
  73340. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  73341. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  73342. });
  73343. markerGroupMap.each(function (item) {
  73344. !inner$h(item).keep && _this.group.remove(item.group);
  73345. });
  73346. };
  73347. MarkerView.prototype.markKeep = function (drawGroup) {
  73348. inner$h(drawGroup).keep = true;
  73349. };
  73350. MarkerView.prototype.blurSeries = function (seriesModelList) {
  73351. var _this = this;
  73352. each(seriesModelList, function (seriesModel) {
  73353. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  73354. if (markerModel) {
  73355. var data = markerModel.getData();
  73356. data.eachItemGraphicEl(function (el) {
  73357. if (el) {
  73358. enterBlur(el);
  73359. }
  73360. });
  73361. }
  73362. });
  73363. };
  73364. MarkerView.type = 'marker';
  73365. return MarkerView;
  73366. }(ComponentView);
  73367. function updateMarkerLayout(mpData, seriesModel, api) {
  73368. var coordSys = seriesModel.coordinateSystem;
  73369. mpData.each(function (idx) {
  73370. var itemModel = mpData.getItemModel(idx);
  73371. var point;
  73372. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  73373. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  73374. if (!isNaN(xPx) && !isNaN(yPx)) {
  73375. point = [xPx, yPx];
  73376. } // Chart like bar may have there own marker positioning logic
  73377. else if (seriesModel.getMarkerPosition) {
  73378. // Use the getMarkerPoisition
  73379. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  73380. } else if (coordSys) {
  73381. var x = mpData.get(coordSys.dimensions[0], idx);
  73382. var y = mpData.get(coordSys.dimensions[1], idx);
  73383. point = coordSys.dataToPoint([x, y]);
  73384. } // Use x, y if has any
  73385. if (!isNaN(xPx)) {
  73386. point[0] = xPx;
  73387. }
  73388. if (!isNaN(yPx)) {
  73389. point[1] = yPx;
  73390. }
  73391. mpData.setItemLayout(idx, point);
  73392. });
  73393. }
  73394. var MarkPointView =
  73395. /** @class */
  73396. function (_super) {
  73397. __extends(MarkPointView, _super);
  73398. function MarkPointView() {
  73399. var _this = _super !== null && _super.apply(this, arguments) || this;
  73400. _this.type = MarkPointView.type;
  73401. return _this;
  73402. }
  73403. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  73404. ecModel.eachSeries(function (seriesModel) {
  73405. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  73406. if (mpModel) {
  73407. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  73408. this.markerGroupMap.get(seriesModel.id).updateLayout();
  73409. }
  73410. }, this);
  73411. };
  73412. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  73413. var coordSys = seriesModel.coordinateSystem;
  73414. var seriesId = seriesModel.id;
  73415. var seriesData = seriesModel.getData();
  73416. var symbolDrawMap = this.markerGroupMap;
  73417. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  73418. var mpData = createData(coordSys, seriesModel, mpModel); // FIXME
  73419. mpModel.setData(mpData);
  73420. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  73421. mpData.each(function (idx) {
  73422. var itemModel = mpData.getItemModel(idx);
  73423. var symbol = itemModel.getShallow('symbol');
  73424. var symbolSize = itemModel.getShallow('symbolSize');
  73425. var symbolRotate = itemModel.getShallow('symbolRotate');
  73426. var symbolOffset = itemModel.getShallow('symbolOffset');
  73427. var symbolKeepAspect = itemModel.getShallow('symbolKeepAspect'); // TODO: refactor needed: single data item should not support callback function
  73428. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate) || isFunction(symbolOffset)) {
  73429. var rawIdx = mpModel.getRawValue(idx);
  73430. var dataParams = mpModel.getDataParams(idx);
  73431. if (isFunction(symbol)) {
  73432. symbol = symbol(rawIdx, dataParams);
  73433. }
  73434. if (isFunction(symbolSize)) {
  73435. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  73436. symbolSize = symbolSize(rawIdx, dataParams);
  73437. }
  73438. if (isFunction(symbolRotate)) {
  73439. symbolRotate = symbolRotate(rawIdx, dataParams);
  73440. }
  73441. if (isFunction(symbolOffset)) {
  73442. symbolOffset = symbolOffset(rawIdx, dataParams);
  73443. }
  73444. }
  73445. var style = itemModel.getModel('itemStyle').getItemStyle();
  73446. var color = getVisualFromData(seriesData, 'color');
  73447. if (!style.fill) {
  73448. style.fill = color;
  73449. }
  73450. mpData.setItemVisual(idx, {
  73451. symbol: symbol,
  73452. symbolSize: symbolSize,
  73453. symbolRotate: symbolRotate,
  73454. symbolOffset: symbolOffset,
  73455. symbolKeepAspect: symbolKeepAspect,
  73456. style: style
  73457. });
  73458. }); // TODO Text are wrong
  73459. symbolDraw.updateData(mpData);
  73460. this.group.add(symbolDraw.group); // Set host model for tooltip
  73461. // FIXME
  73462. mpData.eachItemGraphicEl(function (el) {
  73463. el.traverse(function (child) {
  73464. getECData(child).dataModel = mpModel;
  73465. });
  73466. });
  73467. this.markKeep(symbolDraw);
  73468. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  73469. };
  73470. MarkPointView.type = 'markPoint';
  73471. return MarkPointView;
  73472. }(MarkerView);
  73473. function createData(coordSys, seriesModel, mpModel) {
  73474. var coordDimsInfos;
  73475. if (coordSys) {
  73476. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  73477. 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
  73478. return extend(extend({}, info), {
  73479. name: coordDim,
  73480. // DON'T use ordinalMeta to parse and collect ordinal.
  73481. ordinalMeta: null
  73482. });
  73483. });
  73484. } else {
  73485. coordDimsInfos = [{
  73486. name: 'value',
  73487. type: 'float'
  73488. }];
  73489. }
  73490. var mpData = new SeriesData(coordDimsInfos, mpModel);
  73491. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  73492. if (coordSys) {
  73493. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  73494. }
  73495. mpData.initData(dataOpt, null, coordSys ? dimValueGetter : function (item) {
  73496. return item.value;
  73497. });
  73498. return mpData;
  73499. }
  73500. function install$E(registers) {
  73501. registers.registerComponentModel(MarkPointModel);
  73502. registers.registerComponentView(MarkPointView);
  73503. registers.registerPreprocessor(function (opt) {
  73504. if (checkMarkerInSeries(opt.series, 'markPoint')) {
  73505. // Make sure markPoint component is enabled
  73506. opt.markPoint = opt.markPoint || {};
  73507. }
  73508. });
  73509. }
  73510. var MarkLineModel =
  73511. /** @class */
  73512. function (_super) {
  73513. __extends(MarkLineModel, _super);
  73514. function MarkLineModel() {
  73515. var _this = _super !== null && _super.apply(this, arguments) || this;
  73516. _this.type = MarkLineModel.type;
  73517. return _this;
  73518. }
  73519. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  73520. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  73521. };
  73522. MarkLineModel.type = 'markLine';
  73523. MarkLineModel.defaultOption = {
  73524. zlevel: 0,
  73525. z: 5,
  73526. symbol: ['circle', 'arrow'],
  73527. symbolSize: [8, 16],
  73528. //symbolRotate: 0,
  73529. symbolOffset: 0,
  73530. precision: 2,
  73531. tooltip: {
  73532. trigger: 'item'
  73533. },
  73534. label: {
  73535. show: true,
  73536. position: 'end',
  73537. distance: 5
  73538. },
  73539. lineStyle: {
  73540. type: 'dashed'
  73541. },
  73542. emphasis: {
  73543. label: {
  73544. show: true
  73545. },
  73546. lineStyle: {
  73547. width: 3
  73548. }
  73549. },
  73550. animationEasing: 'linear'
  73551. };
  73552. return MarkLineModel;
  73553. }(MarkerModel);
  73554. var inner$i = makeInner();
  73555. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  73556. var data = seriesModel.getData();
  73557. var itemArray;
  73558. if (!isArray(item)) {
  73559. // Special type markLine like 'min', 'max', 'average', 'median'
  73560. var mlType = item.type;
  73561. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median' // In case
  73562. // data: [{
  73563. // yAxis: 10
  73564. // }]
  73565. || item.xAxis != null || item.yAxis != null) {
  73566. var valueAxis = void 0;
  73567. var value = void 0;
  73568. if (item.yAxis != null || item.xAxis != null) {
  73569. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  73570. value = retrieve(item.yAxis, item.xAxis);
  73571. } else {
  73572. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  73573. valueAxis = axisInfo.valueAxis;
  73574. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  73575. value = numCalculate(data, valueDataDim, mlType);
  73576. }
  73577. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  73578. var baseIndex = 1 - valueIndex; // Normized to 2d data with start and end point
  73579. var mlFrom = clone(item);
  73580. var mlTo = {
  73581. coord: []
  73582. };
  73583. mlFrom.type = null;
  73584. mlFrom.coord = [];
  73585. mlFrom.coord[baseIndex] = -Infinity;
  73586. mlTo.coord[baseIndex] = Infinity;
  73587. var precision = mlModel.get('precision');
  73588. if (precision >= 0 && typeof value === 'number') {
  73589. value = +value.toFixed(Math.min(precision, 20));
  73590. }
  73591. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  73592. itemArray = [mlFrom, mlTo, {
  73593. type: mlType,
  73594. valueIndex: item.valueIndex,
  73595. // Force to use the value of calculated value.
  73596. value: value
  73597. }];
  73598. } else {
  73599. // Invalid data
  73600. if ("development" !== 'production') {
  73601. logError('Invalid markLine data.');
  73602. }
  73603. itemArray = [];
  73604. }
  73605. } else {
  73606. itemArray = item;
  73607. }
  73608. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])]; // Avoid line data type is extended by from(to) data type
  73609. normalizedItem[2].type = normalizedItem[2].type || null; // Merge from option and to option into line option
  73610. merge(normalizedItem[2], normalizedItem[0]);
  73611. merge(normalizedItem[2], normalizedItem[1]);
  73612. return normalizedItem;
  73613. };
  73614. function isInifinity(val) {
  73615. return !isNaN(val) && !isFinite(val);
  73616. } // If a markLine has one dim
  73617. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  73618. var otherDimIndex = 1 - dimIndex;
  73619. var dimName = coordSys.dimensions[dimIndex];
  73620. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  73621. }
  73622. function markLineFilter(coordSys, item) {
  73623. if (coordSys.type === 'cartesian2d') {
  73624. var fromCoord = item[0].coord;
  73625. var toCoord = item[1].coord; // In case
  73626. // {
  73627. // markLine: {
  73628. // data: [{ yAxis: 2 }]
  73629. // }
  73630. // }
  73631. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  73632. return true;
  73633. }
  73634. }
  73635. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  73636. }
  73637. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  73638. var coordSys = seriesModel.coordinateSystem;
  73639. var itemModel = data.getItemModel(idx);
  73640. var point;
  73641. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  73642. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  73643. if (!isNaN(xPx) && !isNaN(yPx)) {
  73644. point = [xPx, yPx];
  73645. } else {
  73646. // Chart like bar may have there own marker positioning logic
  73647. if (seriesModel.getMarkerPosition) {
  73648. // Use the getMarkerPoisition
  73649. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  73650. } else {
  73651. var dims = coordSys.dimensions;
  73652. var x = data.get(dims[0], idx);
  73653. var y = data.get(dims[1], idx);
  73654. point = coordSys.dataToPoint([x, y]);
  73655. } // Expand line to the edge of grid if value on one axis is Inifnity
  73656. // In case
  73657. // markLine: {
  73658. // data: [{
  73659. // yAxis: 2
  73660. // // or
  73661. // type: 'average'
  73662. // }]
  73663. // }
  73664. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  73665. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  73666. var xAxis = coordSys.getAxis('x');
  73667. var yAxis = coordSys.getAxis('y');
  73668. var dims = coordSys.dimensions;
  73669. if (isInifinity(data.get(dims[0], idx))) {
  73670. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  73671. } else if (isInifinity(data.get(dims[1], idx))) {
  73672. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  73673. }
  73674. } // Use x, y if has any
  73675. if (!isNaN(xPx)) {
  73676. point[0] = xPx;
  73677. }
  73678. if (!isNaN(yPx)) {
  73679. point[1] = yPx;
  73680. }
  73681. }
  73682. data.setItemLayout(idx, point);
  73683. }
  73684. var MarkLineView =
  73685. /** @class */
  73686. function (_super) {
  73687. __extends(MarkLineView, _super);
  73688. function MarkLineView() {
  73689. var _this = _super !== null && _super.apply(this, arguments) || this;
  73690. _this.type = MarkLineView.type;
  73691. return _this;
  73692. }
  73693. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  73694. ecModel.eachSeries(function (seriesModel) {
  73695. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  73696. if (mlModel) {
  73697. var mlData_1 = mlModel.getData();
  73698. var fromData_1 = inner$i(mlModel).from;
  73699. var toData_1 = inner$i(mlModel).to; // Update visual and layout of from symbol and to symbol
  73700. fromData_1.each(function (idx) {
  73701. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  73702. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  73703. }); // Update layout of line
  73704. mlData_1.each(function (idx) {
  73705. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  73706. });
  73707. this.markerGroupMap.get(seriesModel.id).updateLayout();
  73708. }
  73709. }, this);
  73710. };
  73711. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  73712. var coordSys = seriesModel.coordinateSystem;
  73713. var seriesId = seriesModel.id;
  73714. var seriesData = seriesModel.getData();
  73715. var lineDrawMap = this.markerGroupMap;
  73716. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  73717. this.group.add(lineDraw.group);
  73718. var mlData = createList$1(coordSys, seriesModel, mlModel);
  73719. var fromData = mlData.from;
  73720. var toData = mlData.to;
  73721. var lineData = mlData.line;
  73722. inner$i(mlModel).from = fromData;
  73723. inner$i(mlModel).to = toData; // Line data for tooltip and formatter
  73724. mlModel.setData(lineData); // TODO
  73725. // Functionally, `symbolSize` & `symbolOffset` can also be 2D array now.
  73726. // But the related logic and type definition are not finished yet.
  73727. // Finish it if required
  73728. var symbolType = mlModel.get('symbol');
  73729. var symbolSize = mlModel.get('symbolSize');
  73730. var symbolRotate = mlModel.get('symbolRotate');
  73731. var symbolOffset = mlModel.get('symbolOffset'); // TODO: support callback function like markPoint
  73732. if (!isArray(symbolType)) {
  73733. symbolType = [symbolType, symbolType];
  73734. }
  73735. if (!isArray(symbolSize)) {
  73736. symbolSize = [symbolSize, symbolSize];
  73737. }
  73738. if (!isArray(symbolRotate)) {
  73739. symbolRotate = [symbolRotate, symbolRotate];
  73740. }
  73741. if (!isArray(symbolOffset)) {
  73742. symbolOffset = [symbolOffset, symbolOffset];
  73743. } // Update visual and layout of from symbol and to symbol
  73744. mlData.from.each(function (idx) {
  73745. updateDataVisualAndLayout(fromData, idx, true);
  73746. updateDataVisualAndLayout(toData, idx, false);
  73747. }); // Update visual and layout of line
  73748. lineData.each(function (idx) {
  73749. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle(); // lineData.setItemVisual(idx, {
  73750. // color: lineColor || fromData.getItemVisual(idx, 'color')
  73751. // });
  73752. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  73753. if (lineStyle.stroke == null) {
  73754. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  73755. }
  73756. lineData.setItemVisual(idx, {
  73757. fromSymbolKeepAspect: fromData.getItemVisual(idx, 'symbolKeepAspect'),
  73758. fromSymbolOffset: fromData.getItemVisual(idx, 'symbolOffset'),
  73759. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  73760. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  73761. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  73762. toSymbolKeepAspect: toData.getItemVisual(idx, 'symbolKeepAspect'),
  73763. toSymbolOffset: toData.getItemVisual(idx, 'symbolOffset'),
  73764. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  73765. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  73766. toSymbol: toData.getItemVisual(idx, 'symbol'),
  73767. style: lineStyle
  73768. });
  73769. });
  73770. lineDraw.updateData(lineData); // Set host model for tooltip
  73771. // FIXME
  73772. mlData.line.eachItemGraphicEl(function (el, idx) {
  73773. el.traverse(function (child) {
  73774. getECData(child).dataModel = mlModel;
  73775. });
  73776. });
  73777. function updateDataVisualAndLayout(data, idx, isFrom) {
  73778. var itemModel = data.getItemModel(idx);
  73779. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  73780. var style = itemModel.getModel('itemStyle').getItemStyle();
  73781. if (style.fill == null) {
  73782. style.fill = getVisualFromData(seriesData, 'color');
  73783. }
  73784. data.setItemVisual(idx, {
  73785. symbolKeepAspect: itemModel.get('symbolKeepAspect'),
  73786. // `0` should be considered as a valid value, so use `retrieve2` instead of `||`
  73787. symbolOffset: retrieve2(itemModel.get('symbolOffset', true), symbolOffset[isFrom ? 0 : 1]),
  73788. symbolRotate: retrieve2(itemModel.get('symbolRotate', true), symbolRotate[isFrom ? 0 : 1]),
  73789. // TODO: when 2d array is supported, it should ignore parent
  73790. symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]),
  73791. symbol: retrieve2(itemModel.get('symbol', true), symbolType[isFrom ? 0 : 1]),
  73792. style: style
  73793. });
  73794. }
  73795. this.markKeep(lineDraw);
  73796. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  73797. };
  73798. MarkLineView.type = 'markLine';
  73799. return MarkLineView;
  73800. }(MarkerView);
  73801. function createList$1(coordSys, seriesModel, mlModel) {
  73802. var coordDimsInfos;
  73803. if (coordSys) {
  73804. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  73805. 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
  73806. return extend(extend({}, info), {
  73807. name: coordDim,
  73808. // DON'T use ordinalMeta to parse and collect ordinal.
  73809. ordinalMeta: null
  73810. });
  73811. });
  73812. } else {
  73813. coordDimsInfos = [{
  73814. name: 'value',
  73815. type: 'float'
  73816. }];
  73817. }
  73818. var fromData = new SeriesData(coordDimsInfos, mlModel);
  73819. var toData = new SeriesData(coordDimsInfos, mlModel); // No dimensions
  73820. var lineData = new SeriesData([], mlModel);
  73821. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  73822. if (coordSys) {
  73823. optData = filter(optData, curry(markLineFilter, coordSys));
  73824. }
  73825. var dimValueGetter$1 = coordSys ? dimValueGetter : function (item) {
  73826. return item.value;
  73827. };
  73828. fromData.initData(map(optData, function (item) {
  73829. return item[0];
  73830. }), null, dimValueGetter$1);
  73831. toData.initData(map(optData, function (item) {
  73832. return item[1];
  73833. }), null, dimValueGetter$1);
  73834. lineData.initData(map(optData, function (item) {
  73835. return item[2];
  73836. }));
  73837. lineData.hasItemOption = true;
  73838. return {
  73839. from: fromData,
  73840. to: toData,
  73841. line: lineData
  73842. };
  73843. }
  73844. function install$F(registers) {
  73845. registers.registerComponentModel(MarkLineModel);
  73846. registers.registerComponentView(MarkLineView);
  73847. registers.registerPreprocessor(function (opt) {
  73848. if (checkMarkerInSeries(opt.series, 'markLine')) {
  73849. // Make sure markLine component is enabled
  73850. opt.markLine = opt.markLine || {};
  73851. }
  73852. });
  73853. }
  73854. var MarkAreaModel =
  73855. /** @class */
  73856. function (_super) {
  73857. __extends(MarkAreaModel, _super);
  73858. function MarkAreaModel() {
  73859. var _this = _super !== null && _super.apply(this, arguments) || this;
  73860. _this.type = MarkAreaModel.type;
  73861. return _this;
  73862. }
  73863. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  73864. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  73865. };
  73866. MarkAreaModel.type = 'markArea';
  73867. MarkAreaModel.defaultOption = {
  73868. zlevel: 0,
  73869. // PENDING
  73870. z: 1,
  73871. tooltip: {
  73872. trigger: 'item'
  73873. },
  73874. // markArea should fixed on the coordinate system
  73875. animation: false,
  73876. label: {
  73877. show: true,
  73878. position: 'top'
  73879. },
  73880. itemStyle: {
  73881. // color and borderColor default to use color from series
  73882. // color: 'auto'
  73883. // borderColor: 'auto'
  73884. borderWidth: 0
  73885. },
  73886. emphasis: {
  73887. label: {
  73888. show: true,
  73889. position: 'top'
  73890. }
  73891. }
  73892. };
  73893. return MarkAreaModel;
  73894. }(MarkerModel);
  73895. var inner$j = makeInner();
  73896. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  73897. var lt = dataTransform(seriesModel, item[0]);
  73898. var rb = dataTransform(seriesModel, item[1]); // FIXME make sure lt is less than rb
  73899. var ltCoord = lt.coord;
  73900. var rbCoord = rb.coord;
  73901. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  73902. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  73903. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  73904. rbCoord[1] = retrieve(rbCoord[1], Infinity); // Merge option into one
  73905. var result = mergeAll([{}, lt, rb]);
  73906. result.coord = [lt.coord, rb.coord];
  73907. result.x0 = lt.x;
  73908. result.y0 = lt.y;
  73909. result.x1 = rb.x;
  73910. result.y1 = rb.y;
  73911. return result;
  73912. };
  73913. function isInifinity$1(val) {
  73914. return !isNaN(val) && !isFinite(val);
  73915. } // If a markArea has one dim
  73916. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  73917. var otherDimIndex = 1 - dimIndex;
  73918. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  73919. }
  73920. function markAreaFilter(coordSys, item) {
  73921. var fromCoord = item.coord[0];
  73922. var toCoord = item.coord[1];
  73923. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  73924. // In case
  73925. // {
  73926. // markArea: {
  73927. // data: [{ yAxis: 2 }]
  73928. // }
  73929. // }
  73930. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  73931. return true;
  73932. }
  73933. }
  73934. return dataFilter$1(coordSys, {
  73935. coord: fromCoord,
  73936. x: item.x0,
  73937. y: item.y0
  73938. }) || dataFilter$1(coordSys, {
  73939. coord: toCoord,
  73940. x: item.x1,
  73941. y: item.y1
  73942. });
  73943. } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  73944. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  73945. var coordSys = seriesModel.coordinateSystem;
  73946. var itemModel = data.getItemModel(idx);
  73947. var point;
  73948. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  73949. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  73950. if (!isNaN(xPx) && !isNaN(yPx)) {
  73951. point = [xPx, yPx];
  73952. } else {
  73953. // Chart like bar may have there own marker positioning logic
  73954. if (seriesModel.getMarkerPosition) {
  73955. // Use the getMarkerPoisition
  73956. point = seriesModel.getMarkerPosition(data.getValues(dims, idx));
  73957. } else {
  73958. var x = data.get(dims[0], idx);
  73959. var y = data.get(dims[1], idx);
  73960. var pt = [x, y];
  73961. coordSys.clampData && coordSys.clampData(pt, pt);
  73962. point = coordSys.dataToPoint(pt, true);
  73963. }
  73964. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  73965. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  73966. var xAxis = coordSys.getAxis('x');
  73967. var yAxis = coordSys.getAxis('y');
  73968. var x = data.get(dims[0], idx);
  73969. var y = data.get(dims[1], idx);
  73970. if (isInifinity$1(x)) {
  73971. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  73972. } else if (isInifinity$1(y)) {
  73973. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  73974. }
  73975. } // Use x, y if has any
  73976. if (!isNaN(xPx)) {
  73977. point[0] = xPx;
  73978. }
  73979. if (!isNaN(yPx)) {
  73980. point[1] = yPx;
  73981. }
  73982. }
  73983. return point;
  73984. }
  73985. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  73986. var MarkAreaView =
  73987. /** @class */
  73988. function (_super) {
  73989. __extends(MarkAreaView, _super);
  73990. function MarkAreaView() {
  73991. var _this = _super !== null && _super.apply(this, arguments) || this;
  73992. _this.type = MarkAreaView.type;
  73993. return _this;
  73994. }
  73995. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  73996. ecModel.eachSeries(function (seriesModel) {
  73997. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  73998. if (maModel) {
  73999. var areaData_1 = maModel.getData();
  74000. areaData_1.each(function (idx) {
  74001. var points = map(dimPermutations, function (dim) {
  74002. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  74003. }); // Layout
  74004. areaData_1.setItemLayout(idx, points);
  74005. var el = areaData_1.getItemGraphicEl(idx);
  74006. el.setShape('points', points);
  74007. });
  74008. }
  74009. }, this);
  74010. };
  74011. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  74012. var coordSys = seriesModel.coordinateSystem;
  74013. var seriesId = seriesModel.id;
  74014. var seriesData = seriesModel.getData();
  74015. var areaGroupMap = this.markerGroupMap;
  74016. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  74017. group: new Group()
  74018. });
  74019. this.group.add(polygonGroup.group);
  74020. this.markKeep(polygonGroup);
  74021. var areaData = createList$2(coordSys, seriesModel, maModel); // Line data for tooltip and formatter
  74022. maModel.setData(areaData); // Update visual and layout of line
  74023. areaData.each(function (idx) {
  74024. // Layout
  74025. var points = map(dimPermutations, function (dim) {
  74026. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  74027. });
  74028. var xAxisScale = coordSys.getAxis('x').scale;
  74029. var yAxisScale = coordSys.getAxis('y').scale;
  74030. var xAxisExtent = xAxisScale.getExtent();
  74031. var yAxisExtent = yAxisScale.getExtent();
  74032. var xPointExtent = [xAxisScale.parse(areaData.get('x0', idx)), xAxisScale.parse(areaData.get('x1', idx))];
  74033. var yPointExtent = [yAxisScale.parse(areaData.get('y0', idx)), yAxisScale.parse(areaData.get('y1', idx))];
  74034. asc(xPointExtent);
  74035. asc(yPointExtent);
  74036. 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
  74037. // in layout so that label will not be displayed. See #12591
  74038. var allClipped = !overlapped;
  74039. areaData.setItemLayout(idx, {
  74040. points: points,
  74041. allClipped: allClipped
  74042. });
  74043. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  74044. var color$1 = getVisualFromData(seriesData, 'color');
  74045. if (!style.fill) {
  74046. style.fill = color$1;
  74047. if (typeof style.fill === 'string') {
  74048. style.fill = modifyAlpha(style.fill, 0.4);
  74049. }
  74050. }
  74051. if (!style.stroke) {
  74052. style.stroke = color$1;
  74053. } // Visual
  74054. areaData.setItemVisual(idx, 'style', style);
  74055. });
  74056. areaData.diff(inner$j(polygonGroup).data).add(function (idx) {
  74057. var layout = areaData.getItemLayout(idx);
  74058. if (!layout.allClipped) {
  74059. var polygon = new Polygon({
  74060. shape: {
  74061. points: layout.points
  74062. }
  74063. });
  74064. areaData.setItemGraphicEl(idx, polygon);
  74065. polygonGroup.group.add(polygon);
  74066. }
  74067. }).update(function (newIdx, oldIdx) {
  74068. var polygon = inner$j(polygonGroup).data.getItemGraphicEl(oldIdx);
  74069. var layout = areaData.getItemLayout(newIdx);
  74070. if (!layout.allClipped) {
  74071. if (polygon) {
  74072. updateProps(polygon, {
  74073. shape: {
  74074. points: layout.points
  74075. }
  74076. }, maModel, newIdx);
  74077. } else {
  74078. polygon = new Polygon({
  74079. shape: {
  74080. points: layout.points
  74081. }
  74082. });
  74083. }
  74084. areaData.setItemGraphicEl(newIdx, polygon);
  74085. polygonGroup.group.add(polygon);
  74086. } else if (polygon) {
  74087. polygonGroup.group.remove(polygon);
  74088. }
  74089. }).remove(function (idx) {
  74090. var polygon = inner$j(polygonGroup).data.getItemGraphicEl(idx);
  74091. polygonGroup.group.remove(polygon);
  74092. }).execute();
  74093. areaData.eachItemGraphicEl(function (polygon, idx) {
  74094. var itemModel = areaData.getItemModel(idx);
  74095. var style = areaData.getItemVisual(idx, 'style');
  74096. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  74097. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  74098. labelFetcher: maModel,
  74099. labelDataIndex: idx,
  74100. defaultText: areaData.getName(idx) || '',
  74101. inheritColor: typeof style.fill === 'string' ? modifyAlpha(style.fill, 1) : '#000'
  74102. });
  74103. setStatesStylesFromModel(polygon, itemModel);
  74104. enableHoverEmphasis(polygon);
  74105. getECData(polygon).dataModel = maModel;
  74106. });
  74107. inner$j(polygonGroup).data = areaData;
  74108. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  74109. };
  74110. MarkAreaView.type = 'markArea';
  74111. return MarkAreaView;
  74112. }(MarkerView);
  74113. function createList$2(coordSys, seriesModel, maModel) {
  74114. var coordDimsInfos;
  74115. var areaData;
  74116. var dims = ['x0', 'y0', 'x1', 'y1'];
  74117. if (coordSys) {
  74118. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  74119. var data = seriesModel.getData();
  74120. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  74121. return extend(extend({}, info), {
  74122. name: coordDim,
  74123. // DON'T use ordinalMeta to parse and collect ordinal.
  74124. ordinalMeta: null
  74125. });
  74126. });
  74127. areaData = new SeriesData(map(dims, function (dim, idx) {
  74128. return {
  74129. name: dim,
  74130. type: coordDimsInfos[idx % 2].type
  74131. };
  74132. }), maModel);
  74133. } else {
  74134. coordDimsInfos = [{
  74135. name: 'value',
  74136. type: 'float'
  74137. }];
  74138. areaData = new SeriesData(coordDimsInfos, maModel);
  74139. }
  74140. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  74141. if (coordSys) {
  74142. optData = filter(optData, curry(markAreaFilter, coordSys));
  74143. }
  74144. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  74145. // TODO should convert to ParsedValue?
  74146. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  74147. } : function (item) {
  74148. return item.value;
  74149. };
  74150. areaData.initData(optData, null, dimValueGetter);
  74151. areaData.hasItemOption = true;
  74152. return areaData;
  74153. }
  74154. function install$G(registers) {
  74155. registers.registerComponentModel(MarkAreaModel);
  74156. registers.registerComponentView(MarkAreaView);
  74157. registers.registerPreprocessor(function (opt) {
  74158. if (checkMarkerInSeries(opt.series, 'markArea')) {
  74159. // Make sure markArea component is enabled
  74160. opt.markArea = opt.markArea || {};
  74161. }
  74162. });
  74163. }
  74164. var getDefaultSelectorOptions = function (ecModel, type) {
  74165. if (type === 'all') {
  74166. return {
  74167. type: 'all',
  74168. title: ecModel.getLocaleModel().get(['legend', 'selector', 'all'])
  74169. };
  74170. } else if (type === 'inverse') {
  74171. return {
  74172. type: 'inverse',
  74173. title: ecModel.getLocaleModel().get(['legend', 'selector', 'inverse'])
  74174. };
  74175. }
  74176. };
  74177. var LegendModel =
  74178. /** @class */
  74179. function (_super) {
  74180. __extends(LegendModel, _super);
  74181. function LegendModel() {
  74182. var _this = _super !== null && _super.apply(this, arguments) || this;
  74183. _this.type = LegendModel.type;
  74184. _this.layoutMode = {
  74185. type: 'box',
  74186. // legend.width/height are maxWidth/maxHeight actually,
  74187. // whereas realy width/height is calculated by its content.
  74188. // (Setting {left: 10, right: 10} does not make sense).
  74189. // So consider the case:
  74190. // `setOption({legend: {left: 10});`
  74191. // then `setOption({legend: {right: 10});`
  74192. // The previous `left` should be cleared by setting `ignoreSize`.
  74193. ignoreSize: true
  74194. };
  74195. return _this;
  74196. }
  74197. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  74198. this.mergeDefaultAndTheme(option, ecModel);
  74199. option.selected = option.selected || {};
  74200. this._updateSelector(option);
  74201. };
  74202. LegendModel.prototype.mergeOption = function (option, ecModel) {
  74203. _super.prototype.mergeOption.call(this, option, ecModel);
  74204. this._updateSelector(option);
  74205. };
  74206. LegendModel.prototype._updateSelector = function (option) {
  74207. var selector = option.selector;
  74208. var ecModel = this.ecModel;
  74209. if (selector === true) {
  74210. selector = option.selector = ['all', 'inverse'];
  74211. }
  74212. if (isArray(selector)) {
  74213. each(selector, function (item, index) {
  74214. isString(item) && (item = {
  74215. type: item
  74216. });
  74217. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  74218. });
  74219. }
  74220. };
  74221. LegendModel.prototype.optionUpdated = function () {
  74222. this._updateData(this.ecModel);
  74223. var legendData = this._data; // If selectedMode is single, try to select one
  74224. if (legendData[0] && this.get('selectedMode') === 'single') {
  74225. var hasSelected = false; // If has any selected in option.selected
  74226. for (var i = 0; i < legendData.length; i++) {
  74227. var name_1 = legendData[i].get('name');
  74228. if (this.isSelected(name_1)) {
  74229. // Force to unselect others
  74230. this.select(name_1);
  74231. hasSelected = true;
  74232. break;
  74233. }
  74234. } // Try select the first if selectedMode is single
  74235. !hasSelected && this.select(legendData[0].get('name'));
  74236. }
  74237. };
  74238. LegendModel.prototype._updateData = function (ecModel) {
  74239. var potentialData = [];
  74240. var availableNames = [];
  74241. ecModel.eachRawSeries(function (seriesModel) {
  74242. var seriesName = seriesModel.name;
  74243. availableNames.push(seriesName);
  74244. var isPotential;
  74245. if (seriesModel.legendVisualProvider) {
  74246. var provider = seriesModel.legendVisualProvider;
  74247. var names = provider.getAllNames();
  74248. if (!ecModel.isSeriesFiltered(seriesModel)) {
  74249. availableNames = availableNames.concat(names);
  74250. }
  74251. if (names.length) {
  74252. potentialData = potentialData.concat(names);
  74253. } else {
  74254. isPotential = true;
  74255. }
  74256. } else {
  74257. isPotential = true;
  74258. }
  74259. if (isPotential && isNameSpecified(seriesModel)) {
  74260. potentialData.push(seriesModel.name);
  74261. }
  74262. });
  74263. /**
  74264. * @type {Array.<string>}
  74265. * @private
  74266. */
  74267. this._availableNames = availableNames; // If legend.data not specified in option, use availableNames as data,
  74268. // which is convinient for user preparing option.
  74269. var rawData = this.get('data') || potentialData;
  74270. var legendData = map(rawData, function (dataItem) {
  74271. // Can be string or number
  74272. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  74273. dataItem = {
  74274. name: dataItem
  74275. };
  74276. }
  74277. return new Model(dataItem, this, this.ecModel);
  74278. }, this);
  74279. /**
  74280. * @type {Array.<module:echarts/model/Model>}
  74281. * @private
  74282. */
  74283. this._data = legendData;
  74284. };
  74285. LegendModel.prototype.getData = function () {
  74286. return this._data;
  74287. };
  74288. LegendModel.prototype.select = function (name) {
  74289. var selected = this.option.selected;
  74290. var selectedMode = this.get('selectedMode');
  74291. if (selectedMode === 'single') {
  74292. var data = this._data;
  74293. each(data, function (dataItem) {
  74294. selected[dataItem.get('name')] = false;
  74295. });
  74296. }
  74297. selected[name] = true;
  74298. };
  74299. LegendModel.prototype.unSelect = function (name) {
  74300. if (this.get('selectedMode') !== 'single') {
  74301. this.option.selected[name] = false;
  74302. }
  74303. };
  74304. LegendModel.prototype.toggleSelected = function (name) {
  74305. var selected = this.option.selected; // Default is true
  74306. if (!selected.hasOwnProperty(name)) {
  74307. selected[name] = true;
  74308. }
  74309. this[selected[name] ? 'unSelect' : 'select'](name);
  74310. };
  74311. LegendModel.prototype.allSelect = function () {
  74312. var data = this._data;
  74313. var selected = this.option.selected;
  74314. each(data, function (dataItem) {
  74315. selected[dataItem.get('name', true)] = true;
  74316. });
  74317. };
  74318. LegendModel.prototype.inverseSelect = function () {
  74319. var data = this._data;
  74320. var selected = this.option.selected;
  74321. each(data, function (dataItem) {
  74322. var name = dataItem.get('name', true); // Initially, default value is true
  74323. if (!selected.hasOwnProperty(name)) {
  74324. selected[name] = true;
  74325. }
  74326. selected[name] = !selected[name];
  74327. });
  74328. };
  74329. LegendModel.prototype.isSelected = function (name) {
  74330. var selected = this.option.selected;
  74331. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  74332. };
  74333. LegendModel.prototype.getOrient = function () {
  74334. return this.get('orient') === 'vertical' ? {
  74335. index: 1,
  74336. name: 'vertical'
  74337. } : {
  74338. index: 0,
  74339. name: 'horizontal'
  74340. };
  74341. };
  74342. LegendModel.type = 'legend.plain';
  74343. LegendModel.dependencies = ['series'];
  74344. LegendModel.defaultOption = {
  74345. zlevel: 0,
  74346. z: 4,
  74347. show: true,
  74348. orient: 'horizontal',
  74349. left: 'center',
  74350. // right: 'center',
  74351. top: 0,
  74352. // bottom: null,
  74353. align: 'auto',
  74354. backgroundColor: 'rgba(0,0,0,0)',
  74355. borderColor: '#ccc',
  74356. borderRadius: 0,
  74357. borderWidth: 0,
  74358. padding: 5,
  74359. itemGap: 10,
  74360. itemWidth: 25,
  74361. itemHeight: 14,
  74362. symbolRotate: 'inherit',
  74363. inactiveColor: '#ccc',
  74364. inactiveBorderColor: '#ccc',
  74365. inactiveBorderWidth: 'auto',
  74366. itemStyle: {
  74367. color: 'inherit',
  74368. opacity: 'inherit',
  74369. decal: 'inherit',
  74370. shadowBlur: 0,
  74371. shadowColor: null,
  74372. shadowOffsetX: 0,
  74373. shadowOffsetY: 0,
  74374. borderColor: 'inherit',
  74375. borderWidth: 'auto',
  74376. borderCap: 'inherit',
  74377. borderJoin: 'inherit',
  74378. borderDashOffset: 'inherit',
  74379. borderMiterLimit: 'inherit'
  74380. },
  74381. lineStyle: {
  74382. width: 'auto',
  74383. color: 'inherit',
  74384. inactiveColor: '#ccc',
  74385. inactiveWidth: 2,
  74386. opacity: 'inherit',
  74387. type: 'inherit',
  74388. cap: 'inherit',
  74389. join: 'inherit',
  74390. dashOffset: 'inherit',
  74391. miterLimit: 'inherit',
  74392. shadowBlur: 0,
  74393. shadowColor: null,
  74394. shadowOffsetX: 0,
  74395. shadowOffsetY: 0
  74396. },
  74397. textStyle: {
  74398. color: '#333'
  74399. },
  74400. selectedMode: true,
  74401. selector: false,
  74402. selectorLabel: {
  74403. show: true,
  74404. borderRadius: 10,
  74405. padding: [3, 5, 3, 5],
  74406. fontSize: 12,
  74407. fontFamily: ' sans-serif',
  74408. color: '#666',
  74409. borderWidth: 1,
  74410. borderColor: '#666'
  74411. },
  74412. emphasis: {
  74413. selectorLabel: {
  74414. show: true,
  74415. color: '#eee',
  74416. backgroundColor: '#666'
  74417. }
  74418. },
  74419. selectorPosition: 'auto',
  74420. selectorItemGap: 7,
  74421. selectorButtonGap: 10,
  74422. tooltip: {
  74423. show: false
  74424. }
  74425. };
  74426. return LegendModel;
  74427. }(ComponentModel);
  74428. var curry$1 = curry;
  74429. var each$d = each;
  74430. var Group$2 = Group;
  74431. var LegendView =
  74432. /** @class */
  74433. function (_super) {
  74434. __extends(LegendView, _super);
  74435. function LegendView() {
  74436. var _this = _super !== null && _super.apply(this, arguments) || this;
  74437. _this.type = LegendView.type;
  74438. _this.newlineDisabled = false;
  74439. return _this;
  74440. }
  74441. LegendView.prototype.init = function () {
  74442. this.group.add(this._contentGroup = new Group$2());
  74443. this.group.add(this._selectorGroup = new Group$2());
  74444. this._isFirstRender = true;
  74445. };
  74446. /**
  74447. * @protected
  74448. */
  74449. LegendView.prototype.getContentGroup = function () {
  74450. return this._contentGroup;
  74451. };
  74452. /**
  74453. * @protected
  74454. */
  74455. LegendView.prototype.getSelectorGroup = function () {
  74456. return this._selectorGroup;
  74457. };
  74458. /**
  74459. * @override
  74460. */
  74461. LegendView.prototype.render = function (legendModel, ecModel, api) {
  74462. var isFirstRender = this._isFirstRender;
  74463. this._isFirstRender = false;
  74464. this.resetInner();
  74465. if (!legendModel.get('show', true)) {
  74466. return;
  74467. }
  74468. var itemAlign = legendModel.get('align');
  74469. var orient = legendModel.get('orient');
  74470. if (!itemAlign || itemAlign === 'auto') {
  74471. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  74472. } // selector has been normalized to an array in model
  74473. var selector = legendModel.get('selector', true);
  74474. var selectorPosition = legendModel.get('selectorPosition', true);
  74475. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  74476. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  74477. }
  74478. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  74479. var positionInfo = legendModel.getBoxLayoutParams();
  74480. var viewportSize = {
  74481. width: api.getWidth(),
  74482. height: api.getHeight()
  74483. };
  74484. var padding = legendModel.get('padding');
  74485. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  74486. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  74487. var layoutRect = getLayoutRect(defaults({
  74488. width: mainRect.width,
  74489. height: mainRect.height
  74490. }, positionInfo), viewportSize, padding);
  74491. this.group.x = layoutRect.x - mainRect.x;
  74492. this.group.y = layoutRect.y - mainRect.y;
  74493. this.group.markRedraw(); // Render background after group is layout.
  74494. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  74495. };
  74496. LegendView.prototype.resetInner = function () {
  74497. this.getContentGroup().removeAll();
  74498. this._backgroundEl && this.group.remove(this._backgroundEl);
  74499. this.getSelectorGroup().removeAll();
  74500. };
  74501. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  74502. var contentGroup = this.getContentGroup();
  74503. var legendDrawnMap = createHashMap();
  74504. var selectMode = legendModel.get('selectedMode');
  74505. var excludeSeriesId = [];
  74506. ecModel.eachRawSeries(function (seriesModel) {
  74507. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  74508. });
  74509. each$d(legendModel.getData(), function (legendItemModel, dataIndex) {
  74510. var name = legendItemModel.get('name'); // Use empty string or \n as a newline string
  74511. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  74512. var g = new Group$2(); // @ts-ignore
  74513. g.newline = true;
  74514. contentGroup.add(g);
  74515. return;
  74516. } // Representitive series.
  74517. var seriesModel = ecModel.getSeriesByName(name)[0];
  74518. if (legendDrawnMap.get(name)) {
  74519. // Have been drawed
  74520. return;
  74521. } // Legend to control series.
  74522. if (seriesModel) {
  74523. var data = seriesModel.getData();
  74524. var lineVisualStyle = data.getVisual('legendLineStyle') || {};
  74525. var legendIcon = data.getVisual('legendIcon');
  74526. /**
  74527. * `data.getVisual('style')` may be the color from the register
  74528. * in series. For example, for line series,
  74529. */
  74530. var style = data.getVisual('style');
  74531. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode);
  74532. 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));
  74533. legendDrawnMap.set(name, true);
  74534. } else {
  74535. // Legend to control data. In pie and funnel.
  74536. ecModel.eachRawSeries(function (seriesModel) {
  74537. // In case multiple series has same data name
  74538. if (legendDrawnMap.get(name)) {
  74539. return;
  74540. }
  74541. if (seriesModel.legendVisualProvider) {
  74542. var provider = seriesModel.legendVisualProvider;
  74543. if (!provider.containName(name)) {
  74544. return;
  74545. }
  74546. var idx = provider.indexOfName(name);
  74547. var style = provider.getItemVisual(idx, 'style');
  74548. var legendIcon = provider.getItemVisual(idx, 'legendIcon');
  74549. var colorArr = parse(style.fill); // Color may be set to transparent in visualMap when data is out of range.
  74550. // Do not show nothing.
  74551. if (colorArr && colorArr[3] === 0) {
  74552. colorArr[3] = 0.2; // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  74553. style.fill = stringify(colorArr, 'rgba');
  74554. }
  74555. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode); // FIXME: consider different series has items with the same name.
  74556. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  74557. // more than one pie series.
  74558. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  74559. legendDrawnMap.set(name, true);
  74560. }
  74561. }, this);
  74562. }
  74563. if ("development" !== 'production') {
  74564. if (!legendDrawnMap.get(name)) {
  74565. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  74566. }
  74567. }
  74568. }, this);
  74569. if (selector) {
  74570. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  74571. }
  74572. };
  74573. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  74574. var selectorGroup = this.getSelectorGroup();
  74575. each$d(selector, function createSelectorButton(selectorItem) {
  74576. var type = selectorItem.type;
  74577. var labelText = new ZRText({
  74578. style: {
  74579. x: 0,
  74580. y: 0,
  74581. align: 'center',
  74582. verticalAlign: 'middle'
  74583. },
  74584. onclick: function () {
  74585. api.dispatchAction({
  74586. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  74587. });
  74588. }
  74589. });
  74590. selectorGroup.add(labelText);
  74591. var labelModel = legendModel.getModel('selectorLabel');
  74592. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  74593. setLabelStyle(labelText, {
  74594. normal: labelModel,
  74595. emphasis: emphasisLabelModel
  74596. }, {
  74597. defaultText: selectorItem.title
  74598. });
  74599. enableHoverEmphasis(labelText);
  74600. });
  74601. };
  74602. LegendView.prototype._createItem = function (seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, legendIcon, selectMode) {
  74603. var drawType = seriesModel.visualDrawType;
  74604. var itemWidth = legendModel.get('itemWidth');
  74605. var itemHeight = legendModel.get('itemHeight');
  74606. var isSelected = legendModel.isSelected(name);
  74607. var iconRotate = legendItemModel.get('symbolRotate');
  74608. var legendIconType = legendItemModel.get('icon');
  74609. legendIcon = legendIconType || legendIcon || 'roundRect';
  74610. var legendLineStyle = legendModel.getModel('lineStyle');
  74611. var style = getLegendStyle(legendIcon, legendItemModel, legendLineStyle, lineVisualStyle, itemVisualStyle, drawType, isSelected);
  74612. var itemGroup = new Group$2();
  74613. var textStyleModel = legendItemModel.getModel('textStyle');
  74614. if (typeof seriesModel.getLegendIcon === 'function' && (!legendIconType || legendIconType === 'inherit')) {
  74615. // Series has specific way to define legend icon
  74616. itemGroup.add(seriesModel.getLegendIcon({
  74617. itemWidth: itemWidth,
  74618. itemHeight: itemHeight,
  74619. icon: legendIcon,
  74620. iconRotate: iconRotate,
  74621. itemStyle: style.itemStyle,
  74622. lineStyle: style.lineStyle
  74623. }));
  74624. } else {
  74625. // Use default legend icon policy for most series
  74626. var rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate : 0; // No rotation for no icon
  74627. itemGroup.add(getDefaultLegendIcon({
  74628. itemWidth: itemWidth,
  74629. itemHeight: itemHeight,
  74630. icon: legendIcon,
  74631. iconRotate: rotate,
  74632. itemStyle: style.itemStyle,
  74633. lineStyle: style.lineStyle
  74634. }));
  74635. }
  74636. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  74637. var textAlign = itemAlign;
  74638. var formatter = legendModel.get('formatter');
  74639. var content = name;
  74640. if (typeof formatter === 'string' && formatter) {
  74641. content = formatter.replace('{name}', name != null ? name : '');
  74642. } else if (typeof formatter === 'function') {
  74643. content = formatter(name);
  74644. }
  74645. var inactiveColor = legendItemModel.get('inactiveColor');
  74646. itemGroup.add(new ZRText({
  74647. style: createTextStyle(textStyleModel, {
  74648. text: content,
  74649. x: textX,
  74650. y: itemHeight / 2,
  74651. fill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  74652. align: textAlign,
  74653. verticalAlign: 'middle'
  74654. })
  74655. })); // Add a invisible rect to increase the area of mouse hover
  74656. var hitRect = new Rect({
  74657. shape: itemGroup.getBoundingRect(),
  74658. invisible: true
  74659. });
  74660. var tooltipModel = legendItemModel.getModel('tooltip');
  74661. if (tooltipModel.get('show')) {
  74662. setTooltipConfig({
  74663. el: hitRect,
  74664. componentModel: legendModel,
  74665. itemName: name,
  74666. itemTooltipOption: tooltipModel.option
  74667. });
  74668. }
  74669. itemGroup.add(hitRect);
  74670. itemGroup.eachChild(function (child) {
  74671. child.silent = true;
  74672. });
  74673. hitRect.silent = !selectMode;
  74674. this.getContentGroup().add(itemGroup);
  74675. enableHoverEmphasis(itemGroup); // @ts-ignore
  74676. itemGroup.__legendDataIndex = dataIndex;
  74677. return itemGroup;
  74678. };
  74679. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  74680. var contentGroup = this.getContentGroup();
  74681. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  74682. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  74683. var contentRect = contentGroup.getBoundingRect();
  74684. var contentPos = [-contentRect.x, -contentRect.y];
  74685. selectorGroup.markRedraw();
  74686. contentGroup.markRedraw();
  74687. if (selector) {
  74688. // Place buttons in selectorGroup
  74689. box( // Buttons in selectorGroup always layout horizontally
  74690. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  74691. var selectorRect = selectorGroup.getBoundingRect();
  74692. var selectorPos = [-selectorRect.x, -selectorRect.y];
  74693. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  74694. var orientIdx = legendModel.getOrient().index;
  74695. var wh = orientIdx === 0 ? 'width' : 'height';
  74696. var hw = orientIdx === 0 ? 'height' : 'width';
  74697. var yx = orientIdx === 0 ? 'y' : 'x';
  74698. if (selectorPosition === 'end') {
  74699. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  74700. } else {
  74701. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  74702. } //Always align selector to content as 'middle'
  74703. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  74704. selectorGroup.x = selectorPos[0];
  74705. selectorGroup.y = selectorPos[1];
  74706. contentGroup.x = contentPos[0];
  74707. contentGroup.y = contentPos[1];
  74708. var mainRect = {
  74709. x: 0,
  74710. y: 0
  74711. };
  74712. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  74713. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  74714. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  74715. return mainRect;
  74716. } else {
  74717. contentGroup.x = contentPos[0];
  74718. contentGroup.y = contentPos[1];
  74719. return this.group.getBoundingRect();
  74720. }
  74721. };
  74722. /**
  74723. * @protected
  74724. */
  74725. LegendView.prototype.remove = function () {
  74726. this.getContentGroup().removeAll();
  74727. this._isFirstRender = true;
  74728. };
  74729. LegendView.type = 'legend.plain';
  74730. return LegendView;
  74731. }(ComponentView);
  74732. function getLegendStyle(iconType, legendModel, legendLineStyle, lineVisualStyle, itemVisualStyle, drawType, isSelected) {
  74733. /**
  74734. * Use series style if is inherit;
  74735. * elsewise, use legend style
  74736. */
  74737. // itemStyle
  74738. var legendItemModel = legendModel.getModel('itemStyle');
  74739. var itemProperties = ITEM_STYLE_KEY_MAP.concat([['decal']]);
  74740. var itemStyle = {};
  74741. for (var i = 0; i < itemProperties.length; ++i) {
  74742. var propName = itemProperties[i][itemProperties[i].length - 1];
  74743. var visualName = itemProperties[i][0];
  74744. var value = legendItemModel.getShallow(propName);
  74745. if (value === 'inherit') {
  74746. switch (visualName) {
  74747. case 'fill':
  74748. /**
  74749. * Series with visualDrawType as 'stroke' should have
  74750. * series stroke as legend fill
  74751. */
  74752. itemStyle.fill = itemVisualStyle[drawType];
  74753. break;
  74754. case 'stroke':
  74755. /**
  74756. * icon type with "emptyXXX" should use fill color
  74757. * in visual style
  74758. */
  74759. itemStyle.stroke = itemVisualStyle[iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke'];
  74760. break;
  74761. case 'opacity':
  74762. /**
  74763. * Use lineStyle.opacity if drawType is stroke
  74764. */
  74765. itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity;
  74766. break;
  74767. default:
  74768. itemStyle[visualName] = itemVisualStyle[visualName];
  74769. }
  74770. } else if (value === 'auto' && visualName === 'lineWidth') {
  74771. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  74772. itemStyle.lineWidth = itemVisualStyle.lineWidth > 0 ? 2 : 0;
  74773. } else {
  74774. itemStyle[visualName] = value;
  74775. }
  74776. } // lineStyle
  74777. var legendLineModel = legendModel.getModel('lineStyle');
  74778. var lineProperties = LINE_STYLE_KEY_MAP.concat([['inactiveColor'], ['inactiveWidth']]);
  74779. var lineStyle = {};
  74780. for (var i = 0; i < lineProperties.length; ++i) {
  74781. var propName = lineProperties[i][1];
  74782. var visualName = lineProperties[i][0];
  74783. var value = legendLineModel.getShallow(propName);
  74784. if (value === 'inherit') {
  74785. lineStyle[visualName] = lineVisualStyle[visualName];
  74786. } else if (value === 'auto' && visualName === 'lineWidth') {
  74787. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  74788. lineStyle.lineWidth = lineVisualStyle.lineWidth > 0 ? 2 : 0;
  74789. } else {
  74790. lineStyle[visualName] = value;
  74791. }
  74792. } // Fix auto color to real color
  74793. itemStyle.fill === 'auto' && (itemStyle.fill = itemVisualStyle.fill);
  74794. itemStyle.stroke === 'auto' && (itemStyle.stroke = itemVisualStyle.fill);
  74795. lineStyle.stroke === 'auto' && (lineStyle.stroke = itemVisualStyle.fill);
  74796. if (!isSelected) {
  74797. var borderWidth = legendModel.get('inactiveBorderWidth');
  74798. /**
  74799. * Since stroke is set to be inactiveBorderColor, it may occur that
  74800. * there is no border in series but border in legend, so we need to
  74801. * use border only when series has border if is set to be auto
  74802. */
  74803. var visualHasBorder = itemStyle[iconType.indexOf('empty') > -1 ? 'fill' : 'stroke'];
  74804. itemStyle.lineWidth = borderWidth === 'auto' ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth;
  74805. itemStyle.fill = legendModel.get('inactiveColor');
  74806. itemStyle.stroke = legendModel.get('inactiveBorderColor');
  74807. lineStyle.stroke = legendLineStyle.get('inactiveColor');
  74808. lineStyle.lineWidth = legendLineStyle.get('inactiveWidth');
  74809. }
  74810. return {
  74811. itemStyle: itemStyle,
  74812. lineStyle: lineStyle
  74813. };
  74814. }
  74815. function getDefaultLegendIcon(opt) {
  74816. var symboType = opt.icon || 'roundRect';
  74817. var icon = createSymbol(symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill);
  74818. icon.setStyle(opt.itemStyle);
  74819. icon.rotation = (opt.iconRotate || 0) * Math.PI / 180;
  74820. icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  74821. if (symboType.indexOf('empty') > -1) {
  74822. icon.style.stroke = icon.style.fill;
  74823. icon.style.fill = '#fff';
  74824. icon.style.lineWidth = 2;
  74825. }
  74826. return icon;
  74827. }
  74828. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  74829. // downplay before unselect
  74830. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  74831. api.dispatchAction({
  74832. type: 'legendToggleSelect',
  74833. name: seriesName != null ? seriesName : dataName
  74834. }); // highlight after select
  74835. // TODO higlight immediately may cause animation loss.
  74836. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  74837. }
  74838. function isUseHoverLayer(api) {
  74839. var list = api.getZr().storage.getDisplayList();
  74840. var emphasisState;
  74841. var i = 0;
  74842. var len = list.length;
  74843. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  74844. i++;
  74845. }
  74846. return emphasisState && emphasisState.hoverLayer;
  74847. }
  74848. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  74849. // If element hover will move to a hoverLayer.
  74850. if (!isUseHoverLayer(api)) {
  74851. api.dispatchAction({
  74852. type: 'highlight',
  74853. seriesName: seriesName,
  74854. name: dataName,
  74855. excludeSeriesId: excludeSeriesId
  74856. });
  74857. }
  74858. }
  74859. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  74860. // If element hover will move to a hoverLayer.
  74861. if (!isUseHoverLayer(api)) {
  74862. api.dispatchAction({
  74863. type: 'downplay',
  74864. seriesName: seriesName,
  74865. name: dataName,
  74866. excludeSeriesId: excludeSeriesId
  74867. });
  74868. }
  74869. }
  74870. /*
  74871. * Licensed to the Apache Software Foundation (ASF) under one
  74872. * or more contributor license agreements. See the NOTICE file
  74873. * distributed with this work for additional information
  74874. * regarding copyright ownership. The ASF licenses this file
  74875. * to you under the Apache License, Version 2.0 (the
  74876. * "License"); you may not use this file except in compliance
  74877. * with the License. You may obtain a copy of the License at
  74878. *
  74879. * http://www.apache.org/licenses/LICENSE-2.0
  74880. *
  74881. * Unless required by applicable law or agreed to in writing,
  74882. * software distributed under the License is distributed on an
  74883. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74884. * KIND, either express or implied. See the License for the
  74885. * specific language governing permissions and limitations
  74886. * under the License.
  74887. */
  74888. /**
  74889. * AUTO-GENERATED FILE. DO NOT MODIFY.
  74890. */
  74891. /*
  74892. * Licensed to the Apache Software Foundation (ASF) under one
  74893. * or more contributor license agreements. See the NOTICE file
  74894. * distributed with this work for additional information
  74895. * regarding copyright ownership. The ASF licenses this file
  74896. * to you under the Apache License, Version 2.0 (the
  74897. * "License"); you may not use this file except in compliance
  74898. * with the License. You may obtain a copy of the License at
  74899. *
  74900. * http://www.apache.org/licenses/LICENSE-2.0
  74901. *
  74902. * Unless required by applicable law or agreed to in writing,
  74903. * software distributed under the License is distributed on an
  74904. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74905. * KIND, either express or implied. See the License for the
  74906. * specific language governing permissions and limitations
  74907. * under the License.
  74908. */
  74909. function legendFilter(ecModel) {
  74910. var legendModels = ecModel.findComponents({
  74911. mainType: 'legend'
  74912. });
  74913. if (legendModels && legendModels.length) {
  74914. ecModel.filterSeries(function (series) {
  74915. // If in any legend component the status is not selected.
  74916. // Because in legend series is assumed selected when it is not in the legend data.
  74917. for (var i = 0; i < legendModels.length; i++) {
  74918. if (!legendModels[i].isSelected(series.name)) {
  74919. return false;
  74920. }
  74921. }
  74922. return true;
  74923. });
  74924. }
  74925. }
  74926. function legendSelectActionHandler(methodName, payload, ecModel) {
  74927. var selectedMap = {};
  74928. var isToggleSelect = methodName === 'toggleSelected';
  74929. var isSelected; // Update all legend components
  74930. ecModel.eachComponent('legend', function (legendModel) {
  74931. if (isToggleSelect && isSelected != null) {
  74932. // Force other legend has same selected status
  74933. // Or the first is toggled to true and other are toggled to false
  74934. // In the case one legend has some item unSelected in option. And if other legend
  74935. // doesn't has the item, they will assume it is selected.
  74936. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  74937. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  74938. legendModel[methodName]();
  74939. } else {
  74940. legendModel[methodName](payload.name);
  74941. isSelected = legendModel.isSelected(payload.name);
  74942. }
  74943. var legendData = legendModel.getData();
  74944. each(legendData, function (model) {
  74945. var name = model.get('name'); // Wrap element
  74946. if (name === '\n' || name === '') {
  74947. return;
  74948. }
  74949. var isItemSelected = legendModel.isSelected(name);
  74950. if (selectedMap.hasOwnProperty(name)) {
  74951. // Unselected if any legend is unselected
  74952. selectedMap[name] = selectedMap[name] && isItemSelected;
  74953. } else {
  74954. selectedMap[name] = isItemSelected;
  74955. }
  74956. });
  74957. }); // Return the event explicitly
  74958. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  74959. selected: selectedMap
  74960. } : {
  74961. name: payload.name,
  74962. selected: selectedMap
  74963. };
  74964. }
  74965. function installLegendAction(registers) {
  74966. /**
  74967. * @event legendToggleSelect
  74968. * @type {Object}
  74969. * @property {string} type 'legendToggleSelect'
  74970. * @property {string} [from]
  74971. * @property {string} name Series name or data item name
  74972. */
  74973. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  74974. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  74975. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  74976. /**
  74977. * @event legendSelect
  74978. * @type {Object}
  74979. * @property {string} type 'legendSelect'
  74980. * @property {string} name Series name or data item name
  74981. */
  74982. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  74983. /**
  74984. * @event legendUnSelect
  74985. * @type {Object}
  74986. * @property {string} type 'legendUnSelect'
  74987. * @property {string} name Series name or data item name
  74988. */
  74989. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  74990. }
  74991. function install$H(registers) {
  74992. registers.registerComponentModel(LegendModel);
  74993. registers.registerComponentView(LegendView);
  74994. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  74995. registers.registerSubTypeDefaulter('legend', function () {
  74996. return 'plain';
  74997. });
  74998. installLegendAction(registers);
  74999. }
  75000. var ScrollableLegendModel =
  75001. /** @class */
  75002. function (_super) {
  75003. __extends(ScrollableLegendModel, _super);
  75004. function ScrollableLegendModel() {
  75005. var _this = _super !== null && _super.apply(this, arguments) || this;
  75006. _this.type = ScrollableLegendModel.type;
  75007. return _this;
  75008. }
  75009. /**
  75010. * @param {number} scrollDataIndex
  75011. */
  75012. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  75013. this.option.scrollDataIndex = scrollDataIndex;
  75014. };
  75015. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  75016. var inputPositionParams = getLayoutParams(option);
  75017. _super.prototype.init.call(this, option, parentModel, ecModel);
  75018. mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams);
  75019. };
  75020. /**
  75021. * @override
  75022. */
  75023. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  75024. _super.prototype.mergeOption.call(this, option, ecModel);
  75025. mergeAndNormalizeLayoutParams$1(this, this.option, option);
  75026. };
  75027. ScrollableLegendModel.type = 'legend.scroll';
  75028. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  75029. scrollDataIndex: 0,
  75030. pageButtonItemGap: 5,
  75031. pageButtonGap: null,
  75032. pageButtonPosition: 'end',
  75033. pageFormatter: '{current}/{total}',
  75034. pageIcons: {
  75035. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  75036. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  75037. },
  75038. pageIconColor: '#2f4554',
  75039. pageIconInactiveColor: '#aaa',
  75040. pageIconSize: 15,
  75041. pageTextStyle: {
  75042. color: '#333'
  75043. },
  75044. animationDurationUpdate: 800
  75045. });
  75046. return ScrollableLegendModel;
  75047. }(LegendModel);
  75048. function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) {
  75049. var orient = legendModel.getOrient();
  75050. var ignoreSize = [1, 1];
  75051. ignoreSize[orient.index] = 0;
  75052. mergeLayoutParam(target, raw, {
  75053. type: 'box',
  75054. ignoreSize: !!ignoreSize
  75055. });
  75056. }
  75057. var Group$3 = Group;
  75058. var WH$1 = ['width', 'height'];
  75059. var XY$1 = ['x', 'y'];
  75060. var ScrollableLegendView =
  75061. /** @class */
  75062. function (_super) {
  75063. __extends(ScrollableLegendView, _super);
  75064. function ScrollableLegendView() {
  75065. var _this = _super !== null && _super.apply(this, arguments) || this;
  75066. _this.type = ScrollableLegendView.type;
  75067. _this.newlineDisabled = true;
  75068. _this._currentIndex = 0;
  75069. return _this;
  75070. }
  75071. ScrollableLegendView.prototype.init = function () {
  75072. _super.prototype.init.call(this);
  75073. this.group.add(this._containerGroup = new Group$3());
  75074. this._containerGroup.add(this.getContentGroup());
  75075. this.group.add(this._controllerGroup = new Group$3());
  75076. };
  75077. /**
  75078. * @override
  75079. */
  75080. ScrollableLegendView.prototype.resetInner = function () {
  75081. _super.prototype.resetInner.call(this);
  75082. this._controllerGroup.removeAll();
  75083. this._containerGroup.removeClipPath();
  75084. this._containerGroup.__rectSize = null;
  75085. };
  75086. /**
  75087. * @override
  75088. */
  75089. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  75090. var self = this; // Render content items.
  75091. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  75092. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  75093. // e.g., '3/12345' should not overlap with the control arrow button.
  75094. var pageIconSize = legendModel.get('pageIconSize', true);
  75095. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  75096. createPageButton('pagePrev', 0);
  75097. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  75098. controllerGroup.add(new ZRText({
  75099. name: 'pageText',
  75100. style: {
  75101. // Placeholder to calculate a proper layout.
  75102. text: 'xx/xx',
  75103. fill: pageTextStyleModel.getTextColor(),
  75104. font: pageTextStyleModel.getFont(),
  75105. verticalAlign: 'middle',
  75106. align: 'center'
  75107. },
  75108. silent: true
  75109. }));
  75110. createPageButton('pageNext', 1);
  75111. function createPageButton(name, iconIdx) {
  75112. var pageDataIndexName = name + 'DataIndex';
  75113. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  75114. // Buttons will be created in each render, so we do not need
  75115. // to worry about avoiding using legendModel kept in scope.
  75116. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  75117. }, {
  75118. x: -pageIconSizeArr[0] / 2,
  75119. y: -pageIconSizeArr[1] / 2,
  75120. width: pageIconSizeArr[0],
  75121. height: pageIconSizeArr[1]
  75122. });
  75123. icon.name = name;
  75124. controllerGroup.add(icon);
  75125. }
  75126. };
  75127. /**
  75128. * @override
  75129. */
  75130. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  75131. var selectorGroup = this.getSelectorGroup();
  75132. var orientIdx = legendModel.getOrient().index;
  75133. var wh = WH$1[orientIdx];
  75134. var xy = XY$1[orientIdx];
  75135. var hw = WH$1[1 - orientIdx];
  75136. var yx = XY$1[1 - orientIdx];
  75137. selector && box( // Buttons in selectorGroup always layout horizontally
  75138. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  75139. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  75140. var selectorRect = selectorGroup.getBoundingRect();
  75141. var selectorPos = [-selectorRect.x, -selectorRect.y];
  75142. var processMaxSize = clone(maxSize);
  75143. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  75144. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  75145. if (selector) {
  75146. if (selectorPosition === 'end') {
  75147. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  75148. } else {
  75149. var offset = selectorRect[wh] + selectorButtonGap;
  75150. selectorPos[orientIdx] -= offset;
  75151. mainRect[xy] -= offset;
  75152. }
  75153. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  75154. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  75155. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  75156. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  75157. selectorGroup.x = selectorPos[0];
  75158. selectorGroup.y = selectorPos[1];
  75159. selectorGroup.markRedraw();
  75160. }
  75161. return mainRect;
  75162. };
  75163. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  75164. var contentGroup = this.getContentGroup();
  75165. var containerGroup = this._containerGroup;
  75166. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  75167. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  75168. box( // Buttons in controller are layout always horizontally.
  75169. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  75170. var contentRect = contentGroup.getBoundingRect();
  75171. var controllerRect = controllerGroup.getBoundingRect();
  75172. var showController = this._showController = contentRect[wh] > maxSize[wh]; // In case that the inner elements of contentGroup layout do not based on [0, 0]
  75173. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  75174. // If first rendering, `contentGroup.position` is [0, 0], which
  75175. // does not make sense and may cause unexepcted animation if adopted.
  75176. if (!isFirstRender) {
  75177. contentPos[orientIdx] = contentGroup[xy];
  75178. } // Layout container group based on 0.
  75179. var containerPos = [0, 0];
  75180. var controllerPos = [-controllerRect.x, -controllerRect.y];
  75181. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  75182. if (showController) {
  75183. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  75184. if (pageButtonPosition === 'end') {
  75185. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  75186. } // controller is on the left / top.
  75187. else {
  75188. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  75189. }
  75190. } // Always align controller to content as 'middle'.
  75191. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  75192. contentGroup.setPosition(contentPos);
  75193. containerGroup.setPosition(containerPos);
  75194. controllerGroup.setPosition(controllerPos); // Calculate `mainRect` and set `clipPath`.
  75195. // mainRect should not be calculated by `this.group.getBoundingRect()`
  75196. // for sake of the overflow.
  75197. var mainRect = {
  75198. x: 0,
  75199. y: 0
  75200. }; // Consider content may be overflow (should be clipped).
  75201. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  75202. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  75203. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  75204. containerGroup.__rectSize = maxSize[wh];
  75205. if (showController) {
  75206. var clipShape = {
  75207. x: 0,
  75208. y: 0
  75209. };
  75210. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  75211. clipShape[hw] = mainRect[hw];
  75212. containerGroup.setClipPath(new Rect({
  75213. shape: clipShape
  75214. })); // Consider content may be larger than container, container rect
  75215. // can not be obtained from `containerGroup.getBoundingRect()`.
  75216. containerGroup.__rectSize = clipShape[wh];
  75217. } else {
  75218. // Do not remove or ignore controller. Keep them set as placeholders.
  75219. controllerGroup.eachChild(function (child) {
  75220. child.attr({
  75221. invisible: true,
  75222. silent: true
  75223. });
  75224. });
  75225. } // Content translate animation.
  75226. var pageInfo = this._getPageInfo(legendModel);
  75227. pageInfo.pageIndex != null && updateProps(contentGroup, {
  75228. x: pageInfo.contentPosition[0],
  75229. y: pageInfo.contentPosition[1]
  75230. }, // When switch from "show controller" to "not show controller", view should be
  75231. // updated immediately without animation, otherwise causes weird effect.
  75232. showController ? legendModel : null);
  75233. this._updatePageInfoView(legendModel, pageInfo);
  75234. return mainRect;
  75235. };
  75236. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  75237. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  75238. scrollDataIndex != null && api.dispatchAction({
  75239. type: 'legendScroll',
  75240. scrollDataIndex: scrollDataIndex,
  75241. legendId: legendModel.id
  75242. });
  75243. };
  75244. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  75245. var controllerGroup = this._controllerGroup;
  75246. each(['pagePrev', 'pageNext'], function (name) {
  75247. var key = name + 'DataIndex';
  75248. var canJump = pageInfo[key] != null;
  75249. var icon = controllerGroup.childOfName(name);
  75250. if (icon) {
  75251. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  75252. icon.cursor = canJump ? 'pointer' : 'default';
  75253. }
  75254. });
  75255. var pageText = controllerGroup.childOfName('pageText');
  75256. var pageFormatter = legendModel.get('pageFormatter');
  75257. var pageIndex = pageInfo.pageIndex;
  75258. var current = pageIndex != null ? pageIndex + 1 : 0;
  75259. var total = pageInfo.pageCount;
  75260. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  75261. current: current,
  75262. total: total
  75263. }));
  75264. };
  75265. /**
  75266. * contentPosition: Array.<number>, null when data item not found.
  75267. * pageIndex: number, null when data item not found.
  75268. * pageCount: number, always be a number, can be 0.
  75269. * pagePrevDataIndex: number, null when no previous page.
  75270. * pageNextDataIndex: number, null when no next page.
  75271. * }
  75272. */
  75273. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  75274. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  75275. var contentGroup = this.getContentGroup();
  75276. var containerRectSize = this._containerGroup.__rectSize;
  75277. var orientIdx = legendModel.getOrient().index;
  75278. var wh = WH$1[orientIdx];
  75279. var xy = XY$1[orientIdx];
  75280. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  75281. var children = contentGroup.children();
  75282. var targetItem = children[targetItemIndex];
  75283. var itemCount = children.length;
  75284. var pCount = !itemCount ? 0 : 1;
  75285. var result = {
  75286. contentPosition: [contentGroup.x, contentGroup.y],
  75287. pageCount: pCount,
  75288. pageIndex: pCount - 1,
  75289. pagePrevDataIndex: null,
  75290. pageNextDataIndex: null
  75291. };
  75292. if (!targetItem) {
  75293. return result;
  75294. }
  75295. var targetItemInfo = getItemInfo(targetItem);
  75296. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  75297. // (1) Always align based on the left/top most item.
  75298. // (2) It is user-friendly that the last item shown in the
  75299. // current window is shown at the begining of next window.
  75300. // Otherwise if half of the last item is cut by the window,
  75301. // it will have no chance to display entirely.
  75302. // (3) Consider that item size probably be different, we
  75303. // have calculate pageIndex by size rather than item index,
  75304. // and we can not get page index directly by division.
  75305. // (4) The window is to narrow to contain more than
  75306. // one item, we should make sure that the page can be fliped.
  75307. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  75308. currItemInfo = getItemInfo(children[i]);
  75309. if ( // Half of the last item is out of the window.
  75310. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  75311. // can be started at the current item or the last item.
  75312. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  75313. if (winEndItemInfo.i > winStartItemInfo.i) {
  75314. winStartItemInfo = winEndItemInfo;
  75315. } else {
  75316. // e.g., when page size is smaller than item size.
  75317. winStartItemInfo = currItemInfo;
  75318. }
  75319. if (winStartItemInfo) {
  75320. if (result.pageNextDataIndex == null) {
  75321. result.pageNextDataIndex = winStartItemInfo.i;
  75322. }
  75323. ++result.pageCount;
  75324. }
  75325. }
  75326. winEndItemInfo = currItemInfo;
  75327. }
  75328. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  75329. currItemInfo = getItemInfo(children[i]);
  75330. if ( // If the the end item does not intersect with the window started
  75331. // from the current item, a page can be settled.
  75332. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  75333. winStartItemInfo.i < winEndItemInfo.i) {
  75334. winEndItemInfo = winStartItemInfo;
  75335. if (result.pagePrevDataIndex == null) {
  75336. result.pagePrevDataIndex = winStartItemInfo.i;
  75337. }
  75338. ++result.pageCount;
  75339. ++result.pageIndex;
  75340. }
  75341. winStartItemInfo = currItemInfo;
  75342. }
  75343. return result;
  75344. function getItemInfo(el) {
  75345. if (el) {
  75346. var itemRect = el.getBoundingRect();
  75347. var start = itemRect[xy] + el[xy];
  75348. return {
  75349. s: start,
  75350. e: start + itemRect[wh],
  75351. i: el.__legendDataIndex
  75352. };
  75353. }
  75354. }
  75355. function intersect(itemInfo, winStart) {
  75356. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  75357. }
  75358. };
  75359. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  75360. if (!this._showController) {
  75361. return 0;
  75362. }
  75363. var index;
  75364. var contentGroup = this.getContentGroup();
  75365. var defaultIndex;
  75366. contentGroup.eachChild(function (child, idx) {
  75367. var legendDataIdx = child.__legendDataIndex; // FIXME
  75368. // If the given targetDataIndex (from model) is illegal,
  75369. // we use defaultIndex. But the index on the legend model and
  75370. // action payload is still illegal. That case will not be
  75371. // changed until some scenario requires.
  75372. if (defaultIndex == null && legendDataIdx != null) {
  75373. defaultIndex = idx;
  75374. }
  75375. if (legendDataIdx === targetDataIndex) {
  75376. index = idx;
  75377. }
  75378. });
  75379. return index != null ? index : defaultIndex;
  75380. };
  75381. ScrollableLegendView.type = 'legend.scroll';
  75382. return ScrollableLegendView;
  75383. }(LegendView);
  75384. /*
  75385. * Licensed to the Apache Software Foundation (ASF) under one
  75386. * or more contributor license agreements. See the NOTICE file
  75387. * distributed with this work for additional information
  75388. * regarding copyright ownership. The ASF licenses this file
  75389. * to you under the Apache License, Version 2.0 (the
  75390. * "License"); you may not use this file except in compliance
  75391. * with the License. You may obtain a copy of the License at
  75392. *
  75393. * http://www.apache.org/licenses/LICENSE-2.0
  75394. *
  75395. * Unless required by applicable law or agreed to in writing,
  75396. * software distributed under the License is distributed on an
  75397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75398. * KIND, either express or implied. See the License for the
  75399. * specific language governing permissions and limitations
  75400. * under the License.
  75401. */
  75402. /**
  75403. * AUTO-GENERATED FILE. DO NOT MODIFY.
  75404. */
  75405. /*
  75406. * Licensed to the Apache Software Foundation (ASF) under one
  75407. * or more contributor license agreements. See the NOTICE file
  75408. * distributed with this work for additional information
  75409. * regarding copyright ownership. The ASF licenses this file
  75410. * to you under the Apache License, Version 2.0 (the
  75411. * "License"); you may not use this file except in compliance
  75412. * with the License. You may obtain a copy of the License at
  75413. *
  75414. * http://www.apache.org/licenses/LICENSE-2.0
  75415. *
  75416. * Unless required by applicable law or agreed to in writing,
  75417. * software distributed under the License is distributed on an
  75418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75419. * KIND, either express or implied. See the License for the
  75420. * specific language governing permissions and limitations
  75421. * under the License.
  75422. */
  75423. function installScrollableLegendAction(registers) {
  75424. /**
  75425. * @event legendScroll
  75426. * @type {Object}
  75427. * @property {string} type 'legendScroll'
  75428. * @property {string} scrollDataIndex
  75429. */
  75430. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  75431. var scrollDataIndex = payload.scrollDataIndex;
  75432. scrollDataIndex != null && ecModel.eachComponent({
  75433. mainType: 'legend',
  75434. subType: 'scroll',
  75435. query: payload
  75436. }, function (legendModel) {
  75437. legendModel.setScrollDataIndex(scrollDataIndex);
  75438. });
  75439. });
  75440. }
  75441. function install$I(registers) {
  75442. use(install$H);
  75443. registers.registerComponentModel(ScrollableLegendModel);
  75444. registers.registerComponentView(ScrollableLegendView);
  75445. installScrollableLegendAction(registers);
  75446. }
  75447. function install$J(registers) {
  75448. use(install$H);
  75449. use(install$I);
  75450. }
  75451. var InsideZoomModel =
  75452. /** @class */
  75453. function (_super) {
  75454. __extends(InsideZoomModel, _super);
  75455. function InsideZoomModel() {
  75456. var _this = _super !== null && _super.apply(this, arguments) || this;
  75457. _this.type = InsideZoomModel.type;
  75458. return _this;
  75459. }
  75460. InsideZoomModel.type = 'dataZoom.inside';
  75461. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  75462. disabled: false,
  75463. zoomLock: false,
  75464. zoomOnMouseWheel: true,
  75465. moveOnMouseMove: true,
  75466. moveOnMouseWheel: false,
  75467. preventDefaultMouseMove: true
  75468. });
  75469. return InsideZoomModel;
  75470. }(DataZoomModel);
  75471. var inner$k = makeInner();
  75472. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  75473. inner$k(api).coordSysRecordMap.each(function (coordSysRecord) {
  75474. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  75475. if (dzInfo) {
  75476. dzInfo.getRange = getRange;
  75477. }
  75478. });
  75479. }
  75480. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  75481. var coordSysRecordMap = inner$k(api).coordSysRecordMap;
  75482. var coordSysKeyArr = coordSysRecordMap.keys();
  75483. for (var i = 0; i < coordSysKeyArr.length; i++) {
  75484. var coordSysKey = coordSysKeyArr[i];
  75485. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  75486. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  75487. if (dataZoomInfoMap) {
  75488. var dzUid = dataZoomModel.uid;
  75489. var dzInfo = dataZoomInfoMap.get(dzUid);
  75490. if (dzInfo) {
  75491. dataZoomInfoMap.removeKey(dzUid);
  75492. if (!dataZoomInfoMap.keys().length) {
  75493. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  75494. }
  75495. }
  75496. }
  75497. }
  75498. }
  75499. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  75500. if (coordSysRecord) {
  75501. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  75502. var controller = coordSysRecord.controller;
  75503. controller && controller.dispose();
  75504. }
  75505. }
  75506. function createCoordSysRecord(api, coordSysModel) {
  75507. // These init props will never change after record created.
  75508. var coordSysRecord = {
  75509. model: coordSysModel,
  75510. containsPoint: curry(containsPoint, coordSysModel),
  75511. dispatchAction: curry(dispatchAction$1, api),
  75512. dataZoomInfoMap: null,
  75513. controller: null
  75514. }; // Must not do anything depends on coordSysRecord outside the event handler here,
  75515. // because coordSysRecord not completed yet.
  75516. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  75517. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  75518. controller.on(eventName, function (event) {
  75519. var batch = [];
  75520. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  75521. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  75522. // moveOnMouseWheel, ...) enabled.
  75523. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  75524. return;
  75525. }
  75526. var method = (dzInfo.getRange || {})[eventName];
  75527. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  75528. !dzInfo.model.get('disabled', true) && range && batch.push({
  75529. dataZoomId: dzInfo.model.id,
  75530. start: range[0],
  75531. end: range[1]
  75532. });
  75533. });
  75534. batch.length && coordSysRecord.dispatchAction(batch);
  75535. });
  75536. });
  75537. return coordSysRecord;
  75538. }
  75539. /**
  75540. * This action will be throttled.
  75541. */
  75542. function dispatchAction$1(api, batch) {
  75543. api.dispatchAction({
  75544. type: 'dataZoom',
  75545. animation: {
  75546. easing: 'cubicOut',
  75547. duration: 100
  75548. },
  75549. batch: batch
  75550. });
  75551. }
  75552. function containsPoint(coordSysModel, e, x, y) {
  75553. return coordSysModel.coordinateSystem.containPoint([x, y]);
  75554. }
  75555. /**
  75556. * Merge roamController settings when multiple dataZooms share one roamController.
  75557. */
  75558. function mergeControllerParams(dataZoomInfoMap) {
  75559. var controlType; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  75560. // as string, it is probably revert to reserved word by compress tool. See #7411.
  75561. var prefix = 'type_';
  75562. var typePriority = {
  75563. 'type_true': 2,
  75564. 'type_move': 1,
  75565. 'type_false': 0,
  75566. 'type_undefined': -1
  75567. };
  75568. var preventDefaultMouseMove = true;
  75569. dataZoomInfoMap.each(function (dataZoomInfo) {
  75570. var dataZoomModel = dataZoomInfo.model;
  75571. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  75572. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  75573. controlType = oneType;
  75574. } // Prevent default move event by default. If one false, do not prevent. Otherwise
  75575. // users may be confused why it does not work when multiple insideZooms exist.
  75576. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  75577. });
  75578. return {
  75579. controlType: controlType,
  75580. opt: {
  75581. // RoamController will enable all of these functionalities,
  75582. // and the final behavior is determined by its event listener
  75583. // provided by each inside zoom.
  75584. zoomOnMouseWheel: true,
  75585. moveOnMouseMove: true,
  75586. moveOnMouseWheel: true,
  75587. preventDefaultMouseMove: !!preventDefaultMouseMove
  75588. }
  75589. };
  75590. }
  75591. function installDataZoomRoamProcessor(registers) {
  75592. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  75593. var apiInner = inner$k(api);
  75594. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  75595. coordSysRecordMap.each(function (coordSysRecord) {
  75596. // `coordSysRecordMap` always exists (becuase it hold the `roam controller`, which should
  75597. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  75598. coordSysRecord.dataZoomInfoMap = null;
  75599. });
  75600. ecModel.eachComponent({
  75601. mainType: 'dataZoom',
  75602. subType: 'inside'
  75603. }, function (dataZoomModel) {
  75604. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  75605. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  75606. var coordSysUid = dzCoordSysInfo.model.uid;
  75607. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  75608. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap()); // Notice these props might be changed each time for a single dataZoomModel.
  75609. dataZoomInfoMap.set(dataZoomModel.uid, {
  75610. dzReferCoordSysInfo: dzCoordSysInfo,
  75611. model: dataZoomModel,
  75612. getRange: null
  75613. });
  75614. });
  75615. }); // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  75616. // (2) Clear coord sys if not refered by any dataZoom.
  75617. coordSysRecordMap.each(function (coordSysRecord) {
  75618. var controller = coordSysRecord.controller;
  75619. var firstDzInfo;
  75620. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  75621. if (dataZoomInfoMap) {
  75622. var firstDzKey = dataZoomInfoMap.keys()[0];
  75623. if (firstDzKey != null) {
  75624. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  75625. }
  75626. }
  75627. if (!firstDzInfo) {
  75628. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  75629. return;
  75630. }
  75631. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  75632. controller.enable(controllerParams.controlType, controllerParams.opt);
  75633. controller.setPointerChecker(coordSysRecord.containsPoint);
  75634. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  75635. });
  75636. });
  75637. }
  75638. var InsideZoomView =
  75639. /** @class */
  75640. function (_super) {
  75641. __extends(InsideZoomView, _super);
  75642. function InsideZoomView() {
  75643. var _this = _super !== null && _super.apply(this, arguments) || this;
  75644. _this.type = 'dataZoom.inside';
  75645. return _this;
  75646. }
  75647. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  75648. _super.prototype.render.apply(this, arguments);
  75649. if (dataZoomModel.noTarget()) {
  75650. this._clear();
  75651. return;
  75652. } // Hence the `throttle` util ensures to preserve command order,
  75653. // here simply updating range all the time will not cause missing
  75654. // any of the the roam change.
  75655. this.range = dataZoomModel.getPercentRange(); // Reset controllers.
  75656. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  75657. pan: bind(getRangeHandlers.pan, this),
  75658. zoom: bind(getRangeHandlers.zoom, this),
  75659. scrollMove: bind(getRangeHandlers.scrollMove, this)
  75660. });
  75661. };
  75662. InsideZoomView.prototype.dispose = function () {
  75663. this._clear();
  75664. _super.prototype.dispose.apply(this, arguments);
  75665. };
  75666. InsideZoomView.prototype._clear = function () {
  75667. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  75668. this.range = null;
  75669. };
  75670. InsideZoomView.type = 'dataZoom.inside';
  75671. return InsideZoomView;
  75672. }(DataZoomView);
  75673. var getRangeHandlers = {
  75674. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  75675. var lastRange = this.range;
  75676. var range = lastRange.slice(); // Calculate transform by the first axis.
  75677. var axisModel = coordSysInfo.axisModels[0];
  75678. if (!axisModel) {
  75679. return;
  75680. }
  75681. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  75682. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  75683. var scale = Math.max(1 / e.scale, 0);
  75684. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  75685. range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range.
  75686. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  75687. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  75688. this.range = range;
  75689. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  75690. return range;
  75691. }
  75692. },
  75693. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  75694. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  75695. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  75696. }),
  75697. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  75698. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  75699. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  75700. })
  75701. };
  75702. function makeMover(getPercentDelta) {
  75703. return function (coordSysInfo, coordSysMainType, controller, e) {
  75704. var lastRange = this.range;
  75705. var range = lastRange.slice(); // Calculate transform by the first axis.
  75706. var axisModel = coordSysInfo.axisModels[0];
  75707. if (!axisModel) {
  75708. return;
  75709. }
  75710. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  75711. sliderMove(percentDelta, range, [0, 100], 'all');
  75712. this.range = range;
  75713. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  75714. return range;
  75715. }
  75716. };
  75717. }
  75718. var getDirectionInfo = {
  75719. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  75720. var axis = axisModel.axis;
  75721. var ret = {};
  75722. var rect = coordSysInfo.model.coordinateSystem.getRect();
  75723. oldPoint = oldPoint || [0, 0];
  75724. if (axis.dim === 'x') {
  75725. ret.pixel = newPoint[0] - oldPoint[0];
  75726. ret.pixelLength = rect.width;
  75727. ret.pixelStart = rect.x;
  75728. ret.signal = axis.inverse ? 1 : -1;
  75729. } else {
  75730. // axis.dim === 'y'
  75731. ret.pixel = newPoint[1] - oldPoint[1];
  75732. ret.pixelLength = rect.height;
  75733. ret.pixelStart = rect.y;
  75734. ret.signal = axis.inverse ? -1 : 1;
  75735. }
  75736. return ret;
  75737. },
  75738. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  75739. var axis = axisModel.axis;
  75740. var ret = {};
  75741. var polar = coordSysInfo.model.coordinateSystem;
  75742. var radiusExtent = polar.getRadiusAxis().getExtent();
  75743. var angleExtent = polar.getAngleAxis().getExtent();
  75744. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  75745. newPoint = polar.pointToCoord(newPoint);
  75746. if (axisModel.mainType === 'radiusAxis') {
  75747. ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  75748. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  75749. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  75750. ret.pixelStart = radiusExtent[0];
  75751. ret.signal = axis.inverse ? 1 : -1;
  75752. } else {
  75753. // 'angleAxis'
  75754. ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  75755. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  75756. ret.pixelLength = angleExtent[1] - angleExtent[0];
  75757. ret.pixelStart = angleExtent[0];
  75758. ret.signal = axis.inverse ? -1 : 1;
  75759. }
  75760. return ret;
  75761. },
  75762. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  75763. var axis = axisModel.axis;
  75764. var rect = coordSysInfo.model.coordinateSystem.getRect();
  75765. var ret = {};
  75766. oldPoint = oldPoint || [0, 0];
  75767. if (axis.orient === 'horizontal') {
  75768. ret.pixel = newPoint[0] - oldPoint[0];
  75769. ret.pixelLength = rect.width;
  75770. ret.pixelStart = rect.x;
  75771. ret.signal = axis.inverse ? 1 : -1;
  75772. } else {
  75773. // 'vertical'
  75774. ret.pixel = newPoint[1] - oldPoint[1];
  75775. ret.pixelLength = rect.height;
  75776. ret.pixelStart = rect.y;
  75777. ret.signal = axis.inverse ? -1 : 1;
  75778. }
  75779. return ret;
  75780. }
  75781. };
  75782. function install$K(registers) {
  75783. installCommon(registers);
  75784. registers.registerComponentModel(InsideZoomModel);
  75785. registers.registerComponentView(InsideZoomView);
  75786. installDataZoomRoamProcessor(registers);
  75787. }
  75788. var SliderZoomModel =
  75789. /** @class */
  75790. function (_super) {
  75791. __extends(SliderZoomModel, _super);
  75792. function SliderZoomModel() {
  75793. var _this = _super !== null && _super.apply(this, arguments) || this;
  75794. _this.type = SliderZoomModel.type;
  75795. return _this;
  75796. }
  75797. SliderZoomModel.type = 'dataZoom.slider';
  75798. SliderZoomModel.layoutMode = 'box';
  75799. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  75800. show: true,
  75801. // deault value can only be drived in view stage.
  75802. right: 'ph',
  75803. top: 'ph',
  75804. width: 'ph',
  75805. height: 'ph',
  75806. left: null,
  75807. bottom: null,
  75808. borderColor: '#d2dbee',
  75809. borderRadius: 3,
  75810. backgroundColor: 'rgba(47,69,84,0)',
  75811. // dataBackgroundColor: '#ddd',
  75812. dataBackground: {
  75813. lineStyle: {
  75814. color: '#d2dbee',
  75815. width: 0.5
  75816. },
  75817. areaStyle: {
  75818. color: '#d2dbee',
  75819. opacity: 0.2
  75820. }
  75821. },
  75822. selectedDataBackground: {
  75823. lineStyle: {
  75824. color: '#8fb0f7',
  75825. width: 0.5
  75826. },
  75827. areaStyle: {
  75828. color: '#8fb0f7',
  75829. opacity: 0.2
  75830. }
  75831. },
  75832. // Color of selected window.
  75833. fillerColor: 'rgba(135,175,274,0.2)',
  75834. 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',
  75835. // Percent of the slider height
  75836. handleSize: '100%',
  75837. handleStyle: {
  75838. color: '#fff',
  75839. borderColor: '#ACB8D1'
  75840. },
  75841. moveHandleSize: 7,
  75842. 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',
  75843. moveHandleStyle: {
  75844. color: '#D2DBEE',
  75845. opacity: 0.7
  75846. },
  75847. showDetail: true,
  75848. showDataShadow: 'auto',
  75849. realtime: true,
  75850. zoomLock: false,
  75851. textStyle: {
  75852. color: '#6E7079'
  75853. },
  75854. brushSelect: true,
  75855. brushStyle: {
  75856. color: 'rgba(135,175,274,0.15)'
  75857. },
  75858. emphasis: {
  75859. handleStyle: {
  75860. borderColor: '#8FB0F7'
  75861. },
  75862. moveHandleStyle: {
  75863. color: '#8FB0F7'
  75864. }
  75865. }
  75866. });
  75867. return SliderZoomModel;
  75868. }(DataZoomModel);
  75869. var Rect$2 = Rect; // Constants
  75870. var DEFAULT_LOCATION_EDGE_GAP = 7;
  75871. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  75872. var DEFAULT_FILLER_SIZE = 30;
  75873. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  75874. var HORIZONTAL = 'horizontal';
  75875. var VERTICAL = 'vertical';
  75876. var LABEL_GAP = 5;
  75877. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  75878. var REALTIME_ANIMATION_CONFIG = {
  75879. easing: 'cubicOut',
  75880. duration: 100,
  75881. delay: 0
  75882. };
  75883. var SliderZoomView =
  75884. /** @class */
  75885. function (_super) {
  75886. __extends(SliderZoomView, _super);
  75887. function SliderZoomView() {
  75888. var _this = _super !== null && _super.apply(this, arguments) || this;
  75889. _this.type = SliderZoomView.type;
  75890. _this._displayables = {};
  75891. return _this;
  75892. }
  75893. SliderZoomView.prototype.init = function (ecModel, api) {
  75894. this.api = api; // A unique handler for each dataZoom component
  75895. this._onBrush = bind(this._onBrush, this);
  75896. this._onBrushEnd = bind(this._onBrushEnd, this);
  75897. };
  75898. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  75899. _super.prototype.render.apply(this, arguments);
  75900. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  75901. this._orient = dataZoomModel.getOrient();
  75902. if (dataZoomModel.get('show') === false) {
  75903. this.group.removeAll();
  75904. return;
  75905. }
  75906. if (dataZoomModel.noTarget()) {
  75907. this._clear();
  75908. this.group.removeAll();
  75909. return;
  75910. } // Notice: this._resetInterval() should not be executed when payload.type
  75911. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  75912. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  75913. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  75914. this._buildView();
  75915. }
  75916. this._updateView();
  75917. };
  75918. SliderZoomView.prototype.dispose = function () {
  75919. this._clear();
  75920. _super.prototype.dispose.apply(this, arguments);
  75921. };
  75922. SliderZoomView.prototype._clear = function () {
  75923. clear(this, '_dispatchZoomAction');
  75924. var zr = this.api.getZr();
  75925. zr.off('mousemove', this._onBrush);
  75926. zr.off('mouseup', this._onBrushEnd);
  75927. };
  75928. SliderZoomView.prototype._buildView = function () {
  75929. var thisGroup = this.group;
  75930. thisGroup.removeAll();
  75931. this._brushing = false;
  75932. this._displayables.brushRect = null;
  75933. this._resetLocation();
  75934. this._resetInterval();
  75935. var barGroup = this._displayables.sliderGroup = new Group();
  75936. this._renderBackground();
  75937. this._renderHandle();
  75938. this._renderDataShadow();
  75939. thisGroup.add(barGroup);
  75940. this._positionGroup();
  75941. };
  75942. SliderZoomView.prototype._resetLocation = function () {
  75943. var dataZoomModel = this.dataZoomModel;
  75944. var api = this.api;
  75945. var showMoveHandle = dataZoomModel.get('brushSelect');
  75946. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0; // If some of x/y/width/height are not specified,
  75947. // auto-adapt according to target grid.
  75948. var coordRect = this._findCoordRect();
  75949. var ecSize = {
  75950. width: api.getWidth(),
  75951. height: api.getHeight()
  75952. }; // Default align by coordinate system rect.
  75953. var positionInfo = this._orient === HORIZONTAL ? {
  75954. // Why using 'right', because right should be used in vertical,
  75955. // and it is better to be consistent for dealing with position param merge.
  75956. right: ecSize.width - coordRect.x - coordRect.width,
  75957. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  75958. width: coordRect.width,
  75959. height: DEFAULT_FILLER_SIZE
  75960. } : {
  75961. right: DEFAULT_LOCATION_EDGE_GAP,
  75962. top: coordRect.y,
  75963. width: DEFAULT_FILLER_SIZE,
  75964. height: coordRect.height
  75965. }; // Do not write back to option and replace value 'ph', because
  75966. // the 'ph' value should be recalculated when resize.
  75967. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
  75968. each(['right', 'top', 'width', 'height'], function (name) {
  75969. if (layoutParams[name] === 'ph') {
  75970. layoutParams[name] = positionInfo[name];
  75971. }
  75972. });
  75973. var layoutRect = getLayoutRect(layoutParams, ecSize);
  75974. this._location = {
  75975. x: layoutRect.x,
  75976. y: layoutRect.y
  75977. };
  75978. this._size = [layoutRect.width, layoutRect.height];
  75979. this._orient === VERTICAL && this._size.reverse();
  75980. };
  75981. SliderZoomView.prototype._positionGroup = function () {
  75982. var thisGroup = this.group;
  75983. var location = this._location;
  75984. var orient = this._orient; // Just use the first axis to determine mapping.
  75985. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  75986. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  75987. var sliderGroup = this._displayables.sliderGroup;
  75988. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
  75989. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  75990. scaleY: otherAxisInverse ? 1 : -1,
  75991. scaleX: 1
  75992. } : orient === HORIZONTAL && inverse ? {
  75993. scaleY: otherAxisInverse ? 1 : -1,
  75994. scaleX: -1
  75995. } : orient === VERTICAL && !inverse ? {
  75996. scaleY: otherAxisInverse ? -1 : 1,
  75997. scaleX: 1,
  75998. rotation: Math.PI / 2
  75999. } // Dont use Math.PI, considering shadow direction.
  76000. : {
  76001. scaleY: otherAxisInverse ? -1 : 1,
  76002. scaleX: -1,
  76003. rotation: Math.PI / 2
  76004. }); // Position barGroup
  76005. var rect = thisGroup.getBoundingRect([sliderGroup]);
  76006. thisGroup.x = location.x - rect.x;
  76007. thisGroup.y = location.y - rect.y;
  76008. thisGroup.markRedraw();
  76009. };
  76010. SliderZoomView.prototype._getViewExtent = function () {
  76011. return [0, this._size[0]];
  76012. };
  76013. SliderZoomView.prototype._renderBackground = function () {
  76014. var dataZoomModel = this.dataZoomModel;
  76015. var size = this._size;
  76016. var barGroup = this._displayables.sliderGroup;
  76017. var brushSelect = dataZoomModel.get('brushSelect');
  76018. barGroup.add(new Rect$2({
  76019. silent: true,
  76020. shape: {
  76021. x: 0,
  76022. y: 0,
  76023. width: size[0],
  76024. height: size[1]
  76025. },
  76026. style: {
  76027. fill: dataZoomModel.get('backgroundColor')
  76028. },
  76029. z2: -40
  76030. })); // Click panel, over shadow, below handles.
  76031. var clickPanel = new Rect$2({
  76032. shape: {
  76033. x: 0,
  76034. y: 0,
  76035. width: size[0],
  76036. height: size[1]
  76037. },
  76038. style: {
  76039. fill: 'transparent'
  76040. },
  76041. z2: 0,
  76042. onclick: bind(this._onClickPanel, this)
  76043. });
  76044. var zr = this.api.getZr();
  76045. if (brushSelect) {
  76046. clickPanel.on('mousedown', this._onBrushStart, this);
  76047. clickPanel.cursor = 'crosshair';
  76048. zr.on('mousemove', this._onBrush);
  76049. zr.on('mouseup', this._onBrushEnd);
  76050. } else {
  76051. zr.off('mousemove', this._onBrush);
  76052. zr.off('mouseup', this._onBrushEnd);
  76053. }
  76054. barGroup.add(clickPanel);
  76055. };
  76056. SliderZoomView.prototype._renderDataShadow = function () {
  76057. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  76058. this._displayables.dataShadowSegs = [];
  76059. if (!info) {
  76060. return;
  76061. }
  76062. var size = this._size;
  76063. var seriesModel = info.series;
  76064. var data = seriesModel.getRawData();
  76065. var otherDim = seriesModel.getShadowDim ? seriesModel.getShadowDim() // @see candlestick
  76066. : info.otherDim;
  76067. if (otherDim == null) {
  76068. return;
  76069. }
  76070. var otherDataExtent = data.getDataExtent(otherDim); // Nice extent.
  76071. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  76072. otherDataExtent = [otherDataExtent[0] - otherOffset, otherDataExtent[1] + otherOffset];
  76073. var otherShadowExtent = [0, size[1]];
  76074. var thisShadowExtent = [0, size[0]];
  76075. var areaPoints = [[size[0], 0], [0, 0]];
  76076. var linePoints = [];
  76077. var step = thisShadowExtent[1] / (data.count() - 1);
  76078. var thisCoord = 0; // Optimize for large data shadow
  76079. var stride = Math.round(data.count() / size[0]);
  76080. var lastIsEmpty;
  76081. data.each([otherDim], function (value, index) {
  76082. if (stride > 0 && index % stride) {
  76083. thisCoord += step;
  76084. return;
  76085. } // FIXME
  76086. // Should consider axis.min/axis.max when drawing dataShadow.
  76087. // FIXME
  76088. // 应该使用统一的空判断?还是在list里进行空判断?
  76089. var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
  76090. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent, otherShadowExtent, true); // Attempt to draw data shadow precisely when there are empty value.
  76091. if (isEmpty && !lastIsEmpty && index) {
  76092. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  76093. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  76094. } else if (!isEmpty && lastIsEmpty) {
  76095. areaPoints.push([thisCoord, 0]);
  76096. linePoints.push([thisCoord, 0]);
  76097. }
  76098. areaPoints.push([thisCoord, otherCoord]);
  76099. linePoints.push([thisCoord, otherCoord]);
  76100. thisCoord += step;
  76101. lastIsEmpty = isEmpty;
  76102. });
  76103. var dataZoomModel = this.dataZoomModel;
  76104. function createDataShadowGroup(isSelectedArea) {
  76105. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  76106. var group = new Group();
  76107. var polygon = new Polygon({
  76108. shape: {
  76109. points: areaPoints
  76110. },
  76111. segmentIgnoreThreshold: 1,
  76112. style: model.getModel('areaStyle').getAreaStyle(),
  76113. silent: true,
  76114. z2: -20
  76115. });
  76116. var polyline = new Polyline({
  76117. shape: {
  76118. points: linePoints
  76119. },
  76120. segmentIgnoreThreshold: 1,
  76121. style: model.getModel('lineStyle').getLineStyle(),
  76122. silent: true,
  76123. z2: -19
  76124. });
  76125. group.add(polygon);
  76126. group.add(polyline);
  76127. return group;
  76128. } // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  76129. for (var i = 0; i < 3; i++) {
  76130. var group = createDataShadowGroup(i === 1);
  76131. this._displayables.sliderGroup.add(group);
  76132. this._displayables.dataShadowSegs.push(group);
  76133. }
  76134. };
  76135. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  76136. var dataZoomModel = this.dataZoomModel;
  76137. var showDataShadow = dataZoomModel.get('showDataShadow');
  76138. if (showDataShadow === false) {
  76139. return;
  76140. } // Find a representative series.
  76141. var result;
  76142. var ecModel = this.ecModel;
  76143. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  76144. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  76145. each(seriesModels, function (seriesModel) {
  76146. if (result) {
  76147. return;
  76148. }
  76149. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  76150. return;
  76151. }
  76152. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  76153. var otherDim = getOtherDim(axisDim);
  76154. var otherAxisInverse;
  76155. var coordSys = seriesModel.coordinateSystem;
  76156. if (otherDim != null && coordSys.getOtherAxis) {
  76157. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  76158. }
  76159. otherDim = seriesModel.getData().mapDimension(otherDim);
  76160. result = {
  76161. thisAxis: thisAxis,
  76162. series: seriesModel,
  76163. thisDim: axisDim,
  76164. otherDim: otherDim,
  76165. otherAxisInverse: otherAxisInverse
  76166. };
  76167. }, this);
  76168. }, this);
  76169. return result;
  76170. };
  76171. SliderZoomView.prototype._renderHandle = function () {
  76172. var thisGroup = this.group;
  76173. var displayables = this._displayables;
  76174. var handles = displayables.handles = [null, null];
  76175. var handleLabels = displayables.handleLabels = [null, null];
  76176. var sliderGroup = this._displayables.sliderGroup;
  76177. var size = this._size;
  76178. var dataZoomModel = this.dataZoomModel;
  76179. var api = this.api;
  76180. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  76181. var brushSelect = dataZoomModel.get('brushSelect');
  76182. var filler = displayables.filler = new Rect$2({
  76183. silent: brushSelect,
  76184. style: {
  76185. fill: dataZoomModel.get('fillerColor')
  76186. },
  76187. textConfig: {
  76188. position: 'inside'
  76189. }
  76190. });
  76191. sliderGroup.add(filler); // Frame border.
  76192. sliderGroup.add(new Rect$2({
  76193. silent: true,
  76194. subPixelOptimize: true,
  76195. shape: {
  76196. x: 0,
  76197. y: 0,
  76198. width: size[0],
  76199. height: size[1],
  76200. r: borderRadius
  76201. },
  76202. style: {
  76203. stroke: dataZoomModel.get('dataBackgroundColor') // deprecated option
  76204. || dataZoomModel.get('borderColor'),
  76205. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  76206. fill: 'rgba(0,0,0,0)'
  76207. }
  76208. })); // Left and right handle to resize
  76209. each([0, 1], function (handleIndex) {
  76210. var iconStr = dataZoomModel.get('handleIcon');
  76211. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  76212. // Compatitable with the old icon parsers. Which can use a path string without path://
  76213. iconStr = 'path://' + iconStr;
  76214. if ("development" !== 'production') {
  76215. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  76216. }
  76217. }
  76218. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  76219. path.attr({
  76220. cursor: getCursor(this._orient),
  76221. draggable: true,
  76222. drift: bind(this._onDragMove, this, handleIndex),
  76223. ondragend: bind(this._onDragEnd, this),
  76224. onmouseover: bind(this._showDataInfo, this, true),
  76225. onmouseout: bind(this._showDataInfo, this, false),
  76226. z2: 5
  76227. });
  76228. var bRect = path.getBoundingRect();
  76229. var handleSize = dataZoomModel.get('handleSize');
  76230. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  76231. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  76232. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  76233. path.style.strokeNoScale = true;
  76234. path.rectHover = true;
  76235. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  76236. enableHoverEmphasis(path);
  76237. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  76238. // Compatitable with previous version
  76239. if (handleColor != null) {
  76240. path.style.fill = handleColor;
  76241. }
  76242. sliderGroup.add(handles[handleIndex] = path);
  76243. var textStyleModel = dataZoomModel.getModel('textStyle');
  76244. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  76245. silent: true,
  76246. invisible: true,
  76247. style: createTextStyle(textStyleModel, {
  76248. x: 0,
  76249. y: 0,
  76250. text: '',
  76251. verticalAlign: 'middle',
  76252. align: 'center',
  76253. fill: textStyleModel.getTextColor(),
  76254. font: textStyleModel.getFont()
  76255. }),
  76256. z2: 10
  76257. }));
  76258. }, this); // Handle to move. Only visible when brushSelect is set true.
  76259. var actualMoveZone = filler;
  76260. if (brushSelect) {
  76261. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  76262. var moveHandle_1 = displayables.moveHandle = new Rect({
  76263. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  76264. silent: true,
  76265. shape: {
  76266. r: [0, 0, 2, 2],
  76267. y: size[1] - 0.5,
  76268. height: moveHandleHeight
  76269. }
  76270. });
  76271. var iconSize = moveHandleHeight * 0.8;
  76272. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  76273. moveHandleIcon.silent = true;
  76274. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  76275. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  76276. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  76277. actualMoveZone = displayables.moveZone = new Rect({
  76278. invisible: true,
  76279. shape: {
  76280. y: size[1] - moveZoneExpandSize,
  76281. height: moveHandleHeight + moveZoneExpandSize
  76282. }
  76283. });
  76284. actualMoveZone.on('mouseover', function () {
  76285. api.enterEmphasis(moveHandle_1);
  76286. }).on('mouseout', function () {
  76287. api.leaveEmphasis(moveHandle_1);
  76288. });
  76289. sliderGroup.add(moveHandle_1);
  76290. sliderGroup.add(moveHandleIcon);
  76291. sliderGroup.add(actualMoveZone);
  76292. }
  76293. actualMoveZone.attr({
  76294. draggable: true,
  76295. cursor: getCursor(this._orient),
  76296. drift: bind(this._onDragMove, this, 'all'),
  76297. ondragstart: bind(this._showDataInfo, this, true),
  76298. ondragend: bind(this._onDragEnd, this),
  76299. onmouseover: bind(this._showDataInfo, this, true),
  76300. onmouseout: bind(this._showDataInfo, this, false)
  76301. });
  76302. };
  76303. SliderZoomView.prototype._resetInterval = function () {
  76304. var range = this._range = this.dataZoomModel.getPercentRange();
  76305. var viewExtent = this._getViewExtent();
  76306. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  76307. };
  76308. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  76309. var dataZoomModel = this.dataZoomModel;
  76310. var handleEnds = this._handleEnds;
  76311. var viewExtend = this._getViewExtent();
  76312. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  76313. var percentExtent = [0, 100];
  76314. 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);
  76315. var lastRange = this._range;
  76316. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  76317. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  76318. };
  76319. SliderZoomView.prototype._updateView = function (nonRealtime) {
  76320. var displaybles = this._displayables;
  76321. var handleEnds = this._handleEnds;
  76322. var handleInterval = asc(handleEnds.slice());
  76323. var size = this._size;
  76324. each([0, 1], function (handleIndex) {
  76325. // Handles
  76326. var handle = displaybles.handles[handleIndex];
  76327. var handleHeight = this._handleHeight;
  76328. handle.attr({
  76329. scaleX: handleHeight / 2,
  76330. scaleY: handleHeight / 2,
  76331. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  76332. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  76333. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  76334. y: size[1] / 2 - handleHeight / 2
  76335. });
  76336. }, this); // Filler
  76337. displaybles.filler.setShape({
  76338. x: handleInterval[0],
  76339. y: 0,
  76340. width: handleInterval[1] - handleInterval[0],
  76341. height: size[1]
  76342. });
  76343. var viewExtent = {
  76344. x: handleInterval[0],
  76345. width: handleInterval[1] - handleInterval[0]
  76346. }; // Move handle
  76347. if (displaybles.moveHandle) {
  76348. displaybles.moveHandle.setShape(viewExtent);
  76349. displaybles.moveZone.setShape(viewExtent); // Force update path on the invisible object
  76350. displaybles.moveZone.getBoundingRect();
  76351. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  76352. } // update clip path of shadow.
  76353. var dataShadowSegs = displaybles.dataShadowSegs;
  76354. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  76355. for (var i = 0; i < dataShadowSegs.length; i++) {
  76356. var segGroup = dataShadowSegs[i];
  76357. var clipPath = segGroup.getClipPath();
  76358. if (!clipPath) {
  76359. clipPath = new Rect();
  76360. segGroup.setClipPath(clipPath);
  76361. }
  76362. clipPath.setShape({
  76363. x: segIntervals[i],
  76364. y: 0,
  76365. width: segIntervals[i + 1] - segIntervals[i],
  76366. height: size[1]
  76367. });
  76368. }
  76369. this._updateDataInfo(nonRealtime);
  76370. };
  76371. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  76372. var dataZoomModel = this.dataZoomModel;
  76373. var displaybles = this._displayables;
  76374. var handleLabels = displaybles.handleLabels;
  76375. var orient = this._orient;
  76376. var labelTexts = ['', '']; // FIXME
  76377. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  76378. if (dataZoomModel.get('showDetail')) {
  76379. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  76380. if (axisProxy) {
  76381. var axis = axisProxy.getAxisModel().axis;
  76382. var range = this._range;
  76383. var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  76384. ? axisProxy.calculateDataWindow({
  76385. start: range[0],
  76386. end: range[1]
  76387. }).valueWindow : axisProxy.getDataValueWindow();
  76388. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  76389. }
  76390. }
  76391. var orderedHandleEnds = asc(this._handleEnds.slice());
  76392. setLabel.call(this, 0);
  76393. setLabel.call(this, 1);
  76394. function setLabel(handleIndex) {
  76395. // Label
  76396. // Text should not transform by barGroup.
  76397. // Ignore handlers transform
  76398. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  76399. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  76400. var offset = this._handleWidth / 2 + LABEL_GAP;
  76401. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  76402. handleLabels[handleIndex].setStyle({
  76403. x: textPoint[0],
  76404. y: textPoint[1],
  76405. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  76406. align: orient === HORIZONTAL ? direction : 'center',
  76407. text: labelTexts[handleIndex]
  76408. });
  76409. }
  76410. };
  76411. SliderZoomView.prototype._formatLabel = function (value, axis) {
  76412. var dataZoomModel = this.dataZoomModel;
  76413. var labelFormatter = dataZoomModel.get('labelFormatter');
  76414. var labelPrecision = dataZoomModel.get('labelPrecision');
  76415. if (labelPrecision == null || labelPrecision === 'auto') {
  76416. labelPrecision = axis.getPixelPrecision();
  76417. }
  76418. var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
  76419. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  76420. value: Math.round(value)
  76421. }) // param of toFixed should less then 20.
  76422. : value.toFixed(Math.min(labelPrecision, 20));
  76423. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  76424. };
  76425. /**
  76426. * @param showOrHide true: show, false: hide
  76427. */
  76428. SliderZoomView.prototype._showDataInfo = function (showOrHide) {
  76429. // Always show when drgging.
  76430. showOrHide = this._dragging || showOrHide;
  76431. var displayables = this._displayables;
  76432. var handleLabels = displayables.handleLabels;
  76433. handleLabels[0].attr('invisible', !showOrHide);
  76434. handleLabels[1].attr('invisible', !showOrHide); // Highlight move handle
  76435. displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  76436. };
  76437. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  76438. this._dragging = true; // For mobile device, prevent screen slider on the button.
  76439. stop(event.event); // Transform dx, dy to bar coordination.
  76440. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  76441. var vertex = applyTransform$1([dx, dy], barTransform, true);
  76442. var changed = this._updateInterval(handleIndex, vertex[0]);
  76443. var realtime = this.dataZoomModel.get('realtime');
  76444. this._updateView(!realtime); // Avoid dispatch dataZoom repeatly but range not changed,
  76445. // which cause bad visual effect when progressive enabled.
  76446. changed && realtime && this._dispatchZoomAction(true);
  76447. };
  76448. SliderZoomView.prototype._onDragEnd = function () {
  76449. this._dragging = false;
  76450. this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when
  76451. // drag end will cause the whole view rerender, which is unnecessary.
  76452. var realtime = this.dataZoomModel.get('realtime');
  76453. !realtime && this._dispatchZoomAction(false);
  76454. };
  76455. SliderZoomView.prototype._onClickPanel = function (e) {
  76456. var size = this._size;
  76457. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  76458. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  76459. return;
  76460. }
  76461. var handleEnds = this._handleEnds;
  76462. var center = (handleEnds[0] + handleEnds[1]) / 2;
  76463. var changed = this._updateInterval('all', localPoint[0] - center);
  76464. this._updateView();
  76465. changed && this._dispatchZoomAction(false);
  76466. };
  76467. SliderZoomView.prototype._onBrushStart = function (e) {
  76468. var x = e.offsetX;
  76469. var y = e.offsetY;
  76470. this._brushStart = new Point(x, y);
  76471. this._brushing = true;
  76472. this._brushStartTime = +new Date(); // this._updateBrushRect(x, y);
  76473. };
  76474. SliderZoomView.prototype._onBrushEnd = function (e) {
  76475. if (!this._brushing) {
  76476. return;
  76477. }
  76478. var brushRect = this._displayables.brushRect;
  76479. this._brushing = false;
  76480. if (!brushRect) {
  76481. return;
  76482. }
  76483. brushRect.attr('ignore', true);
  76484. var brushShape = brushRect.shape;
  76485. var brushEndTime = +new Date(); // console.log(brushEndTime - this._brushStartTime);
  76486. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  76487. // Will treat it as a click
  76488. return;
  76489. }
  76490. var viewExtend = this._getViewExtent();
  76491. var percentExtent = [0, 100];
  76492. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  76493. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  76494. this._updateView();
  76495. this._dispatchZoomAction(false);
  76496. };
  76497. SliderZoomView.prototype._onBrush = function (e) {
  76498. if (this._brushing) {
  76499. // For mobile device, prevent screen slider on the button.
  76500. stop(e.event);
  76501. this._updateBrushRect(e.offsetX, e.offsetY);
  76502. }
  76503. };
  76504. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  76505. var displayables = this._displayables;
  76506. var dataZoomModel = this.dataZoomModel;
  76507. var brushRect = displayables.brushRect;
  76508. if (!brushRect) {
  76509. brushRect = displayables.brushRect = new Rect$2({
  76510. silent: true,
  76511. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  76512. });
  76513. displayables.sliderGroup.add(brushRect);
  76514. }
  76515. brushRect.attr('ignore', false);
  76516. var brushStart = this._brushStart;
  76517. var sliderGroup = this._displayables.sliderGroup;
  76518. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  76519. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  76520. var size = this._size;
  76521. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  76522. brushRect.setShape({
  76523. x: startPoint[0],
  76524. y: 0,
  76525. width: endPoint[0] - startPoint[0],
  76526. height: size[1]
  76527. });
  76528. };
  76529. /**
  76530. * This action will be throttled.
  76531. */
  76532. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  76533. var range = this._range;
  76534. this.api.dispatchAction({
  76535. type: 'dataZoom',
  76536. from: this.uid,
  76537. dataZoomId: this.dataZoomModel.id,
  76538. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  76539. start: range[0],
  76540. end: range[1]
  76541. });
  76542. };
  76543. SliderZoomView.prototype._findCoordRect = function () {
  76544. // Find the grid coresponding to the first axis referred by dataZoom.
  76545. var rect;
  76546. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  76547. if (!rect && coordSysInfoList.length) {
  76548. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  76549. rect = coordSys.getRect && coordSys.getRect();
  76550. }
  76551. if (!rect) {
  76552. var width = this.api.getWidth();
  76553. var height = this.api.getHeight();
  76554. rect = {
  76555. x: width * 0.2,
  76556. y: height * 0.2,
  76557. width: width * 0.6,
  76558. height: height * 0.6
  76559. };
  76560. }
  76561. return rect;
  76562. };
  76563. SliderZoomView.type = 'dataZoom.slider';
  76564. return SliderZoomView;
  76565. }(DataZoomView);
  76566. function getOtherDim(thisDim) {
  76567. // FIXME
  76568. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  76569. var map = {
  76570. x: 'y',
  76571. y: 'x',
  76572. radius: 'angle',
  76573. angle: 'radius'
  76574. };
  76575. return map[thisDim];
  76576. }
  76577. function getCursor(orient) {
  76578. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  76579. }
  76580. function install$L(registers) {
  76581. registers.registerComponentModel(SliderZoomModel);
  76582. registers.registerComponentView(SliderZoomView);
  76583. installCommon(registers);
  76584. }
  76585. function install$M(registers) {
  76586. use(install$K);
  76587. use(install$L); // Do not install './dataZoomSelect',
  76588. // since it only work for toolbox dataZoom.
  76589. }
  76590. var visualDefault = {
  76591. /**
  76592. * @public
  76593. */
  76594. get: function (visualType, key, isCategory) {
  76595. var value = clone((defaultOption$1[visualType] || {})[key]);
  76596. return isCategory ? isArray(value) ? value[value.length - 1] : value : value;
  76597. }
  76598. };
  76599. var defaultOption$1 = {
  76600. color: {
  76601. active: ['#006edd', '#e0ffff'],
  76602. inactive: ['rgba(0,0,0,0)']
  76603. },
  76604. colorHue: {
  76605. active: [0, 360],
  76606. inactive: [0, 0]
  76607. },
  76608. colorSaturation: {
  76609. active: [0.3, 1],
  76610. inactive: [0, 0]
  76611. },
  76612. colorLightness: {
  76613. active: [0.9, 0.5],
  76614. inactive: [0, 0]
  76615. },
  76616. colorAlpha: {
  76617. active: [0.3, 1],
  76618. inactive: [0, 0]
  76619. },
  76620. opacity: {
  76621. active: [0.3, 1],
  76622. inactive: [0, 0]
  76623. },
  76624. symbol: {
  76625. active: ['circle', 'roundRect', 'diamond'],
  76626. inactive: ['none']
  76627. },
  76628. symbolSize: {
  76629. active: [10, 50],
  76630. inactive: [0, 0]
  76631. }
  76632. };
  76633. var mapVisual$1 = VisualMapping.mapVisual;
  76634. var eachVisual = VisualMapping.eachVisual;
  76635. var isArray$1 = isArray;
  76636. var each$e = each;
  76637. var asc$2 = asc;
  76638. var linearMap$1 = linearMap;
  76639. var VisualMapModel =
  76640. /** @class */
  76641. function (_super) {
  76642. __extends(VisualMapModel, _super);
  76643. function VisualMapModel() {
  76644. var _this = _super !== null && _super.apply(this, arguments) || this;
  76645. _this.type = VisualMapModel.type;
  76646. _this.stateList = ['inRange', 'outOfRange'];
  76647. _this.replacableOptionKeys = ['inRange', 'outOfRange', 'target', 'controller', 'color'];
  76648. _this.layoutMode = {
  76649. type: 'box',
  76650. ignoreSize: true
  76651. };
  76652. /**
  76653. * [lowerBound, upperBound]
  76654. */
  76655. _this.dataBound = [-Infinity, Infinity];
  76656. _this.targetVisuals = {};
  76657. _this.controllerVisuals = {};
  76658. return _this;
  76659. }
  76660. VisualMapModel.prototype.init = function (option, parentModel, ecModel) {
  76661. this.mergeDefaultAndTheme(option, ecModel);
  76662. };
  76663. /**
  76664. * @protected
  76665. */
  76666. VisualMapModel.prototype.optionUpdated = function (newOption, isInit) {
  76667. var thisOption = this.option; // FIXME
  76668. // necessary?
  76669. // Disable realtime view update if canvas is not supported.
  76670. if (!env.canvasSupported) {
  76671. thisOption.realtime = false;
  76672. }
  76673. !isInit && replaceVisualOption(thisOption, newOption, this.replacableOptionKeys);
  76674. this.textStyleModel = this.getModel('textStyle');
  76675. this.resetItemSize();
  76676. this.completeVisualOption();
  76677. };
  76678. /**
  76679. * @protected
  76680. */
  76681. VisualMapModel.prototype.resetVisual = function (supplementVisualOption) {
  76682. var stateList = this.stateList;
  76683. supplementVisualOption = bind(supplementVisualOption, this);
  76684. this.controllerVisuals = createVisualMappings(this.option.controller, stateList, supplementVisualOption);
  76685. this.targetVisuals = createVisualMappings(this.option.target, stateList, supplementVisualOption);
  76686. };
  76687. /**
  76688. * @public
  76689. */
  76690. VisualMapModel.prototype.getItemSymbol = function () {
  76691. return null;
  76692. };
  76693. /**
  76694. * @protected
  76695. * @return {Array.<number>} An array of series indices.
  76696. */
  76697. VisualMapModel.prototype.getTargetSeriesIndices = function () {
  76698. var optionSeriesIndex = this.option.seriesIndex;
  76699. var seriesIndices = [];
  76700. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  76701. this.ecModel.eachSeries(function (seriesModel, index) {
  76702. seriesIndices.push(index);
  76703. });
  76704. } else {
  76705. seriesIndices = normalizeToArray(optionSeriesIndex);
  76706. }
  76707. return seriesIndices;
  76708. };
  76709. /**
  76710. * @public
  76711. */
  76712. VisualMapModel.prototype.eachTargetSeries = function (callback, context) {
  76713. each(this.getTargetSeriesIndices(), function (seriesIndex) {
  76714. var seriesModel = this.ecModel.getSeriesByIndex(seriesIndex);
  76715. if (seriesModel) {
  76716. callback.call(context, seriesModel);
  76717. }
  76718. }, this);
  76719. };
  76720. /**
  76721. * @pubilc
  76722. */
  76723. VisualMapModel.prototype.isTargetSeries = function (seriesModel) {
  76724. var is = false;
  76725. this.eachTargetSeries(function (model) {
  76726. model === seriesModel && (is = true);
  76727. });
  76728. return is;
  76729. };
  76730. /**
  76731. * @example
  76732. * this.formatValueText(someVal); // format single numeric value to text.
  76733. * this.formatValueText(someVal, true); // format single category value to text.
  76734. * this.formatValueText([min, max]); // format numeric min-max to text.
  76735. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  76736. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  76737. *
  76738. * @param value Real value, or this.dataBound[0 or 1].
  76739. * @param isCategory Only available when value is number.
  76740. * @param edgeSymbols Open-close symbol when value is interval.
  76741. * @protected
  76742. */
  76743. VisualMapModel.prototype.formatValueText = function (value, isCategory, edgeSymbols) {
  76744. var option = this.option;
  76745. var precision = option.precision;
  76746. var dataBound = this.dataBound;
  76747. var formatter = option.formatter;
  76748. var isMinMax;
  76749. edgeSymbols = edgeSymbols || ['<', '>'];
  76750. if (isArray(value)) {
  76751. value = value.slice();
  76752. isMinMax = true;
  76753. }
  76754. var textValue = isCategory ? value // Value is string when isCategory
  76755. : isMinMax ? [toFixed(value[0]), toFixed(value[1])] : toFixed(value);
  76756. if (isString(formatter)) {
  76757. return formatter.replace('{value}', isMinMax ? textValue[0] : textValue).replace('{value2}', isMinMax ? textValue[1] : textValue);
  76758. } else if (isFunction(formatter)) {
  76759. return isMinMax ? formatter(value[0], value[1]) : formatter(value);
  76760. }
  76761. if (isMinMax) {
  76762. if (value[0] === dataBound[0]) {
  76763. return edgeSymbols[0] + ' ' + textValue[1];
  76764. } else if (value[1] === dataBound[1]) {
  76765. return edgeSymbols[1] + ' ' + textValue[0];
  76766. } else {
  76767. return textValue[0] + ' - ' + textValue[1];
  76768. }
  76769. } else {
  76770. // Format single value (includes category case).
  76771. return textValue;
  76772. }
  76773. function toFixed(val) {
  76774. return val === dataBound[0] ? 'min' : val === dataBound[1] ? 'max' : (+val).toFixed(Math.min(precision, 20));
  76775. }
  76776. };
  76777. /**
  76778. * @protected
  76779. */
  76780. VisualMapModel.prototype.resetExtent = function () {
  76781. var thisOption = this.option; // Can not calculate data extent by data here.
  76782. // Because series and data may be modified in processing stage.
  76783. // So we do not support the feature "auto min/max".
  76784. var extent = asc$2([thisOption.min, thisOption.max]);
  76785. this._dataExtent = extent;
  76786. };
  76787. /**
  76788. * PENDING:
  76789. * delete this method if no outer usage.
  76790. *
  76791. * Return Concrete dimention. If return null/undefined, no dimension used.
  76792. */
  76793. // getDataDimension(data: SeriesData) {
  76794. // const optDim = this.option.dimension;
  76795. // if (optDim != null) {
  76796. // return data.getDimension(optDim);
  76797. // }
  76798. // const dimNames = data.dimensions;
  76799. // for (let i = dimNames.length - 1; i >= 0; i--) {
  76800. // const dimName = dimNames[i];
  76801. // const dimInfo = data.getDimensionInfo(dimName);
  76802. // if (!dimInfo.isCalculationCoord) {
  76803. // return dimName;
  76804. // }
  76805. // }
  76806. // }
  76807. VisualMapModel.prototype.getDataDimensionIndex = function (data) {
  76808. var optDim = this.option.dimension;
  76809. if (optDim != null) {
  76810. return data.getDimensionIndex(optDim);
  76811. }
  76812. var dimNames = data.dimensions;
  76813. for (var i = dimNames.length - 1; i >= 0; i--) {
  76814. var dimName = dimNames[i];
  76815. var dimInfo = data.getDimensionInfo(dimName);
  76816. if (!dimInfo.isCalculationCoord) {
  76817. return dimInfo.storeDimIndex;
  76818. }
  76819. }
  76820. };
  76821. VisualMapModel.prototype.getExtent = function () {
  76822. return this._dataExtent.slice();
  76823. };
  76824. VisualMapModel.prototype.completeVisualOption = function () {
  76825. var ecModel = this.ecModel;
  76826. var thisOption = this.option;
  76827. var base = {
  76828. inRange: thisOption.inRange,
  76829. outOfRange: thisOption.outOfRange
  76830. };
  76831. var target = thisOption.target || (thisOption.target = {});
  76832. var controller = thisOption.controller || (thisOption.controller = {});
  76833. merge(target, base); // Do not override
  76834. merge(controller, base); // Do not override
  76835. var isCategory = this.isCategory();
  76836. completeSingle.call(this, target);
  76837. completeSingle.call(this, controller);
  76838. completeInactive.call(this, target, 'inRange', 'outOfRange'); // completeInactive.call(this, target, 'outOfRange', 'inRange');
  76839. completeController.call(this, controller);
  76840. function completeSingle(base) {
  76841. // Compatible with ec2 dataRange.color.
  76842. // The mapping order of dataRange.color is: [high value, ..., low value]
  76843. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  76844. // Notice: ec2 has no inverse.
  76845. if (isArray$1(thisOption.color) // If there has been inRange: {symbol: ...}, adding color is a mistake.
  76846. // So adding color only when no inRange defined.
  76847. && !base.inRange) {
  76848. base.inRange = {
  76849. color: thisOption.color.slice().reverse()
  76850. };
  76851. } // Compatible with previous logic, always give a defautl color, otherwise
  76852. // simple config with no inRange and outOfRange will not work.
  76853. // Originally we use visualMap.color as the default color, but setOption at
  76854. // the second time the default color will be erased. So we change to use
  76855. // constant DEFAULT_COLOR.
  76856. // If user do not want the default color, set inRange: {color: null}.
  76857. base.inRange = base.inRange || {
  76858. color: ecModel.get('gradientColor')
  76859. };
  76860. }
  76861. function completeInactive(base, stateExist, stateAbsent) {
  76862. var optExist = base[stateExist];
  76863. var optAbsent = base[stateAbsent];
  76864. if (optExist && !optAbsent) {
  76865. optAbsent = base[stateAbsent] = {};
  76866. each$e(optExist, function (visualData, visualType) {
  76867. if (!VisualMapping.isValidType(visualType)) {
  76868. return;
  76869. }
  76870. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  76871. if (defa != null) {
  76872. optAbsent[visualType] = defa; // Compatibable with ec2:
  76873. // Only inactive color to rgba(0,0,0,0) can not
  76874. // make label transparent, so use opacity also.
  76875. if (visualType === 'color' && !optAbsent.hasOwnProperty('opacity') && !optAbsent.hasOwnProperty('colorAlpha')) {
  76876. optAbsent.opacity = [0, 0];
  76877. }
  76878. }
  76879. });
  76880. }
  76881. }
  76882. function completeController(controller) {
  76883. var symbolExists = (controller.inRange || {}).symbol || (controller.outOfRange || {}).symbol;
  76884. var symbolSizeExists = (controller.inRange || {}).symbolSize || (controller.outOfRange || {}).symbolSize;
  76885. var inactiveColor = this.get('inactiveColor');
  76886. var itemSymbol = this.getItemSymbol();
  76887. var defaultSymbol = itemSymbol || 'roundRect';
  76888. each$e(this.stateList, function (state) {
  76889. var itemSize = this.itemSize;
  76890. var visuals = controller[state]; // Set inactive color for controller if no other color
  76891. // attr (like colorAlpha) specified.
  76892. if (!visuals) {
  76893. visuals = controller[state] = {
  76894. color: isCategory ? inactiveColor : [inactiveColor]
  76895. };
  76896. } // Consistent symbol and symbolSize if not specified.
  76897. if (visuals.symbol == null) {
  76898. visuals.symbol = symbolExists && clone(symbolExists) || (isCategory ? defaultSymbol : [defaultSymbol]);
  76899. }
  76900. if (visuals.symbolSize == null) {
  76901. visuals.symbolSize = symbolSizeExists && clone(symbolSizeExists) || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  76902. } // Filter none
  76903. visuals.symbol = mapVisual$1(visuals.symbol, function (symbol) {
  76904. return symbol === 'none' ? defaultSymbol : symbol;
  76905. }); // Normalize symbolSize
  76906. var symbolSize = visuals.symbolSize;
  76907. if (symbolSize != null) {
  76908. var max_1 = -Infinity; // symbolSize can be object when categories defined.
  76909. eachVisual(symbolSize, function (value) {
  76910. value > max_1 && (max_1 = value);
  76911. });
  76912. visuals.symbolSize = mapVisual$1(symbolSize, function (value) {
  76913. return linearMap$1(value, [0, max_1], [0, itemSize[0]], true);
  76914. });
  76915. }
  76916. }, this);
  76917. }
  76918. };
  76919. VisualMapModel.prototype.resetItemSize = function () {
  76920. this.itemSize = [parseFloat(this.get('itemWidth')), parseFloat(this.get('itemHeight'))];
  76921. };
  76922. VisualMapModel.prototype.isCategory = function () {
  76923. return !!this.option.categories;
  76924. };
  76925. /**
  76926. * @public
  76927. * @abstract
  76928. */
  76929. VisualMapModel.prototype.setSelected = function (selected) {};
  76930. VisualMapModel.prototype.getSelected = function () {
  76931. return null;
  76932. };
  76933. /**
  76934. * @public
  76935. * @abstract
  76936. */
  76937. VisualMapModel.prototype.getValueState = function (value) {
  76938. return null;
  76939. };
  76940. /**
  76941. * FIXME
  76942. * Do not publish to thirt-part-dev temporarily
  76943. * util the interface is stable. (Should it return
  76944. * a function but not visual meta?)
  76945. *
  76946. * @pubilc
  76947. * @abstract
  76948. * @param getColorVisual
  76949. * params: value, valueState
  76950. * return: color
  76951. * @return {Object} visualMeta
  76952. * should includes {stops, outerColors}
  76953. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  76954. */
  76955. VisualMapModel.prototype.getVisualMeta = function (getColorVisual) {
  76956. return null;
  76957. };
  76958. VisualMapModel.type = 'visualMap';
  76959. VisualMapModel.dependencies = ['series'];
  76960. VisualMapModel.defaultOption = {
  76961. show: true,
  76962. zlevel: 0,
  76963. z: 4,
  76964. seriesIndex: 'all',
  76965. min: 0,
  76966. max: 200,
  76967. left: 0,
  76968. right: null,
  76969. top: null,
  76970. bottom: 0,
  76971. itemWidth: null,
  76972. itemHeight: null,
  76973. inverse: false,
  76974. orient: 'vertical',
  76975. backgroundColor: 'rgba(0,0,0,0)',
  76976. borderColor: '#ccc',
  76977. contentColor: '#5793f3',
  76978. inactiveColor: '#aaa',
  76979. borderWidth: 0,
  76980. padding: 5,
  76981. // 接受数组分别设定上右下左边距,同css
  76982. textGap: 10,
  76983. precision: 0,
  76984. textStyle: {
  76985. color: '#333' // 值域文字颜色
  76986. }
  76987. };
  76988. return VisualMapModel;
  76989. }(ComponentModel);
  76990. var DEFAULT_BAR_BOUND = [20, 140];
  76991. var ContinuousModel =
  76992. /** @class */
  76993. function (_super) {
  76994. __extends(ContinuousModel, _super);
  76995. function ContinuousModel() {
  76996. var _this = _super !== null && _super.apply(this, arguments) || this;
  76997. _this.type = ContinuousModel.type;
  76998. return _this;
  76999. }
  77000. /**
  77001. * @override
  77002. */
  77003. ContinuousModel.prototype.optionUpdated = function (newOption, isInit) {
  77004. _super.prototype.optionUpdated.apply(this, arguments);
  77005. this.resetExtent();
  77006. this.resetVisual(function (mappingOption) {
  77007. mappingOption.mappingMethod = 'linear';
  77008. mappingOption.dataExtent = this.getExtent();
  77009. });
  77010. this._resetRange();
  77011. };
  77012. /**
  77013. * @protected
  77014. * @override
  77015. */
  77016. ContinuousModel.prototype.resetItemSize = function () {
  77017. _super.prototype.resetItemSize.apply(this, arguments);
  77018. var itemSize = this.itemSize;
  77019. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  77020. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  77021. };
  77022. /**
  77023. * @private
  77024. */
  77025. ContinuousModel.prototype._resetRange = function () {
  77026. var dataExtent = this.getExtent();
  77027. var range = this.option.range;
  77028. if (!range || range.auto) {
  77029. // `range` should always be array (so we dont use other
  77030. // value like 'auto') for user-friend. (consider getOption).
  77031. dataExtent.auto = 1;
  77032. this.option.range = dataExtent;
  77033. } else if (isArray(range)) {
  77034. if (range[0] > range[1]) {
  77035. range.reverse();
  77036. }
  77037. range[0] = Math.max(range[0], dataExtent[0]);
  77038. range[1] = Math.min(range[1], dataExtent[1]);
  77039. }
  77040. };
  77041. /**
  77042. * @protected
  77043. * @override
  77044. */
  77045. ContinuousModel.prototype.completeVisualOption = function () {
  77046. _super.prototype.completeVisualOption.apply(this, arguments);
  77047. each(this.stateList, function (state) {
  77048. var symbolSize = this.option.controller[state].symbolSize;
  77049. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  77050. symbolSize[0] = symbolSize[1] / 3; // For good looking.
  77051. }
  77052. }, this);
  77053. };
  77054. /**
  77055. * @override
  77056. */
  77057. ContinuousModel.prototype.setSelected = function (selected) {
  77058. this.option.range = selected.slice();
  77059. this._resetRange();
  77060. };
  77061. /**
  77062. * @public
  77063. */
  77064. ContinuousModel.prototype.getSelected = function () {
  77065. var dataExtent = this.getExtent();
  77066. var dataInterval = asc((this.get('range') || []).slice()); // Clamp
  77067. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  77068. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  77069. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  77070. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  77071. return dataInterval;
  77072. };
  77073. /**
  77074. * @override
  77075. */
  77076. ContinuousModel.prototype.getValueState = function (value) {
  77077. var range = this.option.range;
  77078. var dataExtent = this.getExtent(); // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  77079. // range[1] is processed likewise.
  77080. return (range[0] <= dataExtent[0] || range[0] <= value) && (range[1] >= dataExtent[1] || value <= range[1]) ? 'inRange' : 'outOfRange';
  77081. };
  77082. ContinuousModel.prototype.findTargetDataIndices = function (range) {
  77083. var result = [];
  77084. this.eachTargetSeries(function (seriesModel) {
  77085. var dataIndices = [];
  77086. var data = seriesModel.getData();
  77087. data.each(this.getDataDimensionIndex(data), function (value, dataIndex) {
  77088. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  77089. }, this);
  77090. result.push({
  77091. seriesId: seriesModel.id,
  77092. dataIndex: dataIndices
  77093. });
  77094. }, this);
  77095. return result;
  77096. };
  77097. /**
  77098. * @implement
  77099. */
  77100. ContinuousModel.prototype.getVisualMeta = function (getColorVisual) {
  77101. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  77102. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  77103. var stops = [];
  77104. function setStop(value, valueState) {
  77105. stops.push({
  77106. value: value,
  77107. color: getColorVisual(value, valueState)
  77108. });
  77109. } // Format to: outOfRange -- inRange -- outOfRange.
  77110. var iIdx = 0;
  77111. var oIdx = 0;
  77112. var iLen = iVals.length;
  77113. var oLen = oVals.length;
  77114. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  77115. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  77116. if (oVals[oIdx] < iVals[iIdx]) {
  77117. setStop(oVals[oIdx], 'outOfRange');
  77118. }
  77119. }
  77120. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  77121. // If range is full, value beyond min, max will be clamped.
  77122. // make a singularity
  77123. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  77124. setStop(iVals[iIdx], 'inRange');
  77125. }
  77126. for (var first = 1; oIdx < oLen; oIdx++) {
  77127. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  77128. // make a singularity
  77129. if (first) {
  77130. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  77131. first = 0;
  77132. }
  77133. setStop(oVals[oIdx], 'outOfRange');
  77134. }
  77135. }
  77136. var stopsLen = stops.length;
  77137. return {
  77138. stops: stops,
  77139. outerColors: [stopsLen ? stops[0].color : 'transparent', stopsLen ? stops[stopsLen - 1].color : 'transparent']
  77140. };
  77141. };
  77142. ContinuousModel.type = 'visualMap.continuous';
  77143. ContinuousModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  77144. align: 'auto',
  77145. calculable: false,
  77146. hoverLink: true,
  77147. realtime: true,
  77148. 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',
  77149. handleSize: '120%',
  77150. handleStyle: {
  77151. borderColor: '#fff',
  77152. borderWidth: 1
  77153. },
  77154. indicatorIcon: 'circle',
  77155. indicatorSize: '50%',
  77156. indicatorStyle: {
  77157. borderColor: '#fff',
  77158. borderWidth: 2,
  77159. shadowBlur: 2,
  77160. shadowOffsetX: 1,
  77161. shadowOffsetY: 1,
  77162. shadowColor: 'rgba(0,0,0,0.2)'
  77163. } // emphasis: {
  77164. // handleStyle: {
  77165. // shadowBlur: 3,
  77166. // shadowOffsetX: 1,
  77167. // shadowOffsetY: 1,
  77168. // shadowColor: 'rgba(0,0,0,0.2)'
  77169. // }
  77170. // }
  77171. });
  77172. return ContinuousModel;
  77173. }(VisualMapModel);
  77174. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  77175. if (dataExtent[0] === dataExtent[1]) {
  77176. return dataExtent.slice();
  77177. } // When using colorHue mapping, it is not linear color any more.
  77178. // Moreover, canvas gradient seems not to be accurate linear.
  77179. // FIXME
  77180. // Should be arbitrary value 100? or based on pixel size?
  77181. var count = 200;
  77182. var step = (dataExtent[1] - dataExtent[0]) / count;
  77183. var value = dataExtent[0];
  77184. var stopValues = [];
  77185. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  77186. stopValues.push(value);
  77187. value += step;
  77188. }
  77189. stopValues.push(dataExtent[1]);
  77190. return stopValues;
  77191. }
  77192. var VisualMapView =
  77193. /** @class */
  77194. function (_super) {
  77195. __extends(VisualMapView, _super);
  77196. function VisualMapView() {
  77197. var _this = _super !== null && _super.apply(this, arguments) || this;
  77198. _this.type = VisualMapView.type;
  77199. _this.autoPositionValues = {
  77200. left: 1,
  77201. right: 1,
  77202. top: 1,
  77203. bottom: 1
  77204. };
  77205. return _this;
  77206. }
  77207. VisualMapView.prototype.init = function (ecModel, api) {
  77208. this.ecModel = ecModel;
  77209. this.api = api;
  77210. };
  77211. /**
  77212. * @protected
  77213. */
  77214. VisualMapView.prototype.render = function (visualMapModel, ecModel, api, payload // TODO: TYPE
  77215. ) {
  77216. this.visualMapModel = visualMapModel;
  77217. if (visualMapModel.get('show') === false) {
  77218. this.group.removeAll();
  77219. return;
  77220. }
  77221. this.doRender(visualMapModel, ecModel, api, payload);
  77222. };
  77223. /**
  77224. * @protected
  77225. */
  77226. VisualMapView.prototype.renderBackground = function (group) {
  77227. var visualMapModel = this.visualMapModel;
  77228. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  77229. var rect = group.getBoundingRect();
  77230. group.add(new Rect({
  77231. z2: -1,
  77232. silent: true,
  77233. shape: {
  77234. x: rect.x - padding[3],
  77235. y: rect.y - padding[0],
  77236. width: rect.width + padding[3] + padding[1],
  77237. height: rect.height + padding[0] + padding[2]
  77238. },
  77239. style: {
  77240. fill: visualMapModel.get('backgroundColor'),
  77241. stroke: visualMapModel.get('borderColor'),
  77242. lineWidth: visualMapModel.get('borderWidth')
  77243. }
  77244. }));
  77245. };
  77246. /**
  77247. * @protected
  77248. * @param targetValue can be Infinity or -Infinity
  77249. * @param visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  77250. * @param opts
  77251. * @param opts.forceState Specify state, instead of using getValueState method.
  77252. * @param opts.convertOpacityToAlpha For color gradient in controller widget.
  77253. * @return {*} Visual value.
  77254. */
  77255. VisualMapView.prototype.getControllerVisual = function (targetValue, visualCluster, opts) {
  77256. opts = opts || {};
  77257. var forceState = opts.forceState;
  77258. var visualMapModel = this.visualMapModel;
  77259. var visualObj = {}; // Default values.
  77260. if (visualCluster === 'color') {
  77261. var defaultColor = visualMapModel.get('contentColor');
  77262. visualObj.color = defaultColor;
  77263. }
  77264. function getter(key) {
  77265. return visualObj[key];
  77266. }
  77267. function setter(key, value) {
  77268. visualObj[key] = value;
  77269. }
  77270. var mappings = visualMapModel.controllerVisuals[forceState || visualMapModel.getValueState(targetValue)];
  77271. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  77272. each(visualTypes, function (type) {
  77273. var visualMapping = mappings[type];
  77274. if (opts.convertOpacityToAlpha && type === 'opacity') {
  77275. type = 'colorAlpha';
  77276. visualMapping = mappings.__alphaForOpacity;
  77277. }
  77278. if (VisualMapping.dependsOn(type, visualCluster)) {
  77279. visualMapping && visualMapping.applyVisual(targetValue, getter, setter);
  77280. }
  77281. });
  77282. return visualObj[visualCluster];
  77283. };
  77284. VisualMapView.prototype.positionGroup = function (group) {
  77285. var model = this.visualMapModel;
  77286. var api = this.api;
  77287. positionElement(group, model.getBoxLayoutParams(), {
  77288. width: api.getWidth(),
  77289. height: api.getHeight()
  77290. });
  77291. };
  77292. VisualMapView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {};
  77293. VisualMapView.type = 'visualMap';
  77294. return VisualMapView;
  77295. }(ComponentView);
  77296. var paramsSet = [['left', 'right', 'width'], ['top', 'bottom', 'height']];
  77297. /**
  77298. * @param visualMapModel
  77299. * @param api
  77300. * @param itemSize always [short, long]
  77301. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  77302. */
  77303. function getItemAlign(visualMapModel, api, itemSize) {
  77304. var modelOption = visualMapModel.option;
  77305. var itemAlign = modelOption.align;
  77306. if (itemAlign != null && itemAlign !== 'auto') {
  77307. return itemAlign;
  77308. } // Auto decision align.
  77309. var ecSize = {
  77310. width: api.getWidth(),
  77311. height: api.getHeight()
  77312. };
  77313. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  77314. var reals = paramsSet[realIndex];
  77315. var fakeValue = [0, null, 10];
  77316. var layoutInput = {};
  77317. for (var i = 0; i < 3; i++) {
  77318. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  77319. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  77320. }
  77321. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  77322. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  77323. return reals[(rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5 < ecSize[rParam[1]] * 0.5 ? 0 : 1];
  77324. }
  77325. /**
  77326. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  77327. * dataIndexInside means filtered index.
  77328. */
  77329. // TODO: TYPE more specified payload types.
  77330. function makeHighDownBatch(batch, visualMapModel) {
  77331. each(batch || [], function (batchItem) {
  77332. if (batchItem.dataIndex != null) {
  77333. batchItem.dataIndexInside = batchItem.dataIndex;
  77334. batchItem.dataIndex = null;
  77335. }
  77336. batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : '');
  77337. });
  77338. return batch;
  77339. }
  77340. var linearMap$2 = linearMap;
  77341. var each$f = each;
  77342. var mathMin$a = Math.min;
  77343. var mathMax$a = Math.max; // Arbitrary value
  77344. var HOVER_LINK_SIZE = 12;
  77345. var HOVER_LINK_OUT = 6; // Notice:
  77346. // Any "interval" should be by the order of [low, high].
  77347. // "handle0" (handleIndex === 0) maps to
  77348. // low data value: this._dataInterval[0] and has low coord.
  77349. // "handle1" (handleIndex === 1) maps to
  77350. // high data value: this._dataInterval[1] and has high coord.
  77351. // The logic of transform is implemented in this._createBarGroup.
  77352. var ContinuousView =
  77353. /** @class */
  77354. function (_super) {
  77355. __extends(ContinuousView, _super);
  77356. function ContinuousView() {
  77357. var _this = _super !== null && _super.apply(this, arguments) || this;
  77358. _this.type = ContinuousView.type;
  77359. _this._shapes = {};
  77360. _this._dataInterval = [];
  77361. _this._handleEnds = [];
  77362. _this._hoverLinkDataIndices = [];
  77363. return _this;
  77364. }
  77365. ContinuousView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {
  77366. this._api = api;
  77367. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  77368. this._buildView();
  77369. }
  77370. };
  77371. ContinuousView.prototype._buildView = function () {
  77372. this.group.removeAll();
  77373. var visualMapModel = this.visualMapModel;
  77374. var thisGroup = this.group;
  77375. this._orient = visualMapModel.get('orient');
  77376. this._useHandle = visualMapModel.get('calculable');
  77377. this._resetInterval();
  77378. this._renderBar(thisGroup);
  77379. var dataRangeText = visualMapModel.get('text');
  77380. this._renderEndsText(thisGroup, dataRangeText, 0);
  77381. this._renderEndsText(thisGroup, dataRangeText, 1); // Do this for background size calculation.
  77382. this._updateView(true); // After updating view, inner shapes is built completely,
  77383. // and then background can be rendered.
  77384. this.renderBackground(thisGroup); // Real update view
  77385. this._updateView();
  77386. this._enableHoverLinkToSeries();
  77387. this._enableHoverLinkFromSeries();
  77388. this.positionGroup(thisGroup);
  77389. };
  77390. ContinuousView.prototype._renderEndsText = function (group, dataRangeText, endsIndex) {
  77391. if (!dataRangeText) {
  77392. return;
  77393. } // Compatible with ec2, text[0] map to high value, text[1] map low value.
  77394. var text = dataRangeText[1 - endsIndex];
  77395. text = text != null ? text + '' : '';
  77396. var visualMapModel = this.visualMapModel;
  77397. var textGap = visualMapModel.get('textGap');
  77398. var itemSize = visualMapModel.itemSize;
  77399. var barGroup = this._shapes.mainGroup;
  77400. var position = this._applyTransform([itemSize[0] / 2, endsIndex === 0 ? -textGap : itemSize[1] + textGap], barGroup);
  77401. var align = this._applyTransform(endsIndex === 0 ? 'bottom' : 'top', barGroup);
  77402. var orient = this._orient;
  77403. var textStyleModel = this.visualMapModel.textStyleModel;
  77404. this.group.add(new ZRText({
  77405. style: {
  77406. x: position[0],
  77407. y: position[1],
  77408. verticalAlign: orient === 'horizontal' ? 'middle' : align,
  77409. align: orient === 'horizontal' ? align : 'center',
  77410. text: text,
  77411. font: textStyleModel.getFont(),
  77412. fill: textStyleModel.getTextColor()
  77413. }
  77414. }));
  77415. };
  77416. ContinuousView.prototype._renderBar = function (targetGroup) {
  77417. var visualMapModel = this.visualMapModel;
  77418. var shapes = this._shapes;
  77419. var itemSize = visualMapModel.itemSize;
  77420. var orient = this._orient;
  77421. var useHandle = this._useHandle;
  77422. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  77423. var mainGroup = shapes.mainGroup = this._createBarGroup(itemAlign);
  77424. var gradientBarGroup = new Group();
  77425. mainGroup.add(gradientBarGroup); // Bar
  77426. gradientBarGroup.add(shapes.outOfRange = createPolygon());
  77427. 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.
  77428. gradientBarGroup.setClipPath(new Rect({
  77429. shape: {
  77430. x: 0,
  77431. y: 0,
  77432. width: itemSize[0],
  77433. height: itemSize[1],
  77434. r: 3
  77435. }
  77436. }));
  77437. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  77438. var textSize = mathMax$a(textRect.width, textRect.height); // Handle
  77439. if (useHandle) {
  77440. shapes.handleThumbs = [];
  77441. shapes.handleLabels = [];
  77442. shapes.handleLabelPoints = [];
  77443. this._createHandle(visualMapModel, mainGroup, 0, itemSize, textSize, orient);
  77444. this._createHandle(visualMapModel, mainGroup, 1, itemSize, textSize, orient);
  77445. }
  77446. this._createIndicator(visualMapModel, mainGroup, itemSize, textSize, orient);
  77447. targetGroup.add(mainGroup);
  77448. };
  77449. ContinuousView.prototype._createHandle = function (visualMapModel, mainGroup, handleIndex, itemSize, textSize, orient) {
  77450. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  77451. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  77452. var handleSize = parsePercent(visualMapModel.get('handleSize'), itemSize[0]);
  77453. var handleThumb = createSymbol(visualMapModel.get('handleIcon'), -handleSize / 2, -handleSize / 2, handleSize, handleSize, null, true);
  77454. var cursor = getCursor$1(this._orient);
  77455. handleThumb.attr({
  77456. cursor: cursor,
  77457. draggable: true,
  77458. drift: onDrift,
  77459. ondragend: onDragEnd,
  77460. onmousemove: function (e) {
  77461. stop(e.event);
  77462. }
  77463. });
  77464. handleThumb.x = itemSize[0] / 2;
  77465. handleThumb.useStyle(visualMapModel.getModel('handleStyle').getItemStyle());
  77466. handleThumb.setStyle({
  77467. strokeNoScale: true,
  77468. strokeFirst: true
  77469. });
  77470. handleThumb.style.lineWidth *= 2;
  77471. handleThumb.ensureState('emphasis').style = visualMapModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  77472. setAsHighDownDispatcher(handleThumb, true);
  77473. mainGroup.add(handleThumb); // Text is always horizontal layout but should not be effected by
  77474. // transform (orient/inverse). So label is built separately but not
  77475. // use zrender/graphic/helper/RectText, and is located based on view
  77476. // group (according to handleLabelPoint) but not barGroup.
  77477. var textStyleModel = this.visualMapModel.textStyleModel;
  77478. var handleLabel = new ZRText({
  77479. cursor: cursor,
  77480. draggable: true,
  77481. drift: onDrift,
  77482. onmousemove: function (e) {
  77483. // Fot mobile devicem, prevent screen slider on the button.
  77484. stop(e.event);
  77485. },
  77486. ondragend: onDragEnd,
  77487. style: {
  77488. x: 0,
  77489. y: 0,
  77490. text: '',
  77491. font: textStyleModel.getFont(),
  77492. fill: textStyleModel.getTextColor()
  77493. }
  77494. });
  77495. handleLabel.ensureState('blur').style = {
  77496. opacity: 0.1
  77497. };
  77498. handleLabel.stateTransition = {
  77499. duration: 200
  77500. };
  77501. this.group.add(handleLabel);
  77502. var handleLabelPoint = [handleSize, 0];
  77503. var shapes = this._shapes;
  77504. shapes.handleThumbs[handleIndex] = handleThumb;
  77505. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  77506. shapes.handleLabels[handleIndex] = handleLabel;
  77507. };
  77508. ContinuousView.prototype._createIndicator = function (visualMapModel, mainGroup, itemSize, textSize, orient) {
  77509. var scale = parsePercent(visualMapModel.get('indicatorSize'), itemSize[0]);
  77510. var indicator = createSymbol(visualMapModel.get('indicatorIcon'), -scale / 2, -scale / 2, scale, scale, null, true);
  77511. indicator.attr({
  77512. cursor: 'move',
  77513. invisible: true,
  77514. silent: true,
  77515. x: itemSize[0] / 2
  77516. });
  77517. var indicatorStyle = visualMapModel.getModel('indicatorStyle').getItemStyle();
  77518. if (indicator instanceof ZRImage) {
  77519. var pathStyle = indicator.style;
  77520. indicator.useStyle(extend({
  77521. // TODO other properties like x, y ?
  77522. image: pathStyle.image,
  77523. x: pathStyle.x,
  77524. y: pathStyle.y,
  77525. width: pathStyle.width,
  77526. height: pathStyle.height
  77527. }, indicatorStyle));
  77528. } else {
  77529. indicator.useStyle(indicatorStyle);
  77530. }
  77531. mainGroup.add(indicator);
  77532. var textStyleModel = this.visualMapModel.textStyleModel;
  77533. var indicatorLabel = new ZRText({
  77534. silent: true,
  77535. invisible: true,
  77536. style: {
  77537. x: 0,
  77538. y: 0,
  77539. text: '',
  77540. font: textStyleModel.getFont(),
  77541. fill: textStyleModel.getTextColor()
  77542. }
  77543. });
  77544. this.group.add(indicatorLabel);
  77545. var indicatorLabelPoint = [(orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT) + itemSize[0] / 2, 0];
  77546. var shapes = this._shapes;
  77547. shapes.indicator = indicator;
  77548. shapes.indicatorLabel = indicatorLabel;
  77549. shapes.indicatorLabelPoint = indicatorLabelPoint;
  77550. this._firstShowIndicator = true;
  77551. };
  77552. ContinuousView.prototype._dragHandle = function (handleIndex, isEnd, // dx is event from ondragend if isEnd is true. It's not used
  77553. dx, dy) {
  77554. if (!this._useHandle) {
  77555. return;
  77556. }
  77557. this._dragging = !isEnd;
  77558. if (!isEnd) {
  77559. // Transform dx, dy to bar coordination.
  77560. var vertex = this._applyTransform([dx, dy], this._shapes.mainGroup, true);
  77561. this._updateInterval(handleIndex, vertex[1]);
  77562. this._hideIndicator(); // Considering realtime, update view should be executed
  77563. // before dispatch action.
  77564. this._updateView();
  77565. } // dragEnd do not dispatch action when realtime.
  77566. if (isEnd === !this.visualMapModel.get('realtime')) {
  77567. // jshint ignore:line
  77568. this.api.dispatchAction({
  77569. type: 'selectDataRange',
  77570. from: this.uid,
  77571. visualMapId: this.visualMapModel.id,
  77572. selected: this._dataInterval.slice()
  77573. });
  77574. }
  77575. if (isEnd) {
  77576. !this._hovering && this._clearHoverLinkToSeries();
  77577. } else if (useHoverLinkOnHandle(this.visualMapModel)) {
  77578. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  77579. }
  77580. };
  77581. ContinuousView.prototype._resetInterval = function () {
  77582. var visualMapModel = this.visualMapModel;
  77583. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  77584. var dataExtent = visualMapModel.getExtent();
  77585. var sizeExtent = [0, visualMapModel.itemSize[1]];
  77586. this._handleEnds = [linearMap$2(dataInterval[0], dataExtent, sizeExtent, true), linearMap$2(dataInterval[1], dataExtent, sizeExtent, true)];
  77587. };
  77588. /**
  77589. * @private
  77590. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  77591. * @param {number} dx
  77592. * @param {number} dy
  77593. */
  77594. ContinuousView.prototype._updateInterval = function (handleIndex, delta) {
  77595. delta = delta || 0;
  77596. var visualMapModel = this.visualMapModel;
  77597. var handleEnds = this._handleEnds;
  77598. var sizeExtent = [0, visualMapModel.itemSize[1]];
  77599. sliderMove(delta, handleEnds, sizeExtent, handleIndex, // cross is forbiden
  77600. 0);
  77601. var dataExtent = visualMapModel.getExtent(); // Update data interval.
  77602. this._dataInterval = [linearMap$2(handleEnds[0], sizeExtent, dataExtent, true), linearMap$2(handleEnds[1], sizeExtent, dataExtent, true)];
  77603. };
  77604. ContinuousView.prototype._updateView = function (forSketch) {
  77605. var visualMapModel = this.visualMapModel;
  77606. var dataExtent = visualMapModel.getExtent();
  77607. var shapes = this._shapes;
  77608. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  77609. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  77610. var visualInRange = this._createBarVisual(this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange');
  77611. var visualOutOfRange = this._createBarVisual(dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange');
  77612. shapes.inRange.setStyle({
  77613. fill: visualInRange.barColor // opacity: visualInRange.opacity
  77614. }).setShape('points', visualInRange.barPoints);
  77615. shapes.outOfRange.setStyle({
  77616. fill: visualOutOfRange.barColor // opacity: visualOutOfRange.opacity
  77617. }).setShape('points', visualOutOfRange.barPoints);
  77618. this._updateHandle(inRangeHandleEnds, visualInRange);
  77619. };
  77620. ContinuousView.prototype._createBarVisual = function (dataInterval, dataExtent, handleEnds, forceState) {
  77621. var opts = {
  77622. forceState: forceState,
  77623. convertOpacityToAlpha: true
  77624. };
  77625. var colorStops = this._makeColorGradient(dataInterval, opts);
  77626. var symbolSizes = [this.getControllerVisual(dataInterval[0], 'symbolSize', opts), this.getControllerVisual(dataInterval[1], 'symbolSize', opts)];
  77627. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  77628. return {
  77629. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  77630. barPoints: barPoints,
  77631. handlesColor: [colorStops[0].color, colorStops[colorStops.length - 1].color]
  77632. };
  77633. };
  77634. ContinuousView.prototype._makeColorGradient = function (dataInterval, opts) {
  77635. // Considering colorHue, which is not linear, so we have to sample
  77636. // to calculate gradient color stops, but not only caculate head
  77637. // and tail.
  77638. var sampleNumber = 100; // Arbitrary value.
  77639. var colorStops = [];
  77640. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  77641. colorStops.push({
  77642. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  77643. offset: 0
  77644. });
  77645. for (var i = 1; i < sampleNumber; i++) {
  77646. var currValue = dataInterval[0] + step * i;
  77647. if (currValue > dataInterval[1]) {
  77648. break;
  77649. }
  77650. colorStops.push({
  77651. color: this.getControllerVisual(currValue, 'color', opts),
  77652. offset: i / sampleNumber
  77653. });
  77654. }
  77655. colorStops.push({
  77656. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  77657. offset: 1
  77658. });
  77659. return colorStops;
  77660. };
  77661. ContinuousView.prototype._createBarPoints = function (handleEnds, symbolSizes) {
  77662. var itemSize = this.visualMapModel.itemSize;
  77663. return [[itemSize[0] - symbolSizes[0], handleEnds[0]], [itemSize[0], handleEnds[0]], [itemSize[0], handleEnds[1]], [itemSize[0] - symbolSizes[1], handleEnds[1]]];
  77664. };
  77665. ContinuousView.prototype._createBarGroup = function (itemAlign) {
  77666. var orient = this._orient;
  77667. var inverse = this.visualMapModel.get('inverse');
  77668. return new Group(orient === 'horizontal' && !inverse ? {
  77669. scaleX: itemAlign === 'bottom' ? 1 : -1,
  77670. rotation: Math.PI / 2
  77671. } : orient === 'horizontal' && inverse ? {
  77672. scaleX: itemAlign === 'bottom' ? -1 : 1,
  77673. rotation: -Math.PI / 2
  77674. } : orient === 'vertical' && !inverse ? {
  77675. scaleX: itemAlign === 'left' ? 1 : -1,
  77676. scaleY: -1
  77677. } : {
  77678. scaleX: itemAlign === 'left' ? 1 : -1
  77679. });
  77680. };
  77681. ContinuousView.prototype._updateHandle = function (handleEnds, visualInRange) {
  77682. if (!this._useHandle) {
  77683. return;
  77684. }
  77685. var shapes = this._shapes;
  77686. var visualMapModel = this.visualMapModel;
  77687. var handleThumbs = shapes.handleThumbs;
  77688. var handleLabels = shapes.handleLabels;
  77689. var itemSize = visualMapModel.itemSize;
  77690. var dataExtent = visualMapModel.getExtent();
  77691. each$f([0, 1], function (handleIndex) {
  77692. var handleThumb = handleThumbs[handleIndex];
  77693. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  77694. handleThumb.y = handleEnds[handleIndex];
  77695. var val = linearMap$2(handleEnds[handleIndex], [0, itemSize[1]], dataExtent, true);
  77696. var symbolSize = this.getControllerVisual(val, 'symbolSize');
  77697. handleThumb.scaleX = handleThumb.scaleY = symbolSize / itemSize[0];
  77698. handleThumb.x = itemSize[0] - symbolSize / 2; // Update handle label position.
  77699. var textPoint = applyTransform$1(shapes.handleLabelPoints[handleIndex], getTransform(handleThumb, this.group));
  77700. handleLabels[handleIndex].setStyle({
  77701. x: textPoint[0],
  77702. y: textPoint[1],
  77703. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  77704. verticalAlign: 'middle',
  77705. align: this._orient === 'vertical' ? this._applyTransform('left', shapes.mainGroup) : 'center'
  77706. });
  77707. }, this);
  77708. };
  77709. ContinuousView.prototype._showIndicator = function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  77710. var visualMapModel = this.visualMapModel;
  77711. var dataExtent = visualMapModel.getExtent();
  77712. var itemSize = visualMapModel.itemSize;
  77713. var sizeExtent = [0, itemSize[1]];
  77714. var shapes = this._shapes;
  77715. var indicator = shapes.indicator;
  77716. if (!indicator) {
  77717. return;
  77718. }
  77719. indicator.attr('invisible', false);
  77720. var opts = {
  77721. convertOpacityToAlpha: true
  77722. };
  77723. var color = this.getControllerVisual(cursorValue, 'color', opts);
  77724. var symbolSize = this.getControllerVisual(cursorValue, 'symbolSize');
  77725. var y = linearMap$2(cursorValue, dataExtent, sizeExtent, true);
  77726. var x = itemSize[0] - symbolSize / 2;
  77727. var oldIndicatorPos = {
  77728. x: indicator.x,
  77729. y: indicator.y
  77730. }; // Update handle label position.
  77731. indicator.y = y;
  77732. indicator.x = x;
  77733. var textPoint = applyTransform$1(shapes.indicatorLabelPoint, getTransform(indicator, this.group));
  77734. var indicatorLabel = shapes.indicatorLabel;
  77735. indicatorLabel.attr('invisible', false);
  77736. var align = this._applyTransform('left', shapes.mainGroup);
  77737. var orient = this._orient;
  77738. var isHorizontal = orient === 'horizontal';
  77739. indicatorLabel.setStyle({
  77740. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  77741. verticalAlign: isHorizontal ? align : 'middle',
  77742. align: isHorizontal ? 'center' : align
  77743. });
  77744. var indicatorNewProps = {
  77745. x: x,
  77746. y: y,
  77747. style: {
  77748. fill: color
  77749. }
  77750. };
  77751. var labelNewProps = {
  77752. style: {
  77753. x: textPoint[0],
  77754. y: textPoint[1]
  77755. }
  77756. };
  77757. if (visualMapModel.ecModel.isAnimationEnabled() && !this._firstShowIndicator) {
  77758. var animationCfg = {
  77759. duration: 100,
  77760. easing: 'cubicInOut',
  77761. additive: true
  77762. };
  77763. indicator.x = oldIndicatorPos.x;
  77764. indicator.y = oldIndicatorPos.y;
  77765. indicator.animateTo(indicatorNewProps, animationCfg);
  77766. indicatorLabel.animateTo(labelNewProps, animationCfg);
  77767. } else {
  77768. indicator.attr(indicatorNewProps);
  77769. indicatorLabel.attr(labelNewProps);
  77770. }
  77771. this._firstShowIndicator = false;
  77772. var handleLabels = this._shapes.handleLabels;
  77773. if (handleLabels) {
  77774. for (var i = 0; i < handleLabels.length; i++) {
  77775. // Fade out handle labels.
  77776. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  77777. this._api.enterBlur(handleLabels[i]);
  77778. }
  77779. }
  77780. };
  77781. ContinuousView.prototype._enableHoverLinkToSeries = function () {
  77782. var self = this;
  77783. this._shapes.mainGroup.on('mousemove', function (e) {
  77784. self._hovering = true;
  77785. if (!self._dragging) {
  77786. var itemSize = self.visualMapModel.itemSize;
  77787. var pos = self._applyTransform([e.offsetX, e.offsetY], self._shapes.mainGroup, true, true); // For hover link show when hover handle, which might be
  77788. // below or upper than sizeExtent.
  77789. pos[1] = mathMin$a(mathMax$a(0, pos[1]), itemSize[1]);
  77790. self._doHoverLinkToSeries(pos[1], 0 <= pos[0] && pos[0] <= itemSize[0]);
  77791. }
  77792. }).on('mouseout', function () {
  77793. // When mouse is out of handle, hoverLink still need
  77794. // to be displayed when realtime is set as false.
  77795. self._hovering = false;
  77796. !self._dragging && self._clearHoverLinkToSeries();
  77797. });
  77798. };
  77799. ContinuousView.prototype._enableHoverLinkFromSeries = function () {
  77800. var zr = this.api.getZr();
  77801. if (this.visualMapModel.option.hoverLink) {
  77802. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  77803. zr.on('mouseout', this._hideIndicator, this);
  77804. } else {
  77805. this._clearHoverLinkFromSeries();
  77806. }
  77807. };
  77808. ContinuousView.prototype._doHoverLinkToSeries = function (cursorPos, hoverOnBar) {
  77809. var visualMapModel = this.visualMapModel;
  77810. var itemSize = visualMapModel.itemSize;
  77811. if (!visualMapModel.option.hoverLink) {
  77812. return;
  77813. }
  77814. var sizeExtent = [0, itemSize[1]];
  77815. var dataExtent = visualMapModel.getExtent(); // For hover link show when hover handle, which might be below or upper than sizeExtent.
  77816. cursorPos = mathMin$a(mathMax$a(sizeExtent[0], cursorPos), sizeExtent[1]);
  77817. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  77818. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  77819. var cursorValue = linearMap$2(cursorPos, sizeExtent, dataExtent, true);
  77820. 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,
  77821. // where china and india has very large population.
  77822. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  77823. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity); // Do not show indicator when mouse is over handle,
  77824. // otherwise labels overlap, especially when dragging.
  77825. if (hoverOnBar) {
  77826. if (valueRange[0] === -Infinity) {
  77827. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  77828. } else if (valueRange[1] === Infinity) {
  77829. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  77830. } else {
  77831. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  77832. }
  77833. } // When realtime is set as false, handles, which are in barGroup,
  77834. // also trigger hoverLink, which help user to realize where they
  77835. // focus on when dragging. (see test/heatmap-large.html)
  77836. // When realtime is set as true, highlight will not show when hover
  77837. // handle, because the label on handle, which displays a exact value
  77838. // but not range, might mislead users.
  77839. var oldBatch = this._hoverLinkDataIndices;
  77840. var newBatch = [];
  77841. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  77842. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  77843. }
  77844. var resultBatches = compressBatches(oldBatch, newBatch);
  77845. this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel));
  77846. this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel));
  77847. };
  77848. ContinuousView.prototype._hoverLinkFromSeriesMouseOver = function (e) {
  77849. var el = e.target;
  77850. var visualMapModel = this.visualMapModel;
  77851. if (!el || getECData(el).dataIndex == null) {
  77852. return;
  77853. }
  77854. var ecData = getECData(el);
  77855. var dataModel = this.ecModel.getSeriesByIndex(ecData.seriesIndex);
  77856. if (!visualMapModel.isTargetSeries(dataModel)) {
  77857. return;
  77858. }
  77859. var data = dataModel.getData(ecData.dataType);
  77860. var value = data.getStore().get(visualMapModel.getDataDimensionIndex(data), ecData.dataIndex);
  77861. if (!isNaN(value)) {
  77862. this._showIndicator(value, value);
  77863. }
  77864. };
  77865. ContinuousView.prototype._hideIndicator = function () {
  77866. var shapes = this._shapes;
  77867. shapes.indicator && shapes.indicator.attr('invisible', true);
  77868. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  77869. var handleLabels = this._shapes.handleLabels;
  77870. if (handleLabels) {
  77871. for (var i = 0; i < handleLabels.length; i++) {
  77872. // Fade out handle labels.
  77873. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  77874. this._api.leaveBlur(handleLabels[i]);
  77875. }
  77876. }
  77877. };
  77878. ContinuousView.prototype._clearHoverLinkToSeries = function () {
  77879. this._hideIndicator();
  77880. var indices = this._hoverLinkDataIndices;
  77881. this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel));
  77882. indices.length = 0;
  77883. };
  77884. ContinuousView.prototype._clearHoverLinkFromSeries = function () {
  77885. this._hideIndicator();
  77886. var zr = this.api.getZr();
  77887. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  77888. zr.off('mouseout', this._hideIndicator);
  77889. };
  77890. ContinuousView.prototype._applyTransform = function (vertex, element, inverse, global) {
  77891. var transform = getTransform(element, global ? null : this.group);
  77892. return isArray(vertex) ? applyTransform$1(vertex, transform, inverse) : transformDirection(vertex, transform, inverse);
  77893. }; // TODO: TYPE more specified payload types.
  77894. ContinuousView.prototype._dispatchHighDown = function (type, batch) {
  77895. batch && batch.length && this.api.dispatchAction({
  77896. type: type,
  77897. batch: batch
  77898. });
  77899. };
  77900. /**
  77901. * @override
  77902. */
  77903. ContinuousView.prototype.dispose = function () {
  77904. this._clearHoverLinkFromSeries();
  77905. this._clearHoverLinkToSeries();
  77906. };
  77907. /**
  77908. * @override
  77909. */
  77910. ContinuousView.prototype.remove = function () {
  77911. this._clearHoverLinkFromSeries();
  77912. this._clearHoverLinkToSeries();
  77913. };
  77914. ContinuousView.type = 'visualMap.continuous';
  77915. return ContinuousView;
  77916. }(VisualMapView);
  77917. function createPolygon(points, cursor, onDrift, onDragEnd) {
  77918. return new Polygon({
  77919. shape: {
  77920. points: points
  77921. },
  77922. draggable: !!onDrift,
  77923. cursor: cursor,
  77924. drift: onDrift,
  77925. onmousemove: function (e) {
  77926. // Fot mobile devicem, prevent screen slider on the button.
  77927. stop(e.event);
  77928. },
  77929. ondragend: onDragEnd
  77930. });
  77931. }
  77932. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  77933. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  77934. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  77935. if (hoverLinkDataSize) {
  77936. halfHoverLinkSize = linearMap$2(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  77937. }
  77938. return halfHoverLinkSize;
  77939. }
  77940. function useHoverLinkOnHandle(visualMapModel) {
  77941. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  77942. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  77943. }
  77944. function getCursor$1(orient) {
  77945. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  77946. }
  77947. /*
  77948. * Licensed to the Apache Software Foundation (ASF) under one
  77949. * or more contributor license agreements. See the NOTICE file
  77950. * distributed with this work for additional information
  77951. * regarding copyright ownership. The ASF licenses this file
  77952. * to you under the Apache License, Version 2.0 (the
  77953. * "License"); you may not use this file except in compliance
  77954. * with the License. You may obtain a copy of the License at
  77955. *
  77956. * http://www.apache.org/licenses/LICENSE-2.0
  77957. *
  77958. * Unless required by applicable law or agreed to in writing,
  77959. * software distributed under the License is distributed on an
  77960. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77961. * KIND, either express or implied. See the License for the
  77962. * specific language governing permissions and limitations
  77963. * under the License.
  77964. */
  77965. /**
  77966. * AUTO-GENERATED FILE. DO NOT MODIFY.
  77967. */
  77968. /*
  77969. * Licensed to the Apache Software Foundation (ASF) under one
  77970. * or more contributor license agreements. See the NOTICE file
  77971. * distributed with this work for additional information
  77972. * regarding copyright ownership. The ASF licenses this file
  77973. * to you under the Apache License, Version 2.0 (the
  77974. * "License"); you may not use this file except in compliance
  77975. * with the License. You may obtain a copy of the License at
  77976. *
  77977. * http://www.apache.org/licenses/LICENSE-2.0
  77978. *
  77979. * Unless required by applicable law or agreed to in writing,
  77980. * software distributed under the License is distributed on an
  77981. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77982. * KIND, either express or implied. See the License for the
  77983. * specific language governing permissions and limitations
  77984. * under the License.
  77985. */
  77986. var visualMapActionInfo = {
  77987. type: 'selectDataRange',
  77988. event: 'dataRangeSelected',
  77989. // FIXME use updateView appears wrong
  77990. update: 'update'
  77991. };
  77992. var visualMapActionHander = function (payload, ecModel) {
  77993. ecModel.eachComponent({
  77994. mainType: 'visualMap',
  77995. query: payload
  77996. }, function (model) {
  77997. model.setSelected(payload.selected);
  77998. });
  77999. };
  78000. var visualMapEncodingHandlers = [{
  78001. createOnAllSeries: true,
  78002. reset: function (seriesModel, ecModel) {
  78003. var resetDefines = [];
  78004. ecModel.eachComponent('visualMap', function (visualMapModel) {
  78005. var pipelineContext = seriesModel.pipelineContext;
  78006. if (!visualMapModel.isTargetSeries(seriesModel) || pipelineContext && pipelineContext.large) {
  78007. return;
  78008. }
  78009. resetDefines.push(incrementalApplyVisual(visualMapModel.stateList, visualMapModel.targetVisuals, bind(visualMapModel.getValueState, visualMapModel), visualMapModel.getDataDimensionIndex(seriesModel.getData())));
  78010. });
  78011. return resetDefines;
  78012. }
  78013. }, // Only support color.
  78014. {
  78015. createOnAllSeries: true,
  78016. reset: function (seriesModel, ecModel) {
  78017. var data = seriesModel.getData();
  78018. var visualMetaList = [];
  78019. ecModel.eachComponent('visualMap', function (visualMapModel) {
  78020. if (visualMapModel.isTargetSeries(seriesModel)) {
  78021. var visualMeta = visualMapModel.getVisualMeta(bind(getColorVisual, null, seriesModel, visualMapModel)) || {
  78022. stops: [],
  78023. outerColors: []
  78024. };
  78025. var dimIdx = visualMapModel.getDataDimensionIndex(data);
  78026. if (dimIdx >= 0) {
  78027. // visualMeta.dimension should be dimension index, but not concrete dimension.
  78028. visualMeta.dimension = dimIdx;
  78029. visualMetaList.push(visualMeta);
  78030. }
  78031. }
  78032. }); // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  78033. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  78034. }
  78035. }]; // FIXME
  78036. // performance and export for heatmap?
  78037. // value can be Infinity or -Infinity
  78038. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  78039. var mappings = visualMapModel.targetVisuals[valueState];
  78040. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  78041. var resultVisual = {
  78042. color: getVisualFromData(seriesModel.getData(), 'color') // default color.
  78043. };
  78044. for (var i = 0, len = visualTypes.length; i < len; i++) {
  78045. var type = visualTypes[i];
  78046. var mapping = mappings[type === 'opacity' ? '__alphaForOpacity' : type];
  78047. mapping && mapping.applyVisual(value, getVisual, setVisual);
  78048. }
  78049. return resultVisual.color;
  78050. function getVisual(key) {
  78051. return resultVisual[key];
  78052. }
  78053. function setVisual(key, value) {
  78054. resultVisual[key] = value;
  78055. }
  78056. }
  78057. var each$g = each;
  78058. function visualMapPreprocessor(option) {
  78059. var visualMap = option && option.visualMap;
  78060. if (!isArray(visualMap)) {
  78061. visualMap = visualMap ? [visualMap] : [];
  78062. }
  78063. each$g(visualMap, function (opt) {
  78064. if (!opt) {
  78065. return;
  78066. } // rename splitList to pieces
  78067. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  78068. opt.pieces = opt.splitList;
  78069. delete opt.splitList;
  78070. }
  78071. var pieces = opt.pieces;
  78072. if (pieces && isArray(pieces)) {
  78073. each$g(pieces, function (piece) {
  78074. if (isObject(piece)) {
  78075. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  78076. piece.min = piece.start;
  78077. }
  78078. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  78079. piece.max = piece.end;
  78080. }
  78081. }
  78082. });
  78083. }
  78084. });
  78085. }
  78086. function has$1(obj, name) {
  78087. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  78088. }
  78089. var installed$1 = false;
  78090. function installCommon$1(registers) {
  78091. if (installed$1) {
  78092. return;
  78093. }
  78094. installed$1 = true;
  78095. registers.registerSubTypeDefaulter('visualMap', function (option) {
  78096. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  78097. return !option.categories && (!(option.pieces ? option.pieces.length > 0 : option.splitNumber > 0) || option.calculable) ? 'continuous' : 'piecewise';
  78098. });
  78099. registers.registerAction(visualMapActionInfo, visualMapActionHander);
  78100. each(visualMapEncodingHandlers, function (handler) {
  78101. registers.registerVisual(registers.PRIORITY.VISUAL.COMPONENT, handler);
  78102. });
  78103. registers.registerPreprocessor(visualMapPreprocessor);
  78104. }
  78105. function install$N(registers) {
  78106. registers.registerComponentModel(ContinuousModel);
  78107. registers.registerComponentView(ContinuousView);
  78108. installCommon$1(registers);
  78109. }
  78110. var PiecewiseModel =
  78111. /** @class */
  78112. function (_super) {
  78113. __extends(PiecewiseModel, _super);
  78114. function PiecewiseModel() {
  78115. var _this = _super !== null && _super.apply(this, arguments) || this;
  78116. _this.type = PiecewiseModel.type;
  78117. /**
  78118. * The order is always [low, ..., high].
  78119. * [{text: string, interval: Array.<number>}, ...]
  78120. */
  78121. _this._pieceList = [];
  78122. return _this;
  78123. }
  78124. PiecewiseModel.prototype.optionUpdated = function (newOption, isInit) {
  78125. _super.prototype.optionUpdated.apply(this, arguments);
  78126. this.resetExtent();
  78127. var mode = this._mode = this._determineMode();
  78128. this._pieceList = [];
  78129. resetMethods[this._mode].call(this, this._pieceList);
  78130. this._resetSelected(newOption, isInit);
  78131. var categories = this.option.categories;
  78132. this.resetVisual(function (mappingOption, state) {
  78133. if (mode === 'categories') {
  78134. mappingOption.mappingMethod = 'category';
  78135. mappingOption.categories = clone(categories);
  78136. } else {
  78137. mappingOption.dataExtent = this.getExtent();
  78138. mappingOption.mappingMethod = 'piecewise';
  78139. mappingOption.pieceList = map(this._pieceList, function (piece) {
  78140. piece = clone(piece);
  78141. if (state !== 'inRange') {
  78142. // FIXME
  78143. // outOfRange do not support special visual in pieces.
  78144. piece.visual = null;
  78145. }
  78146. return piece;
  78147. });
  78148. }
  78149. });
  78150. };
  78151. /**
  78152. * @protected
  78153. * @override
  78154. */
  78155. PiecewiseModel.prototype.completeVisualOption = function () {
  78156. // Consider this case:
  78157. // visualMap: {
  78158. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  78159. // }
  78160. // where no inRange/outOfRange set but only pieces. So we should make
  78161. // default inRange/outOfRange for this case, otherwise visuals that only
  78162. // appear in `pieces` will not be taken into account in visual encoding.
  78163. var option = this.option;
  78164. var visualTypesInPieces = {};
  78165. var visualTypes = VisualMapping.listVisualTypes();
  78166. var isCategory = this.isCategory();
  78167. each(option.pieces, function (piece) {
  78168. each(visualTypes, function (visualType) {
  78169. if (piece.hasOwnProperty(visualType)) {
  78170. visualTypesInPieces[visualType] = 1;
  78171. }
  78172. });
  78173. });
  78174. each(visualTypesInPieces, function (v, visualType) {
  78175. var exists = false;
  78176. each(this.stateList, function (state) {
  78177. exists = exists || has(option, state, visualType) || has(option.target, state, visualType);
  78178. }, this);
  78179. !exists && each(this.stateList, function (state) {
  78180. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(visualType, state === 'inRange' ? 'active' : 'inactive', isCategory);
  78181. });
  78182. }, this);
  78183. function has(obj, state, visualType) {
  78184. return obj && obj[state] && obj[state].hasOwnProperty(visualType);
  78185. }
  78186. _super.prototype.completeVisualOption.apply(this, arguments);
  78187. };
  78188. PiecewiseModel.prototype._resetSelected = function (newOption, isInit) {
  78189. var thisOption = this.option;
  78190. var pieceList = this._pieceList; // Selected do not merge but all override.
  78191. var selected = (isInit ? thisOption : newOption).selected || {};
  78192. thisOption.selected = selected; // Consider 'not specified' means true.
  78193. each(pieceList, function (piece, index) {
  78194. var key = this.getSelectedMapKey(piece);
  78195. if (!selected.hasOwnProperty(key)) {
  78196. selected[key] = true;
  78197. }
  78198. }, this);
  78199. if (thisOption.selectedMode === 'single') {
  78200. // Ensure there is only one selected.
  78201. var hasSel_1 = false;
  78202. each(pieceList, function (piece, index) {
  78203. var key = this.getSelectedMapKey(piece);
  78204. if (selected[key]) {
  78205. hasSel_1 ? selected[key] = false : hasSel_1 = true;
  78206. }
  78207. }, this);
  78208. } // thisOption.selectedMode === 'multiple', default: all selected.
  78209. };
  78210. /**
  78211. * @public
  78212. */
  78213. PiecewiseModel.prototype.getItemSymbol = function () {
  78214. return this.get('itemSymbol');
  78215. };
  78216. /**
  78217. * @public
  78218. */
  78219. PiecewiseModel.prototype.getSelectedMapKey = function (piece) {
  78220. return this._mode === 'categories' ? piece.value + '' : piece.index + '';
  78221. };
  78222. /**
  78223. * @public
  78224. */
  78225. PiecewiseModel.prototype.getPieceList = function () {
  78226. return this._pieceList;
  78227. };
  78228. /**
  78229. * @return {string}
  78230. */
  78231. PiecewiseModel.prototype._determineMode = function () {
  78232. var option = this.option;
  78233. return option.pieces && option.pieces.length > 0 ? 'pieces' : this.option.categories ? 'categories' : 'splitNumber';
  78234. };
  78235. /**
  78236. * @override
  78237. */
  78238. PiecewiseModel.prototype.setSelected = function (selected) {
  78239. this.option.selected = clone(selected);
  78240. };
  78241. /**
  78242. * @override
  78243. */
  78244. PiecewiseModel.prototype.getValueState = function (value) {
  78245. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  78246. return index != null ? this.option.selected[this.getSelectedMapKey(this._pieceList[index])] ? 'inRange' : 'outOfRange' : 'outOfRange';
  78247. };
  78248. /**
  78249. * @public
  78250. * @param pieceIndex piece index in visualMapModel.getPieceList()
  78251. */
  78252. PiecewiseModel.prototype.findTargetDataIndices = function (pieceIndex) {
  78253. var result = [];
  78254. var pieceList = this._pieceList;
  78255. this.eachTargetSeries(function (seriesModel) {
  78256. var dataIndices = [];
  78257. var data = seriesModel.getData();
  78258. data.each(this.getDataDimensionIndex(data), function (value, dataIndex) {
  78259. // Should always base on model pieceList, because it is order sensitive.
  78260. var pIdx = VisualMapping.findPieceIndex(value, pieceList);
  78261. pIdx === pieceIndex && dataIndices.push(dataIndex);
  78262. }, this);
  78263. result.push({
  78264. seriesId: seriesModel.id,
  78265. dataIndex: dataIndices
  78266. });
  78267. }, this);
  78268. return result;
  78269. };
  78270. /**
  78271. * @private
  78272. * @param piece piece.value or piece.interval is required.
  78273. * @return Can be Infinity or -Infinity
  78274. */
  78275. PiecewiseModel.prototype.getRepresentValue = function (piece) {
  78276. var representValue;
  78277. if (this.isCategory()) {
  78278. representValue = piece.value;
  78279. } else {
  78280. if (piece.value != null) {
  78281. representValue = piece.value;
  78282. } else {
  78283. var pieceInterval = piece.interval || [];
  78284. representValue = pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity ? 0 : (pieceInterval[0] + pieceInterval[1]) / 2;
  78285. }
  78286. }
  78287. return representValue;
  78288. };
  78289. PiecewiseModel.prototype.getVisualMeta = function (getColorVisual) {
  78290. // Do not support category. (category axis is ordinal, numerical)
  78291. if (this.isCategory()) {
  78292. return;
  78293. }
  78294. var stops = [];
  78295. var outerColors = ['', ''];
  78296. var visualMapModel = this;
  78297. function setStop(interval, valueState) {
  78298. var representValue = visualMapModel.getRepresentValue({
  78299. interval: interval
  78300. }); // Not category
  78301. if (!valueState) {
  78302. valueState = visualMapModel.getValueState(representValue);
  78303. }
  78304. var color = getColorVisual(representValue, valueState);
  78305. if (interval[0] === -Infinity) {
  78306. outerColors[0] = color;
  78307. } else if (interval[1] === Infinity) {
  78308. outerColors[1] = color;
  78309. } else {
  78310. stops.push({
  78311. value: interval[0],
  78312. color: color
  78313. }, {
  78314. value: interval[1],
  78315. color: color
  78316. });
  78317. }
  78318. } // Suplement
  78319. var pieceList = this._pieceList.slice();
  78320. if (!pieceList.length) {
  78321. pieceList.push({
  78322. interval: [-Infinity, Infinity]
  78323. });
  78324. } else {
  78325. var edge = pieceList[0].interval[0];
  78326. edge !== -Infinity && pieceList.unshift({
  78327. interval: [-Infinity, edge]
  78328. });
  78329. edge = pieceList[pieceList.length - 1].interval[1];
  78330. edge !== Infinity && pieceList.push({
  78331. interval: [edge, Infinity]
  78332. });
  78333. }
  78334. var curr = -Infinity;
  78335. each(pieceList, function (piece) {
  78336. var interval = piece.interval;
  78337. if (interval) {
  78338. // Fulfill gap.
  78339. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  78340. setStop(interval.slice());
  78341. curr = interval[1];
  78342. }
  78343. }, this);
  78344. return {
  78345. stops: stops,
  78346. outerColors: outerColors
  78347. };
  78348. };
  78349. PiecewiseModel.type = 'visualMap.piecewise';
  78350. PiecewiseModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  78351. selected: null,
  78352. minOpen: false,
  78353. maxOpen: false,
  78354. align: 'auto',
  78355. itemWidth: 20,
  78356. itemHeight: 14,
  78357. itemSymbol: 'roundRect',
  78358. pieces: null,
  78359. categories: null,
  78360. splitNumber: 5,
  78361. selectedMode: 'multiple',
  78362. itemGap: 10,
  78363. hoverLink: true // Enable hover highlight.
  78364. });
  78365. return PiecewiseModel;
  78366. }(VisualMapModel);
  78367. /**
  78368. * Key is this._mode
  78369. * @type {Object}
  78370. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  78371. */
  78372. var resetMethods = {
  78373. splitNumber: function (outPieceList) {
  78374. var thisOption = this.option;
  78375. var precision = Math.min(thisOption.precision, 20);
  78376. var dataExtent = this.getExtent();
  78377. var splitNumber = thisOption.splitNumber;
  78378. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  78379. thisOption.splitNumber = splitNumber;
  78380. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber; // Precision auto-adaption
  78381. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  78382. precision++;
  78383. }
  78384. thisOption.precision = precision;
  78385. splitStep = +splitStep.toFixed(precision);
  78386. if (thisOption.minOpen) {
  78387. outPieceList.push({
  78388. interval: [-Infinity, dataExtent[0]],
  78389. close: [0, 0]
  78390. });
  78391. }
  78392. for (var index = 0, curr = dataExtent[0]; index < splitNumber; curr += splitStep, index++) {
  78393. var max = index === splitNumber - 1 ? dataExtent[1] : curr + splitStep;
  78394. outPieceList.push({
  78395. interval: [curr, max],
  78396. close: [1, 1]
  78397. });
  78398. }
  78399. if (thisOption.maxOpen) {
  78400. outPieceList.push({
  78401. interval: [dataExtent[1], Infinity],
  78402. close: [0, 0]
  78403. });
  78404. }
  78405. reformIntervals(outPieceList);
  78406. each(outPieceList, function (piece, index) {
  78407. piece.index = index;
  78408. piece.text = this.formatValueText(piece.interval);
  78409. }, this);
  78410. },
  78411. categories: function (outPieceList) {
  78412. var thisOption = this.option;
  78413. each(thisOption.categories, function (cate) {
  78414. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  78415. // 是否改一致。
  78416. outPieceList.push({
  78417. text: this.formatValueText(cate, true),
  78418. value: cate
  78419. });
  78420. }, this); // See "Order Rule".
  78421. normalizeReverse(thisOption, outPieceList);
  78422. },
  78423. pieces: function (outPieceList) {
  78424. var thisOption = this.option;
  78425. each(thisOption.pieces, function (pieceListItem, index) {
  78426. if (!isObject(pieceListItem)) {
  78427. pieceListItem = {
  78428. value: pieceListItem
  78429. };
  78430. }
  78431. var item = {
  78432. text: '',
  78433. index: index
  78434. };
  78435. if (pieceListItem.label != null) {
  78436. item.text = pieceListItem.label;
  78437. }
  78438. if (pieceListItem.hasOwnProperty('value')) {
  78439. var value = item.value = pieceListItem.value;
  78440. item.interval = [value, value];
  78441. item.close = [1, 1];
  78442. } else {
  78443. // `min` `max` is legacy option.
  78444. // `lt` `gt` `lte` `gte` is recommanded.
  78445. var interval = item.interval = [];
  78446. var close_1 = item.close = [0, 0];
  78447. var closeList = [1, 0, 1];
  78448. var infinityList = [-Infinity, Infinity];
  78449. var useMinMax = [];
  78450. for (var lg = 0; lg < 2; lg++) {
  78451. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  78452. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  78453. interval[lg] = pieceListItem[names[i]];
  78454. close_1[lg] = closeList[i];
  78455. useMinMax[lg] = i === 2;
  78456. }
  78457. interval[lg] == null && (interval[lg] = infinityList[lg]);
  78458. }
  78459. useMinMax[0] && interval[1] === Infinity && (close_1[0] = 0);
  78460. useMinMax[1] && interval[0] === -Infinity && (close_1[1] = 0);
  78461. if ("development" !== 'production') {
  78462. if (interval[0] > interval[1]) {
  78463. console.warn('Piece ' + index + 'is illegal: ' + interval + ' lower bound should not greater then uppper bound.');
  78464. }
  78465. }
  78466. if (interval[0] === interval[1] && close_1[0] && close_1[1]) {
  78467. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  78468. // we use value to lift the priority when min === max
  78469. item.value = interval[0];
  78470. }
  78471. }
  78472. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  78473. outPieceList.push(item);
  78474. }, this); // See "Order Rule".
  78475. normalizeReverse(thisOption, outPieceList); // Only pieces
  78476. reformIntervals(outPieceList);
  78477. each(outPieceList, function (piece) {
  78478. var close = piece.close;
  78479. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  78480. piece.text = piece.text || this.formatValueText(piece.value != null ? piece.value : piece.interval, false, edgeSymbols);
  78481. }, this);
  78482. }
  78483. };
  78484. function normalizeReverse(thisOption, pieceList) {
  78485. var inverse = thisOption.inverse;
  78486. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  78487. pieceList.reverse();
  78488. }
  78489. }
  78490. var PiecewiseVisualMapView =
  78491. /** @class */
  78492. function (_super) {
  78493. __extends(PiecewiseVisualMapView, _super);
  78494. function PiecewiseVisualMapView() {
  78495. var _this = _super !== null && _super.apply(this, arguments) || this;
  78496. _this.type = PiecewiseVisualMapView.type;
  78497. return _this;
  78498. }
  78499. PiecewiseVisualMapView.prototype.doRender = function () {
  78500. var thisGroup = this.group;
  78501. thisGroup.removeAll();
  78502. var visualMapModel = this.visualMapModel;
  78503. var textGap = visualMapModel.get('textGap');
  78504. var textStyleModel = visualMapModel.textStyleModel;
  78505. var textFont = textStyleModel.getFont();
  78506. var textFill = textStyleModel.getTextColor();
  78507. var itemAlign = this._getItemAlign();
  78508. var itemSize = visualMapModel.itemSize;
  78509. var viewData = this._getViewData();
  78510. var endsText = viewData.endsText;
  78511. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  78512. endsText && this._renderEndsText(thisGroup, endsText[0], itemSize, showLabel, itemAlign);
  78513. each(viewData.viewPieceList, function (item) {
  78514. var piece = item.piece;
  78515. var itemGroup = new Group();
  78516. itemGroup.onclick = bind(this._onItemClick, this, piece);
  78517. this._enableHoverLink(itemGroup, item.indexInModelPieceList); // TODO Category
  78518. var representValue = visualMapModel.getRepresentValue(piece);
  78519. this._createItemSymbol(itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]);
  78520. if (showLabel) {
  78521. var visualState = this.visualMapModel.getValueState(representValue);
  78522. itemGroup.add(new ZRText({
  78523. style: {
  78524. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  78525. y: itemSize[1] / 2,
  78526. text: piece.text,
  78527. verticalAlign: 'middle',
  78528. align: itemAlign,
  78529. font: textFont,
  78530. fill: textFill,
  78531. opacity: visualState === 'outOfRange' ? 0.5 : 1
  78532. }
  78533. }));
  78534. }
  78535. thisGroup.add(itemGroup);
  78536. }, this);
  78537. endsText && this._renderEndsText(thisGroup, endsText[1], itemSize, showLabel, itemAlign);
  78538. box(visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap'));
  78539. this.renderBackground(thisGroup);
  78540. this.positionGroup(thisGroup);
  78541. };
  78542. PiecewiseVisualMapView.prototype._enableHoverLink = function (itemGroup, pieceIndex) {
  78543. var _this = this;
  78544. itemGroup.on('mouseover', function () {
  78545. return onHoverLink('highlight');
  78546. }).on('mouseout', function () {
  78547. return onHoverLink('downplay');
  78548. });
  78549. var onHoverLink = function (method) {
  78550. var visualMapModel = _this.visualMapModel; // TODO: TYPE More detailed action types
  78551. visualMapModel.option.hoverLink && _this.api.dispatchAction({
  78552. type: method,
  78553. batch: makeHighDownBatch(visualMapModel.findTargetDataIndices(pieceIndex), visualMapModel)
  78554. });
  78555. };
  78556. };
  78557. PiecewiseVisualMapView.prototype._getItemAlign = function () {
  78558. var visualMapModel = this.visualMapModel;
  78559. var modelOption = visualMapModel.option;
  78560. if (modelOption.orient === 'vertical') {
  78561. return getItemAlign(visualMapModel, this.api, visualMapModel.itemSize);
  78562. } else {
  78563. // horizontal, most case left unless specifying right.
  78564. var align = modelOption.align;
  78565. if (!align || align === 'auto') {
  78566. align = 'left';
  78567. }
  78568. return align;
  78569. }
  78570. };
  78571. PiecewiseVisualMapView.prototype._renderEndsText = function (group, text, itemSize, showLabel, itemAlign) {
  78572. if (!text) {
  78573. return;
  78574. }
  78575. var itemGroup = new Group();
  78576. var textStyleModel = this.visualMapModel.textStyleModel;
  78577. itemGroup.add(new ZRText({
  78578. style: {
  78579. x: showLabel ? itemAlign === 'right' ? itemSize[0] : 0 : itemSize[0] / 2,
  78580. y: itemSize[1] / 2,
  78581. verticalAlign: 'middle',
  78582. align: showLabel ? itemAlign : 'center',
  78583. text: text,
  78584. font: textStyleModel.getFont(),
  78585. fill: textStyleModel.getTextColor()
  78586. }
  78587. }));
  78588. group.add(itemGroup);
  78589. };
  78590. /**
  78591. * @private
  78592. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  78593. */
  78594. PiecewiseVisualMapView.prototype._getViewData = function () {
  78595. var visualMapModel = this.visualMapModel;
  78596. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  78597. return {
  78598. piece: piece,
  78599. indexInModelPieceList: index
  78600. };
  78601. });
  78602. var endsText = visualMapModel.get('text'); // Consider orient and inverse.
  78603. var orient = visualMapModel.get('orient');
  78604. var inverse = visualMapModel.get('inverse'); // Order of model pieceList is always [low, ..., high]
  78605. if (orient === 'horizontal' ? inverse : !inverse) {
  78606. viewPieceList.reverse();
  78607. } // Origin order of endsText is [high, low]
  78608. else if (endsText) {
  78609. endsText = endsText.slice().reverse();
  78610. }
  78611. return {
  78612. viewPieceList: viewPieceList,
  78613. endsText: endsText
  78614. };
  78615. };
  78616. PiecewiseVisualMapView.prototype._createItemSymbol = function (group, representValue, shapeParam) {
  78617. group.add(createSymbol( // symbol will be string
  78618. this.getControllerVisual(representValue, 'symbol'), shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3], // color will be string
  78619. this.getControllerVisual(representValue, 'color')));
  78620. };
  78621. PiecewiseVisualMapView.prototype._onItemClick = function (piece) {
  78622. var visualMapModel = this.visualMapModel;
  78623. var option = visualMapModel.option;
  78624. var selected = clone(option.selected);
  78625. var newKey = visualMapModel.getSelectedMapKey(piece);
  78626. if (option.selectedMode === 'single') {
  78627. selected[newKey] = true;
  78628. each(selected, function (o, key) {
  78629. selected[key] = key === newKey;
  78630. });
  78631. } else {
  78632. selected[newKey] = !selected[newKey];
  78633. }
  78634. this.api.dispatchAction({
  78635. type: 'selectDataRange',
  78636. from: this.uid,
  78637. visualMapId: this.visualMapModel.id,
  78638. selected: selected
  78639. });
  78640. };
  78641. PiecewiseVisualMapView.type = 'visualMap.piecewise';
  78642. return PiecewiseVisualMapView;
  78643. }(VisualMapView);
  78644. function install$O(registers) {
  78645. registers.registerComponentModel(PiecewiseModel);
  78646. registers.registerComponentView(PiecewiseVisualMapView);
  78647. installCommon$1(registers);
  78648. }
  78649. function install$P(registers) {
  78650. use(install$N);
  78651. use(install$O); // Do not install './dataZoomSelect',
  78652. // since it only work for toolbox dataZoom.
  78653. }
  78654. var DEFAULT_OPTION = {
  78655. label: {
  78656. enabled: true
  78657. },
  78658. decal: {
  78659. show: false
  78660. }
  78661. };
  78662. var inner$l = makeInner();
  78663. var decalPaletteScope = {};
  78664. function ariaVisual(ecModel, api) {
  78665. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  78666. if (!ariaModel.get('enabled')) {
  78667. return;
  78668. }
  78669. var defaultOption = clone(DEFAULT_OPTION);
  78670. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  78671. merge(ariaModel.option, defaultOption, false);
  78672. setDecal();
  78673. setLabel();
  78674. function setDecal() {
  78675. var decalModel = ariaModel.getModel('decal');
  78676. var useDecal = decalModel.get('show');
  78677. if (useDecal) {
  78678. // Each type of series use one scope.
  78679. // Pie and funnel are using diferrent scopes
  78680. var paletteScopeGroupByType_1 = createHashMap();
  78681. ecModel.eachSeries(function (seriesModel) {
  78682. if (seriesModel.isColorBySeries()) {
  78683. return;
  78684. }
  78685. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  78686. if (!decalScope) {
  78687. decalScope = {};
  78688. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  78689. }
  78690. inner$l(seriesModel).scope = decalScope;
  78691. });
  78692. ecModel.eachRawSeries(function (seriesModel) {
  78693. if (ecModel.isSeriesFiltered(seriesModel)) {
  78694. return;
  78695. }
  78696. if (typeof seriesModel.enableAriaDecal === 'function') {
  78697. // Let series define how to use decal palette on data
  78698. seriesModel.enableAriaDecal();
  78699. return;
  78700. }
  78701. var data = seriesModel.getData();
  78702. if (!seriesModel.isColorBySeries()) {
  78703. var dataAll_1 = seriesModel.getRawData();
  78704. var idxMap_1 = {};
  78705. var decalScope_1 = inner$l(seriesModel).scope;
  78706. data.each(function (idx) {
  78707. var rawIdx = data.getRawIndex(idx);
  78708. idxMap_1[rawIdx] = idx;
  78709. });
  78710. var dataCount_1 = dataAll_1.count();
  78711. dataAll_1.each(function (rawIdx) {
  78712. var idx = idxMap_1[rawIdx];
  78713. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  78714. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  78715. var specifiedDecal = data.getItemVisual(idx, 'decal');
  78716. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  78717. });
  78718. } else {
  78719. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  78720. var specifiedDecal = data.getVisual('decal');
  78721. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  78722. }
  78723. function mergeDecal(specifiedDecal, paletteDecal) {
  78724. // Merge decal from palette to decal from itemStyle.
  78725. // User do not need to specify all of the decal props.
  78726. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  78727. resultDecal.dirty = true;
  78728. return resultDecal;
  78729. }
  78730. });
  78731. }
  78732. }
  78733. function setLabel() {
  78734. var labelLocale = ecModel.getLocaleModel().get('aria');
  78735. var labelModel = ariaModel.getModel('label');
  78736. labelModel.option = defaults(labelModel.option, labelLocale);
  78737. if (!labelModel.get('enabled')) {
  78738. return;
  78739. }
  78740. var dom = api.getZr().dom;
  78741. if (labelModel.get('description')) {
  78742. dom.setAttribute('aria-label', labelModel.get('description'));
  78743. return;
  78744. }
  78745. var seriesCnt = ecModel.getSeriesCount();
  78746. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  78747. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  78748. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  78749. var ariaLabel;
  78750. if (seriesCnt < 1) {
  78751. // No series, no aria label
  78752. return;
  78753. } else {
  78754. var title = getTitle();
  78755. if (title) {
  78756. var withTitle = labelModel.get(['general', 'withTitle']);
  78757. ariaLabel = replace(withTitle, {
  78758. title: title
  78759. });
  78760. } else {
  78761. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  78762. }
  78763. var seriesLabels_1 = [];
  78764. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  78765. ariaLabel += replace(prefix, {
  78766. seriesCount: seriesCnt
  78767. });
  78768. ecModel.eachSeries(function (seriesModel, idx) {
  78769. if (idx < displaySeriesCnt) {
  78770. var seriesLabel = void 0;
  78771. var seriesName = seriesModel.get('name');
  78772. var withName = seriesName ? 'withName' : 'withoutName';
  78773. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  78774. seriesLabel = replace(seriesLabel, {
  78775. seriesId: seriesModel.seriesIndex,
  78776. seriesName: seriesModel.get('name'),
  78777. seriesType: getSeriesTypeName(seriesModel.subType)
  78778. });
  78779. var data = seriesModel.getData();
  78780. if (data.count() > maxDataCnt) {
  78781. // Show part of data
  78782. var partialLabel = labelModel.get(['data', 'partialData']);
  78783. seriesLabel += replace(partialLabel, {
  78784. displayCnt: maxDataCnt
  78785. });
  78786. } else {
  78787. seriesLabel += labelModel.get(['data', 'allData']);
  78788. }
  78789. var dataLabels = [];
  78790. for (var i = 0; i < data.count(); i++) {
  78791. if (i < maxDataCnt) {
  78792. var name_1 = data.getName(i);
  78793. var value = retrieveRawValue(data, i);
  78794. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  78795. dataLabels.push(replace(dataLabel, {
  78796. name: name_1,
  78797. value: value
  78798. }));
  78799. }
  78800. }
  78801. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  78802. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  78803. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  78804. seriesLabels_1.push(seriesLabel);
  78805. }
  78806. });
  78807. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  78808. var middleSeparator = separatorModel.get('middle');
  78809. var endSeparator = separatorModel.get('end');
  78810. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  78811. dom.setAttribute('aria-label', ariaLabel);
  78812. }
  78813. }
  78814. function replace(str, keyValues) {
  78815. if (typeof str !== 'string') {
  78816. return str;
  78817. }
  78818. var result = str;
  78819. each(keyValues, function (value, key) {
  78820. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  78821. });
  78822. return result;
  78823. }
  78824. function getTitle() {
  78825. var title = ecModel.get('title');
  78826. if (title && title.length) {
  78827. title = title[0];
  78828. }
  78829. return title && title.text;
  78830. }
  78831. function getSeriesTypeName(type) {
  78832. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  78833. }
  78834. }
  78835. function ariaPreprocessor(option) {
  78836. if (!option || !option.aria) {
  78837. return;
  78838. }
  78839. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  78840. if (aria.show != null) {
  78841. aria.enabled = aria.show;
  78842. }
  78843. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  78844. each(['description', 'general', 'series', 'data'], function (name) {
  78845. if (aria[name] != null) {
  78846. aria.label[name] = aria[name];
  78847. }
  78848. });
  78849. }
  78850. function install$Q(registers) {
  78851. registers.registerPreprocessor(ariaPreprocessor);
  78852. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  78853. }
  78854. var RELATIONAL_EXPRESSION_OP_ALIAS_MAP = {
  78855. value: 'eq',
  78856. // PENDING: not good for literal semantic?
  78857. '<': 'lt',
  78858. '<=': 'lte',
  78859. '>': 'gt',
  78860. '>=': 'gte',
  78861. '=': 'eq',
  78862. '!=': 'ne',
  78863. '<>': 'ne' // Might mileading for sake of the different between '==' and '===',
  78864. // So dont support them.
  78865. // '==': 'eq',
  78866. // '===': 'seq',
  78867. // '!==': 'sne'
  78868. // PENDING: Whether support some common alias "ge", "le", "neq"?
  78869. // ge: 'gte',
  78870. // le: 'lte',
  78871. // neq: 'ne',
  78872. }; // type RelationalExpressionOpEvaluate = (tarVal: unknown, condVal: unknown) => boolean;
  78873. var RegExpEvaluator =
  78874. /** @class */
  78875. function () {
  78876. function RegExpEvaluator(rVal) {
  78877. // Support condVal: RegExp | string
  78878. var condValue = this._condVal = isString(rVal) ? new RegExp(rVal) : isRegExp(rVal) ? rVal : null;
  78879. if (condValue == null) {
  78880. var errMsg = '';
  78881. if ("development" !== 'production') {
  78882. errMsg = makePrintable('Illegal regexp', rVal, 'in');
  78883. }
  78884. throwError(errMsg);
  78885. }
  78886. }
  78887. RegExpEvaluator.prototype.evaluate = function (lVal) {
  78888. var type = typeof lVal;
  78889. return type === 'string' ? this._condVal.test(lVal) : type === 'number' ? this._condVal.test(lVal + '') : false;
  78890. };
  78891. return RegExpEvaluator;
  78892. }();
  78893. var ConstConditionInternal =
  78894. /** @class */
  78895. function () {
  78896. function ConstConditionInternal() {}
  78897. ConstConditionInternal.prototype.evaluate = function () {
  78898. return this.value;
  78899. };
  78900. return ConstConditionInternal;
  78901. }();
  78902. var AndConditionInternal =
  78903. /** @class */
  78904. function () {
  78905. function AndConditionInternal() {}
  78906. AndConditionInternal.prototype.evaluate = function () {
  78907. var children = this.children;
  78908. for (var i = 0; i < children.length; i++) {
  78909. if (!children[i].evaluate()) {
  78910. return false;
  78911. }
  78912. }
  78913. return true;
  78914. };
  78915. return AndConditionInternal;
  78916. }();
  78917. var OrConditionInternal =
  78918. /** @class */
  78919. function () {
  78920. function OrConditionInternal() {}
  78921. OrConditionInternal.prototype.evaluate = function () {
  78922. var children = this.children;
  78923. for (var i = 0; i < children.length; i++) {
  78924. if (children[i].evaluate()) {
  78925. return true;
  78926. }
  78927. }
  78928. return false;
  78929. };
  78930. return OrConditionInternal;
  78931. }();
  78932. var NotConditionInternal =
  78933. /** @class */
  78934. function () {
  78935. function NotConditionInternal() {}
  78936. NotConditionInternal.prototype.evaluate = function () {
  78937. return !this.child.evaluate();
  78938. };
  78939. return NotConditionInternal;
  78940. }();
  78941. var RelationalConditionInternal =
  78942. /** @class */
  78943. function () {
  78944. function RelationalConditionInternal() {}
  78945. RelationalConditionInternal.prototype.evaluate = function () {
  78946. var needParse = !!this.valueParser; // Call getValue with no `this`.
  78947. var getValue = this.getValue;
  78948. var tarValRaw = getValue(this.valueGetterParam);
  78949. var tarValParsed = needParse ? this.valueParser(tarValRaw) : null; // Relational cond follow "and" logic internally.
  78950. for (var i = 0; i < this.subCondList.length; i++) {
  78951. if (!this.subCondList[i].evaluate(needParse ? tarValParsed : tarValRaw)) {
  78952. return false;
  78953. }
  78954. }
  78955. return true;
  78956. };
  78957. return RelationalConditionInternal;
  78958. }();
  78959. function parseOption(exprOption, getters) {
  78960. if (exprOption === true || exprOption === false) {
  78961. var cond = new ConstConditionInternal();
  78962. cond.value = exprOption;
  78963. return cond;
  78964. }
  78965. var errMsg = '';
  78966. if (!isObjectNotArray(exprOption)) {
  78967. if ("development" !== 'production') {
  78968. errMsg = makePrintable('Illegal config. Expect a plain object but actually', exprOption);
  78969. }
  78970. throwError(errMsg);
  78971. }
  78972. if (exprOption.and) {
  78973. return parseAndOrOption('and', exprOption, getters);
  78974. } else if (exprOption.or) {
  78975. return parseAndOrOption('or', exprOption, getters);
  78976. } else if (exprOption.not) {
  78977. return parseNotOption(exprOption, getters);
  78978. }
  78979. return parseRelationalOption(exprOption, getters);
  78980. }
  78981. function parseAndOrOption(op, exprOption, getters) {
  78982. var subOptionArr = exprOption[op];
  78983. var errMsg = '';
  78984. if ("development" !== 'production') {
  78985. errMsg = makePrintable('"and"/"or" condition should only be `' + op + ': [...]` and must not be empty array.', 'Illegal condition:', exprOption);
  78986. }
  78987. if (!isArray(subOptionArr)) {
  78988. throwError(errMsg);
  78989. }
  78990. if (!subOptionArr.length) {
  78991. throwError(errMsg);
  78992. }
  78993. var cond = op === 'and' ? new AndConditionInternal() : new OrConditionInternal();
  78994. cond.children = map(subOptionArr, function (subOption) {
  78995. return parseOption(subOption, getters);
  78996. });
  78997. if (!cond.children.length) {
  78998. throwError(errMsg);
  78999. }
  79000. return cond;
  79001. }
  79002. function parseNotOption(exprOption, getters) {
  79003. var subOption = exprOption.not;
  79004. var errMsg = '';
  79005. if ("development" !== 'production') {
  79006. errMsg = makePrintable('"not" condition should only be `not: {}`.', 'Illegal condition:', exprOption);
  79007. }
  79008. if (!isObjectNotArray(subOption)) {
  79009. throwError(errMsg);
  79010. }
  79011. var cond = new NotConditionInternal();
  79012. cond.child = parseOption(subOption, getters);
  79013. if (!cond.child) {
  79014. throwError(errMsg);
  79015. }
  79016. return cond;
  79017. }
  79018. function parseRelationalOption(exprOption, getters) {
  79019. var errMsg = '';
  79020. var valueGetterParam = getters.prepareGetValue(exprOption);
  79021. var subCondList = [];
  79022. var exprKeys = keys(exprOption);
  79023. var parserName = exprOption.parser;
  79024. var valueParser = parserName ? getRawValueParser(parserName) : null;
  79025. for (var i = 0; i < exprKeys.length; i++) {
  79026. var keyRaw = exprKeys[i];
  79027. if (keyRaw === 'parser' || getters.valueGetterAttrMap.get(keyRaw)) {
  79028. continue;
  79029. }
  79030. var op = hasOwn(RELATIONAL_EXPRESSION_OP_ALIAS_MAP, keyRaw) ? RELATIONAL_EXPRESSION_OP_ALIAS_MAP[keyRaw] : keyRaw;
  79031. var condValueRaw = exprOption[keyRaw];
  79032. var condValueParsed = valueParser ? valueParser(condValueRaw) : condValueRaw;
  79033. var evaluator = createFilterComparator(op, condValueParsed) || op === 'reg' && new RegExpEvaluator(condValueParsed);
  79034. if (!evaluator) {
  79035. if ("development" !== 'production') {
  79036. errMsg = makePrintable('Illegal relational operation: "' + keyRaw + '" in condition:', exprOption);
  79037. }
  79038. throwError(errMsg);
  79039. }
  79040. subCondList.push(evaluator);
  79041. }
  79042. if (!subCondList.length) {
  79043. if ("development" !== 'production') {
  79044. errMsg = makePrintable('Relational condition must have at least one operator.', 'Illegal condition:', exprOption);
  79045. } // No relational operator always disabled in case of dangers result.
  79046. throwError(errMsg);
  79047. }
  79048. var cond = new RelationalConditionInternal();
  79049. cond.valueGetterParam = valueGetterParam;
  79050. cond.valueParser = valueParser;
  79051. cond.getValue = getters.getValue;
  79052. cond.subCondList = subCondList;
  79053. return cond;
  79054. }
  79055. function isObjectNotArray(val) {
  79056. return isObject(val) && !isArrayLike(val);
  79057. }
  79058. var ConditionalExpressionParsed =
  79059. /** @class */
  79060. function () {
  79061. function ConditionalExpressionParsed(exprOption, getters) {
  79062. this._cond = parseOption(exprOption, getters);
  79063. }
  79064. ConditionalExpressionParsed.prototype.evaluate = function () {
  79065. return this._cond.evaluate();
  79066. };
  79067. return ConditionalExpressionParsed;
  79068. }();
  79069. function parseConditionalExpression(exprOption, getters) {
  79070. return new ConditionalExpressionParsed(exprOption, getters);
  79071. }
  79072. var filterTransform = {
  79073. type: 'echarts:filter',
  79074. // PEDING: enhance to filter by index rather than create new data
  79075. transform: function (params) {
  79076. // [Caveat] Fail-Fast:
  79077. // Do not return the whole dataset unless user config indicate it explicitly.
  79078. // For example, if no condition specified by mistake, return an empty result
  79079. // is better than return the entire raw soruce for user to find the mistake.
  79080. var upstream = params.upstream;
  79081. var rawItem;
  79082. var condition = parseConditionalExpression(params.config, {
  79083. valueGetterAttrMap: createHashMap({
  79084. dimension: true
  79085. }),
  79086. prepareGetValue: function (exprOption) {
  79087. var errMsg = '';
  79088. var dimLoose = exprOption.dimension;
  79089. if (!hasOwn(exprOption, 'dimension')) {
  79090. if ("development" !== 'production') {
  79091. errMsg = makePrintable('Relation condition must has prop "dimension" specified.', 'Illegal condition:', exprOption);
  79092. }
  79093. throwError(errMsg);
  79094. }
  79095. var dimInfo = upstream.getDimensionInfo(dimLoose);
  79096. if (!dimInfo) {
  79097. if ("development" !== 'production') {
  79098. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal condition:', exprOption, '.\n');
  79099. }
  79100. throwError(errMsg);
  79101. }
  79102. return {
  79103. dimIdx: dimInfo.index
  79104. };
  79105. },
  79106. getValue: function (param) {
  79107. return upstream.retrieveValueFromItem(rawItem, param.dimIdx);
  79108. }
  79109. });
  79110. var resultData = [];
  79111. for (var i = 0, len = upstream.count(); i < len; i++) {
  79112. rawItem = upstream.getRawDataItem(i);
  79113. if (condition.evaluate()) {
  79114. resultData.push(rawItem);
  79115. }
  79116. }
  79117. return {
  79118. data: resultData
  79119. };
  79120. }
  79121. };
  79122. var sampleLog = '';
  79123. if ("development" !== 'production') {
  79124. sampleLog = ['Valid config is like:', '{ dimension: "age", order: "asc" }', 'or [{ dimension: "age", order: "asc"], { dimension: "date", order: "desc" }]'].join(' ');
  79125. }
  79126. var sortTransform = {
  79127. type: 'echarts:sort',
  79128. transform: function (params) {
  79129. var upstream = params.upstream;
  79130. var config = params.config;
  79131. var errMsg = ''; // Normalize
  79132. // const orderExprList: OrderExpression[] = isArray(config[0])
  79133. // ? config as OrderExpression[]
  79134. // : [config as OrderExpression];
  79135. var orderExprList = normalizeToArray(config);
  79136. if (!orderExprList.length) {
  79137. if ("development" !== 'production') {
  79138. errMsg = 'Empty `config` in sort transform.';
  79139. }
  79140. throwError(errMsg);
  79141. }
  79142. var orderDefList = [];
  79143. each(orderExprList, function (orderExpr) {
  79144. var dimLoose = orderExpr.dimension;
  79145. var order = orderExpr.order;
  79146. var parserName = orderExpr.parser;
  79147. var incomparable = orderExpr.incomparable;
  79148. if (dimLoose == null) {
  79149. if ("development" !== 'production') {
  79150. errMsg = 'Sort transform config must has "dimension" specified.' + sampleLog;
  79151. }
  79152. throwError(errMsg);
  79153. }
  79154. if (order !== 'asc' && order !== 'desc') {
  79155. if ("development" !== 'production') {
  79156. errMsg = 'Sort transform config must has "order" specified.' + sampleLog;
  79157. }
  79158. throwError(errMsg);
  79159. }
  79160. if (incomparable && incomparable !== 'min' && incomparable !== 'max') {
  79161. var errMsg_1 = '';
  79162. if ("development" !== 'production') {
  79163. errMsg_1 = 'incomparable must be "min" or "max" rather than "' + incomparable + '".';
  79164. }
  79165. throwError(errMsg_1);
  79166. }
  79167. if (order !== 'asc' && order !== 'desc') {
  79168. var errMsg_2 = '';
  79169. if ("development" !== 'production') {
  79170. errMsg_2 = 'order must be "asc" or "desc" rather than "' + order + '".';
  79171. }
  79172. throwError(errMsg_2);
  79173. }
  79174. var dimInfo = upstream.getDimensionInfo(dimLoose);
  79175. if (!dimInfo) {
  79176. if ("development" !== 'production') {
  79177. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal config:', orderExpr, '.\n');
  79178. }
  79179. throwError(errMsg);
  79180. }
  79181. var parser = parserName ? getRawValueParser(parserName) : null;
  79182. if (parserName && !parser) {
  79183. if ("development" !== 'production') {
  79184. errMsg = makePrintable('Invalid parser name ' + parserName + '.\n', 'Illegal config:', orderExpr, '.\n');
  79185. }
  79186. throwError(errMsg);
  79187. }
  79188. orderDefList.push({
  79189. dimIdx: dimInfo.index,
  79190. parser: parser,
  79191. comparator: new SortOrderComparator(order, incomparable)
  79192. });
  79193. }); // TODO: support it?
  79194. var sourceFormat = upstream.sourceFormat;
  79195. if (sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS) {
  79196. if ("development" !== 'production') {
  79197. errMsg = 'sourceFormat "' + sourceFormat + '" is not supported yet';
  79198. }
  79199. throwError(errMsg);
  79200. } // Other upstream format are all array.
  79201. var resultData = [];
  79202. for (var i = 0, len = upstream.count(); i < len; i++) {
  79203. resultData.push(upstream.getRawDataItem(i));
  79204. }
  79205. resultData.sort(function (item0, item1) {
  79206. for (var i = 0; i < orderDefList.length; i++) {
  79207. var orderDef = orderDefList[i];
  79208. var val0 = upstream.retrieveValueFromItem(item0, orderDef.dimIdx);
  79209. var val1 = upstream.retrieveValueFromItem(item1, orderDef.dimIdx);
  79210. if (orderDef.parser) {
  79211. val0 = orderDef.parser(val0);
  79212. val1 = orderDef.parser(val1);
  79213. }
  79214. var result = orderDef.comparator.evaluate(val0, val1);
  79215. if (result !== 0) {
  79216. return result;
  79217. }
  79218. }
  79219. return 0;
  79220. });
  79221. return {
  79222. data: resultData
  79223. };
  79224. }
  79225. };
  79226. function install$R(registers) {
  79227. registers.registerTransform(filterTransform);
  79228. registers.registerTransform(sortTransform);
  79229. }
  79230. var DatasetModel =
  79231. /** @class */
  79232. function (_super) {
  79233. __extends(DatasetModel, _super);
  79234. function DatasetModel() {
  79235. var _this = _super !== null && _super.apply(this, arguments) || this;
  79236. _this.type = 'dataset';
  79237. return _this;
  79238. }
  79239. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  79240. _super.prototype.init.call(this, option, parentModel, ecModel);
  79241. this._sourceManager = new SourceManager(this);
  79242. disableTransformOptionMerge(this);
  79243. };
  79244. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  79245. _super.prototype.mergeOption.call(this, newOption, ecModel);
  79246. disableTransformOptionMerge(this);
  79247. };
  79248. DatasetModel.prototype.optionUpdated = function () {
  79249. this._sourceManager.dirty();
  79250. };
  79251. DatasetModel.prototype.getSourceManager = function () {
  79252. return this._sourceManager;
  79253. };
  79254. DatasetModel.type = 'dataset';
  79255. DatasetModel.defaultOption = {
  79256. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  79257. };
  79258. return DatasetModel;
  79259. }(ComponentModel);
  79260. var DatasetView =
  79261. /** @class */
  79262. function (_super) {
  79263. __extends(DatasetView, _super);
  79264. function DatasetView() {
  79265. var _this = _super !== null && _super.apply(this, arguments) || this;
  79266. _this.type = 'dataset';
  79267. return _this;
  79268. }
  79269. DatasetView.type = 'dataset';
  79270. return DatasetView;
  79271. }(ComponentView);
  79272. function install$S(registers) {
  79273. registers.registerComponentModel(DatasetModel);
  79274. registers.registerComponentView(DatasetView);
  79275. }
  79276. var CMD$4 = PathProxy.CMD;
  79277. function aroundEqual(a, b) {
  79278. return Math.abs(a - b) < 1e-5;
  79279. }
  79280. function pathToBezierCurves(path) {
  79281. var data = path.data;
  79282. var len = path.len();
  79283. var bezierArrayGroups = [];
  79284. var currentSubpath;
  79285. var xi = 0;
  79286. var yi = 0;
  79287. var x0 = 0;
  79288. var y0 = 0;
  79289. function createNewSubpath(x, y) {
  79290. if (currentSubpath && currentSubpath.length > 2) {
  79291. bezierArrayGroups.push(currentSubpath);
  79292. }
  79293. currentSubpath = [x, y];
  79294. }
  79295. function addLine(x0, y0, x1, y1) {
  79296. if (!(aroundEqual(x0, x1) && aroundEqual(y0, y1))) {
  79297. currentSubpath.push(x0, y0, x1, y1, x1, y1);
  79298. }
  79299. }
  79300. function addArc(startAngle, endAngle, cx, cy, rx, ry) {
  79301. var delta = Math.abs(endAngle - startAngle);
  79302. var len = Math.tan(delta / 4) * 4 / 3;
  79303. var dir = endAngle < startAngle ? -1 : 1;
  79304. var c1 = Math.cos(startAngle);
  79305. var s1 = Math.sin(startAngle);
  79306. var c2 = Math.cos(endAngle);
  79307. var s2 = Math.sin(endAngle);
  79308. var x1 = c1 * rx + cx;
  79309. var y1 = s1 * ry + cy;
  79310. var x4 = c2 * rx + cx;
  79311. var y4 = s2 * ry + cy;
  79312. var hx = rx * len * dir;
  79313. var hy = ry * len * dir;
  79314. currentSubpath.push(x1 - hx * s1, y1 + hy * c1, x4 + hx * s2, y4 - hy * c2, x4, y4);
  79315. }
  79316. var x1;
  79317. var y1;
  79318. var x2;
  79319. var y2;
  79320. for (var i = 0; i < len;) {
  79321. var cmd = data[i++];
  79322. var isFirst = i === 1;
  79323. if (isFirst) {
  79324. xi = data[i];
  79325. yi = data[i + 1];
  79326. x0 = xi;
  79327. y0 = yi;
  79328. if (cmd === CMD$4.L || cmd === CMD$4.C || cmd === CMD$4.Q) {
  79329. currentSubpath = [x0, y0];
  79330. }
  79331. }
  79332. switch (cmd) {
  79333. case CMD$4.M:
  79334. xi = x0 = data[i++];
  79335. yi = y0 = data[i++];
  79336. createNewSubpath(x0, y0);
  79337. break;
  79338. case CMD$4.L:
  79339. x1 = data[i++];
  79340. y1 = data[i++];
  79341. addLine(xi, yi, x1, y1);
  79342. xi = x1;
  79343. yi = y1;
  79344. break;
  79345. case CMD$4.C:
  79346. currentSubpath.push(data[i++], data[i++], data[i++], data[i++], xi = data[i++], yi = data[i++]);
  79347. break;
  79348. case CMD$4.Q:
  79349. x1 = data[i++];
  79350. y1 = data[i++];
  79351. x2 = data[i++];
  79352. y2 = data[i++];
  79353. currentSubpath.push(xi + 2 / 3 * (x1 - xi), yi + 2 / 3 * (y1 - yi), x2 + 2 / 3 * (x1 - x2), y2 + 2 / 3 * (y1 - y2), x2, y2);
  79354. xi = x2;
  79355. yi = y2;
  79356. break;
  79357. case CMD$4.A:
  79358. var cx = data[i++];
  79359. var cy = data[i++];
  79360. var rx = data[i++];
  79361. var ry = data[i++];
  79362. var startAngle = data[i++];
  79363. var endAngle = data[i++] + startAngle;
  79364. i += 1;
  79365. var anticlockwise = !data[i++];
  79366. x1 = Math.cos(startAngle) * rx + cx;
  79367. y1 = Math.sin(startAngle) * ry + cy;
  79368. if (isFirst) {
  79369. x0 = x1;
  79370. y0 = y1;
  79371. createNewSubpath(x0, y0);
  79372. }
  79373. else {
  79374. addLine(xi, yi, x1, y1);
  79375. }
  79376. xi = Math.cos(endAngle) * rx + cx;
  79377. yi = Math.sin(endAngle) * ry + cy;
  79378. var step = (anticlockwise ? -1 : 1) * Math.PI / 2;
  79379. for (var angle = startAngle; anticlockwise ? angle > endAngle : angle < endAngle; angle += step) {
  79380. var nextAngle = anticlockwise ? Math.max(angle + step, endAngle)
  79381. : Math.min(angle + step, endAngle);
  79382. addArc(angle, nextAngle, cx, cy, rx, ry);
  79383. }
  79384. break;
  79385. case CMD$4.R:
  79386. x0 = xi = data[i++];
  79387. y0 = yi = data[i++];
  79388. x1 = x0 + data[i++];
  79389. y1 = y0 + data[i++];
  79390. createNewSubpath(x1, y0);
  79391. addLine(x1, y0, x1, y1);
  79392. addLine(x1, y1, x0, y1);
  79393. addLine(x0, y1, x0, y0);
  79394. addLine(x0, y0, x1, y0);
  79395. break;
  79396. case CMD$4.Z:
  79397. currentSubpath && addLine(xi, yi, x0, y0);
  79398. xi = x0;
  79399. yi = y0;
  79400. break;
  79401. }
  79402. }
  79403. if (currentSubpath && currentSubpath.length > 2) {
  79404. bezierArrayGroups.push(currentSubpath);
  79405. }
  79406. return bezierArrayGroups;
  79407. }
  79408. function adpativeBezier(x0, y0, x1, y1, x2, y2, x3, y3, out, scale) {
  79409. if (aroundEqual(x0, x1) && aroundEqual(y0, y1) && aroundEqual(x2, x3) && aroundEqual(y2, y3)) {
  79410. out.push(x3, y3);
  79411. return;
  79412. }
  79413. var PIXEL_DISTANCE = 2 / scale;
  79414. var PIXEL_DISTANCE_SQR = PIXEL_DISTANCE * PIXEL_DISTANCE;
  79415. var dx = x3 - x0;
  79416. var dy = y3 - y0;
  79417. var d = Math.sqrt(dx * dx + dy * dy);
  79418. dx /= d;
  79419. dy /= d;
  79420. var dx1 = x1 - x0;
  79421. var dy1 = y1 - y0;
  79422. var dx2 = x2 - x3;
  79423. var dy2 = y2 - y3;
  79424. var cp1LenSqr = dx1 * dx1 + dy1 * dy1;
  79425. var cp2LenSqr = dx2 * dx2 + dy2 * dy2;
  79426. if (cp1LenSqr < PIXEL_DISTANCE_SQR && cp2LenSqr < PIXEL_DISTANCE_SQR) {
  79427. out.push(x3, y3);
  79428. return;
  79429. }
  79430. var projLen1 = dx * dx1 + dy * dy1;
  79431. var projLen2 = -dx * dx2 - dy * dy2;
  79432. var d1Sqr = cp1LenSqr - projLen1 * projLen1;
  79433. var d2Sqr = cp2LenSqr - projLen2 * projLen2;
  79434. if (d1Sqr < PIXEL_DISTANCE_SQR && projLen1 >= 0
  79435. && d2Sqr < PIXEL_DISTANCE_SQR && projLen2 >= 0) {
  79436. out.push(x3, y3);
  79437. return;
  79438. }
  79439. var tmpSegX = [];
  79440. var tmpSegY = [];
  79441. cubicSubdivide(x0, x1, x2, x3, 0.5, tmpSegX);
  79442. cubicSubdivide(y0, y1, y2, y3, 0.5, tmpSegY);
  79443. adpativeBezier(tmpSegX[0], tmpSegY[0], tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], tmpSegX[3], tmpSegY[3], out, scale);
  79444. adpativeBezier(tmpSegX[4], tmpSegY[4], tmpSegX[5], tmpSegY[5], tmpSegX[6], tmpSegY[6], tmpSegX[7], tmpSegY[7], out, scale);
  79445. }
  79446. function pathToPolygons(path, scale) {
  79447. var bezierArrayGroups = pathToBezierCurves(path);
  79448. var polygons = [];
  79449. scale = scale || 1;
  79450. for (var i = 0; i < bezierArrayGroups.length; i++) {
  79451. var beziers = bezierArrayGroups[i];
  79452. var polygon = [];
  79453. var x0 = beziers[0];
  79454. var y0 = beziers[1];
  79455. polygon.push(x0, y0);
  79456. for (var k = 2; k < beziers.length;) {
  79457. var x1 = beziers[k++];
  79458. var y1 = beziers[k++];
  79459. var x2 = beziers[k++];
  79460. var y2 = beziers[k++];
  79461. var x3 = beziers[k++];
  79462. var y3 = beziers[k++];
  79463. adpativeBezier(x0, y0, x1, y1, x2, y2, x3, y3, polygon, scale);
  79464. x0 = x3;
  79465. y0 = y3;
  79466. }
  79467. polygons.push(polygon);
  79468. }
  79469. return polygons;
  79470. }
  79471. function getDividingGrids(dimSize, rowDim, count) {
  79472. var rowSize = dimSize[rowDim];
  79473. var columnSize = dimSize[1 - rowDim];
  79474. var ratio = Math.abs(rowSize / columnSize);
  79475. var rowCount = Math.ceil(Math.sqrt(ratio * count));
  79476. var columnCount = Math.floor(count / rowCount);
  79477. if (columnCount === 0) {
  79478. columnCount = 1;
  79479. rowCount = count;
  79480. }
  79481. var grids = [];
  79482. for (var i = 0; i < rowCount; i++) {
  79483. grids.push(columnCount);
  79484. }
  79485. var currentCount = rowCount * columnCount;
  79486. var remained = count - currentCount;
  79487. if (remained > 0) {
  79488. for (var i = 0; i < remained; i++) {
  79489. grids[i % rowCount] += 1;
  79490. }
  79491. }
  79492. return grids;
  79493. }
  79494. function divideSector(sectorShape, count, outShapes) {
  79495. var r0 = sectorShape.r0;
  79496. var r = sectorShape.r;
  79497. var startAngle = sectorShape.startAngle;
  79498. var endAngle = sectorShape.endAngle;
  79499. var angle = Math.abs(endAngle - startAngle);
  79500. var arcLen = angle * r;
  79501. var deltaR = r - r0;
  79502. var isAngleRow = arcLen > Math.abs(deltaR);
  79503. var grids = getDividingGrids([arcLen, deltaR], isAngleRow ? 0 : 1, count);
  79504. var rowSize = (isAngleRow ? angle : deltaR) / grids.length;
  79505. for (var row = 0; row < grids.length; row++) {
  79506. var columnSize = (isAngleRow ? deltaR : angle) / grids[row];
  79507. for (var column = 0; column < grids[row]; column++) {
  79508. var newShape = {};
  79509. if (isAngleRow) {
  79510. newShape.startAngle = startAngle + rowSize * row;
  79511. newShape.endAngle = startAngle + rowSize * (row + 1);
  79512. newShape.r0 = r0 + columnSize * column;
  79513. newShape.r = r0 + columnSize * (column + 1);
  79514. }
  79515. else {
  79516. newShape.startAngle = startAngle + columnSize * column;
  79517. newShape.endAngle = startAngle + columnSize * (column + 1);
  79518. newShape.r0 = r0 + rowSize * row;
  79519. newShape.r = r0 + rowSize * (row + 1);
  79520. }
  79521. newShape.clockwise = sectorShape.clockwise;
  79522. newShape.cx = sectorShape.cx;
  79523. newShape.cy = sectorShape.cy;
  79524. outShapes.push(newShape);
  79525. }
  79526. }
  79527. }
  79528. function divideRect(rectShape, count, outShapes) {
  79529. var width = rectShape.width;
  79530. var height = rectShape.height;
  79531. var isHorizontalRow = width > height;
  79532. var grids = getDividingGrids([width, height], isHorizontalRow ? 0 : 1, count);
  79533. var rowSizeDim = isHorizontalRow ? 'width' : 'height';
  79534. var columnSizeDim = isHorizontalRow ? 'height' : 'width';
  79535. var rowDim = isHorizontalRow ? 'x' : 'y';
  79536. var columnDim = isHorizontalRow ? 'y' : 'x';
  79537. var rowSize = rectShape[rowSizeDim] / grids.length;
  79538. for (var row = 0; row < grids.length; row++) {
  79539. var columnSize = rectShape[columnSizeDim] / grids[row];
  79540. for (var column = 0; column < grids[row]; column++) {
  79541. var newShape = {};
  79542. newShape[rowDim] = row * rowSize;
  79543. newShape[columnDim] = column * columnSize;
  79544. newShape[rowSizeDim] = rowSize;
  79545. newShape[columnSizeDim] = columnSize;
  79546. newShape.x += rectShape.x;
  79547. newShape.y += rectShape.y;
  79548. outShapes.push(newShape);
  79549. }
  79550. }
  79551. }
  79552. function crossProduct2d$1(x1, y1, x2, y2) {
  79553. return x1 * y2 - x2 * y1;
  79554. }
  79555. function lineLineIntersect$1(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  79556. var mx = a2x - a1x;
  79557. var my = a2y - a1y;
  79558. var nx = b2x - b1x;
  79559. var ny = b2y - b1y;
  79560. var nmCrossProduct = crossProduct2d$1(nx, ny, mx, my);
  79561. if (Math.abs(nmCrossProduct) < 1e-6) {
  79562. return null;
  79563. }
  79564. var b1a1x = a1x - b1x;
  79565. var b1a1y = a1y - b1y;
  79566. var p = crossProduct2d$1(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  79567. if (p < 0 || p > 1) {
  79568. return null;
  79569. }
  79570. return new Point(p * mx + a1x, p * my + a1y);
  79571. }
  79572. function projPtOnLine(pt, lineA, lineB) {
  79573. var dir = new Point();
  79574. Point.sub(dir, lineB, lineA);
  79575. dir.normalize();
  79576. var dir2 = new Point();
  79577. Point.sub(dir2, pt, lineA);
  79578. var len = dir2.dot(dir);
  79579. return len;
  79580. }
  79581. function addToPoly(poly, pt) {
  79582. var last = poly[poly.length - 1];
  79583. if (last && last[0] === pt[0] && last[1] === pt[1]) {
  79584. return;
  79585. }
  79586. poly.push(pt);
  79587. }
  79588. function splitPolygonByLine(points, lineA, lineB) {
  79589. var len = points.length;
  79590. var intersections = [];
  79591. for (var i = 0; i < len; i++) {
  79592. var p0 = points[i];
  79593. var p1 = points[(i + 1) % len];
  79594. var intersectionPt = lineLineIntersect$1(p0[0], p0[1], p1[0], p1[1], lineA.x, lineA.y, lineB.x, lineB.y);
  79595. if (intersectionPt) {
  79596. intersections.push({
  79597. projPt: projPtOnLine(intersectionPt, lineA, lineB),
  79598. pt: intersectionPt,
  79599. idx: i
  79600. });
  79601. }
  79602. }
  79603. if (intersections.length < 2) {
  79604. return [{ points: points }, { points: points }];
  79605. }
  79606. intersections.sort(function (a, b) {
  79607. return a.projPt - b.projPt;
  79608. });
  79609. var splitPt0 = intersections[0];
  79610. var splitPt1 = intersections[intersections.length - 1];
  79611. if (splitPt1.idx < splitPt0.idx) {
  79612. var tmp = splitPt0;
  79613. splitPt0 = splitPt1;
  79614. splitPt1 = tmp;
  79615. }
  79616. var splitPt0Arr = [splitPt0.pt.x, splitPt0.pt.y];
  79617. var splitPt1Arr = [splitPt1.pt.x, splitPt1.pt.y];
  79618. var newPolyA = [splitPt0Arr];
  79619. var newPolyB = [splitPt1Arr];
  79620. for (var i = splitPt0.idx + 1; i <= splitPt1.idx; i++) {
  79621. addToPoly(newPolyA, points[i].slice());
  79622. }
  79623. addToPoly(newPolyA, splitPt1Arr);
  79624. addToPoly(newPolyA, splitPt0Arr);
  79625. for (var i = splitPt1.idx + 1; i <= splitPt0.idx + len; i++) {
  79626. addToPoly(newPolyB, points[i % len].slice());
  79627. }
  79628. addToPoly(newPolyB, splitPt0Arr);
  79629. addToPoly(newPolyB, splitPt1Arr);
  79630. return [{
  79631. points: newPolyA
  79632. }, {
  79633. points: newPolyB
  79634. }];
  79635. }
  79636. function binaryDividePolygon(polygonShape) {
  79637. var points = polygonShape.points;
  79638. var min = [];
  79639. var max = [];
  79640. fromPoints(points, min, max);
  79641. var boundingRect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  79642. var width = boundingRect.width;
  79643. var height = boundingRect.height;
  79644. var x = boundingRect.x;
  79645. var y = boundingRect.y;
  79646. var pt0 = new Point();
  79647. var pt1 = new Point();
  79648. if (width > height) {
  79649. pt0.x = pt1.x = x + width / 2;
  79650. pt0.y = y;
  79651. pt1.y = y + height;
  79652. }
  79653. else {
  79654. pt0.y = pt1.y = y + height / 2;
  79655. pt0.x = x;
  79656. pt1.x = x + width;
  79657. }
  79658. return splitPolygonByLine(points, pt0, pt1);
  79659. }
  79660. function binaryDivideRecursive(divider, shape, count, out) {
  79661. if (count === 1) {
  79662. out.push(shape);
  79663. }
  79664. else {
  79665. var mid = Math.floor(count / 2);
  79666. var sub = divider(shape);
  79667. binaryDivideRecursive(divider, sub[0], mid, out);
  79668. binaryDivideRecursive(divider, sub[1], count - mid, out);
  79669. }
  79670. return out;
  79671. }
  79672. function clone$4(path, count) {
  79673. var paths = [];
  79674. for (var i = 0; i < count; i++) {
  79675. paths.push(clonePath(path));
  79676. }
  79677. return paths;
  79678. }
  79679. function copyPathProps(source, target) {
  79680. target.setStyle(source.style);
  79681. target.z = source.z;
  79682. target.z2 = source.z2;
  79683. target.zlevel = source.zlevel;
  79684. }
  79685. function polygonConvert(points) {
  79686. var out = [];
  79687. for (var i = 0; i < points.length;) {
  79688. out.push([points[i++], points[i++]]);
  79689. }
  79690. return out;
  79691. }
  79692. function split(path, count) {
  79693. var outShapes = [];
  79694. var shape = path.shape;
  79695. var OutShapeCtor;
  79696. switch (path.type) {
  79697. case 'rect':
  79698. divideRect(shape, count, outShapes);
  79699. OutShapeCtor = Rect;
  79700. break;
  79701. case 'sector':
  79702. divideSector(shape, count, outShapes);
  79703. OutShapeCtor = Sector;
  79704. break;
  79705. case 'circle':
  79706. divideSector({
  79707. r0: 0, r: shape.r, startAngle: 0, endAngle: Math.PI * 2,
  79708. cx: shape.cx, cy: shape.cy
  79709. }, count, outShapes);
  79710. OutShapeCtor = Sector;
  79711. break;
  79712. default:
  79713. var m = path.getComputedTransform();
  79714. var scale = m ? Math.sqrt(Math.max(m[0] * m[0] + m[1] * m[1], m[2] * m[2] + m[3] * m[3])) : 1;
  79715. var polygons = map(pathToPolygons(path.getUpdatedPathProxy(), scale), function (poly) { return polygonConvert(poly); });
  79716. var polygonCount = polygons.length;
  79717. if (polygonCount === 0) {
  79718. binaryDivideRecursive(binaryDividePolygon, {
  79719. points: polygons[0]
  79720. }, count, outShapes);
  79721. }
  79722. else if (polygonCount === count) {
  79723. for (var i = 0; i < polygonCount; i++) {
  79724. outShapes.push({
  79725. points: polygons[i]
  79726. });
  79727. }
  79728. }
  79729. else {
  79730. var totalArea_1 = 0;
  79731. var items = map(polygons, function (poly) {
  79732. var min = [];
  79733. var max = [];
  79734. fromPoints(poly, min, max);
  79735. var area = (max[1] - min[1]) * (max[0] - min[0]);
  79736. totalArea_1 += area;
  79737. return { poly: poly, area: area };
  79738. });
  79739. items.sort(function (a, b) { return b.area - a.area; });
  79740. var left = count;
  79741. for (var i = 0; i < polygonCount; i++) {
  79742. var item = items[i];
  79743. if (left <= 0) {
  79744. break;
  79745. }
  79746. var selfCount = i === polygonCount - 1
  79747. ? left
  79748. : Math.ceil(item.area / totalArea_1 * count);
  79749. if (selfCount < 0) {
  79750. continue;
  79751. }
  79752. binaryDivideRecursive(binaryDividePolygon, {
  79753. points: item.poly
  79754. }, selfCount, outShapes);
  79755. left -= selfCount;
  79756. }
  79757. }
  79758. OutShapeCtor = Polygon;
  79759. break;
  79760. }
  79761. if (!OutShapeCtor) {
  79762. return clone$4(path, count);
  79763. }
  79764. var out = [];
  79765. for (var i = 0; i < outShapes.length; i++) {
  79766. var subPath = new OutShapeCtor();
  79767. subPath.setShape(outShapes[i]);
  79768. copyPathProps(path, subPath);
  79769. out.push(subPath);
  79770. }
  79771. return out;
  79772. }
  79773. function alignSubpath(subpath1, subpath2) {
  79774. var len1 = subpath1.length;
  79775. var len2 = subpath2.length;
  79776. if (len1 === len2) {
  79777. return [subpath1, subpath2];
  79778. }
  79779. var tmpSegX = [];
  79780. var tmpSegY = [];
  79781. var shorterPath = len1 < len2 ? subpath1 : subpath2;
  79782. var shorterLen = Math.min(len1, len2);
  79783. var diff = Math.abs(len2 - len1) / 6;
  79784. var shorterBezierCount = (shorterLen - 2) / 6;
  79785. var eachCurveSubDivCount = Math.ceil(diff / shorterBezierCount) + 1;
  79786. var newSubpath = [shorterPath[0], shorterPath[1]];
  79787. var remained = diff;
  79788. for (var i = 2; i < shorterLen;) {
  79789. var x0 = shorterPath[i - 2];
  79790. var y0 = shorterPath[i - 1];
  79791. var x1 = shorterPath[i++];
  79792. var y1 = shorterPath[i++];
  79793. var x2 = shorterPath[i++];
  79794. var y2 = shorterPath[i++];
  79795. var x3 = shorterPath[i++];
  79796. var y3 = shorterPath[i++];
  79797. if (remained <= 0) {
  79798. newSubpath.push(x1, y1, x2, y2, x3, y3);
  79799. continue;
  79800. }
  79801. var actualSubDivCount = Math.min(remained, eachCurveSubDivCount - 1) + 1;
  79802. for (var k = 1; k <= actualSubDivCount; k++) {
  79803. var p = k / actualSubDivCount;
  79804. cubicSubdivide(x0, x1, x2, x3, p, tmpSegX);
  79805. cubicSubdivide(y0, y1, y2, y3, p, tmpSegY);
  79806. x0 = tmpSegX[3];
  79807. y0 = tmpSegY[3];
  79808. newSubpath.push(tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], x0, y0);
  79809. x1 = tmpSegX[5];
  79810. y1 = tmpSegY[5];
  79811. x2 = tmpSegX[6];
  79812. y2 = tmpSegY[6];
  79813. }
  79814. remained -= actualSubDivCount - 1;
  79815. }
  79816. return shorterPath === subpath1 ? [newSubpath, subpath2] : [subpath1, newSubpath];
  79817. }
  79818. function createSubpath(lastSubpathSubpath, otherSubpath) {
  79819. var len = lastSubpathSubpath.length;
  79820. var lastX = lastSubpathSubpath[len - 2];
  79821. var lastY = lastSubpathSubpath[len - 1];
  79822. var newSubpath = [];
  79823. for (var i = 0; i < otherSubpath.length;) {
  79824. newSubpath[i++] = lastX;
  79825. newSubpath[i++] = lastY;
  79826. }
  79827. return newSubpath;
  79828. }
  79829. function alignBezierCurves(array1, array2) {
  79830. var _a;
  79831. var lastSubpath1;
  79832. var lastSubpath2;
  79833. var newArray1 = [];
  79834. var newArray2 = [];
  79835. for (var i = 0; i < Math.max(array1.length, array2.length); i++) {
  79836. var subpath1 = array1[i];
  79837. var subpath2 = array2[i];
  79838. var newSubpath1 = void 0;
  79839. var newSubpath2 = void 0;
  79840. if (!subpath1) {
  79841. newSubpath1 = createSubpath(lastSubpath1 || subpath2, subpath2);
  79842. newSubpath2 = subpath2;
  79843. }
  79844. else if (!subpath2) {
  79845. newSubpath2 = createSubpath(lastSubpath2 || subpath1, subpath1);
  79846. newSubpath1 = subpath1;
  79847. }
  79848. else {
  79849. _a = alignSubpath(subpath1, subpath2), newSubpath1 = _a[0], newSubpath2 = _a[1];
  79850. lastSubpath1 = newSubpath1;
  79851. lastSubpath2 = newSubpath2;
  79852. }
  79853. newArray1.push(newSubpath1);
  79854. newArray2.push(newSubpath2);
  79855. }
  79856. return [newArray1, newArray2];
  79857. }
  79858. function centroid(array) {
  79859. var signedArea = 0;
  79860. var cx = 0;
  79861. var cy = 0;
  79862. var len = array.length;
  79863. for (var i = 0, j = len - 2; i < len; j = i, i += 2) {
  79864. var x0 = array[j];
  79865. var y0 = array[j + 1];
  79866. var x1 = array[i];
  79867. var y1 = array[i + 1];
  79868. var a = x0 * y1 - x1 * y0;
  79869. signedArea += a;
  79870. cx += (x0 + x1) * a;
  79871. cy += (y0 + y1) * a;
  79872. }
  79873. if (signedArea === 0) {
  79874. return [array[0] || 0, array[1] || 0];
  79875. }
  79876. return [cx / signedArea / 3, cy / signedArea / 3, signedArea];
  79877. }
  79878. function findBestRingOffset(fromSubBeziers, toSubBeziers, fromCp, toCp) {
  79879. var bezierCount = (fromSubBeziers.length - 2) / 6;
  79880. var bestScore = Infinity;
  79881. var bestOffset = 0;
  79882. var len = fromSubBeziers.length;
  79883. var len2 = len - 2;
  79884. for (var offset = 0; offset < bezierCount; offset++) {
  79885. var cursorOffset = offset * 6;
  79886. var score = 0;
  79887. for (var k = 0; k < len; k += 2) {
  79888. var idx = k === 0 ? cursorOffset : ((cursorOffset + k - 2) % len2 + 2);
  79889. var x0 = fromSubBeziers[idx] - fromCp[0];
  79890. var y0 = fromSubBeziers[idx + 1] - fromCp[1];
  79891. var x1 = toSubBeziers[k] - toCp[0];
  79892. var y1 = toSubBeziers[k + 1] - toCp[1];
  79893. var dx = x1 - x0;
  79894. var dy = y1 - y0;
  79895. score += dx * dx + dy * dy;
  79896. }
  79897. if (score < bestScore) {
  79898. bestScore = score;
  79899. bestOffset = offset;
  79900. }
  79901. }
  79902. return bestOffset;
  79903. }
  79904. function reverse(array) {
  79905. var newArr = [];
  79906. var len = array.length;
  79907. for (var i = 0; i < len; i += 2) {
  79908. newArr[i] = array[len - i - 2];
  79909. newArr[i + 1] = array[len - i - 1];
  79910. }
  79911. return newArr;
  79912. }
  79913. function findBestMorphingRotation(fromArr, toArr, searchAngleIteration, searchAngleRange) {
  79914. var result = [];
  79915. var fromNeedsReverse;
  79916. for (var i = 0; i < fromArr.length; i++) {
  79917. var fromSubpathBezier = fromArr[i];
  79918. var toSubpathBezier = toArr[i];
  79919. var fromCp = centroid(fromSubpathBezier);
  79920. var toCp = centroid(toSubpathBezier);
  79921. if (fromNeedsReverse == null) {
  79922. fromNeedsReverse = fromCp[2] < 0 !== toCp[2] < 0;
  79923. }
  79924. var newFromSubpathBezier = [];
  79925. var newToSubpathBezier = [];
  79926. var bestAngle = 0;
  79927. var bestScore = Infinity;
  79928. var tmpArr = [];
  79929. var len = fromSubpathBezier.length;
  79930. if (fromNeedsReverse) {
  79931. fromSubpathBezier = reverse(fromSubpathBezier);
  79932. }
  79933. var offset = findBestRingOffset(fromSubpathBezier, toSubpathBezier, fromCp, toCp) * 6;
  79934. var len2 = len - 2;
  79935. for (var k = 0; k < len2; k += 2) {
  79936. var idx = (offset + k) % len2 + 2;
  79937. newFromSubpathBezier[k + 2] = fromSubpathBezier[idx] - fromCp[0];
  79938. newFromSubpathBezier[k + 3] = fromSubpathBezier[idx + 1] - fromCp[1];
  79939. }
  79940. newFromSubpathBezier[0] = fromSubpathBezier[offset] - fromCp[0];
  79941. newFromSubpathBezier[1] = fromSubpathBezier[offset + 1] - fromCp[1];
  79942. if (searchAngleIteration > 0) {
  79943. var step = searchAngleRange / searchAngleIteration;
  79944. for (var angle = -searchAngleRange / 2; angle <= searchAngleRange / 2; angle += step) {
  79945. var sa = Math.sin(angle);
  79946. var ca = Math.cos(angle);
  79947. var score = 0;
  79948. for (var k = 0; k < fromSubpathBezier.length; k += 2) {
  79949. var x0 = newFromSubpathBezier[k];
  79950. var y0 = newFromSubpathBezier[k + 1];
  79951. var x1 = toSubpathBezier[k] - toCp[0];
  79952. var y1 = toSubpathBezier[k + 1] - toCp[1];
  79953. var newX1 = x1 * ca - y1 * sa;
  79954. var newY1 = x1 * sa + y1 * ca;
  79955. tmpArr[k] = newX1;
  79956. tmpArr[k + 1] = newY1;
  79957. var dx = newX1 - x0;
  79958. var dy = newY1 - y0;
  79959. score += dx * dx + dy * dy;
  79960. }
  79961. if (score < bestScore) {
  79962. bestScore = score;
  79963. bestAngle = angle;
  79964. for (var m = 0; m < tmpArr.length; m++) {
  79965. newToSubpathBezier[m] = tmpArr[m];
  79966. }
  79967. }
  79968. }
  79969. }
  79970. else {
  79971. for (var i_1 = 0; i_1 < len; i_1 += 2) {
  79972. newToSubpathBezier[i_1] = toSubpathBezier[i_1] - toCp[0];
  79973. newToSubpathBezier[i_1 + 1] = toSubpathBezier[i_1 + 1] - toCp[1];
  79974. }
  79975. }
  79976. result.push({
  79977. from: newFromSubpathBezier,
  79978. to: newToSubpathBezier,
  79979. fromCp: fromCp,
  79980. toCp: toCp,
  79981. rotation: -bestAngle
  79982. });
  79983. }
  79984. return result;
  79985. }
  79986. function isCombineMorphing(path) {
  79987. return path.__isCombineMorphing;
  79988. }
  79989. var SAVED_METHOD_PREFIX = '__mOriginal_';
  79990. function saveAndModifyMethod(obj, methodName, modifiers) {
  79991. var savedMethodName = SAVED_METHOD_PREFIX + methodName;
  79992. var originalMethod = obj[savedMethodName] || obj[methodName];
  79993. if (!obj[savedMethodName]) {
  79994. obj[savedMethodName] = obj[methodName];
  79995. }
  79996. var replace = modifiers.replace;
  79997. var after = modifiers.after;
  79998. var before = modifiers.before;
  79999. obj[methodName] = function () {
  80000. var args = arguments;
  80001. var res;
  80002. before && before.apply(this, args);
  80003. if (replace) {
  80004. res = replace.apply(this, args);
  80005. }
  80006. else {
  80007. res = originalMethod.apply(this, args);
  80008. }
  80009. after && after.apply(this, args);
  80010. return res;
  80011. };
  80012. }
  80013. function restoreMethod(obj, methodName) {
  80014. var savedMethodName = SAVED_METHOD_PREFIX + methodName;
  80015. if (obj[savedMethodName]) {
  80016. obj[methodName] = obj[savedMethodName];
  80017. obj[savedMethodName] = null;
  80018. }
  80019. }
  80020. function applyTransformOnBeziers(bezierCurves, mm) {
  80021. for (var i = 0; i < bezierCurves.length; i++) {
  80022. var subBeziers = bezierCurves[i];
  80023. for (var k = 0; k < subBeziers.length;) {
  80024. var x = subBeziers[k];
  80025. var y = subBeziers[k + 1];
  80026. subBeziers[k++] = mm[0] * x + mm[2] * y + mm[4];
  80027. subBeziers[k++] = mm[1] * x + mm[3] * y + mm[5];
  80028. }
  80029. }
  80030. }
  80031. function prepareMorphPath(fromPath, toPath) {
  80032. var fromPathProxy = fromPath.getUpdatedPathProxy();
  80033. var toPathProxy = toPath.getUpdatedPathProxy();
  80034. var _a = alignBezierCurves(pathToBezierCurves(fromPathProxy), pathToBezierCurves(toPathProxy)), fromBezierCurves = _a[0], toBezierCurves = _a[1];
  80035. var fromPathTransform = fromPath.getComputedTransform();
  80036. var toPathTransform = toPath.getComputedTransform();
  80037. function updateIdentityTransform() {
  80038. this.transform = null;
  80039. }
  80040. fromPathTransform && applyTransformOnBeziers(fromBezierCurves, fromPathTransform);
  80041. toPathTransform && applyTransformOnBeziers(toBezierCurves, toPathTransform);
  80042. saveAndModifyMethod(toPath, 'updateTransform', { replace: updateIdentityTransform });
  80043. toPath.transform = null;
  80044. var morphingData = findBestMorphingRotation(fromBezierCurves, toBezierCurves, 10, Math.PI);
  80045. var tmpArr = [];
  80046. saveAndModifyMethod(toPath, 'buildPath', { replace: function (path) {
  80047. var t = toPath.__morphT;
  80048. var onet = 1 - t;
  80049. var newCp = [];
  80050. for (var i = 0; i < morphingData.length; i++) {
  80051. var item = morphingData[i];
  80052. var from = item.from;
  80053. var to = item.to;
  80054. var angle = item.rotation * t;
  80055. var fromCp = item.fromCp;
  80056. var toCp = item.toCp;
  80057. var sa = Math.sin(angle);
  80058. var ca = Math.cos(angle);
  80059. lerp(newCp, fromCp, toCp, t);
  80060. for (var m = 0; m < from.length; m += 2) {
  80061. var x0_1 = from[m];
  80062. var y0_1 = from[m + 1];
  80063. var x1 = to[m];
  80064. var y1 = to[m + 1];
  80065. var x = x0_1 * onet + x1 * t;
  80066. var y = y0_1 * onet + y1 * t;
  80067. tmpArr[m] = (x * ca - y * sa) + newCp[0];
  80068. tmpArr[m + 1] = (x * sa + y * ca) + newCp[1];
  80069. }
  80070. var x0 = tmpArr[0];
  80071. var y0 = tmpArr[1];
  80072. path.moveTo(x0, y0);
  80073. for (var m = 2; m < from.length;) {
  80074. var x1 = tmpArr[m++];
  80075. var y1 = tmpArr[m++];
  80076. var x2 = tmpArr[m++];
  80077. var y2 = tmpArr[m++];
  80078. var x3 = tmpArr[m++];
  80079. var y3 = tmpArr[m++];
  80080. if (x0 === x1 && y0 === y1 && x2 === x3 && y2 === y3) {
  80081. path.lineTo(x3, y3);
  80082. }
  80083. else {
  80084. path.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  80085. }
  80086. x0 = x3;
  80087. y0 = y3;
  80088. }
  80089. }
  80090. } });
  80091. }
  80092. function morphPath(fromPath, toPath, animationOpts) {
  80093. if (!fromPath || !toPath) {
  80094. return toPath;
  80095. }
  80096. var oldDone = animationOpts.done;
  80097. var oldDuring = animationOpts.during;
  80098. prepareMorphPath(fromPath, toPath);
  80099. toPath.__morphT = 0;
  80100. function restoreToPath() {
  80101. restoreMethod(toPath, 'buildPath');
  80102. restoreMethod(toPath, 'updateTransform');
  80103. toPath.__morphT = -1;
  80104. toPath.createPathProxy();
  80105. toPath.dirtyShape();
  80106. }
  80107. toPath.animateTo({
  80108. __morphT: 1
  80109. }, defaults({
  80110. during: function (p) {
  80111. toPath.dirtyShape();
  80112. oldDuring && oldDuring(p);
  80113. },
  80114. done: function () {
  80115. restoreToPath();
  80116. oldDone && oldDone();
  80117. }
  80118. }, animationOpts));
  80119. return toPath;
  80120. }
  80121. function hilbert(x, y, minX, minY, maxX, maxY) {
  80122. var bits = 16;
  80123. x = (maxX === minX) ? 0 : Math.round(32767 * (x - minX) / (maxX - minX));
  80124. y = (maxY === minY) ? 0 : Math.round(32767 * (y - minY) / (maxY - minY));
  80125. var d = 0;
  80126. var tmp;
  80127. for (var s = (1 << bits) / 2; s > 0; s /= 2) {
  80128. var rx = 0;
  80129. var ry = 0;
  80130. if ((x & s) > 0) {
  80131. rx = 1;
  80132. }
  80133. if ((y & s) > 0) {
  80134. ry = 1;
  80135. }
  80136. d += s * s * ((3 * rx) ^ ry);
  80137. if (ry === 0) {
  80138. if (rx === 1) {
  80139. x = s - 1 - x;
  80140. y = s - 1 - y;
  80141. }
  80142. tmp = x;
  80143. x = y;
  80144. y = tmp;
  80145. }
  80146. }
  80147. return d;
  80148. }
  80149. function sortPaths(pathList) {
  80150. var xMin = Infinity;
  80151. var yMin = Infinity;
  80152. var xMax = -Infinity;
  80153. var yMax = -Infinity;
  80154. var cps = map(pathList, function (path) {
  80155. var rect = path.getBoundingRect();
  80156. var m = path.getComputedTransform();
  80157. var x = rect.x + rect.width / 2 + (m ? m[4] : 0);
  80158. var y = rect.y + rect.height / 2 + (m ? m[5] : 0);
  80159. xMin = Math.min(x, xMin);
  80160. yMin = Math.min(y, yMin);
  80161. xMax = Math.max(x, xMax);
  80162. yMax = Math.max(y, yMax);
  80163. return [x, y];
  80164. });
  80165. var items = map(cps, function (cp, idx) {
  80166. return {
  80167. cp: cp,
  80168. z: hilbert(cp[0], cp[1], xMin, yMin, xMax, yMax),
  80169. path: pathList[idx]
  80170. };
  80171. });
  80172. return items.sort(function (a, b) { return a.z - b.z; }).map(function (item) { return item.path; });
  80173. }
  80174. function defaultDividePath(param) {
  80175. return split(param.path, param.count);
  80176. }
  80177. function createEmptyReturn() {
  80178. return {
  80179. fromIndividuals: [],
  80180. toIndividuals: [],
  80181. count: 0
  80182. };
  80183. }
  80184. function combineMorph(fromList, toPath, animationOpts) {
  80185. var fromPathList = [];
  80186. function addFromPath(fromList) {
  80187. for (var i = 0; i < fromList.length; i++) {
  80188. var from = fromList[i];
  80189. if (isCombineMorphing(from)) {
  80190. addFromPath(from.childrenRef());
  80191. }
  80192. else if (from instanceof Path) {
  80193. fromPathList.push(from);
  80194. }
  80195. }
  80196. }
  80197. addFromPath(fromList);
  80198. var separateCount = fromPathList.length;
  80199. if (!separateCount) {
  80200. return createEmptyReturn();
  80201. }
  80202. var dividePath = animationOpts.dividePath || defaultDividePath;
  80203. var toSubPathList = dividePath({
  80204. path: toPath, count: separateCount
  80205. });
  80206. if (toSubPathList.length !== separateCount) {
  80207. console.error('Invalid morphing: unmatched splitted path');
  80208. return createEmptyReturn();
  80209. }
  80210. fromPathList = sortPaths(fromPathList);
  80211. toSubPathList = sortPaths(toSubPathList);
  80212. var oldDone = animationOpts.done;
  80213. var oldDuring = animationOpts.during;
  80214. var individualDelay = animationOpts.individualDelay;
  80215. var identityTransform = new Transformable();
  80216. for (var i = 0; i < separateCount; i++) {
  80217. var from = fromPathList[i];
  80218. var to = toSubPathList[i];
  80219. to.parent = toPath;
  80220. to.copyTransform(identityTransform);
  80221. if (!individualDelay) {
  80222. prepareMorphPath(from, to);
  80223. }
  80224. }
  80225. toPath.__isCombineMorphing = true;
  80226. toPath.childrenRef = function () {
  80227. return toSubPathList;
  80228. };
  80229. function addToSubPathListToZr(zr) {
  80230. for (var i = 0; i < toSubPathList.length; i++) {
  80231. toSubPathList[i].addSelfToZr(zr);
  80232. }
  80233. }
  80234. saveAndModifyMethod(toPath, 'addSelfToZr', {
  80235. after: function (zr) {
  80236. addToSubPathListToZr(zr);
  80237. }
  80238. });
  80239. saveAndModifyMethod(toPath, 'removeSelfFromZr', {
  80240. after: function (zr) {
  80241. for (var i = 0; i < toSubPathList.length; i++) {
  80242. toSubPathList[i].removeSelfFromZr(zr);
  80243. }
  80244. }
  80245. });
  80246. function restoreToPath() {
  80247. toPath.__isCombineMorphing = false;
  80248. toPath.__morphT = -1;
  80249. toPath.childrenRef = null;
  80250. restoreMethod(toPath, 'addSelfToZr');
  80251. restoreMethod(toPath, 'removeSelfFromZr');
  80252. }
  80253. var toLen = toSubPathList.length;
  80254. if (individualDelay) {
  80255. var animating_1 = toLen;
  80256. var eachDone = function () {
  80257. animating_1--;
  80258. if (animating_1 === 0) {
  80259. restoreToPath();
  80260. oldDone && oldDone();
  80261. }
  80262. };
  80263. for (var i = 0; i < toLen; i++) {
  80264. var indivdualAnimationOpts = individualDelay ? defaults({
  80265. delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toSubPathList[i]),
  80266. done: eachDone
  80267. }, animationOpts) : animationOpts;
  80268. morphPath(fromPathList[i], toSubPathList[i], indivdualAnimationOpts);
  80269. }
  80270. }
  80271. else {
  80272. toPath.__morphT = 0;
  80273. toPath.animateTo({
  80274. __morphT: 1
  80275. }, defaults({
  80276. during: function (p) {
  80277. for (var i = 0; i < toLen; i++) {
  80278. var child = toSubPathList[i];
  80279. child.__morphT = toPath.__morphT;
  80280. child.dirtyShape();
  80281. }
  80282. oldDuring && oldDuring(p);
  80283. },
  80284. done: function () {
  80285. restoreToPath();
  80286. for (var i = 0; i < fromList.length; i++) {
  80287. restoreMethod(fromList[i], 'updateTransform');
  80288. }
  80289. oldDone && oldDone();
  80290. }
  80291. }, animationOpts));
  80292. }
  80293. if (toPath.__zr) {
  80294. addToSubPathListToZr(toPath.__zr);
  80295. }
  80296. return {
  80297. fromIndividuals: fromPathList,
  80298. toIndividuals: toSubPathList,
  80299. count: toLen
  80300. };
  80301. }
  80302. function separateMorph(fromPath, toPathList, animationOpts) {
  80303. var toLen = toPathList.length;
  80304. var fromPathList = [];
  80305. var dividePath = animationOpts.dividePath || defaultDividePath;
  80306. function addFromPath(fromList) {
  80307. for (var i = 0; i < fromList.length; i++) {
  80308. var from = fromList[i];
  80309. if (isCombineMorphing(from)) {
  80310. addFromPath(from.childrenRef());
  80311. }
  80312. else if (from instanceof Path) {
  80313. fromPathList.push(from);
  80314. }
  80315. }
  80316. }
  80317. if (isCombineMorphing(fromPath)) {
  80318. addFromPath(fromPath.childrenRef());
  80319. var fromLen = fromPathList.length;
  80320. if (fromLen < toLen) {
  80321. var k = 0;
  80322. for (var i = fromLen; i < toLen; i++) {
  80323. fromPathList.push(clonePath(fromPathList[k++ % fromLen]));
  80324. }
  80325. }
  80326. fromPathList.length = toLen;
  80327. }
  80328. else {
  80329. fromPathList = dividePath({ path: fromPath, count: toLen });
  80330. var fromPathTransform = fromPath.getComputedTransform();
  80331. for (var i = 0; i < fromPathList.length; i++) {
  80332. fromPathList[i].setLocalTransform(fromPathTransform);
  80333. }
  80334. if (fromPathList.length !== toLen) {
  80335. console.error('Invalid morphing: unmatched splitted path');
  80336. return createEmptyReturn();
  80337. }
  80338. }
  80339. fromPathList = sortPaths(fromPathList);
  80340. toPathList = sortPaths(toPathList);
  80341. var individualDelay = animationOpts.individualDelay;
  80342. for (var i = 0; i < toLen; i++) {
  80343. var indivdualAnimationOpts = individualDelay ? defaults({
  80344. delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toPathList[i])
  80345. }, animationOpts) : animationOpts;
  80346. morphPath(fromPathList[i], toPathList[i], indivdualAnimationOpts);
  80347. }
  80348. return {
  80349. fromIndividuals: fromPathList,
  80350. toIndividuals: toPathList,
  80351. count: toPathList.length
  80352. };
  80353. }
  80354. function isMultiple(elements) {
  80355. return isArray(elements[0]);
  80356. }
  80357. function prepareMorphBatches(one, many) {
  80358. var batches = [];
  80359. var batchCount = one.length;
  80360. for (var i = 0; i < batchCount; i++) {
  80361. batches.push({
  80362. one: one[i],
  80363. many: []
  80364. });
  80365. }
  80366. for (var i = 0; i < many.length; i++) {
  80367. var len = many[i].length;
  80368. var k = void 0;
  80369. for (k = 0; k < len; k++) {
  80370. batches[k % batchCount].many.push(many[i][k]);
  80371. }
  80372. }
  80373. var off = 0; // If one has more paths than each one of many. average them.
  80374. for (var i = batchCount - 1; i >= 0; i--) {
  80375. if (!batches[i].many.length) {
  80376. var moveFrom = batches[off].many;
  80377. if (moveFrom.length <= 1) {
  80378. // Not enough
  80379. // Start from the first one.
  80380. if (off) {
  80381. off = 0;
  80382. } else {
  80383. return batches;
  80384. }
  80385. }
  80386. var len = moveFrom.length;
  80387. var mid = Math.ceil(len / 2);
  80388. batches[i].many = moveFrom.slice(mid, len);
  80389. batches[off].many = moveFrom.slice(0, mid);
  80390. off++;
  80391. }
  80392. }
  80393. return batches;
  80394. }
  80395. var pathDividers = {
  80396. clone: function (params) {
  80397. var ret = []; // Fitting the alpha
  80398. var approxOpacity = 1 - Math.pow(1 - params.path.style.opacity, 1 / params.count);
  80399. for (var i = 0; i < params.count; i++) {
  80400. var cloned = clonePath(params.path);
  80401. cloned.setStyle('opacity', approxOpacity);
  80402. ret.push(cloned);
  80403. }
  80404. return ret;
  80405. },
  80406. // Use the default divider
  80407. split: null
  80408. };
  80409. function applyMorphAnimation(from, to, divideShape, seriesModel, dataIndex, animateOtherProps) {
  80410. if (!from.length || !to.length) {
  80411. return;
  80412. }
  80413. var updateAnimationCfg = getAnimationConfig('update', seriesModel, dataIndex);
  80414. if (!(updateAnimationCfg && updateAnimationCfg.duration > 0)) {
  80415. return;
  80416. }
  80417. var animationDelay = seriesModel.getModel('universalTransition').get('delay');
  80418. var animationCfg = Object.assign({
  80419. // Need to setToFinal so the further calculation based on the style can be correct.
  80420. // Like emphasis color.
  80421. setToFinal: true
  80422. }, updateAnimationCfg);
  80423. var many;
  80424. var one;
  80425. if (isMultiple(from)) {
  80426. // manyToOne
  80427. many = from;
  80428. one = to;
  80429. }
  80430. if (isMultiple(to)) {
  80431. // oneToMany
  80432. many = to;
  80433. one = from;
  80434. }
  80435. function morphOneBatch(batch, fromIsMany, animateIndex, animateCount, forceManyOne) {
  80436. var batchMany = batch.many;
  80437. var batchOne = batch.one;
  80438. if (batchMany.length === 1 && !forceManyOne) {
  80439. // Is one to one
  80440. var batchFrom = fromIsMany ? batchMany[0] : batchOne;
  80441. var batchTo = fromIsMany ? batchOne : batchMany[0];
  80442. if (isCombineMorphing(batchFrom)) {
  80443. // Keep doing combine animation.
  80444. morphOneBatch({
  80445. many: [batchFrom],
  80446. one: batchTo
  80447. }, true, animateIndex, animateCount, true);
  80448. } else {
  80449. var individualAnimationCfg = animationDelay ? defaults({
  80450. delay: animationDelay(animateIndex, animateCount)
  80451. }, animationCfg) : animationCfg;
  80452. morphPath(batchFrom, batchTo, individualAnimationCfg);
  80453. animateOtherProps(batchFrom, batchTo, batchFrom, batchTo, individualAnimationCfg);
  80454. }
  80455. } else {
  80456. var separateAnimationCfg = defaults({
  80457. dividePath: pathDividers[divideShape],
  80458. individualDelay: animationDelay && function (idx, count, fromPath, toPath) {
  80459. return animationDelay(idx + animateIndex, animateCount);
  80460. }
  80461. }, animationCfg);
  80462. var _a = fromIsMany ? combineMorph(batchMany, batchOne, separateAnimationCfg) : separateMorph(batchOne, batchMany, separateAnimationCfg),
  80463. fromIndividuals = _a.fromIndividuals,
  80464. toIndividuals = _a.toIndividuals;
  80465. var count = fromIndividuals.length;
  80466. for (var k = 0; k < count; k++) {
  80467. var individualAnimationCfg = animationDelay ? defaults({
  80468. delay: animationDelay(k, count)
  80469. }, animationCfg) : animationCfg;
  80470. animateOtherProps(fromIndividuals[k], toIndividuals[k], fromIsMany ? batchMany[k] : batch.one, fromIsMany ? batch.one : batchMany[k], individualAnimationCfg);
  80471. }
  80472. }
  80473. }
  80474. var fromIsMany = many ? many === from // Is one to one. If the path number not match. also needs do merge and separate morphing.
  80475. : from.length > to.length;
  80476. var morphBatches = many ? prepareMorphBatches(one, many) : prepareMorphBatches(fromIsMany ? to : from, [fromIsMany ? from : to]);
  80477. var animateCount = 0;
  80478. for (var i = 0; i < morphBatches.length; i++) {
  80479. animateCount += morphBatches[i].many.length;
  80480. }
  80481. var animateIndex = 0;
  80482. for (var i = 0; i < morphBatches.length; i++) {
  80483. morphOneBatch(morphBatches[i], fromIsMany, animateIndex, animateCount);
  80484. animateIndex += morphBatches[i].many.length;
  80485. }
  80486. }
  80487. function getPathList(elements) {
  80488. if (!elements) {
  80489. return [];
  80490. }
  80491. if (isArray(elements)) {
  80492. var pathList_1 = [];
  80493. for (var i = 0; i < elements.length; i++) {
  80494. pathList_1.push(getPathList(elements[i]));
  80495. }
  80496. return pathList_1;
  80497. }
  80498. var pathList = [];
  80499. elements.traverse(function (el) {
  80500. if (el instanceof Path && !el.disableMorphing && !el.invisible && !el.ignore) {
  80501. pathList.push(el);
  80502. }
  80503. });
  80504. return pathList;
  80505. }
  80506. var DATA_COUNT_THRESHOLD = 1e4;
  80507. var getUniversalTransitionGlobalStore = makeInner();
  80508. function getGroupIdDimension(data) {
  80509. var dimensions = data.dimensions;
  80510. for (var i = 0; i < dimensions.length; i++) {
  80511. var dimInfo = data.getDimensionInfo(dimensions[i]);
  80512. if (dimInfo && dimInfo.otherDims.itemGroupId === 0) {
  80513. return dimensions[i];
  80514. }
  80515. }
  80516. }
  80517. function flattenDataDiffItems(list) {
  80518. var items = [];
  80519. each(list, function (seriesInfo) {
  80520. var data = seriesInfo.data;
  80521. if (data.count() > DATA_COUNT_THRESHOLD) {
  80522. if ("development" !== 'production') {
  80523. warn('Universal transition is disabled on large data > 10k.');
  80524. }
  80525. return;
  80526. }
  80527. var indices = data.getIndices();
  80528. var groupDim = getGroupIdDimension(data);
  80529. for (var dataIndex = 0; dataIndex < indices.length; dataIndex++) {
  80530. items.push({
  80531. data: data,
  80532. dim: seriesInfo.dim || groupDim,
  80533. divide: seriesInfo.divide,
  80534. dataIndex: dataIndex
  80535. });
  80536. }
  80537. });
  80538. return items;
  80539. }
  80540. function fadeInElement(newEl, newSeries, newIndex) {
  80541. newEl.traverse(function (el) {
  80542. if (el instanceof Path) {
  80543. // TODO use fade in animation for target element.
  80544. initProps(el, {
  80545. style: {
  80546. opacity: 0
  80547. }
  80548. }, newSeries, {
  80549. dataIndex: newIndex,
  80550. isFrom: true
  80551. });
  80552. }
  80553. });
  80554. }
  80555. function removeEl$1(el) {
  80556. if (el.parent) {
  80557. // Bake parent transform to element.
  80558. // So it can still have proper transform to transition after it's removed.
  80559. var computedTransform = el.getComputedTransform();
  80560. el.setLocalTransform(computedTransform);
  80561. el.parent.remove(el);
  80562. }
  80563. }
  80564. function stopAnimation(el) {
  80565. el.stopAnimation();
  80566. if (el.isGroup) {
  80567. el.traverse(function (child) {
  80568. child.stopAnimation();
  80569. });
  80570. }
  80571. }
  80572. function animateElementStyles(el, dataIndex, seriesModel) {
  80573. var animationConfig = getAnimationConfig('update', seriesModel, dataIndex);
  80574. animationConfig && el.traverse(function (child) {
  80575. if (child instanceof Displayable) {
  80576. var oldStyle = getOldStyle(child);
  80577. if (oldStyle) {
  80578. child.animateFrom({
  80579. style: oldStyle
  80580. }, animationConfig);
  80581. }
  80582. }
  80583. });
  80584. }
  80585. function isAllIdSame(oldDiffItems, newDiffItems) {
  80586. var len = oldDiffItems.length;
  80587. if (len !== newDiffItems.length) {
  80588. return false;
  80589. }
  80590. for (var i = 0; i < len; i++) {
  80591. var oldItem = oldDiffItems[i];
  80592. var newItem = newDiffItems[i];
  80593. if (oldItem.data.getId(oldItem.dataIndex) !== newItem.data.getId(newItem.dataIndex)) {
  80594. return false;
  80595. }
  80596. }
  80597. return true;
  80598. }
  80599. function transitionBetween(oldList, newList, api) {
  80600. var oldDiffItems = flattenDataDiffItems(oldList);
  80601. var newDiffItems = flattenDataDiffItems(newList);
  80602. function updateMorphingPathProps(from, to, rawFrom, rawTo, animationCfg) {
  80603. if (rawFrom || from) {
  80604. to.animateFrom({
  80605. style: (rawFrom || from).style
  80606. }, animationCfg);
  80607. }
  80608. }
  80609. function findKeyDim(items) {
  80610. for (var i = 0; i < items.length; i++) {
  80611. if (items[i].dim) {
  80612. return items[i].dim;
  80613. }
  80614. }
  80615. }
  80616. var oldKeyDim = findKeyDim(oldDiffItems);
  80617. var newKeyDim = findKeyDim(newDiffItems);
  80618. var hasMorphAnimation = false;
  80619. function createKeyGetter(isOld, onlyGetId) {
  80620. return function (diffItem) {
  80621. var data = diffItem.data;
  80622. var dataIndex = diffItem.dataIndex; // TODO if specified dim
  80623. if (onlyGetId) {
  80624. return data.getId(dataIndex);
  80625. } // Use group id as transition key by default.
  80626. // So we can achieve multiple to multiple animation like drilldown / up naturally.
  80627. // If group id not exits. Use id instead. If so, only one to one transition will be applied.
  80628. var dataGroupId = data.hostModel && data.hostModel.get('dataGroupId'); // If specified key dimension(itemGroupId by default). Use this same dimension from other data.
  80629. // PENDING: If only use key dimension of newData.
  80630. var keyDim = isOld ? oldKeyDim || newKeyDim : newKeyDim || oldKeyDim;
  80631. var dimInfo = keyDim && data.getDimensionInfo(keyDim);
  80632. var dimOrdinalMeta = dimInfo && dimInfo.ordinalMeta;
  80633. if (dimInfo) {
  80634. // Get from encode.itemGroupId.
  80635. var key = data.get(dimInfo.name, dataIndex);
  80636. if (dimOrdinalMeta) {
  80637. return dimOrdinalMeta.categories[key] || key + '';
  80638. }
  80639. return key + '';
  80640. } // Get groupId from raw item. { groupId: '' }
  80641. var itemVal = data.getRawDataItem(dataIndex);
  80642. if (itemVal && itemVal.groupId) {
  80643. return itemVal.groupId + '';
  80644. }
  80645. return dataGroupId || data.getId(dataIndex);
  80646. };
  80647. } // Use id if it's very likely to be an one to one animation
  80648. // It's more robust than groupId
  80649. // TODO Check if key dimension is specified.
  80650. var useId = isAllIdSame(oldDiffItems, newDiffItems);
  80651. var isElementStillInChart = {};
  80652. if (!useId) {
  80653. // We may have different diff strategy with basicTransition if we use other dimension as key.
  80654. // 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.
  80655. // We can't use the elements that already being morphed. Let it keep it's original basic transition.
  80656. for (var i = 0; i < newDiffItems.length; i++) {
  80657. var newItem = newDiffItems[i];
  80658. var el = newItem.data.getItemGraphicEl(newItem.dataIndex);
  80659. if (el) {
  80660. isElementStillInChart[el.id] = true;
  80661. }
  80662. }
  80663. }
  80664. function updateOneToOne(newIndex, oldIndex) {
  80665. var oldItem = oldDiffItems[oldIndex];
  80666. var newItem = newDiffItems[newIndex];
  80667. var newSeries = newItem.data.hostModel; // TODO Mark this elements is morphed and don't morph them anymore
  80668. var oldEl = oldItem.data.getItemGraphicEl(oldItem.dataIndex);
  80669. var newEl = newItem.data.getItemGraphicEl(newItem.dataIndex); // Can't handle same elements.
  80670. if (oldEl === newEl) {
  80671. newEl && animateElementStyles(newEl, newItem.dataIndex, newSeries);
  80672. return;
  80673. }
  80674. if ( // We can't use the elements that already being morphed
  80675. oldEl && isElementStillInChart[oldEl.id]) {
  80676. return;
  80677. }
  80678. if (newEl) {
  80679. // TODO: If keep animating the group in case
  80680. // some of the elements don't want to be morphed.
  80681. // TODO Label?
  80682. stopAnimation(newEl);
  80683. if (oldEl) {
  80684. stopAnimation(oldEl); // If old element is doing leaving animation. stop it and remove it immediately.
  80685. removeEl$1(oldEl);
  80686. hasMorphAnimation = true;
  80687. applyMorphAnimation(getPathList(oldEl), getPathList(newEl), newItem.divide, newSeries, newIndex, updateMorphingPathProps);
  80688. } else {
  80689. fadeInElement(newEl, newSeries, newIndex);
  80690. }
  80691. } // else keep oldEl leaving animation.
  80692. }
  80693. new DataDiffer(oldDiffItems, newDiffItems, createKeyGetter(true, useId), createKeyGetter(false, useId), null, 'multiple').update(updateOneToOne).updateManyToOne(function (newIndex, oldIndices) {
  80694. var newItem = newDiffItems[newIndex];
  80695. var newData = newItem.data;
  80696. var newSeries = newData.hostModel;
  80697. var newEl = newData.getItemGraphicEl(newItem.dataIndex);
  80698. var oldElsList = filter(map(oldIndices, function (idx) {
  80699. return oldDiffItems[idx].data.getItemGraphicEl(oldDiffItems[idx].dataIndex);
  80700. }), function (oldEl) {
  80701. return oldEl && oldEl !== newEl && !isElementStillInChart[oldEl.id];
  80702. });
  80703. if (newEl) {
  80704. stopAnimation(newEl);
  80705. if (oldElsList.length) {
  80706. // If old element is doing leaving animation. stop it and remove it immediately.
  80707. each(oldElsList, function (oldEl) {
  80708. stopAnimation(oldEl);
  80709. removeEl$1(oldEl);
  80710. });
  80711. hasMorphAnimation = true;
  80712. applyMorphAnimation(getPathList(oldElsList), getPathList(newEl), newItem.divide, newSeries, newIndex, updateMorphingPathProps);
  80713. } else {
  80714. fadeInElement(newEl, newSeries, newItem.dataIndex);
  80715. }
  80716. } // else keep oldEl leaving animation.
  80717. }).updateOneToMany(function (newIndices, oldIndex) {
  80718. var oldItem = oldDiffItems[oldIndex];
  80719. var oldEl = oldItem.data.getItemGraphicEl(oldItem.dataIndex); // We can't use the elements that already being morphed
  80720. if (oldEl && isElementStillInChart[oldEl.id]) {
  80721. return;
  80722. }
  80723. var newElsList = filter(map(newIndices, function (idx) {
  80724. return newDiffItems[idx].data.getItemGraphicEl(newDiffItems[idx].dataIndex);
  80725. }), function (el) {
  80726. return el && el !== oldEl;
  80727. });
  80728. var newSeris = newDiffItems[newIndices[0]].data.hostModel;
  80729. if (newElsList.length) {
  80730. each(newElsList, function (newEl) {
  80731. return stopAnimation(newEl);
  80732. });
  80733. if (oldEl) {
  80734. stopAnimation(oldEl); // If old element is doing leaving animation. stop it and remove it immediately.
  80735. removeEl$1(oldEl);
  80736. hasMorphAnimation = true;
  80737. applyMorphAnimation(getPathList(oldEl), getPathList(newElsList), oldItem.divide, // Use divide on old.
  80738. newSeris, newIndices[0], updateMorphingPathProps);
  80739. } else {
  80740. each(newElsList, function (newEl) {
  80741. return fadeInElement(newEl, newSeris, newIndices[0]);
  80742. });
  80743. }
  80744. } // else keep oldEl leaving animation.
  80745. }).updateManyToMany(function (newIndices, oldIndices) {
  80746. // If two data are same and both have groupId.
  80747. // Normally they should be diff by id.
  80748. new DataDiffer(oldIndices, newIndices, function (rawIdx) {
  80749. return oldDiffItems[rawIdx].data.getId(oldDiffItems[rawIdx].dataIndex);
  80750. }, function (rawIdx) {
  80751. return newDiffItems[rawIdx].data.getId(newDiffItems[rawIdx].dataIndex);
  80752. }).update(function (newIndex, oldIndex) {
  80753. // Use the original index
  80754. updateOneToOne(newIndices[newIndex], oldIndices[oldIndex]);
  80755. }).execute();
  80756. }).execute();
  80757. if (hasMorphAnimation) {
  80758. each(newList, function (_a) {
  80759. var data = _a.data;
  80760. var seriesModel = data.hostModel;
  80761. var view = seriesModel && api.getViewOfSeriesModel(seriesModel);
  80762. var animationCfg = getAnimationConfig('update', seriesModel, 0); // use 0 index.
  80763. if (view && seriesModel.isAnimationEnabled() && animationCfg && animationCfg.duration > 0) {
  80764. view.group.traverse(function (el) {
  80765. if (el instanceof Path && !el.animators.length) {
  80766. // We can't accept there still exists element that has no animation
  80767. // if universalTransition is enabled
  80768. el.animateFrom({
  80769. style: {
  80770. opacity: 0
  80771. }
  80772. }, animationCfg);
  80773. }
  80774. });
  80775. }
  80776. });
  80777. }
  80778. }
  80779. function getSeriesTransitionKey(series) {
  80780. var seriesKey = series.getModel('universalTransition').get('seriesKey');
  80781. if (!seriesKey) {
  80782. // Use series id by default.
  80783. return series.id;
  80784. }
  80785. return seriesKey;
  80786. }
  80787. function convertArraySeriesKeyToString(seriesKey) {
  80788. if (isArray(seriesKey)) {
  80789. // Order independent.
  80790. return seriesKey.sort().join(',');
  80791. }
  80792. return seriesKey;
  80793. }
  80794. function getDivideShapeFromData(data) {
  80795. if (data.hostModel) {
  80796. return data.hostModel.getModel('universalTransition').get('divideShape');
  80797. }
  80798. }
  80799. function findTransitionSeriesBatches(globalStore, params) {
  80800. var updateBatches = createHashMap();
  80801. var oldDataMap = createHashMap(); // Map that only store key in array seriesKey.
  80802. // Which is used to query the old data when transition from one to multiple series.
  80803. var oldDataMapForSplit = createHashMap();
  80804. each(globalStore.oldSeries, function (series, idx) {
  80805. var oldData = globalStore.oldData[idx];
  80806. var transitionKey = getSeriesTransitionKey(series);
  80807. var transitionKeyStr = convertArraySeriesKeyToString(transitionKey);
  80808. oldDataMap.set(transitionKeyStr, oldData);
  80809. if (isArray(transitionKey)) {
  80810. // Same key can't in different array seriesKey.
  80811. each(transitionKey, function (key) {
  80812. oldDataMapForSplit.set(key, {
  80813. data: oldData,
  80814. key: transitionKeyStr
  80815. });
  80816. });
  80817. }
  80818. });
  80819. function checkTransitionSeriesKeyDuplicated(transitionKeyStr) {
  80820. if (updateBatches.get(transitionKeyStr)) {
  80821. warn("Duplicated seriesKey in universalTransition " + transitionKeyStr);
  80822. }
  80823. }
  80824. each(params.updatedSeries, function (series) {
  80825. if (series.isUniversalTransitionEnabled() && series.isAnimationEnabled()) {
  80826. var newData = series.getData();
  80827. var transitionKey = getSeriesTransitionKey(series);
  80828. var transitionKeyStr = convertArraySeriesKeyToString(transitionKey); // Only transition between series with same id.
  80829. var oldData = oldDataMap.get(transitionKeyStr); // string transition key is the best match.
  80830. if (oldData) {
  80831. if ("development" !== 'production') {
  80832. checkTransitionSeriesKeyDuplicated(transitionKeyStr);
  80833. } // TODO check if data is same?
  80834. updateBatches.set(transitionKeyStr, {
  80835. oldSeries: [{
  80836. divide: getDivideShapeFromData(oldData),
  80837. data: oldData
  80838. }],
  80839. newSeries: [{
  80840. divide: getDivideShapeFromData(newData),
  80841. data: newData
  80842. }]
  80843. });
  80844. } else {
  80845. // Transition from multiple series.
  80846. if (isArray(transitionKey)) {
  80847. if ("development" !== 'production') {
  80848. checkTransitionSeriesKeyDuplicated(transitionKeyStr);
  80849. }
  80850. var oldSeries_1 = [];
  80851. each(transitionKey, function (key) {
  80852. var oldData = oldDataMap.get(key);
  80853. if (oldData) {
  80854. oldSeries_1.push({
  80855. divide: getDivideShapeFromData(oldData),
  80856. data: oldData
  80857. });
  80858. }
  80859. });
  80860. if (oldSeries_1.length) {
  80861. updateBatches.set(transitionKeyStr, {
  80862. oldSeries: oldSeries_1,
  80863. newSeries: [{
  80864. data: newData,
  80865. divide: getDivideShapeFromData(newData)
  80866. }]
  80867. });
  80868. }
  80869. } else {
  80870. // Try transition to multiple series.
  80871. var oldData_1 = oldDataMapForSplit.get(transitionKey);
  80872. if (oldData_1) {
  80873. var batch = updateBatches.get(oldData_1.key);
  80874. if (!batch) {
  80875. batch = {
  80876. oldSeries: [{
  80877. data: oldData_1.data,
  80878. divide: getDivideShapeFromData(oldData_1.data)
  80879. }],
  80880. newSeries: []
  80881. };
  80882. updateBatches.set(oldData_1.key, batch);
  80883. }
  80884. batch.newSeries.push({
  80885. data: newData,
  80886. divide: getDivideShapeFromData(newData)
  80887. });
  80888. }
  80889. }
  80890. }
  80891. }
  80892. });
  80893. return updateBatches;
  80894. }
  80895. function querySeries(series, finder) {
  80896. for (var i = 0; i < series.length; i++) {
  80897. var found = finder.seriesIndex != null && finder.seriesIndex === series[i].seriesIndex || finder.seriesId != null && finder.seriesId === series[i].id;
  80898. if (found) {
  80899. return i;
  80900. }
  80901. }
  80902. }
  80903. function transitionSeriesFromOpt(transitionOpt, globalStore, params, api) {
  80904. var from = [];
  80905. var to = [];
  80906. each(normalizeToArray(transitionOpt.from), function (finder) {
  80907. var idx = querySeries(globalStore.oldSeries, finder);
  80908. if (idx >= 0) {
  80909. from.push({
  80910. data: globalStore.oldData[idx],
  80911. // TODO can specify divideShape in transition.
  80912. divide: getDivideShapeFromData(globalStore.oldData[idx]),
  80913. dim: finder.dimension
  80914. });
  80915. }
  80916. });
  80917. each(normalizeToArray(transitionOpt.to), function (finder) {
  80918. var idx = querySeries(params.updatedSeries, finder);
  80919. if (idx >= 0) {
  80920. var data = params.updatedSeries[idx].getData();
  80921. to.push({
  80922. data: data,
  80923. divide: getDivideShapeFromData(data),
  80924. dim: finder.dimension
  80925. });
  80926. }
  80927. });
  80928. if (from.length > 0 && to.length > 0) {
  80929. transitionBetween(from, to, api);
  80930. }
  80931. }
  80932. function installUniversalTransition(registers) {
  80933. registers.registerUpdateLifecycle('series:beforeupdate', function (ecMOdel, api, params) {
  80934. each(normalizeToArray(params.seriesTransition), function (transOpt) {
  80935. each(normalizeToArray(transOpt.to), function (finder) {
  80936. var series = params.updatedSeries;
  80937. for (var i = 0; i < series.length; i++) {
  80938. if (finder.seriesIndex != null && finder.seriesIndex === series[i].seriesIndex || finder.seriesId != null && finder.seriesId === series[i].id) {
  80939. series[i][SERIES_UNIVERSAL_TRANSITION_PROP] = true;
  80940. }
  80941. }
  80942. });
  80943. });
  80944. });
  80945. registers.registerUpdateLifecycle('series:transition', function (ecModel, api, params) {
  80946. // TODO api provide an namespace that can save stuff per instance
  80947. var globalStore = getUniversalTransitionGlobalStore(api); // TODO multiple to multiple series.
  80948. if (globalStore.oldSeries && params.updatedSeries && params.optionChanged) {
  80949. // Use give transition config if its' give;
  80950. var transitionOpt = params.seriesTransition;
  80951. if (transitionOpt) {
  80952. each(normalizeToArray(transitionOpt), function (opt) {
  80953. transitionSeriesFromOpt(opt, globalStore, params, api);
  80954. });
  80955. } else {
  80956. // Else guess from series based on transition series key.
  80957. var updateBatches_1 = findTransitionSeriesBatches(globalStore, params);
  80958. each(updateBatches_1.keys(), function (key) {
  80959. var batch = updateBatches_1.get(key);
  80960. transitionBetween(batch.oldSeries, batch.newSeries, api);
  80961. });
  80962. } // Reset
  80963. each(params.updatedSeries, function (series) {
  80964. // Reset;
  80965. if (series[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  80966. series[SERIES_UNIVERSAL_TRANSITION_PROP] = false;
  80967. }
  80968. });
  80969. } // Save all series of current update. Not only the updated one.
  80970. var allSeries = ecModel.getSeries();
  80971. var savedSeries = globalStore.oldSeries = [];
  80972. var savedData = globalStore.oldData = [];
  80973. for (var i = 0; i < allSeries.length; i++) {
  80974. var data = allSeries[i].getData(); // Only save the data that can have transition.
  80975. // Avoid large data costing too much extra memory
  80976. if (data.count() < DATA_COUNT_THRESHOLD) {
  80977. savedSeries.push(allSeries[i]);
  80978. savedData.push(data);
  80979. }
  80980. }
  80981. });
  80982. }
  80983. // Render engines
  80984. // -----------------
  80985. // Render via Canvas.
  80986. // echarts.init(dom, null, { renderer: 'canvas' })
  80987. use([install$1]); // Render via SVG.
  80988. // echarts.init(dom, null, { renderer: 'svg' })
  80989. use([install]); // ----------------
  80990. // Charts (series)
  80991. // ----------------
  80992. // All of the series types, for example:
  80993. // chart.setOption({
  80994. // series: [{
  80995. // type: 'line' // or 'bar', 'pie', ...
  80996. // }]
  80997. // });
  80998. 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]); // -------------------
  80999. // Coordinate systems
  81000. // -------------------
  81001. // All of the axis modules have been included in the
  81002. // coordinate system module below, do not need to
  81003. // make extra import.
  81004. // `cartesian` coordinate system. For some historical
  81005. // reasons, it is named as grid, for example:
  81006. // chart.setOption({
  81007. // grid: {...},
  81008. // xAxis: {...},
  81009. // yAxis: {...},
  81010. // series: [{...}]
  81011. // });
  81012. use(install$t); // `polar` coordinate system, for example:
  81013. // chart.setOption({
  81014. // polar: {...},
  81015. // radiusAxis: {...},
  81016. // angleAxis: {...},
  81017. // series: [{
  81018. // coordinateSystem: 'polar'
  81019. // }]
  81020. // });
  81021. use(install$u); // `geo` coordinate system, for example:
  81022. // chart.setOption({
  81023. // geo: {...},
  81024. // series: [{
  81025. // coordinateSystem: 'geo'
  81026. // }]
  81027. // });
  81028. use(install$9); // `singleAxis` coordinate system (notice, it is a coordinate system
  81029. // with only one axis, work for chart like theme river), for example:
  81030. // chart.setOption({
  81031. // singleAxis: {...}
  81032. // series: [{type: 'themeRiver', ...}]
  81033. // });
  81034. use(install$v); // `parallel` coordinate system, only work for parallel series, for example:
  81035. // chart.setOption({
  81036. // parallel: {...},
  81037. // parallelAxis: [{...}, ...],
  81038. // series: [{
  81039. // type: 'parallel'
  81040. // }]
  81041. // });
  81042. use(install$g); // `calendar` coordinate system. for example,
  81043. // chart.setOptionp({
  81044. // calendar: {...},
  81045. // series: [{
  81046. // coordinateSystem: 'calendar'
  81047. // }]
  81048. // );
  81049. use(install$w); // ------------------
  81050. // Other components
  81051. // ------------------
  81052. // `graphic` component, for example:
  81053. // chart.setOption({
  81054. // graphic: {...}
  81055. // });
  81056. use(install$x); // `toolbox` component, for example:
  81057. // chart.setOption({
  81058. // toolbox: {...}
  81059. // });
  81060. use(install$z); // `tooltip` component, for example:
  81061. // chart.setOption({
  81062. // tooltip: {...}
  81063. // });
  81064. use(install$A); // `axisPointer` component, for example:
  81065. // chart.setOption({
  81066. // tooltip: {axisPointer: {...}, ...}
  81067. // });
  81068. // Or
  81069. // chart.setOption({
  81070. // axisPointer: {...}
  81071. // });
  81072. use(install$s); // `brush` component, for example:
  81073. // chart.setOption({
  81074. // brush: {...}
  81075. // });
  81076. // Or
  81077. // chart.setOption({
  81078. // tooltip: {feature: {brush: {...}}
  81079. // })
  81080. use(install$B); // `title` component, for example:
  81081. // chart.setOption({
  81082. // title: {...}
  81083. // });
  81084. use(install$C); // `timeline` component, for example:
  81085. // chart.setOption({
  81086. // timeline: {...}
  81087. // });
  81088. use(install$D); // `markPoint` component, for example:
  81089. // chart.setOption({
  81090. // series: [{markPoint: {...}}]
  81091. // });
  81092. use(install$E); // `markLine` component, for example:
  81093. // chart.setOption({
  81094. // series: [{markLine: {...}}]
  81095. // });
  81096. use(install$F); // `markArea` component, for example:
  81097. // chart.setOption({
  81098. // series: [{markArea: {...}}]
  81099. // });
  81100. use(install$G); // `legend` component not scrollable. for example:
  81101. // chart.setOption({
  81102. // legend: {...}
  81103. // });
  81104. use(install$J); // `dataZoom` component including both `dataZoomInside` and `dataZoomSlider`.
  81105. use(install$M); // `dataZoom` component providing drag, pinch, wheel behaviors
  81106. // inside coodinate system, for example:
  81107. // chart.setOption({
  81108. // dataZoom: {type: 'inside'}
  81109. // });
  81110. use(install$K); // `dataZoom` component providing a slider bar, for example:
  81111. // chart.setOption({
  81112. // dataZoom: {type: 'slider'}
  81113. // });
  81114. use(install$L); // `visualMap` component including both `visualMapContinuous` and `visualMapPiecewise`.
  81115. use(install$P); // `visualMap` component providing continuous bar, for example:
  81116. // chart.setOption({
  81117. // visualMap: {type: 'continuous'}
  81118. // });
  81119. use(install$N); // `visualMap` component providing pieces bar, for example:
  81120. // chart.setOption({
  81121. // visualMap: {type: 'piecewise'}
  81122. // });
  81123. use(install$O); // `aria` component providing aria, for example:
  81124. // chart.setOption({
  81125. // aria: {...}
  81126. // });
  81127. use(install$Q); // dataset transform
  81128. // chart.setOption({
  81129. // dataset: {
  81130. // transform: []
  81131. // }
  81132. // });
  81133. use(install$R);
  81134. use(install$S); // universal transition
  81135. // chart.setOption({
  81136. // series: {
  81137. // universalTransition: { enabled: true }
  81138. // }
  81139. // })
  81140. use(installUniversalTransition); // label layout
  81141. // chart.setOption({
  81142. // series: {
  81143. // labelLayout: { hideOverlap: true }
  81144. // }
  81145. // })
  81146. use(installLabelLayout);
  81147. exports.Axis = Axis;
  81148. exports.ChartView = ChartView;
  81149. exports.ComponentModel = ComponentModel;
  81150. exports.ComponentView = ComponentView;
  81151. exports.List = SeriesData;
  81152. exports.Model = Model;
  81153. exports.PRIORITY = PRIORITY;
  81154. exports.SeriesModel = SeriesModel;
  81155. exports.color = color;
  81156. exports.connect = connect;
  81157. exports.dataTool = dataTool;
  81158. exports.dependencies = dependencies;
  81159. exports.disConnect = disConnect;
  81160. exports.disconnect = disconnect;
  81161. exports.dispose = dispose$1;
  81162. exports.env = env;
  81163. exports.extendChartView = extendChartView;
  81164. exports.extendComponentModel = extendComponentModel;
  81165. exports.extendComponentView = extendComponentView;
  81166. exports.extendSeriesModel = extendSeriesModel;
  81167. exports.format = format$1;
  81168. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  81169. exports.getInstanceByDom = getInstanceByDom;
  81170. exports.getInstanceById = getInstanceById;
  81171. exports.getMap = getMap;
  81172. exports.graphic = graphic$1;
  81173. exports.helper = helper;
  81174. exports.init = init$1;
  81175. exports.innerDrawElementOnCanvas = brushSingle;
  81176. exports.matrix = matrix;
  81177. exports.number = number;
  81178. exports.parseGeoJSON = parseGeoJSON;
  81179. exports.parseGeoJson = parseGeoJSON;
  81180. exports.registerAction = registerAction;
  81181. exports.registerCoordinateSystem = registerCoordinateSystem;
  81182. exports.registerLayout = registerLayout;
  81183. exports.registerLoading = registerLoading;
  81184. exports.registerLocale = registerLocale;
  81185. exports.registerMap = registerMap;
  81186. exports.registerPostInit = registerPostInit;
  81187. exports.registerPostUpdate = registerPostUpdate;
  81188. exports.registerPreprocessor = registerPreprocessor;
  81189. exports.registerProcessor = registerProcessor;
  81190. exports.registerTheme = registerTheme;
  81191. exports.registerTransform = registerTransform;
  81192. exports.registerUpdateLifecycle = registerUpdateLifecycle;
  81193. exports.registerVisual = registerVisual;
  81194. exports.setCanvasCreator = setCanvasCreator;
  81195. exports.throttle = throttle;
  81196. exports.time = time;
  81197. exports.use = use;
  81198. exports.util = util$1;
  81199. exports.vector = vector;
  81200. exports.version = version$1;
  81201. exports.zrUtil = util;
  81202. exports.zrender = zrender;
  81203. Object.defineProperty(exports, '__esModule', { value: true });
  81204. })));
  81205. })));
  81206. layui.define('echartsTheme', function(exports) {
  81207. echarts.registerTheme('walden', layui.echartsTheme);
  81208. exports('echarts', echarts);
  81209. });